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
@@ -14,6 +14,89 @@ const configByPillar = {
14
14
  };
15
15
  const extensions = new Set(['.py', '.go', '.java', '.cs', '.rs']);
16
16
  const excludedDirectories = '!**/{node_modules,dist,build,coverage,.next,.nuxt,.venv,venv,__pycache__,.cache,.turbo,target,vendor,.worktrees}';
17
+ const excludedDirectoryNames = new Set([
18
+ '.git',
19
+ 'node_modules',
20
+ 'dist',
21
+ 'build',
22
+ 'coverage',
23
+ '.next',
24
+ '.nuxt',
25
+ '.venv',
26
+ 'venv',
27
+ '__pycache__',
28
+ '.cache',
29
+ '.turbo',
30
+ 'target',
31
+ 'vendor',
32
+ '.worktrees',
33
+ ]);
34
+ async function collectNonIgnoredDirectory(directory, isIgnored) {
35
+ const entries = await fs.promises.readdir(directory, { withFileTypes: true });
36
+ const items = [];
37
+ let allKept = true;
38
+ for (const entry of entries) {
39
+ const fullPath = path.join(directory, entry.name);
40
+ if (entry.isDirectory()) {
41
+ if (excludedDirectoryNames.has(entry.name))
42
+ continue;
43
+ if (isIgnored(process.cwd(), fullPath)) {
44
+ allKept = false;
45
+ continue;
46
+ }
47
+ const nested = await collectNonIgnoredDirectory(fullPath, isIgnored);
48
+ if (!nested.allKept)
49
+ allKept = false;
50
+ items.push(...nested.items);
51
+ continue;
52
+ }
53
+ if (!entry.isFile() || !extensions.has(path.extname(entry.name).toLowerCase()))
54
+ continue;
55
+ if (isIgnored(process.cwd(), fullPath)) {
56
+ allKept = false;
57
+ continue;
58
+ }
59
+ items.push(fullPath);
60
+ }
61
+ return allKept ? { items: [directory], allKept: true } : { items, allKept: false };
62
+ }
63
+ // The scanner reports paths as given, but process.cwd() is the real path, so a symlinked
64
+ // spelling (macOS /var -> /private/var) must be compared through its real path.
65
+ function relativeToCwd(filePath) {
66
+ const cwd = process.cwd();
67
+ const relative = path.relative(cwd, filePath);
68
+ const normalized = relative.startsWith('..') ? (realRelativeToCwd(cwd, filePath) ?? relative) : relative;
69
+ return normalized.split(path.sep).join('/');
70
+ }
71
+ // Best effort: a file deleted after the scanner reported it keeps its original spelling instead of failing the scan.
72
+ function realRelativeToCwd(cwd, filePath) {
73
+ try {
74
+ const real = path.relative(cwd, fs.realpathSync(filePath));
75
+ return real.startsWith('..') ? undefined : real;
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ }
81
+ async function applyIgnoreFilter(inputs, explicitFiles, isIgnored) {
82
+ if (!isIgnored)
83
+ return { inputs, explicitFiles };
84
+ const filteredInputs = new Set();
85
+ const filteredExplicit = new Set();
86
+ for (const input of inputs) {
87
+ if (explicitFiles.has(input)) {
88
+ if (!isIgnored(process.cwd(), input)) {
89
+ filteredInputs.add(input);
90
+ filteredExplicit.add(input);
91
+ }
92
+ continue;
93
+ }
94
+ const collected = await collectNonIgnoredDirectory(input, isIgnored);
95
+ for (const item of collected.items)
96
+ filteredInputs.add(item);
97
+ }
98
+ return { inputs: filteredInputs, explicitFiles: filteredExplicit };
99
+ }
17
100
  async function retryRules(configPath, language) {
18
101
  const name = language.toLowerCase();
19
102
  // A rule set may cover fewer languages than the scan globs, so a language without rules retries the parse check alone.
@@ -130,14 +213,19 @@ async function finalizePolyglotFindings(binary, configPath, findings, evidence)
130
213
  previous.ruleId !== entry.ruleId);
131
214
  });
132
215
  }
133
- async function scanPolyglot(configPath, paths) {
216
+ async function scanPolyglot(configPath, paths, isIgnored) {
134
217
  if (!paths.length)
135
218
  throw new Error('Pass at least one source file or directory to polyglot.');
136
- const { inputs, explicitFiles } = await resolveInputs(paths);
219
+ const resolved = await resolveInputs(paths);
220
+ const { inputs, explicitFiles } = await applyIgnoreFilter(resolved.inputs, resolved.explicitFiles, isIgnored);
221
+ if (!inputs.size)
222
+ return { scannedFiles: 0, skippedFiles: 0, findings: [] };
137
223
  const binary = await resolveAstGrepBinary();
138
224
  if (!binary) {
139
- process.stderr.write('Note: @ast-grep/cli is not installed; skipping polyglot checks.\n');
140
- return { scannedFiles: 0, skippedFiles: 0, findings: [] };
225
+ const reason = 'The optional @ast-grep/cli scanner is unavailable. Run npm install --include=optional in the project that provides Loadwise.';
226
+ console.error(reason);
227
+ const skippedFiles = [...inputs].map((input) => ({ file: path.relative(process.cwd(), input) || '.', reason }));
228
+ return { scannedFiles: 0, skippedFiles, findings: [] };
141
229
  }
142
230
  const child = spawn(binary, [
143
231
  'scan',
@@ -155,12 +243,14 @@ async function scanPolyglot(configPath, paths) {
155
243
  const findings = [];
156
244
  const evidence = new Map();
157
245
  const scanned = new Set();
246
+ const skippedFiles = [];
247
+ const skippedPaths = new Set();
158
248
  let finished = false;
159
249
  let failure;
160
250
  async function readMatches() {
161
251
  for await (const line of createInterface({ input: child.stdout, crlfDelay: Infinity })) {
162
252
  const match = JSON.parse(line);
163
- const file = path.relative(process.cwd(), match.file).split(path.sep).join('/');
253
+ const file = relativeToCwd(match.file);
164
254
  if (!compatibilityMatch(match))
165
255
  findings.push(finding(file, match));
166
256
  else {
@@ -170,14 +260,21 @@ async function scanPolyglot(configPath, paths) {
170
260
  }
171
261
  }
172
262
  }
263
+ function recordFileStatus(filePath, status) {
264
+ if (status.startsWith('language=') || status === 'skipped=emptyFile') {
265
+ scanned.add(path.resolve(filePath));
266
+ return;
267
+ }
268
+ const relative = relativeToCwd(filePath);
269
+ skippedPaths.add(path.resolve(filePath));
270
+ if (!skippedFiles.some((entry) => entry.file === relative))
271
+ skippedFiles.push({ file: relative, reason: status });
272
+ }
173
273
  async function readScanStatus() {
174
274
  for await (const line of createInterface({ input: child.stderr, crlfDelay: Infinity })) {
175
275
  const file = line.match(/^sg: entity\|file\|(.+): (language=\w+,appliedRuleCount=\d+|skipped=\w+)$/);
176
276
  if (file) {
177
- if (file[2].startsWith('language=') || file[2] === 'skipped=emptyFile')
178
- scanned.add(path.resolve(file[1]));
179
- else
180
- failure ||= 'Could not scan ' + file[1] + ' (' + file[2] + ').';
277
+ recordFileStatus(file[1], file[2]);
181
278
  }
182
279
  else if (/^sg: summary\|file: scannedFileCount=\d+,skippedFileCount=\d+/.test(line)) {
183
280
  finished = true;
@@ -194,10 +291,10 @@ async function scanPolyglot(configPath, paths) {
194
291
  if (!finished)
195
292
  throw new Error('ast-grep did not report a scan summary.');
196
293
  for (const input of explicitFiles) {
197
- if (!scanned.has(input))
294
+ if (!scanned.has(input) && !skippedPaths.has(input))
198
295
  throw new Error('No polyglot scan result for explicit source file: ' + input);
199
296
  }
200
- if (!scanned.size)
297
+ if (!scanned.size && !skippedFiles.length)
201
298
  throw new Error('No supported source files were scanned.');
202
299
  }
203
300
  catch (error) {
@@ -206,10 +303,10 @@ async function scanPolyglot(configPath, paths) {
206
303
  throw error;
207
304
  }
208
305
  const unique = await finalizePolyglotFindings(binary, configPath, findings, evidence);
209
- return { scannedFiles: scanned.size, skippedFiles: 0, findings: unique };
306
+ return { scannedFiles: scanned.size, skippedFiles: skippedFiles.length ? skippedFiles : 0, findings: unique };
210
307
  }
211
308
  /** Run the ast-grep polyglot performance or reliability checks on the given files or directories. */
212
- async function checkPolyglot(paths, pillar = 'performance') {
213
- return scanPolyglot(configByPillar[pillar], paths);
309
+ async function checkPolyglot(paths, pillar = 'performance', isIgnored) {
310
+ return scanPolyglot(configByPillar[pillar], paths, isIgnored);
214
311
  }
215
312
  export { checkPolyglot, scanPolyglot };
@@ -10,7 +10,7 @@ import { sourcePillarOf } from '../shared/rule-registry.js';
10
10
  import { withoutEmitOptions } from './cli/emit-options.js';
11
11
  import { enableSchemaTooling } from './analysis/schema-tooling.js';
12
12
  import { collectUninstalledDependencies, collectUnresolvedPackages, formatMissingPackagesNote, formatUninstalledDependencyNote, } from './analysis/missing-packages.js';
13
- import { compareFindings, isInScope, isSourceInput, mergeFinding, scanEntries, relativeToWorkingDirectory, resolveConfig, } from './analysis/source-inputs.js';
13
+ import { compareFindings, isInScope, isSourceInput, scopedProjectRoots, mergeFinding, scanEntries, relativeToWorkingDirectory, resolveConfig, } from './analysis/source-inputs.js';
14
14
  import { recordSkippedFile } from '../shared/reporting/coverage-notes.js';
15
15
  import { noteFlowSkips, recordUnparsedFile } from '../shared/reporting/flow-skips.js';
16
16
  import { withCallNameInventory } from '../shared/analysis/caller-name-inventory.js';
@@ -294,7 +294,7 @@ function standaloneReliabilityFindings({ roots, scanned, analyzers, skippedFiles
294
294
  }
295
295
  return findings;
296
296
  }
297
- // `project` is one config or an array of them. `onlyFiles` limits the roots of each config to the changed files;
297
+ // `project` is one config or an array of them. `onlyFiles` limits reportable roots while retaining configured declarations;
298
298
  // imports still resolve through the config.
299
299
  function analyzeSources(options) {
300
300
  return withPrismaPackageInventory(() => withCallNameInventory(() => scanSources(options)));
@@ -419,7 +419,7 @@ function scanSources({ project, files, standaloneFiles = [], standaloneScope, st
419
419
  standaloneRoots.add(folder);
420
420
  }
421
421
  }
422
- scan(onlyFiles ? rootFiles.filter(onlyFiles) : rootFiles, parsed.options, (filename) => isInScope(scope, filename) && isNew(filename));
422
+ scan(scopedProjectRoots(rootFiles, onlyFiles), parsed.options, (filename) => isInScope(scope, filename) && isNew(filename));
423
423
  }
424
424
  // Explicit files, and JavaScript a config without `allowJs` leaves out, have no config of their own.
425
425
  const standaloneOptions = {
@@ -189,6 +189,7 @@ function resultDrivesLoop(call, owner) {
189
189
  }
190
190
  if (ts.isForOfStatement(node) &&
191
191
  ts.isVariableDeclarationList(node.initializer) &&
192
+ node.initializer.declarations.length > 0 &&
192
193
  mentions(node.expression, tainted)) {
193
194
  bindingNames(node.initializer.declarations[0].name, tainted);
194
195
  }
@@ -6,6 +6,7 @@
6
6
  // - webhook-missing-idempotency-check
7
7
  import { ts } from '../engine/compiler.js';
8
8
  import { isTestSource } from '../analysis/review-context.js';
9
+ import { effectiveProperty } from '../../shared/analysis/ast-semantics.js';
9
10
  import { classifyExecutionContext } from '../../shared/analysis/execution-context.js';
10
11
  import { enclosingRequestHandler } from './request-handlers.js';
11
12
  import { findRepeatOwner } from '../collections/repeated.js';
@@ -14,7 +15,9 @@ import { isSequentialByDesign, iteratesArrayLiteral, loopReviewReason } from '..
14
15
  import { declaredInPackage } from '../schema/ts-helpers.js';
15
16
  import { importedFrom } from '../../security/bindings.js';
16
17
  import { calleeName, isFunctionWithBody } from '../analysis/call-syntax.js';
18
+ import { staticPropertyName } from '../../shared/analysis/ast-semantics.js';
17
19
  import { createReferenceChecks } from '../engine/reference-checks.js';
20
+ import { topLevelSelectStar } from './sql-select-star.js';
18
21
  let cachedRefChecksTs;
19
22
  let cachedRefChecks;
20
23
  function mentionsIdentifier(node, name) {
@@ -35,7 +38,6 @@ const SQL_QUERY_PACKAGES = [
35
38
  '.prisma',
36
39
  ];
37
40
  const SQL_QUERY_METHODS = new Set(['query', 'execute', 'raw', '$queryRawUnsafe']);
38
- const SELECT_STAR_RE = /^\s*select\s+(?:\w+\.)?\*\s+from\s+(?!\(|information_schema\b|pg_)/i;
39
41
  const SINGLE_ROW_RE = /\bwhere\b[\s\S]*\bid\s*=|\blimit\s+1\b/i;
40
42
  const HTTP_MODULES = new Set(['got', 'ky', 'undici', 'node-fetch', 'axios']);
41
43
  const HTTP_CLIENT_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'request', 'head']);
@@ -65,22 +67,10 @@ const ROUTER_PACKAGES = [
65
67
  const DATABASE_PACKAGES = [...SQL_QUERY_PACKAGES, 'mongoose', 'sequelize', 'typeorm', 'drizzle-orm', 'mongodb'];
66
68
  const WEBHOOK_PATH_RE = /webhook/i;
67
69
  const INSERT_METHODS = new Set(['create', 'createMany', 'insert', 'insertOne', 'insertMany', 'bulkCreate']);
68
- const DATABASE_READ_METHODS = new Set([
69
- 'find',
70
- 'findOne',
71
- 'findUnique',
72
- 'findFirst',
73
- 'findById',
74
- 'findByPk',
75
- 'findMany',
76
- 'findOneBy',
77
- 'exists',
78
- 'count',
79
- 'select',
80
- ]);
81
70
  const INSERT_SQL_RE = /^\s*insert\b/i;
82
- const IDEMPOTENT_INSERT_SQL_RE = /\bon\s+(?:conflict|duplicate)\b|\binsert\s+ignore\b/i;
83
- const SELECT_SQL_RE = /^\s*(?:select|with)\b/i;
71
+ const IDEMPOTENT_INSERT_SQL_RE = /\bon\s+conflict\s*\(\s*"?event_?id"?\s*\)\s+do\s+nothing\b/i;
72
+ const eventIdFields = new Set(['eventId', 'event_id']);
73
+ const drizzlePackages = ['drizzle-orm'];
84
74
  function propertyAccessCallee(call) {
85
75
  const callee = ts.skipOuterExpressions(call.expression);
86
76
  return ts.isPropertyAccessExpression(callee) ? callee : undefined;
@@ -91,8 +81,9 @@ function staticSqlText(node) {
91
81
  const expression = ts.skipOuterExpressions(node);
92
82
  if (ts.isStringLiteralLike(expression))
93
83
  return expression.text;
94
- if (ts.isTemplateExpression(expression))
95
- return expression.head.text;
84
+ if (ts.isTemplateExpression(expression)) {
85
+ return expression.head.text + expression.templateSpans.map((span) => ` ? ${span.literal.text}`).join('');
86
+ }
96
87
  }
97
88
  // ---- sql-select-star-in-query ----
98
89
  function checkSelectStar(call, context) {
@@ -100,11 +91,14 @@ function checkSelectStar(call, context) {
100
91
  if (!callee || !SQL_QUERY_METHODS.has(callee.name.text))
101
92
  return;
102
93
  const sql = staticSqlText(call.arguments[0]);
103
- if (!sql || !SELECT_STAR_RE.test(sql))
94
+ if (!sql)
95
+ return;
96
+ const parsed = topLevelSelectStar(sql);
97
+ if (!parsed?.isSelectStar)
104
98
  return;
105
99
  if (!declaredInPackage(callee, context.checker, SQL_QUERY_PACKAGES))
106
100
  return;
107
- context.report(call.arguments[0], 'sql-select-star-in-query', 'Raw SQL uses `SELECT *`, which transfers columns the code may not need, defeats covering-index scans, and exposes any column added later. List the columns you need.', SINGLE_ROW_RE.test(sql)
101
+ context.report(call.arguments[0], 'sql-select-star-in-query', 'Raw SQL uses `SELECT *`, which transfers columns the code may not need, defeats covering-index scans, and exposes any column added later. List the columns you need.', SINGLE_ROW_RE.test(parsed.fromClause)
108
102
  ? 'A single-row lookup transfers little data; an explicit column list still keeps newly added sensitive columns out of the result.'
109
103
  : undefined);
110
104
  }
@@ -223,7 +217,12 @@ function hasTransactionOption(argument) {
223
217
  const expression = argument && ts.skipOuterExpressions(argument);
224
218
  return (!!expression &&
225
219
  ts.isObjectLiteralExpression(expression) &&
226
- expression.properties.some((property) => ts.isSpreadAssignment(property) || (property.name && TRANSACTION_OPTIONS.has(property.name.getText()))));
220
+ expression.properties.some((property) => {
221
+ if (ts.isSpreadAssignment(property))
222
+ return true;
223
+ const name = staticPropertyName(property.name);
224
+ return name !== undefined && TRANSACTION_OPTIONS.has(name);
225
+ }));
227
226
  }
228
227
  // `const account = await Account.findById(id)` on a Mongoose or Sequelize model, read outside any
229
228
  // session or lock.
@@ -358,7 +357,7 @@ function hasIdempotencyKey(optionsArgument) {
358
357
  // Anything but a literal (a variable, a spread) may already carry the key.
359
358
  if (!ts.isObjectLiteralExpression(options))
360
359
  return true;
361
- return options.properties.some((property) => ts.isSpreadAssignment(property) || property.name?.getText() === 'idempotencyKey');
360
+ return options.properties.some((property) => ts.isSpreadAssignment(property) || staticPropertyName(property.name) === 'idempotencyKey');
362
361
  }
363
362
  function checkPaymentIdempotency(call, context) {
364
363
  const callee = propertyAccessCallee(call);
@@ -377,41 +376,151 @@ function checkPaymentIdempotency(call, context) {
377
376
  function isDatabaseCall(callee, context) {
378
377
  return declaredInPackage(callee, context.checker, DATABASE_PACKAGES);
379
378
  }
379
+ function unwrapConflictTarget(expr) {
380
+ const inner = ts.skipOuterExpressions(expr);
381
+ return ts.isArrayLiteralExpression(inner) && inner.elements.length === 1
382
+ ? ts.skipOuterExpressions(inner.elements[0])
383
+ : inner;
384
+ }
385
+ function insertRows(arg) {
386
+ if (!arg)
387
+ return undefined;
388
+ const expr = ts.skipOuterExpressions(arg);
389
+ if (ts.isObjectLiteralExpression(expr))
390
+ return [expr];
391
+ if (!ts.isArrayLiteralExpression(expr) || expr.elements.length === 0)
392
+ return undefined;
393
+ const rows = [];
394
+ for (const el of expr.elements) {
395
+ const inner = ts.skipOuterExpressions(el);
396
+ if (!ts.isObjectLiteralExpression(inner))
397
+ return undefined;
398
+ rows.push(inner);
399
+ }
400
+ return rows;
401
+ }
402
+ // Recognize the narrow Drizzle chain that inserts an event ID and ignores conflicts on that column.
403
+ function hasEventConflictTarget(insert, context) {
404
+ const table = insert.arguments[0];
405
+ const values = chainedCall(insert, 'values');
406
+ const conflict = values && chainedCall(values, 'onConflictDoNothing');
407
+ const options = conflict?.arguments[0] && ts.skipOuterExpressions(conflict.arguments[0]);
408
+ const rows = insertRows(values?.arguments[0]);
409
+ if (!table || !ts.isIdentifier(table) || !rows || !options || !ts.isObjectLiteralExpression(options))
410
+ return false;
411
+ const target = effectiveProperty(options, 'target');
412
+ if (!target || target === 'unknown' || !ts.isPropertyAssignment(target))
413
+ return false;
414
+ const column = unwrapConflictTarget(target.initializer);
415
+ if (!ts.isPropertyAccessExpression(column) ||
416
+ !ts.isIdentifier(column.expression) ||
417
+ !eventIdFields.has(column.name.text))
418
+ return false;
419
+ const binding = context.checker.getSymbolAtLocation(table);
420
+ if (!binding || binding !== context.checker.getSymbolAtLocation(column.expression))
421
+ return false;
422
+ return rows.every((row) => {
423
+ const value = effectiveProperty(row, column.name.text);
424
+ return (!!value && value !== 'unknown' && (ts.isPropertyAssignment(value) || ts.isShorthandPropertyAssignment(value)));
425
+ });
426
+ }
427
+ function chainedCall(call, method) {
428
+ const member = call.parent;
429
+ if (!ts.isPropertyAccessExpression(member) || member.expression !== call || member.name.text !== method)
430
+ return;
431
+ return ts.isCallExpression(member.parent) && member.parent.expression === member ? member.parent : undefined;
432
+ }
380
433
  function isInsertWithoutConflictHandling(call, callee, context) {
381
434
  if (!isDatabaseCall(callee, context))
382
435
  return false;
383
436
  if (INSERT_METHODS.has(callee.name.text))
384
- return true;
437
+ return !(callee.name.text === 'insert' &&
438
+ declaredInPackage(callee, context.checker, drizzlePackages) &&
439
+ hasEventConflictTarget(call, context));
385
440
  if (!SQL_QUERY_METHODS.has(callee.name.text))
386
441
  return false;
387
442
  const sql = staticSqlText(call.arguments[0]);
388
443
  return !!sql && INSERT_SQL_RE.test(sql) && !IDEMPOTENT_INSERT_SQL_RE.test(sql);
389
444
  }
390
- function isDatabaseRead(call, callee, context) {
391
- if (!isDatabaseCall(callee, context))
445
+ // `const claimed = await db.insert(t).values(..).onConflictDoNothing({target: t.eventId}).returning(..)`
446
+ function claimedEventVariable(statement, context) {
447
+ if (!ts.isVariableStatement(statement))
448
+ return;
449
+ const [declaration] = statement.declarationList.declarations;
450
+ if (statement.declarationList.declarations.length !== 1 || !ts.isIdentifier(declaration.name))
451
+ return;
452
+ let chain = declaration.initializer && ts.skipOuterExpressions(declaration.initializer);
453
+ if (chain && ts.isAwaitExpression(chain))
454
+ chain = ts.skipOuterExpressions(chain.expression);
455
+ const steps = ['returning', 'onConflictDoNothing', 'values', 'insert'];
456
+ for (const step of steps) {
457
+ const callee = chain && ts.isCallExpression(chain) ? propertyAccessCallee(chain) : undefined;
458
+ if (!chain || !callee || !ts.isCallExpression(chain) || callee.name.text !== step)
459
+ return;
460
+ if (step === 'insert') {
461
+ const claimsEvent = declaredInPackage(callee, context.checker, drizzlePackages) &&
462
+ isDatabaseCall(callee, context) &&
463
+ hasEventConflictTarget(chain, context);
464
+ return claimsEvent ? declaration.name.text : undefined;
465
+ }
466
+ chain = ts.skipOuterExpressions(callee.expression);
467
+ }
468
+ }
469
+ // True for `if (!claimed.length) return`, `if (claimed.length === 0) return` and `if (!claimed[0]) return`.
470
+ function returnsWhenClaimEmpty(statement, claimed) {
471
+ if (!ts.isIfStatement(statement) || statement.elseStatement)
392
472
  return false;
393
- if (DATABASE_READ_METHODS.has(callee.name.text))
394
- return true;
395
- const sql = SQL_QUERY_METHODS.has(callee.name.text) ? staticSqlText(call.arguments[0]) : undefined;
396
- return !!sql && SELECT_SQL_RE.test(sql);
473
+ const exits = (branch) => ts.isReturnStatement(branch) ||
474
+ (ts.isBlock(branch) && branch.statements.length > 0 && exits(branch.statements[branch.statements.length - 1]));
475
+ if (!exits(statement.thenStatement))
476
+ return false;
477
+ const condition = ts.skipOuterExpressions(statement.expression);
478
+ const isClaimLength = (node) => {
479
+ const inner = ts.skipOuterExpressions(node);
480
+ return (ts.isPropertyAccessExpression(inner) &&
481
+ inner.name.text === 'length' &&
482
+ ts.isIdentifier(inner.expression) &&
483
+ inner.expression.text === claimed);
484
+ };
485
+ if (ts.isPrefixUnaryExpression(condition) && condition.operator === ts.SyntaxKind.ExclamationToken) {
486
+ const operand = ts.skipOuterExpressions(condition.operand);
487
+ return (isClaimLength(operand) ||
488
+ (ts.isElementAccessExpression(operand) &&
489
+ ts.isIdentifier(operand.expression) &&
490
+ operand.expression.text === claimed));
491
+ }
492
+ return (ts.isBinaryExpression(condition) &&
493
+ condition.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken &&
494
+ isClaimLength(condition.left) &&
495
+ ts.isNumericLiteral(condition.right) &&
496
+ condition.right.text === '0');
397
497
  }
398
- // The first insert the handler runs that no earlier database read could have guarded.
498
+ // A prior lookup cannot enforce uniqueness across concurrent deliveries; an atomic claim that returns early when empty can.
399
499
  function unguardedInsert(handler, context) {
400
- let readSeen = false;
401
- let unguarded;
402
- (function visit(node) {
403
- if (unguarded)
500
+ function visitStatements(statements) {
501
+ for (let index = 0; index < statements.length; index++) {
502
+ const found = visit(statements[index]);
503
+ if (found)
504
+ return found;
505
+ const claimed = claimedEventVariable(statements[index], context);
506
+ if (claimed && statements[index + 1] && returnsWhenClaimEmpty(statements[index + 1], claimed))
507
+ // The empty-result branch itself still runs for duplicate deliveries, so inspect it before stopping.
508
+ return visit(statements[index + 1]);
509
+ }
510
+ }
511
+ function visit(node) {
512
+ if (ts.isFunctionLike(node))
404
513
  return;
514
+ if (ts.isBlock(node))
515
+ return visitStatements(node.statements);
405
516
  if (ts.isCallExpression(node)) {
406
517
  const callee = propertyAccessCallee(node);
407
- if (callee && isDatabaseRead(node, callee, context))
408
- readSeen = true;
409
- else if (callee && !readSeen && isInsertWithoutConflictHandling(node, callee, context))
410
- unguarded = node;
518
+ if (callee && isInsertWithoutConflictHandling(node, callee, context))
519
+ return node;
411
520
  }
412
- ts.forEachChild(node, visit);
413
- })(handler.body);
414
- return unguarded;
521
+ return ts.forEachChild(node, visit);
522
+ }
523
+ return visit(handler.body);
415
524
  }
416
525
  function webhookHandler(call) {
417
526
  const handler = call.arguments.length > 1 ? ts.skipOuterExpressions(call.arguments[call.arguments.length - 1]) : undefined;
@@ -430,7 +539,7 @@ function checkWebhookIdempotency(call, context) {
430
539
  const insert = handler && unguardedInsert(handler, context);
431
540
  if (!insert)
432
541
  return;
433
- context.report(insert, 'webhook-missing-idempotency-check', `Webhook route \`${route.text}\` inserts a row without first checking whether the event was already handled. Providers deliver webhooks at least once, so a redelivery creates a duplicate. Store the event id under a unique constraint (or insert with a conflict clause) before applying the effect.`, 'The check may live in middleware or the insert may be keyed by the event id through a unique index; confirm before changing.');
542
+ context.report(insert, 'webhook-missing-idempotency-check', `Webhook route \`${route.text}\` inserts a row without a visible atomic event-id guard. Concurrent deliveries can both pass a lookup. Enforce a unique event ID and handle duplicate events before applying the effect.`, 'The check may live in middleware or the insert may be keyed by the event id through a unique index; confirm before changing.');
434
543
  }
435
544
  function checkBackendMasteryCall(call, context) {
436
545
  checkSequentialHttp(call, context);
@@ -0,0 +1,111 @@
1
+ import { ts } from '../engine/compiler.js';
2
+ import { unwrapExpression } from '../../shared/analysis/ast-semantics.js';
3
+ import { constSource, enclosingLoop, isGlobalMethodCall, MAX_SOURCE_DEPTH, valueSymbol } from './phase5-ast.js';
4
+ // Follow the entries of a caller-supplied collection, including a scalar normalized to a singleton list.
5
+ function fromBatchInput(value, method, checker, key, depth = 0) {
6
+ const expression = unwrapExpression(value);
7
+ if (ts.isIdentifier(expression)) {
8
+ const declaration = valueSymbol(expression, checker)?.valueDeclaration;
9
+ if (declaration && ts.isParameter(declaration))
10
+ return !key && declaration.parent === method;
11
+ const source = depth < MAX_SOURCE_DEPTH && constSource(expression, checker);
12
+ return !!source && fromBatchInput(source, method, checker, key, depth + 1);
13
+ }
14
+ if (ts.isElementAccessExpression(expression) || ts.isPropertyAccessExpression(expression)) {
15
+ const indexedByKey = ts.isElementAccessExpression(expression) &&
16
+ ts.isIdentifier(expression.argumentExpression) &&
17
+ valueSymbol(expression.argumentExpression, checker)?.valueDeclaration === key;
18
+ return fromBatchInput(expression.expression, method, checker, indexedByKey ? undefined : key, depth);
19
+ }
20
+ if (ts.isConditionalExpression(expression)) {
21
+ return (fromBatchInput(expression.whenTrue, method, checker, key, depth) &&
22
+ fromBatchInput(expression.whenFalse, method, checker, key, depth));
23
+ }
24
+ return (ts.isArrayLiteralExpression(expression) &&
25
+ expression.elements.length === 1 &&
26
+ fromBatchInput(expression.elements[0], method, checker, key, depth));
27
+ }
28
+ function iterationEntry(loop) {
29
+ if (ts.isVariableDeclarationList(loop.initializer) && loop.initializer.flags & ts.NodeFlags.Const)
30
+ return loop.initializer.declarations[0];
31
+ }
32
+ function returnsRemoval(method, checker) {
33
+ const last = method.body?.statements.at(-1);
34
+ if (!last || !ts.isReturnStatement(last))
35
+ return false;
36
+ const disposer = unwrapExpression(last.expression);
37
+ if (!disposer || !ts.isArrowFunction(disposer) || disposer.parameters.length)
38
+ return false;
39
+ const body = disposer.body;
40
+ const statement = ts.isBlock(body) && body.statements.length === 1 ? body.statements[0] : undefined;
41
+ const removal = unwrapExpression(statement && ts.isExpressionStatement(statement) ? statement.expression : body);
42
+ if (!ts.isCallExpression(removal))
43
+ return false;
44
+ const callee = unwrapExpression(removal.expression);
45
+ if (!ts.isPropertyAccessExpression(callee) ||
46
+ callee.expression.kind !== ts.SyntaxKind.ThisKeyword ||
47
+ callee.name.text !== 'removeListener')
48
+ return false;
49
+ const [event, callback] = removal.arguments;
50
+ const refersTo = (value, index) => method.parameters[index] !== undefined &&
51
+ value !== undefined &&
52
+ ts.isIdentifier(value) &&
53
+ valueSymbol(value, checker)?.valueDeclaration === method.parameters[index];
54
+ if (!refersTo(event, 0) || !callback)
55
+ return false;
56
+ if (refersTo(callback, 1))
57
+ return true;
58
+ return (ts.isBinaryExpression(callback) &&
59
+ callback.operatorToken.kind === ts.SyntaxKind.BarBarToken &&
60
+ refersTo(callback.left, 2) &&
61
+ refersTo(callback.right, 1));
62
+ }
63
+ // A bulk registration API deliberately retains each supplied callback. Verify the receiver's own
64
+ // singular API returns its removal callback before treating this loop as delegation.
65
+ export function isBulkListenerRegistration(call, loop, checker) {
66
+ const callee = unwrapExpression(call.expression);
67
+ if (!ts.isPropertyAccessExpression(callee) ||
68
+ callee.name.text !== 'addListener' ||
69
+ callee.expression.kind !== ts.SyntaxKind.ThisKeyword ||
70
+ !ts.isForOfStatement(loop))
71
+ return false;
72
+ const method = ts.findAncestor(call, ts.isFunctionLike);
73
+ if (!method ||
74
+ !ts.isMethodDeclaration(method) ||
75
+ !ts.isIdentifier(method.name) ||
76
+ method.name.text !== 'addListeners' ||
77
+ !ts.isClassLike(method.parent))
78
+ return false;
79
+ const registration = checker.getSymbolAtLocation(callee.name)?.valueDeclaration;
80
+ if (!registration || !ts.isMethodDeclaration(registration) || registration.parent !== method.parent)
81
+ return false;
82
+ const entry = iterationEntry(loop);
83
+ if (!entry)
84
+ return false;
85
+ const outer = enclosingLoop(loop);
86
+ if (outer && !ts.isForOfStatement(outer))
87
+ return false;
88
+ const key = outer && iterationEntry(outer);
89
+ if (outer) {
90
+ // Object.keys produces a fresh list with one entry per key. A supplied list can repeat a
91
+ // key and register every listener in that group more than once.
92
+ const event = unwrapExpression(call.arguments[0]);
93
+ const keySource = unwrapExpression(outer.expression);
94
+ if (!key ||
95
+ enclosingLoop(outer) ||
96
+ !ts.isCallExpression(keySource) ||
97
+ !isGlobalMethodCall(keySource, 'Object', 'keys', checker) ||
98
+ !event ||
99
+ !ts.isIdentifier(event) ||
100
+ valueSymbol(event, checker)?.valueDeclaration !== key)
101
+ return false;
102
+ }
103
+ const callback = unwrapExpression(call.arguments[1]);
104
+ if (!callback)
105
+ return false;
106
+ const origin = ts.isPropertyAccessExpression(callback) ? callback.expression : callback;
107
+ return (ts.isIdentifier(origin) &&
108
+ valueSymbol(origin, checker)?.valueDeclaration === entry &&
109
+ fromBatchInput(loop.expression, method, checker, key) &&
110
+ returnsRemoval(registration, checker));
111
+ }