loadwise 0.6.2 → 0.8.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 (278) hide show
  1. package/README.md +175 -115
  2. package/dist/bin/loadwise.js +132 -67
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/frontend-detect.js +6 -5
  10. package/dist/lib/accessibility/jsx-elements.js +13 -3
  11. package/dist/lib/accessibility/markup-files.js +7 -2
  12. package/dist/lib/accessibility/rule-ids.js +3 -0
  13. package/dist/lib/accessibility/rules.js +128 -41
  14. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  15. package/dist/lib/accessibility/template-attributes.js +5 -3
  16. package/dist/lib/accessibility/template-elements.js +25 -6
  17. package/dist/lib/accessibility/template-file.js +40 -25
  18. package/dist/lib/accessibility/usage.js +10 -2
  19. package/dist/lib/editor/accessibility-examples.js +6 -1
  20. package/dist/lib/editor/actions.js +46 -7
  21. package/dist/lib/editor/apply-fix.js +69 -4
  22. package/dist/lib/editor/configured-setup.js +63 -0
  23. package/dist/lib/editor/diagnostics.js +206 -17
  24. package/dist/lib/editor/dismissals.js +85 -26
  25. package/dist/lib/editor/editor-document.js +5 -2
  26. package/dist/lib/editor/editor-launcher.js +170 -0
  27. package/dist/lib/editor/fix-edits.js +19 -0
  28. package/dist/lib/editor/jetbrains-setup.js +53 -0
  29. package/dist/lib/editor/language-server.js +80 -24
  30. package/dist/lib/editor/managed-config.js +37 -0
  31. package/dist/lib/editor/native-setup.js +86 -0
  32. package/dist/lib/editor/perf-watch.js +8 -6
  33. package/dist/lib/editor/release-vsix.js +61 -0
  34. package/dist/lib/editor/reliability-examples.js +15 -0
  35. package/dist/lib/editor/scan-session.js +29 -8
  36. package/dist/lib/editor/server-commands.js +38 -9
  37. package/dist/lib/editor/setup-server.js +87 -0
  38. package/dist/lib/editor/setup-vim.js +63 -0
  39. package/dist/lib/editor/setup.js +131 -0
  40. package/dist/lib/editor/stdio-setup.js +6 -0
  41. package/dist/lib/editor/workspace-files.js +61 -7
  42. package/dist/lib/editor/workspace-paths.js +41 -1
  43. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  44. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  45. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  46. package/dist/lib/maintainability/cli/inputs.js +12 -3
  47. package/dist/lib/maintainability/cli.js +18 -5
  48. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  49. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  50. package/dist/lib/maintainability/examples.js +4 -0
  51. package/dist/lib/maintainability/quality/functions.js +9 -6
  52. package/dist/lib/maintainability/quality/limits.js +19 -0
  53. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  54. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  55. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  56. package/dist/lib/maintainability/rule-ids.js +3 -0
  57. package/dist/lib/maintainability/scan-changed.js +4 -1
  58. package/dist/lib/maintainability/scan-worker.js +6 -2
  59. package/dist/lib/maintainability/scan.js +21 -8
  60. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  61. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  62. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  63. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  64. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  65. package/dist/lib/performance/analysis/source-options.js +7 -6
  66. package/dist/lib/performance/analyze.js +16 -3
  67. package/dist/lib/performance/cli/changed-lines.js +8 -1
  68. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  69. package/dist/lib/performance/cli/cli-output.js +4 -0
  70. package/dist/lib/performance/cli/cli-scan.js +21 -2
  71. package/dist/lib/performance/cli.js +16 -7
  72. package/dist/lib/performance/collections/memory-growth.js +55 -12
  73. package/dist/lib/performance/contracts/openapi.js +13 -4
  74. package/dist/lib/performance/datastores/pg-integrity.js +68 -22
  75. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  76. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  77. package/dist/lib/performance/datastores/pooling.js +62 -3
  78. package/dist/lib/performance/datastores/redis.js +94 -18
  79. package/dist/lib/performance/datastores/session-store.js +2 -1
  80. package/dist/lib/performance/db/checks.js +19 -8
  81. package/dist/lib/performance/db/gateway.js +3 -1
  82. package/dist/lib/performance/db/plan-estimates.js +4 -4
  83. package/dist/lib/performance/engine/native-syntax.js +3 -0
  84. package/dist/lib/performance/engine/native.js +11 -7
  85. package/dist/lib/performance/evidence/plans.js +7 -5
  86. package/dist/lib/performance/evidence/traces.js +21 -1
  87. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  88. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  89. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  90. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  91. package/dist/lib/performance/frontend/frontend-perf.js +149 -74
  92. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  93. package/dist/lib/performance/migrations/extract-code.js +13 -5
  94. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  95. package/dist/lib/performance/migrations/operations.js +56 -13
  96. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  97. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  98. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  99. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  100. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  101. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  102. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  103. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  104. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  105. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  106. package/dist/lib/performance/polyglot.js +111 -14
  107. package/dist/lib/performance/projects.js +3 -3
  108. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  109. package/dist/lib/performance/request/backend-mastery.js +151 -42
  110. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  111. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  112. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  113. package/dist/lib/performance/request/mongoose-lean.js +298 -46
  114. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  115. package/dist/lib/performance/request/phase5-ast.js +6 -7
  116. package/dist/lib/performance/request/phase5-rules.js +204 -23
  117. package/dist/lib/performance/request/request-handlers.js +120 -23
  118. package/dist/lib/performance/request/sql-select-star.js +150 -0
  119. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  120. package/dist/lib/performance/request/upload-limits.js +5 -1
  121. package/dist/lib/performance/site-fix.js +4 -4
  122. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  123. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  124. package/dist/lib/performance/site-fixes/collections.js +1 -2
  125. package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
  126. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  127. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  128. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  129. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  130. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  131. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  132. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  133. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  134. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  135. package/dist/lib/reliability/boundary-access.js +114 -57
  136. package/dist/lib/reliability/react-bugs.js +29 -7
  137. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  138. package/dist/lib/reliability/resource-leaks.js +209 -195
  139. package/dist/lib/reliability/rule-ids.js +10 -1
  140. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  141. package/dist/lib/reliability/swallowed-errors.js +107 -21
  142. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  143. package/dist/lib/reliability/usage.js +16 -5
  144. package/dist/lib/reliability/walk.js +3 -2
  145. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  146. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  147. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  148. package/dist/lib/security/auth-crypto/shared.js +3 -1
  149. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  150. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  151. package/dist/lib/security/cli.js +21 -6
  152. package/dist/lib/security/cookie-credentials.js +115 -0
  153. package/dist/lib/security/cookie-csrf.js +241 -0
  154. package/dist/lib/security/deps/advisory.js +50 -109
  155. package/dist/lib/security/deps/cli.js +1 -1
  156. package/dist/lib/security/deps/cvss-score.js +14 -0
  157. package/dist/lib/security/deps/fixed-version.js +97 -0
  158. package/dist/lib/security/deps/lockfiles.js +135 -74
  159. package/dist/lib/security/deps/osv.js +11 -3
  160. package/dist/lib/security/deps/scan.js +47 -20
  161. package/dist/lib/security/deps/yarn-lock.js +158 -0
  162. package/dist/lib/security/examples/injection.cjs +4 -0
  163. package/dist/lib/security/exposure/cookies.js +17 -2
  164. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  165. package/dist/lib/security/exposure/frontend-security.js +21 -14
  166. package/dist/lib/security/exposure/jsx-url.js +18 -33
  167. package/dist/lib/security/exposure/logging.js +49 -10
  168. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  169. package/dist/lib/security/exposure/react-html.js +26 -0
  170. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  171. package/dist/lib/security/files/compose.js +126 -1
  172. package/dist/lib/security/files/dockerfile.js +62 -4
  173. package/dist/lib/security/files/index.js +1 -1
  174. package/dist/lib/security/injection/command.js +46 -18
  175. package/dist/lib/security/injection/index.js +2 -0
  176. package/dist/lib/security/injection/ldap.js +86 -0
  177. package/dist/lib/security/injection/nosql.js +28 -4
  178. package/dist/lib/security/injection/redos.js +1 -1
  179. package/dist/lib/security/injection/rule-ids.js +1 -0
  180. package/dist/lib/security/injection/shared.js +5 -1
  181. package/dist/lib/security/injection/sql.js +28 -13
  182. package/dist/lib/security/lexical-declaration.js +113 -0
  183. package/dist/lib/security/pg-dynamic-query.js +28 -1
  184. package/dist/lib/security/pg-identifier-guards.js +107 -3
  185. package/dist/lib/security/phase5-rules.js +26 -135
  186. package/dist/lib/security/polyglot.js +2 -2
  187. package/dist/lib/security/redirect-settings.js +98 -0
  188. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  189. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  190. package/dist/lib/security/request-forgery/shared.js +1 -7
  191. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  192. package/dist/lib/security/rule-descriptions.js +5 -1
  193. package/dist/lib/security/rule-ids.js +7 -0
  194. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  195. package/dist/lib/security/site-fixes/exposure.js +21 -3
  196. package/dist/lib/security/site-fixes/files.js +11 -13
  197. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  198. package/dist/lib/security/site-fixes/injection.js +17 -4
  199. package/dist/lib/security/site-fixes/jwt.js +1 -20
  200. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  201. package/dist/lib/security/taint/binding-inputs.js +236 -0
  202. package/dist/lib/security/taint/filename-guard.js +45 -45
  203. package/dist/lib/security/taint/guards.js +14 -8
  204. package/dist/lib/security/taint/index.js +126 -154
  205. package/dist/lib/security/taint/propagate.js +43 -9
  206. package/dist/lib/security/taint/record-writes.js +161 -0
  207. package/dist/lib/security/taint/resolution-cache.js +13 -7
  208. package/dist/lib/security/taint/sanitizers.js +89 -5
  209. package/dist/lib/security/taint/trace-nodes.js +61 -0
  210. package/dist/lib/security/taint/validators.js +89 -9
  211. package/dist/lib/shared/agent/agent-init.js +28 -5
  212. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  213. package/dist/lib/shared/agent/agent-session.js +6 -1
  214. package/dist/lib/shared/agent/agent-verify.js +58 -11
  215. package/dist/lib/shared/agent/git-hook.js +17 -6
  216. package/dist/lib/shared/agent/review-delivery.js +1 -1
  217. package/dist/lib/shared/agent/review-mcp.js +8 -2
  218. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  219. package/dist/lib/shared/analysis/scan-cache.js +99 -14
  220. package/dist/lib/shared/check.js +172 -20
  221. package/dist/lib/shared/cli-dispatch.js +17 -0
  222. package/dist/lib/shared/config.js +27 -10
  223. package/dist/lib/shared/explain.js +1 -1
  224. package/dist/lib/shared/fix/fix-convergence.js +19 -31
  225. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  226. package/dist/lib/shared/fix/fix-imports.js +4 -162
  227. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  228. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  229. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  230. package/dist/lib/shared/fix/fix-presentation.js +9 -6
  231. package/dist/lib/shared/fix/fix-safety.js +32 -1
  232. package/dist/lib/shared/fix/fix-scope.js +82 -0
  233. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  234. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  235. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  236. package/dist/lib/shared/fix/project-file-access.js +17 -26
  237. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  238. package/dist/lib/shared/fix.js +241 -104
  239. package/dist/lib/shared/formats/finding-location.js +4 -1
  240. package/dist/lib/shared/formats/github.js +3 -3
  241. package/dist/lib/shared/formats/sarif.js +9 -3
  242. package/dist/lib/shared/report-fp.js +97 -0
  243. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  244. package/dist/lib/shared/reporting/baseline.js +7 -5
  245. package/dist/lib/shared/reporting/check-text.js +50 -0
  246. package/dist/lib/shared/reporting/pillars.js +54 -19
  247. package/dist/lib/shared/reporting/source-report.js +3 -0
  248. package/dist/lib/shared/system/atomic-write.js +5 -2
  249. package/dist/lib/shared/system/glob.js +34 -8
  250. package/dist/lib/shared/system/sentry.js +222 -0
  251. package/dist/lib/shared/system/shell-argument.js +5 -1
  252. package/dist/lib/shared/system/terminal-safe.js +3 -2
  253. package/dist/lib/shared/system/terminal-style.js +131 -0
  254. package/dist/lib/shared/workspaces.js +15 -3
  255. package/docs/assets/cli-workflow.gif +0 -0
  256. package/integrations/sublime/plugin.py +22 -0
  257. package/integrations/zed/Cargo.lock +845 -0
  258. package/integrations/zed/Cargo.toml +11 -0
  259. package/integrations/zed/extension.toml +11 -0
  260. package/integrations/zed/src/lib.rs +25 -0
  261. package/package.json +15 -3
  262. package/plugin/.claude-plugin/plugin.json +1 -1
  263. package/plugin/commands/loadwise.md +11 -6
  264. package/plugin/hooks/check-edited-file.mjs +27 -5
  265. package/polyglot/performance/rules/csharp.yml +34 -5
  266. package/polyglot/performance/rules/java.yml +24 -1
  267. package/polyglot/performance/rules/python.yml +74 -2
  268. package/polyglot/performance/sgconfig.yml +1 -0
  269. package/polyglot/reliability/rules/csharp.yml +12 -6
  270. package/polyglot/reliability/rules/go.yml +86 -6
  271. package/polyglot/reliability/rules/java.yml +22 -1
  272. package/polyglot/reliability/sgconfig.yml +1 -0
  273. package/polyglot/security/rules/go.yml +100 -22
  274. package/polyglot/security/rules/python.yml +74 -6
  275. package/polyglot/security/rules/rust.yml +65 -0
  276. package/polyglot/security/sgconfig.yml +1 -0
  277. package/schema/loadwise.config.schema.json +556 -76
  278. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -1,48 +1,70 @@
1
+ import { registeredRuleIds } from './reporting/pillar-rules.js';
2
+ import fs from 'node:fs';
3
+ import { fixScopeGuard } from './fix/fix-scope.js';
1
4
  import path from 'node:path';
2
5
  import { parseArgs } from 'node:util';
3
6
  import { scanForFixes } from './check.js';
4
7
  import { pillars } from './reporting/pillars.js';
5
8
  import { realTarget } from './system/real-target.js';
6
9
  import { ruleWhy, withoutWhyComment } from './fix/fix-presentation.js';
7
- import { labelledLines } from './fix/fix-terminal.js';
10
+ import { labelledLines, previewDiff } from './fix/fix-terminal.js';
8
11
  import { groupByReason } from './reporting/reason-groups.js';
9
12
  import { formatHandoff, fixInstructions } from './fix/fix-handoff.js';
10
13
  import { attachRecipeFixes } from './fix/fix-recipes.js';
11
14
  import { recordBulk } from './fix/fix-history.js';
12
15
  import { writeReviewHandoff } from './agent/review-delivery.js';
13
16
  import { hunkRange, writeFixes } from './fix/fix-convergence.js';
17
+ import { stylePatchLine } from './system/terminal-style.js';
14
18
  import { printTerminalLine, terminalSafe } from './system/terminal-safe.js';
19
+ import { optionArguments, quoteArgument } from './system/shell-argument.js';
15
20
  function hasFix(finding) {
16
21
  return Boolean(finding.fix);
17
22
  }
18
- const usage = `Usage: loadwise fix (--yes | --all | --handoff) [checkers...]
19
- --yes Apply automatic fixes.
23
+ const usage = `Usage: loadwise fix [--apply | --all | --id <id> | --handoff] [directory] [checkers...]
24
+ With no edit mode, preview automatic fixes.
25
+ --apply, --yes Apply automatic fixes.
20
26
  --all Apply every generated fix, including edits marked for individual review.
21
- --dry-run Preview converged unified diffs without writing files.
27
+ --dry-run Show generated edits before project formatting, without writing files.
28
+ --id <id> Apply exactly the named findings, including review-marked edits (repeatable or comma-separated).
29
+ [directory] Project folder (default: current folder). Use ./perf for a folder named like a checker.
30
+ --config <file> Read project settings from this file.
31
+ --workspace <name|path> Restrict edits to selected packages (repeatable).
32
+ --uncommitted Limit edits to changes since HEAD, including untracked files.
33
+ --staged | --changed-since <ref> Limit edits to changed lines.
22
34
  --rule <id> Limit fixes to the named rule ID (repeatable).
23
35
  --handoff Print a read-only Markdown brief for manual findings.
24
- --review With --yes or --all, save this run and print a handoff for any coding agent.
25
- --json With --yes or --all, print the applied hunks, manual findings and pending review findings as JSON.
36
+ --review Save an applied fix report for a coding agent.
37
+ --json Print the preview or applied fix report as JSON.
26
38
  --recipe <name|file.cjs> With --all, use verified-private-types or a trusted local fix recipe.
27
39
  --only Select checkers by name. Spaces or commas separate multiple names.
28
40
  --no-verify-types Skip Layer-2 semantic type-check verification on modified TS files.
29
41
  --no-comments Do not add the "// Loadwise <rule-id>: <why>" comment above each fixed statement.
30
- --no-format Do not format the changed lines with the project's Prettier.
42
+ --no-format Skip project Prettier when applying edits.
31
43
  Checkers: performance (perf), reliability (rel), maintainability (maint), security (sec), accessibility (a11y).
32
44
  Omit checker names to use the project's configured checkers.
33
45
 
34
- loadwise fix --all
35
- loadwise fix --yes performance
46
+ loadwise fix
47
+ loadwise fix --only perf --id <finding-id>
48
+ loadwise fix --apply --only perf
36
49
  loadwise fix --all --only perf,sec`;
37
- function fixOptions(args) {
38
- const { values, positionals } = parseArgs({
50
+ function parseFixArgs(args) {
51
+ return parseArgs({
39
52
  args,
40
53
  allowPositionals: true,
54
+ tokens: true,
41
55
  options: {
56
+ help: { type: 'boolean', short: 'h' },
57
+ config: { type: 'string' },
58
+ workspace: { type: 'string', multiple: true, default: [] },
59
+ staged: { type: 'boolean' },
60
+ uncommitted: { type: 'boolean' },
61
+ 'changed-since': { type: 'string' },
42
62
  yes: { type: 'boolean' },
63
+ apply: { type: 'boolean' },
43
64
  all: { type: 'boolean' },
44
65
  'dry-run': { type: 'boolean' },
45
66
  rule: { type: 'string', multiple: true },
67
+ id: { type: 'string', multiple: true },
46
68
  handoff: { type: 'boolean' },
47
69
  review: { type: 'boolean' },
48
70
  json: { type: 'boolean' },
@@ -54,36 +76,91 @@ function fixOptions(args) {
54
76
  'no-verify-types': { type: 'boolean' },
55
77
  },
56
78
  });
57
- if (values.handoff && (values.yes || values.all || values.recipe !== undefined))
58
- throw new Error('--handoff is read-only. Use it separately from --yes, --all and --recipe.');
59
- if (values.handoff && values.json)
60
- throw new Error('--handoff prints Markdown. Use check --json for a read-only JSON report.');
61
- if (values.handoff && values.review)
62
- throw new Error('--review requires a fix run with --yes or --all.');
63
- if (values.handoff && (values.comments || values['no-comments'] || values['no-format']))
64
- throw new Error('--comments, --no-comments and --no-format apply to a fix run with --yes or --all.');
65
- if (!values.yes && !values.all && !values.handoff)
66
- throw new Error(usage);
67
- if (values.recipe !== undefined && (!values.all || !values.recipe.trim())) {
68
- throw new Error('--recipe needs --all and a recipe name or local filename.');
69
- }
79
+ }
80
+ function fixTarget(values, positionals) {
70
81
  const selected = new Set();
71
- for (const list of [...(values.only ?? []), ...positionals]) {
82
+ const checkerFor = (selector) => pillars.find(({ name, jsonKey }) => selector === name || selector === jsonKey);
83
+ const directoryOperands = positionals.filter((value) => {
84
+ if (value.split(',').every((item) => checkerFor(item.trim())))
85
+ return false;
86
+ const target = fs.statSync(value, { throwIfNoEntry: false });
87
+ if (target?.isDirectory())
88
+ return true;
89
+ if (target || path.isAbsolute(value) || value.includes('/') || value.includes(path.sep)) {
90
+ throw new Error(`Project directory "${value}" ${target ? 'is not a directory' : 'does not exist'}.`);
91
+ }
92
+ return false;
93
+ });
94
+ if (directoryOperands.length > 1)
95
+ throw new Error('fix accepts at most one project directory.');
96
+ const directory = path.resolve(directoryOperands[0] ?? '.');
97
+ const scopeArgs = [
98
+ ...directoryOperands.map((operand) => (operand.startsWith('-') ? './' + operand : operand)),
99
+ ...(values.config === undefined ? [] : optionArguments('--config', values.config)),
100
+ ...values.workspace.flatMap((selector) => optionArguments('--workspace', selector)),
101
+ ...(values.uncommitted ? ['--uncommitted'] : []),
102
+ ...(values.staged ? ['--staged'] : []),
103
+ ...(values['changed-since'] === undefined ? [] : optionArguments('--changed-since', values['changed-since'])),
104
+ ];
105
+ for (const list of [...(values.only ?? []), ...positionals.filter((value) => !directoryOperands.includes(value))]) {
72
106
  for (const item of list.split(',')) {
73
107
  const selector = item.trim();
74
- const checker = pillars.find(({ name, jsonKey }) => name === selector || jsonKey === selector);
108
+ const checker = checkerFor(selector);
75
109
  if (!checker)
76
110
  throw new Error(`Invalid checker "${selector}". Choose performance, reliability, maintainability, security, or accessibility.`);
77
111
  selected.add(checker.name);
78
112
  }
79
113
  }
80
- const rules = (values.rule ?? [])
81
- .flatMap((entry) => entry.split(','))
82
- .map((entry) => entry.trim())
83
- .filter(Boolean);
84
114
  return {
85
- includeReview: Boolean(values.all),
86
- dryRun: Boolean(values['dry-run']),
115
+ scopeArgs,
116
+ scope: {
117
+ directory,
118
+ workspace: values.workspace,
119
+ staged: values.staged,
120
+ ref: values.uncommitted ? 'HEAD' : values['changed-since'],
121
+ },
122
+ selected: selected.size ? [...selected] : undefined,
123
+ };
124
+ }
125
+ function fixOptions(args, { values, positionals, tokens }) {
126
+ const applyAutomatic = values.apply || values.yes;
127
+ if (values.handoff && (applyAutomatic || values.all || values.recipe !== undefined))
128
+ throw new Error('--handoff is read-only. Use it separately from --apply, --yes, --all and --recipe.');
129
+ if (values.handoff && values.json)
130
+ throw new Error('--handoff prints Markdown. Use check --json for a read-only JSON report.');
131
+ if (values.handoff && values.review)
132
+ throw new Error('--review cannot be combined with --handoff.');
133
+ if (values.handoff && (values.comments || values['no-comments'] || values['no-format']))
134
+ throw new Error('--handoff cannot be combined with --comments, --no-comments or --no-format.');
135
+ const ids = values.id?.flatMap((entry) => entry.split(',').map((id) => id.trim()));
136
+ if (ids?.includes(''))
137
+ throw new Error('--id must be a nonempty finding ID for each selection.');
138
+ if (ids && values.handoff)
139
+ throw new Error('--id cannot be combined with --handoff.');
140
+ if (values.recipe !== undefined && (!values.all || !values.recipe.trim())) {
141
+ throw new Error('--recipe needs --all and a recipe name or local filename.');
142
+ }
143
+ const target = fixTarget(values, positionals);
144
+ const rules = (values.rule ?? []).flatMap((entry) => entry.split(',').map((rule) => rule.trim()));
145
+ if (rules.includes(''))
146
+ throw new Error('--rule must be a nonempty rule ID for each selection.');
147
+ if (rules.length) {
148
+ const knownRules = registeredRuleIds();
149
+ const unknown = rules.find((rule) => !knownRules.has(rule));
150
+ if (unknown)
151
+ throw new Error(`Unknown Loadwise rule "${unknown}" in --rule.`);
152
+ }
153
+ // Remove mode flags by token index so option values and operands after "--" stay verbatim.
154
+ const modeIndexes = new Set(tokens
155
+ .filter((token) => token.kind === 'option' && ['apply', 'yes', 'dry-run'].includes(token.name))
156
+ .map((token) => token.index));
157
+ const applyArgs = [...(values.all || ids ? [] : ['--apply']), ...args.filter((_, index) => !modeIndexes.has(index))];
158
+ return {
159
+ ...target,
160
+ applyCommand: ['npx', 'loadwise', 'fix', ...applyArgs.map(quoteArgument)].join(' '),
161
+ ids: ids ? new Set(ids) : undefined,
162
+ includeReview: Boolean(values.all || ids),
163
+ dryRun: Boolean(values['dry-run'] || (!applyAutomatic && !values.all && !ids && !values.handoff)),
87
164
  rules: rules.length ? new Set(rules) : undefined,
88
165
  handoff: Boolean(values.handoff),
89
166
  requestReview: Boolean(values.review),
@@ -92,48 +169,64 @@ function fixOptions(args) {
92
169
  comments: !values['no-comments'],
93
170
  format: !values['no-format'],
94
171
  verifyTypes: !values['no-verify-types'],
95
- selected: selected.size ? [...selected] : undefined,
96
172
  };
97
173
  }
98
174
  function location(finding) {
99
- return `${finding.checker} ${finding.file}:${finding.line} [${finding.ruleId} #${finding.id}]`;
175
+ return `${finding.file}:${finding.line} ${finding.checker}/${finding.ruleId} #${finding.id}`;
100
176
  }
101
- function printFixed(applied) {
102
- const printNote = (finding, indentation) => {
103
- if (!finding.fix.note)
104
- return;
105
- for (const line of labelledLines('Note', finding.fix.note, indentation))
106
- printTerminalLine(line);
107
- };
108
- const printWhy = (why) => {
109
- if (why)
110
- for (const line of labelledLines('Why', why))
111
- printTerminalLine(line);
112
- };
113
- for (const group of groupByReason(applied, (finding) => finding.ruleId)) {
177
+ function selectFindingIds(findings, ids) {
178
+ if (!ids)
179
+ return findings;
180
+ const matches = findings.filter((finding) => finding.id && ids.has(finding.id));
181
+ const byId = Map.groupBy(matches, (finding) => finding.id);
182
+ for (const id of ids) {
183
+ const count = byId.get(id)?.length ?? 0;
184
+ if (!count)
185
+ throw new Error(`Invalid --id: #${id} is absent from the selected scan. Run loadwise check to refresh the IDs.`);
186
+ if (count > 1)
187
+ throw new Error(`Invalid --id: #${id} is ambiguous. Narrow the scan with --only.`);
188
+ }
189
+ return matches;
190
+ }
191
+ function counted(count, noun, plural = noun + 's') {
192
+ return `${count} ${count === 1 ? noun : plural}`;
193
+ }
194
+ function printExplanation(label, text, indent) {
195
+ if (!text)
196
+ return;
197
+ for (const line of labelledLines(label, text, indent))
198
+ printTerminalLine(line);
199
+ }
200
+ function printFixes(applied) {
201
+ for (const group of groupByReason(applied, (finding) => [finding.checker, finding.ruleId])) {
114
202
  const [first] = group;
115
- const why = ruleWhy(first.ruleId);
116
- if (group.length === 1) {
117
- printTerminalLine('Fixed: ' + location(first));
118
- printWhy(why);
119
- printNote(first, ' ');
120
- continue;
121
- }
122
- printTerminalLine(`Fixed ${group.length} [${first.ruleId}]:`);
123
- printWhy(why);
203
+ const multiple = group.length > 1;
204
+ const title = multiple
205
+ ? `${first.checker}/${first.ruleId} (${counted(group.length, 'fix', 'fixes')})`
206
+ : location(first);
207
+ printTerminalLine(' ' + title);
208
+ printExplanation('Why', ruleWhy(first.ruleId), ' ');
124
209
  for (const finding of group) {
125
- printTerminalLine(` ${finding.checker} ${finding.file}:${finding.line} #${finding.id}`);
126
- printNote(finding, ' ');
210
+ if (multiple)
211
+ printTerminalLine(` ${finding.file}:${finding.line} #${finding.id}`);
212
+ printExplanation('Note', finding.fix.note, multiple ? ' ' : ' ');
127
213
  }
128
214
  }
129
215
  }
130
- function applyBulkFixes(findings, directory, { includeReview = false, format = false, verifyTypes = true, dryRun = false } = {}) {
216
+ function printOutstanding(title, findings) {
217
+ if (!findings.length)
218
+ return;
219
+ console.log(`\n${title} (${findings.length})`);
220
+ for (const finding of findings)
221
+ printTerminalLine(' ' + location(finding));
222
+ }
223
+ function applyBulkFixes(findings, directory, { includeReview = false, format = false, verifyTypes = true, dryRun = false, requireAll = false, guard, reviewReservations = findings, } = {}) {
131
224
  const reviewedRanges = new Map();
132
225
  const target = (change) => {
133
226
  const file = realTarget(path.resolve(directory, change.file));
134
227
  return process.platform === 'win32' ? file.toLowerCase() : file;
135
228
  };
136
- for (const finding of findings) {
229
+ for (const finding of reviewReservations) {
137
230
  if (!finding.fix?.requiresReview)
138
231
  continue;
139
232
  for (const change of finding.fix.changes) {
@@ -152,81 +245,141 @@ function applyBulkFixes(findings, directory, { includeReview = false, format = f
152
245
  const [first, last] = hunkRange(change);
153
246
  return reviewedRanges.get(target(change))?.some(([start, end]) => first <= end && start <= last) ?? false;
154
247
  }
248
+ const outsideScope = [];
155
249
  for (const finding of findings) {
156
250
  if (!hasFix(finding))
157
251
  manual.push(finding);
252
+ else if (guard && !finding.fix.changes.every((change) => guard.allowsChange(change)))
253
+ outsideScope.push({
254
+ finding,
255
+ reason: 'The complete fix extends outside the selected workspace or changed lines, or the staged file has unstaged edits.',
256
+ });
158
257
  else if (finding.fix.requiresReview || finding.fix.changes.some(touchesReviewedLines))
159
258
  review.push(finding);
160
259
  else
161
260
  automatic.push(finding);
162
261
  }
262
+ if (requireAll && outsideScope.length)
263
+ throw new Error(outsideScope.map(({ finding, reason }) => `#${finding.id}: ${reason}`).join('\n'));
163
264
  const written = writeFixes(includeReview ? [...automatic, ...review] : automatic, directory, {
265
+ requireAll,
164
266
  format,
165
267
  verifyTypes,
166
268
  dryRun,
269
+ validateUpdates: guard?.validateUpdates,
167
270
  });
168
- return { automatic, manual, review, ...written };
271
+ return { automatic, manual, review, ...written, refused: [...outsideScope, ...written.refused] };
169
272
  }
170
- async function attachRecipe(scanned, recipe) {
273
+ async function attachRecipe(scanned, recipe, directory) {
171
274
  if (recipe === 'verified-private-types') {
172
275
  const { attachVerifiedPrivateTypes } = await import('../maintainability/unused/verified-private-types.js');
173
- return await attachVerifiedPrivateTypes(scanned, process.cwd());
276
+ return await attachVerifiedPrivateTypes(scanned, directory);
174
277
  }
175
278
  if (recipe)
176
- return await attachRecipeFixes(scanned, recipe, process.cwd());
279
+ return await attachRecipeFixes(scanned, path.resolve(recipe), directory);
177
280
  return scanned;
178
281
  }
179
282
  function withoutFixComment(finding) {
180
283
  return finding.fix ? { ...finding, fix: withoutWhyComment(finding.fix, finding.ruleId) } : finding;
181
284
  }
182
- function fixSummary(includeReview, { applied, changedFiles, manual, review }) {
183
- return includeReview
184
- ? `${applied} generated fix(es) in ${changedFiles} file(s), ${manual} manual, ${review} review-marked fix(es) applied.`
185
- : `${applied} automatic fix(es) in ${changedFiles} file(s), ${manual} manual, ${review} requiring individual review.`;
186
- }
187
285
  function printDryRunDiff(updates, directory) {
286
+ const printPatch = (line) => console.log(stylePatchLine(terminalSafe(line)));
188
287
  for (const { file, before, after } of updates) {
189
288
  const rel = path.relative(directory, file).split(path.sep).join('/');
190
- printTerminalLine(`--- a/${rel}`);
191
- printTerminalLine(`+++ b/${rel}`);
192
- for (const line of (before ?? '').split('\n'))
193
- printTerminalLine(`-${line}`);
194
- for (const line of after.split('\n'))
195
- printTerminalLine(`+${line}`);
289
+ printPatch(before === undefined ? '--- /dev/null' : `--- a/${rel}`);
290
+ printPatch(`+++ b/${rel}`);
291
+ for (const line of previewDiff(before ?? '', after))
292
+ printPatch(line);
196
293
  }
197
294
  }
295
+ function printFixReport(result, includeReview, dryRun, directory, instructions) {
296
+ const { applied, manual, review, refused, changedFiles, updates } = result;
297
+ const editKind = dryRun ? 'proposed' : includeReview ? 'generated' : 'automatic';
298
+ const summary = `${counted(applied.length, editKind + ' fix', editKind + ' fixes')} in ${counted(changedFiles, 'file')}`;
299
+ console.log(`${dryRun ? 'Preview' : 'Applied'}: ${summary}.`);
300
+ printFixes(applied);
301
+ if (includeReview && review.length) {
302
+ const reviewedIds = new Set(review.map((finding) => finding.id));
303
+ const reviewCount = applied.filter((finding) => reviewedIds.has(finding.id)).length;
304
+ if (reviewCount)
305
+ console.log(` Includes ${counted(reviewCount, 'review-marked fix', 'review-marked fixes')}.`);
306
+ }
307
+ if (dryRun && updates.length) {
308
+ console.log('\nDiff');
309
+ printDryRunDiff(updates, directory);
310
+ }
311
+ if (!includeReview)
312
+ printOutstanding('Requires individual review', review);
313
+ printOutstanding('Manual changes', manual);
314
+ if (refused.length) {
315
+ console.log(`\nRefused fixes (${refused.length})`);
316
+ for (const { finding, reason } of refused) {
317
+ printTerminalLine(' ' + location(finding));
318
+ for (const line of labelledLines('Reason', reason, ' '))
319
+ printTerminalLine(line);
320
+ }
321
+ }
322
+ if (!dryRun || changedFiles)
323
+ console.log('\n' + terminalSafe(instructions));
324
+ }
325
+ async function prepareFixes(scanned, { recipe, scope, comments, ids }) {
326
+ const withRecipe = await attachRecipe(scanned, recipe, scope.directory);
327
+ const findings = comments ? withRecipe : withRecipe.map(withoutFixComment);
328
+ const missingFix = ids && findings.find((finding) => !finding.fix);
329
+ if (missingFix)
330
+ throw new Error(`Invalid --id: #${missingFix.id} has no generated fix.`);
331
+ return findings;
332
+ }
198
333
  async function runFix(args) {
199
- if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
334
+ const parsed = parseFixArgs(args);
335
+ if (parsed.values.help) {
200
336
  console.log(usage);
201
337
  return 0;
202
338
  }
203
- const { selected, includeReview, dryRun, rules, recipe, handoff, json, requestReview, comments, format, verifyTypes, } = fixOptions(args);
204
- const scannedAll = await scanForFixes(selected);
205
- const scanned = rules ? scannedAll.filter((finding) => rules.has(finding.ruleId)) : scannedAll;
339
+ const options = fixOptions(args, parsed);
340
+ const { selected, includeReview, dryRun, applyCommand, ids, rules, handoff, json, requestReview, format, verifyTypes, scope, scopeArgs, } = options;
341
+ const action = dryRun ? 'Previewing fixes' : 'Applying fixes';
342
+ const scannedAll = await scanForFixes(selected, scopeArgs, json || handoff ? undefined : action);
343
+ const scanned = selectFindingIds(rules ? scannedAll.filter((finding) => rules.has(finding.ruleId)) : scannedAll, ids);
206
344
  if (handoff) {
207
- console.log(terminalSafe(formatHandoff(scanned, selected)));
345
+ console.log(terminalSafe(formatHandoff(scanned, selected, scopeArgs, rules)));
208
346
  return 0;
209
347
  }
210
- const withRecipe = await attachRecipe(scanned, recipe);
211
- const findings = comments ? withRecipe : withRecipe.map(withoutFixComment);
212
- const { applied, manual, review, refused, changedFiles, updates } = applyBulkFixes(findings, process.cwd(), {
348
+ const findings = await prepareFixes(scanned, options);
349
+ const result = applyBulkFixes(findings, scope.directory, {
350
+ // Filtering the output to one rule must still reserve lines flagged for review by a different rule.
351
+ reviewReservations: rules && !includeReview ? scannedAll : findings,
352
+ guard: fixScopeGuard(scope),
353
+ requireAll: Boolean(ids),
213
354
  includeReview,
214
355
  format,
215
356
  verifyTypes,
216
357
  dryRun,
217
358
  });
359
+ const { applied, manual, review, refused, changedFiles } = result;
218
360
  const pendingReview = includeReview ? [] : review;
219
361
  if (changedFiles && !dryRun)
220
- recordBulk(process.cwd(), {
362
+ recordBulk(scope.directory, {
221
363
  applied,
222
364
  manual,
223
365
  pendingReview,
224
366
  });
225
- const instructions = fixInstructions(findings.length, selected, manual.length);
226
- const notApplied = refused.map(({ finding, reason }) => ({ id: finding.id, ruleId: finding.ruleId, reason }));
367
+ const instructions = dryRun
368
+ ? changedFiles
369
+ ? `To apply these fixes, run:\n${applyCommand}`
370
+ : 'No proposed edits to apply.'
371
+ : fixInstructions(findings.length, selected, manual.length, scopeArgs, rules);
372
+ const notApplied = refused.map(({ finding, reason }) => ({
373
+ checker: finding.checker,
374
+ id: finding.id,
375
+ ruleId: finding.ruleId,
376
+ ...(finding.file && { file: finding.file }),
377
+ ...(finding.line !== undefined && { line: finding.line }),
378
+ reason,
379
+ }));
227
380
  const report = { changedFiles, dryRun, applied, manual, pendingReview, notApplied, instructions };
228
381
  if (requestReview && !dryRun)
229
- await writeReviewHandoff(process.cwd(), 'fix', {
382
+ await writeReviewHandoff(scope.directory, 'fix', {
230
383
  args,
231
384
  format: 'json',
232
385
  report,
@@ -236,23 +389,7 @@ async function runFix(args) {
236
389
  console.log(JSON.stringify(report));
237
390
  return 0;
238
391
  }
239
- if (dryRun && updates.length)
240
- printDryRunDiff(updates, process.cwd());
241
- if (!includeReview)
242
- for (const finding of review)
243
- printTerminalLine('Review individually: ' + location(finding));
244
- for (const finding of manual)
245
- printTerminalLine('Manual change: ' + location(finding));
246
- for (const { finding, reason } of refused)
247
- printTerminalLine(`Not applied: ${location(finding)}: ${reason}`);
248
- printFixed(applied);
249
- console.log(fixSummary(includeReview, {
250
- applied: applied.length,
251
- changedFiles,
252
- manual: manual.length,
253
- review: review.length,
254
- }));
255
- console.log(instructions);
392
+ printFixReport(result, includeReview, dryRun, scope.directory, instructions);
256
393
  return 0;
257
394
  }
258
395
  export { runFix, applyBulkFixes, realTarget };
@@ -32,4 +32,7 @@ function repositoryPathFor(findingRoot, repositoryDirectory = findingRoot) {
32
32
  .split(path.sep)
33
33
  .join('/');
34
34
  }
35
- export { findingLevel, findRepositoryRoot, repositoryPathFor };
35
+ function positivePosition(value) {
36
+ return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.trunc(value) : 1;
37
+ }
38
+ export { findingLevel, findRepositoryRoot, positivePosition, repositoryPathFor };
@@ -1,4 +1,4 @@
1
- import { findingLevel, repositoryPathFor } from './finding-location.js';
1
+ import { findingLevel, positivePosition, repositoryPathFor } from './finding-location.js';
2
2
  // GitHub workflow commands: the message escapes % and line breaks, and properties also escape : and
3
3
  // ,.
4
4
  const commandNames = { error: 'error', warning: 'warning', note: 'notice' };
@@ -11,8 +11,8 @@ function escapeProperty(text) {
11
11
  function annotation(pillar, repositoryPath, finding) {
12
12
  const properties = [
13
13
  `file=${escapeProperty(repositoryPath(finding.file))}`,
14
- `line=${finding.line ?? 1}`,
15
- `col=${finding.column ?? 1}`,
14
+ `line=${positivePosition(finding.line)}`,
15
+ `col=${positivePosition(finding.column)}`,
16
16
  `title=${escapeProperty(finding.ruleId)}`,
17
17
  ];
18
18
  return `::${commandNames[findingLevel(pillar, finding)]} ${properties.join(',')}::${escapeData(finding.message)}`;
@@ -1,6 +1,7 @@
1
+ import path from 'node:path';
1
2
  import { packageManifest } from '../package-root.js';
2
3
  const { version: toolVersion } = packageManifest;
3
- import { findingLevel, repositoryPathFor } from './finding-location.js';
4
+ import { findingLevel, positivePosition, repositoryPathFor } from './finding-location.js';
4
5
  import { rulesByPillar } from '../rule-registry.js';
5
6
  import { repositoryUrl, ruleDocUrl } from '../reporting/rule-docs.js';
6
7
  const sarifSchema = 'https://json.schemastore.org/sarif-2.1.0.json';
@@ -34,7 +35,7 @@ function resultFor(pillar, repositoryPath, finding) {
34
35
  {
35
36
  physicalLocation: {
36
37
  artifactLocation: { uri, uriBaseId: sourceRootId },
37
- region: { startLine: finding.line ?? 1, startColumn: finding.column ?? 1 },
38
+ region: { startLine: positivePosition(finding.line), startColumn: positivePosition(finding.column) },
38
39
  },
39
40
  },
40
41
  ],
@@ -65,6 +66,11 @@ function invocationsFor(repositoryPath, skippedFiles) {
65
66
  function runFor({ pillar, root, repositoryDirectory, report }) {
66
67
  const findings = report.findings;
67
68
  const repositoryPath = repositoryPathFor(root, repositoryDirectory);
69
+ // Findings can be relative to the caller's cwd even when this scan only covers a package.
70
+ const scope = repositoryPath(path.resolve(repositoryDirectory ?? root));
71
+ const category = scope
72
+ ? `loadwise/${pillar}/${scope.split('/').map(encodeURIComponent).join('/')}/`
73
+ : `loadwise/${pillar}/`;
68
74
  return {
69
75
  tool: {
70
76
  driver: {
@@ -74,7 +80,7 @@ function runFor({ pillar, root, repositoryDirectory, report }) {
74
80
  rules: rulesFor(pillar, findings),
75
81
  },
76
82
  },
77
- automationDetails: { id: `loadwise/${pillar}/` },
83
+ automationDetails: { id: category },
78
84
  originalUriBaseIds: { [sourceRootId]: { description: { text: 'Root of the checked repository or project.' } } },
79
85
  results: findings.map((finding) => resultFor(pillar, repositoryPath, finding)),
80
86
  ...invocationsFor(repositoryPath, report.skippedFiles),
@@ -0,0 +1,97 @@
1
+ // `loadwise report-fp`: builds a privacy-safe, pre-filled GitHub false-positive issue URL.
2
+ // Never sends telemetry automatically and never embeds user source code or local file paths.
3
+ import { spawn } from 'node:child_process';
4
+ import { parseArgs } from 'node:util';
5
+ import { packageManifest } from './package-root.js';
6
+ import { pillarOfRule } from './rule-registry.js';
7
+ const fpRepoIssuesUrl = 'https://github.com/IbrahimHafez1/loadwise/issues/new';
8
+ const fpUsage = 'Usage: loadwise report-fp --rule <rule-id> [--command "<cmd>"] [--expected "<text>"] [--note "<generic reason>"] [--open]';
9
+ /** Redacts local paths, credentialed URLs, tokens, and emails before placing text in an issue URL. */
10
+ function sanitizeFpText(text) {
11
+ return (text
12
+ // Quoted paths run before the URL rule so a credentialed URL inside one cannot eat the closing quote;
13
+ // In POSIX paths a backslash before the quote is an escaped quote; in Windows paths it is a trailing separator.
14
+ .replaceAll(/(['"`])[A-Za-z]:\\(?:(?!\1)[^\r\n])+\1/g, '$1<redacted-path>$1')
15
+ .replaceAll(/(['"`])\/(?:\\\1|(?!\1)[^\r\n])+\1/g, '$1<redacted-path>$1')
16
+ .replaceAll(/\b(?:postgres|mysql|mongodb|redis|https?):\/\/[^/\s]+@[^\s]+/gi, '<redacted-url>')
17
+ .replaceAll(/\bBearer\s+\S+/gi, 'Bearer <redacted-token>')
18
+ .replaceAll(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{8,}|(?:AKIA|ASIA)[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]+|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*)\b/g, '<redacted-token>')
19
+ .replaceAll(/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASS|PWD|DSN|AUTH)[A-Z0-9_]*=[^\s'"]+/gi, '<redacted-env>')
20
+ .replaceAll(/[A-Za-z]:\\[^\s'"`]+/g, '<redacted-path>')
21
+ .replaceAll(/(?<![:\w])\/(?:[^\s'"`/]+\/)+[^\s'"`]+/g, '<redacted-path>')
22
+ .replaceAll(/\b(?![0-9]+\/[0-9]+)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+\.[A-Za-z0-9]{1,10}\b/g, '<redacted-path>')
23
+ .replaceAll(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '<redacted-email>')
24
+ .replaceAll(/\s+/g, ' ')
25
+ .trim()
26
+ .slice(0, 400));
27
+ }
28
+ /** Validates `rule` and constructs a pre-filled `.github/ISSUE_TEMPLATE/false-positive.yml` URL. */
29
+ function buildFpIssueUrl(options) {
30
+ const rule = options.rule.trim();
31
+ if (!rule || !pillarOfRule(rule)) {
32
+ throw new Error(`Unknown rule "${options.rule}". Pass the rule id from the Loadwise report (for example, array-repeated-find).`);
33
+ }
34
+ const sanitizedCommand = sanitizeFpText(options.command ?? 'npx loadwise check') || 'npx loadwise check';
35
+ const sanitizedExpected = sanitizeFpText(options.expected ?? 'No warning (code is safe or intentional)') ||
36
+ 'No warning (code is safe or intentional)';
37
+ const sanitizedNote = options.note ? sanitizeFpText(options.note) : '';
38
+ const titleSuffix = sanitizedNote ? sanitizedNote.slice(0, 60) : 'false positive';
39
+ const params = new URLSearchParams({
40
+ template: 'false-positive.yml',
41
+ title: `[FP] ${rule}: ${titleSuffix}`,
42
+ rule,
43
+ command: sanitizedCommand,
44
+ expected: sanitizedExpected,
45
+ code: '// Replace with a minimal, anonymized 5-line repro (no proprietary code, file paths, or project names)',
46
+ why: sanitizedNote || 'Describe why this pattern is safe or intentional (without project internals).',
47
+ version: `${packageManifest.version} (Node ${process.version}, ${process.platform})`,
48
+ });
49
+ return `${fpRepoIssuesUrl}?${params.toString()}`;
50
+ }
51
+ function openUrlInBrowser(url) {
52
+ const [command, args] = process.platform === 'win32'
53
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
54
+ : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
55
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' });
56
+ child.on('error', (error) => {
57
+ console.error(`Could not open browser: ${error.message}`);
58
+ });
59
+ child.unref();
60
+ }
61
+ function runReportFp(args) {
62
+ const { values, positionals } = parseArgs({
63
+ args,
64
+ allowPositionals: true,
65
+ options: {
66
+ help: { type: 'boolean', short: 'h' },
67
+ rule: { type: 'string' },
68
+ command: { type: 'string' },
69
+ expected: { type: 'string' },
70
+ note: { type: 'string' },
71
+ open: { type: 'boolean' },
72
+ },
73
+ });
74
+ if (values.help) {
75
+ console.log(fpUsage);
76
+ return 0;
77
+ }
78
+ if (positionals.length > 0 || !values.rule)
79
+ throw new Error(fpUsage);
80
+ const url = buildFpIssueUrl({
81
+ rule: values.rule,
82
+ command: values.command,
83
+ expected: values.expected,
84
+ note: values.note,
85
+ });
86
+ console.log('Privacy-safe false-positive issue link (review the form for any private details before submitting):');
87
+ console.log(url);
88
+ if (values.open) {
89
+ openUrlInBrowser(url);
90
+ console.log('Opened in your default browser. Review and add a minimal anonymized snippet before submitting.');
91
+ }
92
+ else {
93
+ console.log('Re-run with --open to launch this URL in your browser.');
94
+ }
95
+ return 0;
96
+ }
97
+ export { buildFpIssueUrl, runReportFp, sanitizeFpText };