loadwise 0.8.0 → 0.10.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 (651) hide show
  1. package/PERFORMANCE.md +17 -0
  2. package/README.md +294 -700
  3. package/agent/hooks/check-edited-file.mjs +800 -0
  4. package/dist/bin/github-action.js +72 -18
  5. package/dist/bin/loadwise.js +21 -34
  6. package/dist/lib/accessibility/angular-literal.js +1 -1
  7. package/dist/lib/accessibility/aria-tables.js +10 -6
  8. package/dist/lib/accessibility/astro-template.js +111 -0
  9. package/dist/lib/accessibility/autofocus.js +94 -0
  10. package/dist/lib/accessibility/document-reference-rules.js +143 -0
  11. package/dist/lib/accessibility/form-context.js +7 -2
  12. package/dist/lib/accessibility/frontend-detect.js +18 -8
  13. package/dist/lib/accessibility/heading-order.js +59 -0
  14. package/dist/lib/accessibility/interaction-semantics.js +90 -0
  15. package/dist/lib/accessibility/jinja-template.js +150 -0
  16. package/dist/lib/accessibility/jsx-elements.js +164 -21
  17. package/dist/lib/accessibility/language-tags.js +18 -0
  18. package/dist/lib/accessibility/markup-files.js +44 -17
  19. package/dist/lib/accessibility/markup.js +4 -1
  20. package/dist/lib/accessibility/media-rules.js +81 -0
  21. package/dist/lib/accessibility/native-interactive.js +145 -0
  22. package/dist/lib/accessibility/rule-ids.js +30 -0
  23. package/dist/lib/accessibility/rule-utilities.js +92 -0
  24. package/dist/lib/accessibility/rules.js +77 -140
  25. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  26. package/dist/lib/accessibility/site-fixes/buttons.js +4 -11
  27. package/dist/lib/accessibility/site-fixes/email-autocomplete.js +103 -0
  28. package/dist/lib/accessibility/site-fixes/html-language.js +84 -0
  29. package/dist/lib/accessibility/site-fixes/media-autoplay.js +87 -0
  30. package/dist/lib/accessibility/site-fixes/positive-tabindex.js +102 -0
  31. package/dist/lib/accessibility/site-fixes/source-position.js +11 -0
  32. package/dist/lib/accessibility/site-fixes/viewport.js +107 -0
  33. package/dist/lib/accessibility/table-headers.js +70 -0
  34. package/dist/lib/accessibility/template-attributes.js +13 -2
  35. package/dist/lib/accessibility/template-binding-scope.js +122 -0
  36. package/dist/lib/accessibility/template-elements.js +259 -109
  37. package/dist/lib/accessibility/template-file.js +111 -22
  38. package/dist/lib/accessibility/template-tag-tables.js +86 -0
  39. package/dist/lib/accessibility/usage.js +1 -1
  40. package/dist/lib/editor/accessibility-examples.js +5 -0
  41. package/dist/lib/editor/actions.js +26 -14
  42. package/dist/lib/editor/apply-fix.js +30 -2
  43. package/dist/lib/editor/configured-setup.js +9 -14
  44. package/dist/lib/editor/diagnostics.js +121 -135
  45. package/dist/lib/editor/dismissals.js +21 -10
  46. package/dist/lib/editor/doctor.js +167 -0
  47. package/dist/lib/editor/editor-document.js +17 -1
  48. package/dist/lib/editor/editor-launcher.js +60 -26
  49. package/dist/lib/editor/finding-comparison.js +4 -25
  50. package/dist/lib/editor/fix-edits.js +87 -8
  51. package/dist/lib/editor/hover-markdown.js +104 -0
  52. package/dist/lib/editor/inline-fix.js +50 -0
  53. package/dist/lib/editor/inline-recommendation.js +27 -0
  54. package/dist/lib/editor/jetbrains-setup.js +2 -1
  55. package/dist/lib/editor/language-server.js +305 -56
  56. package/dist/lib/editor/native-setup.js +7 -2
  57. package/dist/lib/editor/perf-watch.js +7 -5
  58. package/dist/lib/editor/performance-examples.js +31 -0
  59. package/dist/lib/editor/polyglot-selection.js +193 -0
  60. package/dist/lib/editor/project-policy.js +146 -0
  61. package/dist/lib/editor/project-watches.js +86 -0
  62. package/dist/lib/editor/release-vsix.js +23 -1
  63. package/dist/lib/editor/reliability-examples.js +36 -0
  64. package/dist/lib/editor/scan-session.js +212 -62
  65. package/dist/lib/editor/security-examples.js +24 -14
  66. package/dist/lib/editor/server-commands.js +24 -11
  67. package/dist/lib/editor/setup.js +7 -12
  68. package/dist/lib/editor/standalone-performance-examples.js +51 -0
  69. package/dist/lib/editor/workspace-files.js +32 -8
  70. package/dist/lib/editor/workspace-paths.js +29 -7
  71. package/dist/lib/editor/zed-settings.js +118 -0
  72. package/dist/lib/editor/zed-setup.js +88 -0
  73. package/dist/lib/maintainability/analysis/analyze-source.js +8 -3
  74. package/dist/lib/maintainability/analysis/source-exclusions.js +2 -1
  75. package/dist/lib/maintainability/analysis/source-facts.js +2 -2
  76. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  77. package/dist/lib/maintainability/architecture/graph.js +2 -1
  78. package/dist/lib/maintainability/architecture/layout.js +2 -1
  79. package/dist/lib/maintainability/cli/apply-fix.js +32 -7
  80. package/dist/lib/maintainability/cli/changed-lines.js +7 -113
  81. package/dist/lib/maintainability/cli/finding-ids.js +3 -6
  82. package/dist/lib/maintainability/cli/fix-cli.js +1 -9
  83. package/dist/lib/maintainability/cli/git-inventory.js +5 -6
  84. package/dist/lib/maintainability/cli/inputs.js +24 -16
  85. package/dist/lib/maintainability/cli/scan-arguments.js +33 -0
  86. package/dist/lib/maintainability/cli/site-fix.js +31 -13
  87. package/dist/lib/maintainability/cli.js +31 -38
  88. package/dist/lib/maintainability/entry-points/entry-points.js +27 -68
  89. package/dist/lib/maintainability/examples.js +60 -0
  90. package/dist/lib/maintainability/polyglot-duplicates.js +1 -0
  91. package/dist/lib/maintainability/polyglot.js +337 -12
  92. package/dist/lib/maintainability/project.js +4 -4
  93. package/dist/lib/maintainability/quality/console-tooling.js +114 -0
  94. package/dist/lib/maintainability/quality/declarative-imports.js +18 -0
  95. package/dist/lib/maintainability/quality/deprecated-apis.js +227 -40
  96. package/dist/lib/maintainability/quality/duplicates.js +5 -11
  97. package/dist/lib/maintainability/quality/generic-assertion-target.js +75 -0
  98. package/dist/lib/maintainability/quality/limits.js +5 -1
  99. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  100. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  101. package/dist/lib/maintainability/quality/size-limits.js +2 -1
  102. package/dist/lib/maintainability/quality/stray-console.js +31 -7
  103. package/dist/lib/maintainability/quality/tsconfig-strict.js +432 -21
  104. package/dist/lib/maintainability/quality/type-escape-hatches.js +411 -0
  105. package/dist/lib/maintainability/quality/type-safety-hygiene.js +132 -42
  106. package/dist/lib/maintainability/quality/unowned-source.js +15 -0
  107. package/dist/lib/maintainability/rule-ids.js +27 -0
  108. package/dist/lib/maintainability/scan-changed.js +39 -3
  109. package/dist/lib/maintainability/scan-worker.js +3 -5
  110. package/dist/lib/maintainability/scan.js +26 -4
  111. package/dist/lib/maintainability/site-fixes/duplicate-edits.js +3 -2
  112. package/dist/lib/maintainability/site-fixes/duplicate-methods.js +7 -2
  113. package/dist/lib/maintainability/site-fixes/duplicates.js +3 -2
  114. package/dist/lib/maintainability/site-fixes/focused-test.js +230 -0
  115. package/dist/lib/maintainability/site-fixes/helpers.js +2 -6
  116. package/dist/lib/maintainability/site-fixes/if-rewrites.js +1 -7
  117. package/dist/lib/maintainability/site-fixes/large-module.js +2 -1
  118. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  119. package/dist/lib/maintainability/unused/ancestor-aliases.js +2 -2
  120. package/dist/lib/maintainability/unused/module-usage-dynamic.js +2 -1
  121. package/dist/lib/maintainability/unused/module-usage-named-exports.js +125 -0
  122. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  123. package/dist/lib/maintainability/unused/module-usage.js +75 -109
  124. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  125. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  126. package/dist/lib/maintainability/unused/unused-modules.js +39 -1
  127. package/dist/lib/performance/analysis/call-syntax.js +2 -1
  128. package/dist/lib/performance/analysis/function-kinds.js +1 -5
  129. package/dist/lib/performance/analysis/missing-packages.js +13 -7
  130. package/dist/lib/performance/analysis/package-types.js +10 -2
  131. package/dist/lib/performance/analysis/schema-tooling.js +157 -8
  132. package/dist/lib/performance/analysis/source-inputs.js +17 -12
  133. package/dist/lib/performance/analysis/source-text.js +2 -2
  134. package/dist/lib/performance/analysis/unscanned-javascript.js +6 -5
  135. package/dist/lib/performance/analyze.js +25 -6
  136. package/dist/lib/performance/async/async-errors.js +162 -14
  137. package/dist/lib/performance/async/await-before-early-exit.js +1 -6
  138. package/dist/lib/performance/async/floating-promises.js +27 -6
  139. package/dist/lib/performance/async/promise-return-escapes-catch.js +35 -2
  140. package/dist/lib/performance/async/stream-errors.js +1 -3
  141. package/dist/lib/performance/cli/changed-lines.js +14 -111
  142. package/dist/lib/performance/cli/cli-arguments.js +11 -9
  143. package/dist/lib/performance/cli/cli-markup.js +42 -0
  144. package/dist/lib/performance/cli/cli-output.js +9 -3
  145. package/dist/lib/performance/cli/cli-policy.js +174 -17
  146. package/dist/lib/performance/cli/cli-scan.js +170 -139
  147. package/dist/lib/performance/cli/finding-ids.js +7 -7
  148. package/dist/lib/performance/cli/fix-cli.js +83 -34
  149. package/dist/lib/performance/cli/prisma-schema-findings.js +23 -0
  150. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  151. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  152. package/dist/lib/performance/cli/watch-security.js +33 -0
  153. package/dist/lib/performance/cli/watch.js +42 -15
  154. package/dist/lib/performance/cli.js +8 -7
  155. package/dist/lib/performance/collections/array-drains.js +354 -0
  156. package/dist/lib/performance/collections/collection-bindings.js +1 -2
  157. package/dist/lib/performance/collections/collection-bounds.js +3 -2
  158. package/dist/lib/performance/collections/collection-copy.js +51 -1
  159. package/dist/lib/performance/collections/collection-lookups.js +74 -13
  160. package/dist/lib/performance/collections/collection-reduce.js +32 -6
  161. package/dist/lib/performance/collections/collections.js +34 -2
  162. package/dist/lib/performance/collections/json-clone.js +137 -17
  163. package/dist/lib/performance/collections/regex-allocation.js +156 -0
  164. package/dist/lib/performance/collections/repeated.js +26 -8
  165. package/dist/lib/performance/collections/sort-extreme.js +18 -1
  166. package/dist/lib/performance/collections/workbook-decodes.js +3 -2
  167. package/dist/lib/performance/contracts/cli.js +340 -21
  168. package/dist/lib/performance/contracts/git-files.js +102 -5
  169. package/dist/lib/performance/contracts/openapi-schema.js +187 -0
  170. package/dist/lib/performance/contracts/openapi-sources.js +260 -0
  171. package/dist/lib/performance/contracts/openapi.js +172 -233
  172. package/dist/lib/performance/contracts/protobuf.js +301 -0
  173. package/dist/lib/performance/contracts/trpc-moves.js +46 -0
  174. package/dist/lib/performance/contracts/trpc.js +477 -0
  175. package/dist/lib/performance/datastores/pg-integrity.js +2 -1
  176. package/dist/lib/performance/datastores/pooling.js +3 -18
  177. package/dist/lib/performance/datastores/postgres.js +41 -33
  178. package/dist/lib/performance/datastores/redis-keys.js +4 -3
  179. package/dist/lib/performance/datastores/redis.js +8 -1
  180. package/dist/lib/performance/datastores/repeated-reads.js +104 -0
  181. package/dist/lib/performance/datastores/search-clients.js +9 -0
  182. package/dist/lib/performance/datastores/session-store.js +166 -7
  183. package/dist/lib/performance/datastores/supabase.js +73 -0
  184. package/dist/lib/performance/db/checks.js +1 -1
  185. package/dist/lib/performance/db/cli-mysql.js +12 -2
  186. package/dist/lib/performance/db/cli.js +38 -5
  187. package/dist/lib/performance/db/drivers.js +20 -4
  188. package/dist/lib/performance/db/measure.js +1 -1
  189. package/dist/lib/performance/db/mysql-catalog.js +1 -1
  190. package/dist/lib/performance/db/plan-estimates.js +46 -7
  191. package/dist/lib/performance/db/redact.js +1 -3
  192. package/dist/lib/performance/db/snapshot.js +1 -1
  193. package/dist/lib/performance/db/sqlite-plan.js +95 -0
  194. package/dist/lib/performance/engine/compiler.js +3 -2
  195. package/dist/lib/performance/engine/native-checker.js +85 -10
  196. package/dist/lib/performance/engine/native-syntax.js +17 -0
  197. package/dist/lib/performance/engine/native-workspaces.js +36 -8
  198. package/dist/lib/performance/engine/native.js +42 -16
  199. package/dist/lib/performance/engine/review-config-inputs.js +57 -0
  200. package/dist/lib/performance/evidence/plans.js +14 -16
  201. package/dist/lib/performance/evidence/trace-formats.js +182 -0
  202. package/dist/lib/performance/evidence/traces.js +6 -6
  203. package/dist/lib/performance/frontend/angular-bootstrap.js +309 -0
  204. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  205. package/dist/lib/performance/frontend/barrel-subpaths.js +204 -0
  206. package/dist/lib/performance/frontend/effect-cleanup.js +30 -4
  207. package/dist/lib/performance/frontend/frontend-dom-perf.js +79 -15
  208. package/dist/lib/performance/frontend/frontend-perf.js +119 -176
  209. package/dist/lib/performance/frontend/frontend-render-perf.js +17 -13
  210. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  211. package/dist/lib/performance/frontend/layout-binary-probe.js +186 -0
  212. package/dist/lib/performance/frontend/next-fetch-waterfall.js +405 -0
  213. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  214. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  215. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  216. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  217. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  218. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  219. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  220. package/dist/lib/performance/frontend/template-tracking.js +215 -0
  221. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  222. package/dist/lib/performance/index-rules/index-rules-table.js +3 -3
  223. package/dist/lib/performance/index-rules/redundant-indexes.js +6 -13
  224. package/dist/lib/performance/migrations/cli.js +65 -14
  225. package/dist/lib/performance/migrations/discover.js +63 -32
  226. package/dist/lib/performance/migrations/enforce.js +5 -12
  227. package/dist/lib/performance/migrations/extract-code-sql.js +10 -7
  228. package/dist/lib/performance/migrations/extract-code.js +1 -0
  229. package/dist/lib/performance/migrations/extract-sql.js +45 -4
  230. package/dist/lib/performance/migrations/extract-sqlite.js +302 -0
  231. package/dist/lib/performance/migrations/operations.js +122 -8
  232. package/dist/lib/performance/migrations/postgres-registry.js +6 -6
  233. package/dist/lib/performance/migrations/postgres-table-history.js +147 -0
  234. package/dist/lib/performance/migrations/rules-postgres-shared.js +4 -6
  235. package/dist/lib/performance/migrations/rules-postgres.js +67 -13
  236. package/dist/lib/performance/migrations/rules-sqlite.js +118 -0
  237. package/dist/lib/performance/migrations/sqlserver-creation.js +131 -0
  238. package/dist/lib/performance/migrations/sqlserver.js +81 -0
  239. package/dist/lib/performance/models/client-imports.js +286 -0
  240. package/dist/lib/performance/models/index.js +46 -8
  241. package/dist/lib/performance/orm/cartesian-includes.js +49 -22
  242. package/dist/lib/performance/orm/drizzle.js +86 -27
  243. package/dist/lib/performance/orm/knex-loop-operations.js +96 -0
  244. package/dist/lib/performance/orm/orm-owners.js +3 -5
  245. package/dist/lib/performance/orm/orm-queries.js +50 -152
  246. package/dist/lib/performance/orm/orm-result-uses.js +116 -0
  247. package/dist/lib/performance/orm/prisma-integrity.js +24 -3
  248. package/dist/lib/performance/orm/prisma.js +32 -33
  249. package/dist/lib/performance/orm/typeorm-batch-filter.js +43 -0
  250. package/dist/lib/performance/orm/typeorm-projection.js +2 -2
  251. package/dist/lib/performance/orm/typeorm-transaction-loops.js +3 -4
  252. package/dist/lib/performance/orm/typeorm-updates.js +1 -3
  253. package/dist/lib/performance/orm/unbounded-list-page-size.js +179 -0
  254. package/dist/lib/performance/orm/unbounded-list-queries.js +63 -146
  255. package/dist/lib/performance/polyglot.js +173 -61
  256. package/dist/lib/performance/probe-caches.js +42 -0
  257. package/dist/lib/performance/program-batches.js +138 -0
  258. package/dist/lib/performance/projects.js +86 -89
  259. package/dist/lib/performance/query-loops/guard-queries.js +2 -1
  260. package/dist/lib/performance/query-loops/parallel-reads-policy.js +1 -3
  261. package/dist/lib/performance/query-loops/query-loop-batch.js +81 -7
  262. package/dist/lib/performance/query-loops/query-loop-bounds.js +1 -13
  263. package/dist/lib/performance/query-loops/query-policy.js +19 -20
  264. package/dist/lib/performance/query-loops/query-results.js +1 -6
  265. package/dist/lib/performance/query-loops/query-write-context.js +89 -0
  266. package/dist/lib/performance/query-loops/sequential-loops.js +6 -24
  267. package/dist/lib/performance/query-loops/service-call-resolution.js +17 -2
  268. package/dist/lib/performance/query-loops/service-loop-source.js +124 -0
  269. package/dist/lib/performance/query-loops/service-loops.js +86 -25
  270. package/dist/lib/performance/query-loops/throw-on-miss-loops.js +141 -0
  271. package/dist/lib/performance/request/backend-mastery.js +18 -30
  272. package/dist/lib/performance/request/fixed-emitter-loop.js +98 -0
  273. package/dist/lib/performance/request/fresh-mapped-elements.js +137 -0
  274. package/dist/lib/performance/request/graphql-list-lookups.js +258 -0
  275. package/dist/lib/performance/request/http-options-writes.js +2 -8
  276. package/dist/lib/performance/request/http-timeouts.js +3 -2
  277. package/dist/lib/performance/request/json-stringify-output.js +217 -0
  278. package/dist/lib/performance/request/llm-max-tokens.js +27 -8
  279. package/dist/lib/performance/request/mongoose-lean.js +15 -10
  280. package/dist/lib/performance/request/node-event-listener-leak.js +190 -35
  281. package/dist/lib/performance/request/node-fs-context.js +6 -8
  282. package/dist/lib/performance/request/node-fs.js +4 -6
  283. package/dist/lib/performance/request/password-hashing.js +4 -3
  284. package/dist/lib/performance/request/phase5-ast.js +3 -9
  285. package/dist/lib/performance/request/phase5-rules.js +50 -102
  286. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  287. package/dist/lib/performance/request/pure-js-hashing.js +2 -1
  288. package/dist/lib/performance/request/request-handlers.js +44 -7
  289. package/dist/lib/performance/request/request-inputs.js +121 -26
  290. package/dist/lib/performance/request/unbounded-promise-all.js +142 -52
  291. package/dist/lib/performance/rule-ids.js +72 -5
  292. package/dist/lib/performance/schema/context.js +7 -16
  293. package/dist/lib/performance/schema/model.js +1 -9
  294. package/dist/lib/performance/schema/prisma-owners.js +15 -1
  295. package/dist/lib/performance/schema/prisma-schema.js +5 -6
  296. package/dist/lib/performance/schema/project-indexes-events.js +8 -2
  297. package/dist/lib/performance/schema/project-indexes.js +4 -2
  298. package/dist/lib/performance/schema/query-site-support.js +1 -1
  299. package/dist/lib/performance/schema/sequelize-schema.js +1 -3
  300. package/dist/lib/performance/schema/ts-helpers.js +3 -7
  301. package/dist/lib/performance/shared-libs.js +48 -0
  302. package/dist/lib/performance/site-fix.js +33 -7
  303. package/dist/lib/performance/site-fixes/collection-copy.js +2 -1
  304. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  305. package/dist/lib/performance/site-fixes/collection-find.js +2 -1
  306. package/dist/lib/performance/site-fixes/collection-helpers.js +0 -6
  307. package/dist/lib/performance/site-fixes/collection-lookups.js +2 -1
  308. package/dist/lib/performance/site-fixes/database.js +7 -16
  309. package/dist/lib/performance/site-fixes/drizzle-index.js +2 -9
  310. package/dist/lib/performance/site-fixes/frontend-fixes.js +47 -15
  311. package/dist/lib/performance/site-fixes/helpers.js +19 -18
  312. package/dist/lib/performance/site-fixes/last-insert-id.js +2 -1
  313. package/dist/lib/performance/site-fixes/llm-max-tokens.js +56 -0
  314. package/dist/lib/performance/site-fixes/migration-column-rules.js +11 -7
  315. package/dist/lib/performance/site-fixes/migration-lock-rules.js +6 -3
  316. package/dist/lib/performance/site-fixes/migrations.js +4 -0
  317. package/dist/lib/performance/site-fixes/pure-js-hashing.js +2 -2
  318. package/dist/lib/performance/site-fixes/query-shapes.js +1 -4
  319. package/dist/lib/performance/site-fixes/service-loop-ast.js +1 -9
  320. package/dist/lib/performance/site-fixes/small-rewrites.js +28 -2
  321. package/dist/lib/performance/site-fixes/template-tracking-fixes.js +82 -0
  322. package/dist/lib/performance/site-fixes/writes.js +1 -6
  323. package/dist/lib/performance/sql/local-statements.js +108 -0
  324. package/dist/lib/performance/sql/mysql-tokens.js +1 -4
  325. package/dist/lib/performance/sql/pg-parser.js +3 -5
  326. package/dist/lib/performance/sql/sqlserver-control.js +43 -0
  327. package/dist/lib/reliability/analyze.js +48 -5
  328. package/dist/lib/reliability/boundary-access.js +34 -27
  329. package/dist/lib/reliability/callback-completion.js +10 -2
  330. package/dist/lib/reliability/child-process.js +2 -2
  331. package/dist/lib/reliability/crlf-line-split.js +124 -73
  332. package/dist/lib/reliability/crlf-references.js +78 -0
  333. package/dist/lib/reliability/default-numeric-sort.js +25 -0
  334. package/dist/lib/reliability/error-cause-plan.js +29 -0
  335. package/dist/lib/reliability/error-values.js +68 -27
  336. package/dist/lib/reliability/json-cast.js +368 -0
  337. package/dist/lib/reliability/key-test-callee.js +50 -0
  338. package/dist/lib/reliability/lossy-text-rewrite.js +94 -0
  339. package/dist/lib/reliability/manifest-boundary.js +466 -0
  340. package/dist/lib/reliability/manifest-snapshot.js +40 -0
  341. package/dist/lib/reliability/parse-failure-flow.js +5 -2
  342. package/dist/lib/reliability/parse-failure-paths.js +39 -8
  343. package/dist/lib/reliability/parse-failure-reset.js +5 -17
  344. package/dist/lib/reliability/pool-timeout.js +31 -7
  345. package/dist/lib/reliability/promise-usage.js +281 -0
  346. package/dist/lib/reliability/react-bugs.js +16 -6
  347. package/dist/lib/reliability/react-state-aliases.js +94 -4
  348. package/dist/lib/reliability/react-state-order.js +2 -2
  349. package/dist/lib/reliability/react-state-paths.js +2 -2
  350. package/dist/lib/reliability/react-state-setter.js +5 -11
  351. package/dist/lib/reliability/react-state-walker.js +3 -3
  352. package/dist/lib/reliability/react-state.js +24 -5
  353. package/dist/lib/reliability/required-member.js +19 -0
  354. package/dist/lib/reliability/resource-leak-intervals.js +4 -7
  355. package/dist/lib/reliability/resource-leaks.js +4 -7
  356. package/dist/lib/reliability/rule-ids.js +70 -1
  357. package/dist/lib/reliability/same-file-io.js +135 -0
  358. package/dist/lib/reliability/short-write.js +220 -0
  359. package/dist/lib/reliability/site-fixes/crlf-line-split.js +71 -0
  360. package/dist/lib/reliability/site-fixes/error-values.js +40 -0
  361. package/dist/lib/reliability/site-fixes/pool-timeout.js +51 -0
  362. package/dist/lib/reliability/source-helpers.js +18 -8
  363. package/dist/lib/reliability/standalone-sources.js +8 -6
  364. package/dist/lib/reliability/suspicious-logic.js +6 -8
  365. package/dist/lib/reliability/swallowed-errors.js +3 -7
  366. package/dist/lib/reliability/switch-exhaustive.js +195 -5
  367. package/dist/lib/reliability/test-cleanup-after-await.js +2 -2
  368. package/dist/lib/reliability/throw-string-plan.js +121 -0
  369. package/dist/lib/reliability/uncaught-exception.js +2 -7
  370. package/dist/lib/reliability/usage.js +1 -1
  371. package/dist/lib/reliability/working-directory.js +101 -0
  372. package/dist/lib/security/analyze.js +2 -0
  373. package/dist/lib/security/auth-crypto/hashing.js +21 -4
  374. package/dist/lib/security/auth-crypto/index.js +6 -1
  375. package/dist/lib/security/auth-crypto/jwt-decode-helpers.js +163 -0
  376. package/dist/lib/security/auth-crypto/jwt.js +52 -36
  377. package/dist/lib/security/auth-crypto/plaintext-password.js +2 -1
  378. package/dist/lib/security/auth-crypto/random.js +2 -1
  379. package/dist/lib/security/auth-crypto/rate-limits.js +79 -8
  380. package/dist/lib/security/auth-crypto/rule-ids.js +2 -0
  381. package/dist/lib/security/auth-crypto/secrets.js +132 -19
  382. package/dist/lib/security/auth-crypto/shared.js +1 -4
  383. package/dist/lib/security/auth-crypto/signature-verification.js +29 -0
  384. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +43 -3
  385. package/dist/lib/security/auth-crypto/weak-hash.js +183 -0
  386. package/dist/lib/security/bindings.js +41 -9
  387. package/dist/lib/security/cli.js +84 -27
  388. package/dist/lib/security/cookie-csrf.js +316 -7
  389. package/dist/lib/security/credential-entropy.js +12 -0
  390. package/dist/lib/security/deps/cargo-lock.js +78 -0
  391. package/dist/lib/security/deps/cli.js +4 -4
  392. package/dist/lib/security/deps/fixed-version.js +2 -2
  393. package/dist/lib/security/deps/lockfiles.js +207 -17
  394. package/dist/lib/security/deps/osv.js +190 -59
  395. package/dist/lib/security/deps/scan.js +87 -19
  396. package/dist/lib/security/examples/{auth-crypto.cjs → auth-crypto.js} +11 -5
  397. package/dist/lib/security/examples/{deps.cjs → deps.js} +1 -3
  398. package/dist/lib/security/examples/{exposure.cjs → exposure.js} +17 -3
  399. package/dist/lib/security/examples/files.js +146 -0
  400. package/dist/lib/security/examples/{injection.cjs → injection.js} +13 -3
  401. package/dist/lib/security/examples/{moved.cjs → moved.js} +1 -3
  402. package/dist/lib/security/examples/{request-forgery.cjs → request-forgery.js} +2 -4
  403. package/dist/lib/security/exposure/backend-security-mastery.js +2 -1
  404. package/dist/lib/security/exposure/client-env.js +2 -1
  405. package/dist/lib/security/exposure/content-disposition.js +71 -0
  406. package/dist/lib/security/exposure/cookies.js +200 -1
  407. package/dist/lib/security/exposure/cors.js +63 -4
  408. package/dist/lib/security/exposure/frontend-security.js +18 -62
  409. package/dist/lib/security/exposure/index.js +9 -0
  410. package/dist/lib/security/exposure/js-yaml.js +203 -0
  411. package/dist/lib/security/exposure/message-effects.js +266 -0
  412. package/dist/lib/security/exposure/package-manifest.js +2 -2
  413. package/dist/lib/security/exposure/prototype-pollution.js +99 -5
  414. package/dist/lib/security/exposure/reflected-xss.js +47 -12
  415. package/dist/lib/security/exposure/response-content-type.js +181 -0
  416. package/dist/lib/security/exposure/rule-ids.js +4 -0
  417. package/dist/lib/security/exposure/trust-boundary.js +142 -0
  418. package/dist/lib/security/exposure/url-secrets.js +38 -2
  419. package/dist/lib/security/exposure/webhook-verification.js +231 -0
  420. package/dist/lib/security/express-registration.js +45 -0
  421. package/dist/lib/security/express-router-factories.js +118 -0
  422. package/dist/lib/security/files/azure-pipelines.js +69 -0
  423. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  424. package/dist/lib/security/files/ci-platforms.js +16 -0
  425. package/dist/lib/security/files/ci-shared.js +260 -0
  426. package/dist/lib/security/files/circleci.js +81 -0
  427. package/dist/lib/security/files/component-markup.js +66 -0
  428. package/dist/lib/security/files/compose.js +2 -1
  429. package/dist/lib/security/files/dockerfile.js +188 -3
  430. package/dist/lib/security/files/github-actions.js +490 -0
  431. package/dist/lib/security/files/gitlab-ci.js +90 -0
  432. package/dist/lib/security/files/hcl.js +264 -0
  433. package/dist/lib/security/files/hosting-config.js +159 -0
  434. package/dist/lib/security/files/http-headers.js +65 -0
  435. package/dist/lib/security/files/index.js +182 -33
  436. package/dist/lib/security/files/jenkinsfile.js +482 -0
  437. package/dist/lib/security/files/json-nodes.js +67 -0
  438. package/dist/lib/security/files/kubernetes.js +136 -0
  439. package/dist/lib/security/files/nginx.js +501 -0
  440. package/dist/lib/security/files/package-scripts.js +175 -0
  441. package/dist/lib/security/files/project-files.js +98 -31
  442. package/dist/lib/security/files/rule-ids.js +31 -0
  443. package/dist/lib/security/files/secret-values.js +31 -5
  444. package/dist/lib/security/files/secrets.js +53 -18
  445. package/dist/lib/security/files/terraform.js +345 -0
  446. package/dist/lib/security/injection/code.js +33 -5
  447. package/dist/lib/security/injection/command.js +51 -4
  448. package/dist/lib/security/injection/escape-preserving.js +219 -0
  449. package/dist/lib/security/injection/escape-replace.js +174 -2
  450. package/dist/lib/security/injection/index.js +5 -1
  451. package/dist/lib/security/injection/nosql.js +3 -2
  452. package/dist/lib/security/injection/redos.js +25 -4
  453. package/dist/lib/security/injection/rule-ids.js +3 -0
  454. package/dist/lib/security/injection/shell-output-guard.js +97 -0
  455. package/dist/lib/security/injection/sql.js +53 -2
  456. package/dist/lib/security/injection/xpath.js +35 -0
  457. package/dist/lib/security/lexical-declaration.js +28 -0
  458. package/dist/lib/security/pg-identifier-guards.js +146 -5
  459. package/dist/lib/security/phase5-rules.js +1 -0
  460. package/dist/lib/security/polyglot.js +35 -3
  461. package/dist/lib/security/provider-credentials.js +29 -0
  462. package/dist/lib/security/redirect-settings.js +131 -6
  463. package/dist/lib/security/request-forgery/contained-helper.js +75 -0
  464. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  465. package/dist/lib/security/request-forgery/open-redirect-query.js +2 -1
  466. package/dist/lib/security/request-forgery/open-redirect.js +69 -9
  467. package/dist/lib/security/request-forgery/parsed-host-guard.js +213 -0
  468. package/dist/lib/security/request-forgery/path-traversal.js +36 -1
  469. package/dist/lib/security/request-forgery/shared.js +205 -30
  470. package/dist/lib/security/request-forgery/ssrf.js +145 -1
  471. package/dist/lib/security/rule-descriptions.js +46 -1
  472. package/dist/lib/security/rule-ids.js +50 -0
  473. package/dist/lib/security/scope/drizzle-policy.js +2 -1
  474. package/dist/lib/security/scope/kysely-policy.js +173 -0
  475. package/dist/lib/security/site-fixes/auth-crypto.js +3 -1
  476. package/dist/lib/security/taint/accessors.js +364 -0
  477. package/dist/lib/security/taint/array-writes.js +139 -0
  478. package/dist/lib/security/taint/binding-inputs.js +4 -3
  479. package/dist/lib/security/taint/field-access.js +80 -0
  480. package/dist/lib/security/taint/filename-guard.js +81 -6
  481. package/dist/lib/security/taint/guards.js +150 -17
  482. package/dist/lib/security/taint/index.js +41 -116
  483. package/dist/lib/security/taint/original-string-validation.js +229 -0
  484. package/dist/lib/security/taint/propagate.js +5 -6
  485. package/dist/lib/security/taint/resolution-cache.js +10 -1
  486. package/dist/lib/security/taint/sanitizers.js +5 -5
  487. package/dist/lib/security/taint/shape-flows.js +128 -0
  488. package/dist/lib/security/taint/sink-alphabets.js +237 -0
  489. package/dist/lib/security/taint/sources.js +151 -8
  490. package/dist/lib/security/taint/trace-nodes.js +35 -2
  491. package/dist/lib/security/taint/validators.js +59 -20
  492. package/dist/lib/security/trusted-bindings.js +44 -0
  493. package/dist/lib/shared/agent/agent-init.js +84 -9
  494. package/dist/lib/shared/agent/agent-integrations.js +626 -0
  495. package/dist/lib/shared/agent/agent-prompt.js +2 -1
  496. package/dist/lib/shared/agent/agent-session.js +1 -1
  497. package/dist/lib/shared/agent/agent-toml.js +98 -0
  498. package/dist/lib/shared/agent/agent-verify.js +21 -3
  499. package/dist/lib/shared/agent/git-hook.js +31 -4
  500. package/dist/lib/shared/agent/notify-editor.js +2 -1
  501. package/dist/lib/shared/agent/review-delivery.js +3 -1
  502. package/dist/lib/shared/agent/review-mcp.js +67 -13
  503. package/dist/lib/shared/agent/review-request.js +4 -0
  504. package/dist/lib/shared/analysis/ast-helpers.js +50 -0
  505. package/dist/lib/shared/analysis/ast-semantics.js +23 -1
  506. package/dist/lib/shared/analysis/binding-names.js +13 -0
  507. package/dist/lib/shared/analysis/execution-context.js +49 -9
  508. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  509. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  510. package/dist/lib/shared/analysis/polyglot-compatibility.js +102 -23
  511. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  512. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  513. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  514. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  515. package/dist/lib/shared/analysis/scan-cache-storage.js +204 -0
  516. package/dist/lib/shared/analysis/scan-cache.js +373 -166
  517. package/dist/lib/shared/analysis/valid-javascript.js +118 -0
  518. package/dist/lib/shared/changed-lines.js +129 -0
  519. package/dist/lib/shared/check-options.js +63 -0
  520. package/dist/lib/shared/check-watch-inputs.js +152 -0
  521. package/dist/lib/shared/check-watch-process.js +57 -0
  522. package/dist/lib/shared/check-watch.js +136 -0
  523. package/dist/lib/shared/check.js +97 -40
  524. package/dist/lib/shared/completion-shells.js +127 -0
  525. package/dist/lib/shared/completion.js +124 -0
  526. package/dist/lib/shared/config-rule-validation.js +135 -0
  527. package/dist/lib/shared/config.js +330 -163
  528. package/dist/lib/shared/conventional-projects.js +40 -0
  529. package/dist/lib/shared/declarative-rule-packs.js +173 -0
  530. package/dist/lib/shared/explain.js +47 -9
  531. package/dist/lib/shared/fix/fix-command.js +2 -0
  532. package/dist/lib/shared/fix/fix-convergence.js +45 -128
  533. package/dist/lib/shared/fix/fix-history.js +130 -26
  534. package/dist/lib/shared/fix/fix-interactive.js +78 -0
  535. package/dist/lib/shared/fix/fix-patch.js +89 -0
  536. package/dist/lib/shared/fix/fix-polyglot-preview.js +166 -0
  537. package/dist/lib/shared/fix/fix-presentation-biome.js +120 -0
  538. package/dist/lib/shared/fix/fix-presentation-prettier.js +27 -10
  539. package/dist/lib/shared/fix/fix-presentation-rows.js +5 -1
  540. package/dist/lib/shared/fix/fix-presentation.js +22 -15
  541. package/dist/lib/shared/fix/fix-project-membership.js +79 -0
  542. package/dist/lib/shared/fix/fix-reversal-proof.js +107 -0
  543. package/dist/lib/shared/fix/fix-reverse.js +37 -0
  544. package/dist/lib/shared/fix/fix-safety.js +4 -4
  545. package/dist/lib/shared/fix/fix-scope.js +13 -9
  546. package/dist/lib/shared/fix/fix-source-snapshot.js +92 -0
  547. package/dist/lib/shared/fix/fix-staging.js +129 -0
  548. package/dist/lib/shared/fix/fix-terminal.js +34 -9
  549. package/dist/lib/shared/fix/fix-typecheck.js +21 -8
  550. package/dist/lib/shared/fix/fix-usage.js +47 -0
  551. package/dist/lib/shared/fix/project-file-access.js +85 -29
  552. package/dist/lib/shared/fix/read-fix-text.js +23 -0
  553. package/dist/lib/shared/fix/reversal-lock.js +37 -0
  554. package/dist/lib/shared/fix/review-fix-mode.js +9 -0
  555. package/dist/lib/shared/fix.js +157 -52
  556. package/dist/lib/shared/formats/ci-consumers.js +84 -0
  557. package/dist/lib/shared/formats/finding-location.js +52 -3
  558. package/dist/lib/shared/formats/github.js +22 -7
  559. package/dist/lib/shared/formats/index.js +21 -5
  560. package/dist/lib/shared/formats/readable.js +63 -0
  561. package/dist/lib/shared/formats/report-rows.js +38 -0
  562. package/dist/lib/shared/formats/sarif-fixes.js +261 -0
  563. package/dist/lib/shared/formats/sarif.js +175 -33
  564. package/dist/lib/shared/formats/security-cwe.js +142 -0
  565. package/dist/lib/shared/node-scan.js +64 -0
  566. package/dist/lib/shared/package-root.js +2 -0
  567. package/dist/lib/shared/project-root.js +27 -1
  568. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  569. package/dist/lib/shared/reporting/action-summary.js +31 -0
  570. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  571. package/dist/lib/shared/reporting/baseline.js +12 -12
  572. package/dist/lib/shared/reporting/check-text.js +7 -5
  573. package/dist/lib/shared/reporting/finding-id-hash.js +7 -0
  574. package/dist/lib/shared/reporting/impact-levels.js +1 -1
  575. package/dist/lib/shared/reporting/pillar-rules.js +13 -1
  576. package/dist/lib/shared/reporting/pillars.js +61 -23
  577. package/dist/lib/shared/reporting/rule-docs.js +2 -2
  578. package/dist/lib/shared/reporting/rule-pack-fingerprint.js +21 -0
  579. package/dist/lib/shared/reporting/source-report.js +20 -6
  580. package/dist/lib/shared/reporting/stray-console-methods.js +1 -0
  581. package/dist/lib/shared/rule-registry.js +6 -1
  582. package/dist/lib/shared/system/atomic-write.js +12 -6
  583. package/dist/lib/shared/system/component-source.js +28 -0
  584. package/dist/lib/shared/system/environment.js +12 -0
  585. package/dist/lib/shared/system/file-key.js +8 -0
  586. package/dist/lib/shared/system/git.js +62 -0
  587. package/dist/lib/shared/system/glob.js +233 -28
  588. package/dist/lib/shared/system/jsonc-config.js +63 -0
  589. package/dist/lib/shared/system/path-inside.js +19 -0
  590. package/dist/lib/shared/system/posix-path.js +22 -0
  591. package/dist/lib/shared/system/read-json.js +10 -0
  592. package/dist/lib/shared/system/sentry.js +6 -3
  593. package/dist/lib/shared/system/terminal-style.js +2 -2
  594. package/dist/lib/shared/system/text-helpers.js +40 -0
  595. package/dist/lib/shared/system/windows-orphans-script.js +75 -0
  596. package/dist/lib/shared/system/windows-orphans.js +28 -0
  597. package/dist/lib/shared/types/changed-lines.js +1 -0
  598. package/dist/lib/shared/types/completion.js +1 -0
  599. package/dist/lib/shared/workspace-selection.js +67 -0
  600. package/dist/lib/shared/workspaces.js +215 -68
  601. package/dist/polyglot/maintainability/rules.js +119 -3
  602. package/examples/README.md +45 -0
  603. package/examples/clean/avatar.html +1 -0
  604. package/examples/clean/source.ts +10 -0
  605. package/examples/clean/tsconfig.json +4 -0
  606. package/examples/findings/avatar.html +1 -0
  607. package/examples/findings/source.ts +11 -0
  608. package/examples/findings/tsconfig.json +4 -0
  609. package/examples/labels-clean.py +5 -0
  610. package/integrations/zed/Cargo.lock +1 -1
  611. package/integrations/zed/Cargo.toml +1 -1
  612. package/integrations/zed/LICENSE +201 -0
  613. package/integrations/zed/extension.toml +3 -3
  614. package/integrations/zed/extension.wasm +0 -0
  615. package/integrations/zed/src/lib.rs +108 -8
  616. package/package.json +28 -14
  617. package/polyglot/performance/rules/csharp.yml +173 -10
  618. package/polyglot/performance/rules/go.yml +15 -7
  619. package/polyglot/performance/rules/input.yml +12 -0
  620. package/polyglot/performance/rules/java.yml +52 -1
  621. package/polyglot/performance/rules/php.yml +146 -0
  622. package/polyglot/performance/rules/python.yml +7 -3
  623. package/polyglot/performance/rules/ruby.yml +81 -0
  624. package/polyglot/performance/sgconfig.yml +2 -0
  625. package/polyglot/reliability/rules/csharp.yml +105 -0
  626. package/polyglot/reliability/rules/go.yml +339 -0
  627. package/polyglot/reliability/rules/input.yml +6 -0
  628. package/polyglot/reliability/rules/java.yml +218 -0
  629. package/polyglot/reliability/rules/kotlin.yml +49 -0
  630. package/polyglot/reliability/rules/python.yml +288 -0
  631. package/polyglot/reliability/rules/rust.yml +83 -0
  632. package/polyglot/reliability/sgconfig.yml +1 -0
  633. package/polyglot/security/rules/csharp.yml +143 -3
  634. package/polyglot/security/rules/go.yml +59 -4
  635. package/polyglot/security/rules/java.yml +103 -0
  636. package/polyglot/security/rules/python.yml +413 -21
  637. package/polyglot/security/rules/rust.yml +176 -3
  638. package/polyglot/security/sgconfig.yml +2 -0
  639. package/polyglot/security/utils/java-imported-jca-cipher.yml +32 -0
  640. package/polyglot/security/utils/java-unshadowed-javax.yml +29 -0
  641. package/schema/loadwise.config.schema.json +1137 -600
  642. package/schema/loadwise.outcomes.schema.json +43 -0
  643. package/types/scan.d.ts +53 -0
  644. package/dist/lib/maintainability/site-fixes/exports.js +0 -25
  645. package/dist/lib/security/examples/files.cjs +0 -30
  646. package/docs/assets/cli-workflow.gif +0 -0
  647. package/plugin/.claude-plugin/plugin.json +0 -9
  648. package/plugin/commands/loadwise.md +0 -29
  649. package/plugin/hooks/check-edited-file.mjs +0 -173
  650. package/plugin/hooks/hooks.json +0 -17
  651. /package/dist/lib/{maintainability/types/changed-lines.js → editor/types/workspace-fix.js} +0 -0
@@ -0,0 +1,78 @@
1
+ import { ts } from '../performance/engine/compiler.js';
2
+ import { walkNodes } from './walk.js';
3
+ function identifierBinding(identifier, checker) {
4
+ const parent = identifier.parent;
5
+ return ts.isShorthandPropertyAssignment(parent) && parent.name === identifier
6
+ ? checker.getShorthandAssignmentValueSymbol(parent)
7
+ : checker.getSymbolAtLocation(identifier);
8
+ }
9
+ function identifiersByName(sourceFile) {
10
+ const identifiers = new Map();
11
+ walkNodes(sourceFile, (node) => {
12
+ if (!ts.isIdentifier(node))
13
+ return;
14
+ const sameName = identifiers.get(node.text);
15
+ if (sameName)
16
+ sameName.push(node);
17
+ else
18
+ identifiers.set(node.text, [node]);
19
+ });
20
+ return identifiers;
21
+ }
22
+ function indexReferencesByDeclaration(nameText, scan) {
23
+ const referencesByDeclaration = new Map();
24
+ const identifiers = (scan.identifiersByName ??= identifiersByName(scan.sourceFile));
25
+ // Resolve each spelling only on demand. Separate declarations keep shadowed names apart.
26
+ for (const node of identifiers.get(nameText) ?? []) {
27
+ for (const binding of identifierBinding(node, scan.checker)?.declarations ?? []) {
28
+ const matches = referencesByDeclaration.get(binding);
29
+ if (matches)
30
+ matches.push(node);
31
+ else
32
+ referencesByDeclaration.set(binding, [node]);
33
+ }
34
+ }
35
+ return referencesByDeclaration;
36
+ }
37
+ function references(name, declaration, scope, scan) {
38
+ let referencesByDeclaration = scan.referencesByName.get(name.text);
39
+ if (!referencesByDeclaration) {
40
+ referencesByDeclaration = indexReferencesByDeclaration(name.text, scan);
41
+ scan.referencesByName.set(name.text, referencesByDeclaration);
42
+ }
43
+ return (referencesByDeclaration.get(declaration) ?? []).filter((node) => node !== name && node.pos >= scope.pos && node.end <= scope.end);
44
+ }
45
+ function runtimeParameters(fn) {
46
+ const first = fn.parameters[0];
47
+ return first && ts.isIdentifier(first.name) && first.name.text === 'this' ? fn.parameters.slice(1) : fn.parameters;
48
+ }
49
+ function blockHasReturnOrThrow(root) {
50
+ let found = false;
51
+ const visit = (node) => {
52
+ if (found || ts.isFunctionLike(node))
53
+ return;
54
+ if (ts.isReturnStatement(node) || ts.isThrowStatement(node)) {
55
+ found = true;
56
+ return;
57
+ }
58
+ ts.forEachChild(node, visit);
59
+ };
60
+ ts.forEachChild(root, visit);
61
+ return found;
62
+ }
63
+ function hasAbruptFinallyOverride(returnNode, fn) {
64
+ let current = returnNode.parent;
65
+ while (current && current !== fn) {
66
+ const parent = current.parent;
67
+ if (parent &&
68
+ ts.isTryStatement(parent) &&
69
+ parent.finallyBlock &&
70
+ (current === parent.tryBlock || current === parent.catchClause) &&
71
+ blockHasReturnOrThrow(parent.finallyBlock)) {
72
+ return true;
73
+ }
74
+ current = parent;
75
+ }
76
+ return false;
77
+ }
78
+ export { hasAbruptFinallyOverride, identifierBinding, references, runtimeParameters };
@@ -0,0 +1,25 @@
1
+ // numeric-array-default-sort: `sort()` or `toSorted()` without a comparator orders numbers as strings. The array and
2
+ // number type proofs live with the performance sort analysis, which this rule shares.
3
+ import { ts } from '../performance/engine/compiler.js';
4
+ import { isMemberCall } from '../shared/analysis/ast-helpers.js';
5
+ import { checkDefaultNumericSort } from '../performance/collections/sort-extreme.js';
6
+ import { findingAt } from './source-helpers.js';
7
+ import { walkNodes } from './walk.js';
8
+ function checkDefaultNumericSorts(sourceFile, file, checker) {
9
+ const findings = [];
10
+ const report = (node, ruleId, message, contextualReason) => {
11
+ findings.push({
12
+ ...findingAt(sourceFile, file, node, ruleId, message),
13
+ ...(contextualReason && { contextualReason }),
14
+ });
15
+ };
16
+ walkNodes(sourceFile, (node) => {
17
+ if (!isMemberCall(node) || ts.isOptionalChain(node))
18
+ return;
19
+ const method = node.expression.name.text;
20
+ if (method === 'sort' || method === 'toSorted')
21
+ checkDefaultNumericSort(node, { checker, report });
22
+ });
23
+ return findings;
24
+ }
25
+ export { checkDefaultNumericSorts };
@@ -0,0 +1,29 @@
1
+ import { ts } from '../performance/engine/compiler.js';
2
+ import { isUnshadowedGlobal, staticPropertyName, unwrapExpression } from '../shared/analysis/ast-semantics.js';
3
+ export const errorCausePlan = Symbol('errorCausePlan');
4
+ export function planErrorCause(thrown, caughtName, checker) {
5
+ const formed = unwrapExpression(thrown);
6
+ if (!ts.isCallExpression(formed) && !ts.isNewExpression(formed))
7
+ return;
8
+ const constructor = unwrapExpression(formed.expression);
9
+ if (!isUnshadowedGlobal(constructor, 'Error', checker))
10
+ return;
11
+ const args = formed.arguments;
12
+ if (!args || args.length < 1 || args.length > 2 || args.some(ts.isSpreadElement))
13
+ return;
14
+ if (args.length === 1) {
15
+ const end = args[0].end;
16
+ return { start: end, end, text: `, { cause: ${caughtName} }` };
17
+ }
18
+ const options = unwrapExpression(args[1]);
19
+ if (!ts.isObjectLiteralExpression(options))
20
+ return;
21
+ for (const property of options.properties) {
22
+ const key = staticPropertyName(property.name);
23
+ if (!key || key === 'cause' || key === '__proto__')
24
+ return;
25
+ }
26
+ const start = options.getStart() + 1;
27
+ const suffix = options.properties.length ? ',' : options.getText()[1] === '}' ? ' ' : '';
28
+ return { start, end: start, text: ` cause: ${caughtName}${suffix}` };
29
+ }
@@ -2,9 +2,13 @@
2
2
  // value that is not an Error, and a log line that keeps the message but loses the stack.
3
3
  import { ts } from '../performance/engine/compiler.js';
4
4
  import { walkNodes } from './walk.js';
5
- import { isIgnoredSource } from './source-helpers.js';
6
- import { findingAt, insideNestedFunction, outermostWrapper } from './resource-leaks.js';
7
- import { isUnshadowedGlobal, resolveImportedBinding, staticMemberName, staticPropertyName, unwrapExpression, } from '../shared/analysis/ast-semantics.js';
5
+ import { findingAt, isIgnoredSource } from './source-helpers.js';
6
+ import { insideNestedFunction, outermostWrapper } from './resource-leaks.js';
7
+ import { errorCausePlan, planErrorCause } from './error-cause-plan.js';
8
+ import { planThrownString, throwStringPlan } from './throw-string-plan.js';
9
+ import { isUnshadowedGlobal, resolveImportedBinding, staticMemberName, staticPropertyName, symbolOf, unwrapExpression, } from '../shared/analysis/ast-semantics.js';
10
+ import { normalizeSlashes } from '../shared/system/posix-path.js';
11
+ import { isGlobalNamed } from '../shared/analysis/ast-helpers.js';
8
12
  // Only the built-in error classes: a domain or HTTP error (AppError, NotFoundException) usually translates a failure on
9
13
  // purpose, while a plain Error thrown from a catch block is just a worse copy of the original.
10
14
  const builtInError = /^(?:Error|TypeError|RangeError|SyntaxError|ReferenceError|EvalError|URIError|AggregateError)$/;
@@ -27,11 +31,8 @@ function caughtError(clause, checker) {
27
31
  return;
28
32
  return { name: binding.text, symbol: checker?.getSymbolAtLocation(binding) };
29
33
  }
30
- function isGlobal(identifier, name, checker) {
31
- return checker ? isUnshadowedGlobal(identifier, name, checker) : identifier.text === name;
32
- }
33
34
  function isGlobalErrorConstructor(identifier, checker) {
34
- if (isGlobal(identifier, identifier.text, checker))
35
+ if (isGlobalNamed(identifier, identifier.text, checker))
35
36
  return true;
36
37
  // A merged global interface adds types without introducing a different constructor.
37
38
  const declarations = checker?.getSymbolAtLocation(identifier)?.declarations ?? [];
@@ -39,18 +40,12 @@ function isGlobalErrorConstructor(identifier, checker) {
39
40
  return (declarations.some(fromDeclarationFile) &&
40
41
  declarations.every((declaration) => fromDeclarationFile(declaration) || ts.isInterfaceDeclaration(declaration)));
41
42
  }
42
- function referencedSymbol(identifier, checker) {
43
- const parent = identifier.parent;
44
- return ts.isShorthandPropertyAssignment(parent) && parent.name === identifier
45
- ? checker.getShorthandAssignmentValueSymbol(parent)
46
- : checker.getSymbolAtLocation(identifier);
47
- }
48
43
  // With a checker the binding decides, so a parameter, variable or nested catch that reuses the name is another value.
49
44
  function readsCaughtError(node, caught, clause, checker) {
50
45
  if (!ts.isIdentifier(node) || node.text !== caught.name)
51
46
  return false;
52
47
  if (checker && caught.symbol)
53
- return referencedSymbol(node, checker) === caught.symbol;
48
+ return symbolOf(node, checker) === caught.symbol;
54
49
  const isPropertyName = ts.isPropertyAccessExpression(node.parent) && node.parent.name === node;
55
50
  return !isPropertyName && !isShadowedByNestedCatch(node, caught.name, clause);
56
51
  }
@@ -75,7 +70,7 @@ function builtInErrorConstructed(thrown, checker) {
75
70
  return;
76
71
  const name = staticMemberName(callee);
77
72
  const owner = unwrapExpression(callee.expression);
78
- const isGlobalObject = ts.isIdentifier(owner) && globalObjectName.test(owner.text) && isGlobal(owner, owner.text, checker);
73
+ const isGlobalObject = ts.isIdentifier(owner) && globalObjectName.test(owner.text) && isGlobalNamed(owner, owner.text, checker);
79
74
  return name !== undefined && builtInError.test(name) && isGlobalObject ? name : undefined;
80
75
  }
81
76
  // `new Error('x', { cause: previous })` already keeps a cause, just not the caught one.
@@ -94,7 +89,7 @@ function mayCarryCause(thrown, constructorName) {
94
89
  return (ts.isObjectLiteralExpression(options) &&
95
90
  options.properties.some((property) => staticPropertyName(property.name) === 'cause'));
96
91
  }
97
- function checkRethrowWithoutCause(clause, sourceFile, file, checker, findings) {
92
+ function checkRethrowWithoutCause(clause, sourceFile, file, checker, supportsErrorOptions) {
98
93
  const caught = caughtError(clause, checker);
99
94
  // An underscore name says the value is unused on purpose; any other use in the block means the code looked at it.
100
95
  if (caught === undefined || caught.name.startsWith('_') || mentions(clause, caught, checker))
@@ -105,8 +100,17 @@ function checkRethrowWithoutCause(clause, sourceFile, file, checker, findings) {
105
100
  if (clause.block.statements.length !== 1 || !ts.isThrowStatement(statement) || !statement.expression)
106
101
  return;
107
102
  const created = builtInErrorConstructed(statement.expression, checker);
108
- if (created !== undefined && !mayCarryCause(statement.expression, created))
109
- findings.push(findingAt(sourceFile, file, statement, 'error-rethrown-without-cause', `This throws a new ${created} from a catch block without the caught error, so the original message and stack are lost. Pass it as \`{ cause: ${name} }\`.`));
103
+ if (created === undefined || mayCarryCause(statement.expression, created))
104
+ return;
105
+ const finding = findingAt(sourceFile, file, statement, 'error-rethrown-without-cause', `This throws a new ${created} from a catch block without the caught error, so the original message and stack are lost. Pass it as \`{ cause: ${name} }\`.`);
106
+ const edit = created === 'Error' && supportsErrorOptions && checker && planErrorCause(statement.expression, name, checker);
107
+ if (edit) {
108
+ // Keep the catch binding in the same hunk so application rejects a rename after the scan.
109
+ const start = clause.getStart();
110
+ const source = sourceFile.text;
111
+ finding[errorCausePlan] = { source, edit: { ...edit, start, text: source.slice(start, edit.start) + edit.text } };
112
+ }
113
+ return finding;
110
114
  }
111
115
  function nonErrorValueKind(expression, checker) {
112
116
  const value = unwrapExpression(expression);
@@ -116,7 +120,7 @@ function nonErrorValueKind(expression, checker) {
116
120
  return 'a number';
117
121
  if (ts.isPrefixUnaryExpression(value) && nonErrorValueKind(value.operand, checker) === 'a number')
118
122
  return 'a number';
119
- if (ts.isIdentifier(value) && isGlobal(value, 'undefined', checker))
123
+ if (ts.isIdentifier(value) && isGlobalNamed(value, 'undefined', checker))
120
124
  return 'undefined';
121
125
  if (ts.isObjectLiteralExpression(value))
122
126
  return 'an object literal';
@@ -133,11 +137,45 @@ function nonErrorValueKind(expression, checker) {
133
137
  : undefined;
134
138
  return undefined;
135
139
  }
136
- function checkThrowNonError(node, sourceFile, file, checker, findings) {
137
- const kind = node.expression && nonErrorValueKind(node.expression, checker);
138
- if (!kind)
140
+ function handlesLocalFallback(clause, checker) {
141
+ const final = clause.block.statements.at(-1);
142
+ if (!final || !ts.isReturnStatement(final))
143
+ return false;
144
+ if (!clause.variableDeclaration)
145
+ return true;
146
+ const binding = caughtError(clause, checker);
147
+ return binding !== undefined && !mentions(clause, binding, checker);
148
+ }
149
+ function returnsLocalFallback(node, checker, fallbackByCatch) {
150
+ let child = node;
151
+ for (let parent = node.parent; parent; parent = parent.parent) {
152
+ if (ts.isFunctionLike(parent) || ts.isClassLike(parent))
153
+ return false;
154
+ if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
155
+ const clause = parent.catchClause;
156
+ const cached = fallbackByCatch.get(clause);
157
+ if (cached !== undefined)
158
+ return cached;
159
+ const accepted = handlesLocalFallback(clause, checker);
160
+ fallbackByCatch.set(clause, accepted);
161
+ return accepted;
162
+ }
163
+ child = parent;
164
+ }
165
+ return false;
166
+ }
167
+ function checkThrowNonError(node, sourceFile, file, { checker, program, fallbackByCatch, }, findings) {
168
+ const expression = node.expression && unwrapExpression(node.expression);
169
+ const kind = expression && nonErrorValueKind(expression, checker);
170
+ if (!kind || returnsLocalFallback(node, checker, fallbackByCatch))
139
171
  return;
140
- findings.push(findingAt(sourceFile, file, node, 'throw-non-error', `This throws ${kind}, which has no stack trace and fails \`instanceof Error\` checks. Throw an Error (or a subclass) instead.`));
172
+ const finding = findingAt(sourceFile, file, node, 'throw-non-error', `This throws ${kind}, which has no stack trace and fails \`instanceof Error\` checks. Throw an Error (or a subclass) instead.`);
173
+ if (checker && program && expression && ts.isStringLiteralLike(expression)) {
174
+ const plan = planThrownString(expression, checker, program);
175
+ if (plan)
176
+ finding[throwStringPlan] = plan;
177
+ }
178
+ findings.push(finding);
141
179
  }
142
180
  function isFailureLog(node) {
143
181
  if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
@@ -225,17 +263,20 @@ function checkLoggedWithoutStack(clause, sourceFile, file, checker, findings) {
225
263
  findings.push(findingAt(sourceFile, file, logged, 'error-logged-without-stack', `This catch block logs only ${name}.message and carries on, so the stack trace and any cause are lost. Log the error itself (for example \`logger.error({ err: ${name} }, ...)\`) or rethrow it.`));
226
264
  }
227
265
  // Without a checker, names stand for their globals and catch-variable references are matched by name.
228
- function checkErrorValues(sourceFile, file, checker) {
229
- if (isIgnoredSource(sourceFile, file) || looseFolder.test(file.replaceAll('\\', '/')))
266
+ function checkErrorValues(sourceFile, file, checker, supportsErrorOptions = false, program) {
267
+ if (isIgnoredSource(sourceFile, file) || looseFolder.test(normalizeSlashes(file)))
230
268
  return [];
231
269
  const findings = [];
270
+ const throwContext = { checker, program, fallbackByCatch: new WeakMap() };
232
271
  walkNodes(sourceFile, (node) => {
233
272
  if (ts.isCatchClause(node)) {
234
- checkRethrowWithoutCause(node, sourceFile, file, checker, findings);
273
+ const rethrow = checkRethrowWithoutCause(node, sourceFile, file, checker, supportsErrorOptions);
274
+ if (rethrow)
275
+ findings.push(rethrow);
235
276
  checkLoggedWithoutStack(node, sourceFile, file, checker, findings);
236
277
  }
237
278
  else if (ts.isThrowStatement(node))
238
- checkThrowNonError(node, sourceFile, file, checker, findings);
279
+ checkThrowNonError(node, sourceFile, file, throwContext, findings);
239
280
  });
240
281
  return findings;
241
282
  }
@@ -0,0 +1,368 @@
1
+ import { ts } from '../performance/engine/compiler.js';
2
+ import { walkNodes } from './walk.js';
3
+ import { findingAt, isIgnoredSource } from './source-helpers.js';
4
+ const RULE_ID = 'unchecked-json-cast';
5
+ const TYPESCRIPT_FILE = /\.[cm]?tsx?$/i;
6
+ const REQUEST_NAME = /^req(?:uest)?$/;
7
+ // Methods that check a value against a schema: zod, valibot, yup, joi, superstruct, io-ts, typia, ajv, TypeBox.
8
+ const VALIDATING_METHODS = new Set([
9
+ 'parse',
10
+ 'parseAsync',
11
+ 'safeParse',
12
+ 'safeParseAsync',
13
+ 'validate',
14
+ 'validateSync',
15
+ 'validateAsync',
16
+ 'assert',
17
+ 'assertEquals',
18
+ 'is',
19
+ 'check',
20
+ 'Check',
21
+ 'decode',
22
+ 'cast',
23
+ ]);
24
+ // class-validator and class-transformer functions, plus named guards such as `isUser(value)` or `parseUser(value)`.
25
+ const VALIDATING_FUNCTIONS = new Set([
26
+ 'validate',
27
+ 'validateSync',
28
+ 'validateOrReject',
29
+ 'plainToInstance',
30
+ 'plainToClass',
31
+ ]);
32
+ const VALIDATING_FUNCTION_NAME = /^(?:is|assert|validate|parse|ensure)[A-Z]/;
33
+ // celebrate and express-validator middleware passed next to a route handler.
34
+ const ROUTE_VALIDATORS = new Set(['celebrate', 'checkSchema', 'body']);
35
+ const NUMBER_PARSERS = new Set(['parseInt', 'parseFloat']);
36
+ const NARROWING_CHECK = /\btypeof\b|\binstanceof\b|\bisArray\(|\bisBuffer\(/;
37
+ // Targets that claim nothing beyond what the parser already guarantees.
38
+ const UNCLAIMED_TARGETS = new Set([
39
+ ts.SyntaxKind.UnknownKeyword,
40
+ ts.SyntaxKind.AnyKeyword,
41
+ ts.SyntaxKind.StringKeyword,
42
+ ts.SyntaxKind.NumberKeyword,
43
+ ts.SyntaxKind.BooleanKeyword,
44
+ ts.SyntaxKind.ObjectKeyword,
45
+ ]);
46
+ const LOCAL_REASON = 'The value comes from parsed text or a response body, not directly from a request; check whether its source is trusted.';
47
+ const GENERIC_REASON = 'The cast is to a type parameter, so the caller chooses the type and owns the check.';
48
+ function isJsonCall(call, method) {
49
+ const callee = call.expression;
50
+ return (ts.isPropertyAccessExpression(callee) &&
51
+ ts.isIdentifier(callee.expression) &&
52
+ callee.expression.text === 'JSON' &&
53
+ callee.name.text === method);
54
+ }
55
+ // The receiver of a body read such as `response.json()`.
56
+ function jsonBodyReceiver(node) {
57
+ if (!ts.isCallExpression(node) || node.arguments.length > 0)
58
+ return undefined;
59
+ const callee = node.expression;
60
+ return ts.isPropertyAccessExpression(callee) && callee.name.text === 'json' ? callee.expression : undefined;
61
+ }
62
+ function bindsName(name, text) {
63
+ if (ts.isIdentifier(name))
64
+ return name.text === text;
65
+ return name.elements.some((element) => !ts.isOmittedExpression(element) && bindsName(element.name, text));
66
+ }
67
+ // A handler receives its request as a parameter; a local `req` is usually a fetch response.
68
+ function isParameterName(identifier) {
69
+ for (let ancestor = identifier.parent; ancestor; ancestor = ancestor.parent) {
70
+ if (ts.isFunctionLike(ancestor) && ancestor.parameters.some(({ name }) => bindsName(name, identifier.text))) {
71
+ return true;
72
+ }
73
+ }
74
+ return false;
75
+ }
76
+ function isRequestReceiver(node) {
77
+ const receiver = ts.skipOuterExpressions(node);
78
+ if (ts.isIdentifier(receiver))
79
+ return REQUEST_NAME.test(receiver.text) && isParameterName(receiver);
80
+ // Koa keeps the request one level down: `ctx.request.body`.
81
+ return ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'request';
82
+ }
83
+ // `req.body`, `ctx.request.body`, and a Lambda `event.body` string.
84
+ function isRequestBody(node) {
85
+ const body = ts.skipOuterExpressions(node);
86
+ if (!ts.isPropertyAccessExpression(body) || body.name.text !== 'body')
87
+ return false;
88
+ const receiver = ts.skipOuterExpressions(body.expression);
89
+ return (isRequestReceiver(receiver) || (ts.isIdentifier(receiver) && receiver.text === 'event' && isParameterName(receiver)));
90
+ }
91
+ function jsonSourceOf(expression, target) {
92
+ const value = ts.skipOuterExpressions(expression);
93
+ if (ts.isCallExpression(value) && isJsonCall(value, 'parse')) {
94
+ const text = value.arguments[0] && ts.skipOuterExpressions(value.arguments[0]);
95
+ // `JSON.parse(JSON.stringify(value))` clones a value the program already typed.
96
+ if (text && ts.isCallExpression(text) && isJsonCall(text, 'stringify'))
97
+ return undefined;
98
+ return { source: 'parsed JSON', fromRequest: text !== undefined && isRequestBody(text) };
99
+ }
100
+ if (isRequestBody(value))
101
+ return { source: 'request body', fromRequest: true };
102
+ const awaited = ts.isAwaitExpression(value) ? ts.skipOuterExpressions(value.expression) : undefined;
103
+ const isPromiseTarget = ts.isTypeReferenceNode(target) && ts.isIdentifier(target.typeName) && target.typeName.text === 'Promise';
104
+ const bodyCall = awaited ?? (isPromiseTarget ? value : undefined);
105
+ const receiver = bodyCall && jsonBodyReceiver(bodyCall);
106
+ if (!receiver)
107
+ return undefined;
108
+ const fromRequest = isRequestReceiver(receiver);
109
+ return { source: fromRequest ? 'request body' : 'response body', fromRequest };
110
+ }
111
+ function isUntypedValue(type) {
112
+ return type.kind === ts.SyntaxKind.UnknownKeyword || type.kind === ts.SyntaxKind.AnyKeyword;
113
+ }
114
+ function isUnknownRecord(target) {
115
+ if (ts.isArrayTypeNode(target))
116
+ return isUntypedValue(target.elementType);
117
+ if (!ts.isTypeReferenceNode(target) || !ts.isIdentifier(target.typeName))
118
+ return false;
119
+ const name = target.typeName.text;
120
+ const values = target.typeArguments ?? [];
121
+ if (name === 'Promise' && values.length === 1)
122
+ return claimsNothing(values[0]);
123
+ // `Partial<T>` announces that every field is checked before use.
124
+ if (name === 'Partial')
125
+ return true;
126
+ return name === 'Record' && values.length === 2 && isUntypedValue(values[1]);
127
+ }
128
+ function claimsNothing(target) {
129
+ const type = ts.isParenthesizedTypeNode(target) ? target.type : target;
130
+ if (ts.isUnionTypeNode(type))
131
+ return type.types.every((member) => isNullish(member) || claimsNothing(member));
132
+ // `{ id?: unknown }` names fields without claiming their types.
133
+ if (ts.isTypeLiteralNode(type)) {
134
+ return type.members.every((member) => ts.isPropertySignature(member) && member.type?.kind === ts.SyntaxKind.UnknownKeyword);
135
+ }
136
+ return UNCLAIMED_TARGETS.has(type.kind) || isUnknownRecord(type);
137
+ }
138
+ function isNullish(type) {
139
+ if (type.kind === ts.SyntaxKind.UndefinedKeyword)
140
+ return true;
141
+ return ts.isLiteralTypeNode(type) && type.literal.kind === ts.SyntaxKind.NullKeyword;
142
+ }
143
+ function isTypeParameterTarget(target, at) {
144
+ if (!ts.isTypeReferenceNode(target) || !ts.isIdentifier(target.typeName))
145
+ return false;
146
+ const name = target.typeName.text;
147
+ for (let ancestor = at.parent; ancestor; ancestor = ancestor.parent) {
148
+ if (!ts.isFunctionLike(ancestor) && !ts.isClassLike(ancestor))
149
+ continue;
150
+ if (ancestor.typeParameters?.some((parameter) => parameter.name.text === name))
151
+ return true;
152
+ }
153
+ return false;
154
+ }
155
+ function isValidatingCall(call) {
156
+ const callee = ts.skipOuterExpressions(call.expression);
157
+ if (ts.isPropertyAccessExpression(callee)) {
158
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === 'JSON')
159
+ return false;
160
+ return VALIDATING_METHODS.has(callee.name.text);
161
+ }
162
+ if (!ts.isIdentifier(callee) || NUMBER_PARSERS.has(callee.text))
163
+ return false;
164
+ return VALIDATING_FUNCTIONS.has(callee.text) || VALIDATING_FUNCTION_NAME.test(callee.text);
165
+ }
166
+ const validatedScopes = new WeakMap();
167
+ function scopeValidates(scope) {
168
+ const cached = validatedScopes.get(scope);
169
+ if (cached !== undefined)
170
+ return cached;
171
+ let validates = false;
172
+ walkNodes(scope, (node) => {
173
+ validates = ts.isCallExpression(node) && isValidatingCall(node);
174
+ return validates;
175
+ });
176
+ validatedScopes.set(scope, validates);
177
+ return validates;
178
+ }
179
+ // The value of a static property `name: value`, `'name': value` or shorthand `{ name }`.
180
+ function propertyValue(literal, name) {
181
+ if (!ts.isObjectLiteralExpression(literal))
182
+ return undefined;
183
+ for (const property of literal.properties) {
184
+ if (ts.isShorthandPropertyAssignment(property) && property.name.text === name)
185
+ return property.name;
186
+ const staticName = ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name));
187
+ if (staticName && property.name.text === name)
188
+ return property.initializer;
189
+ }
190
+ return undefined;
191
+ }
192
+ function declarationBinding(declarations, text) {
193
+ return declarations.find((declaration) => (ts.isVariableDeclaration(declaration) || ts.isParameter(declaration)) && bindsName(declaration.name, text));
194
+ }
195
+ // `var` declarations hoist to the enclosing function or file, whatever block they sit in.
196
+ function hoistedVarBinding(scope, text) {
197
+ let found;
198
+ const visit = (node) => {
199
+ if (found || (node !== scope && ts.isFunctionLike(node)))
200
+ return;
201
+ if (ts.isVariableDeclarationList(node) && !(node.flags & ts.NodeFlags.BlockScoped)) {
202
+ found = declarationBinding(node.declarations, text);
203
+ }
204
+ ts.forEachChild(node, visit);
205
+ };
206
+ visit(scope);
207
+ return found;
208
+ }
209
+ function statementBinding(statement, text) {
210
+ if (ts.isVariableStatement(statement))
211
+ return declarationBinding(statement.declarationList.declarations, text);
212
+ if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name?.text === text) {
213
+ return statement;
214
+ }
215
+ const clause = ts.isImportDeclaration(statement) ? statement.importClause : undefined;
216
+ if (!clause)
217
+ return undefined;
218
+ const named = clause.namedBindings;
219
+ const importsName = clause.name?.text === text ||
220
+ (named && ts.isNamespaceImport(named)
221
+ ? named.name.text === text
222
+ : named?.elements.some((item) => item.name.text === text));
223
+ return importsName ? statement : undefined;
224
+ }
225
+ function firstStatementBinding(statements, text) {
226
+ for (const statement of statements) {
227
+ const binding = statementBinding(statement, text);
228
+ if (binding)
229
+ return binding;
230
+ }
231
+ return undefined;
232
+ }
233
+ // The declaration that `text` binds to directly inside one lexical scope, if any.
234
+ function bindingInScope(scope, text) {
235
+ if (ts.isFunctionLike(scope)) {
236
+ return declarationBinding(scope.parameters, text) ?? hoistedVarBinding(scope, text);
237
+ }
238
+ if (ts.isSourceFile(scope) || ts.isBlock(scope) || ts.isModuleBlock(scope)) {
239
+ const own = firstStatementBinding(scope.statements, text);
240
+ return own ?? (ts.isSourceFile(scope) ? hoistedVarBinding(scope, text) : undefined);
241
+ }
242
+ if (ts.isCaseBlock(scope))
243
+ return firstStatementBinding(scope.clauses.flatMap((clause) => [...clause.statements]), text);
244
+ if (ts.isCatchClause(scope)) {
245
+ return scope.variableDeclaration ? declarationBinding([scope.variableDeclaration], text) : undefined;
246
+ }
247
+ const isLoop = ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope);
248
+ const initializer = isLoop ? scope.initializer : undefined;
249
+ if (!initializer || !ts.isVariableDeclarationList(initializer))
250
+ return undefined;
251
+ return declarationBinding(initializer.declarations, text);
252
+ }
253
+ // Resolves `schema` to the innermost binding in scope at the reference, then accepts it only when it is
254
+ // `const schema = { ... }`, so a shadowing parameter or variable never borrows another scope's schema.
255
+ function constObjectNamed(identifier) {
256
+ if (!ts.isIdentifier(identifier))
257
+ return undefined;
258
+ for (let scope = identifier.parent; scope; scope = scope.parent) {
259
+ const declaration = bindingInScope(scope, identifier.text);
260
+ if (!declaration)
261
+ continue;
262
+ if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name))
263
+ return undefined;
264
+ const isConst = (declaration.parent.flags & ts.NodeFlags.Const) !== 0;
265
+ return isConst && declaration.initializer ? ts.skipOuterExpressions(declaration.initializer) : undefined;
266
+ }
267
+ return undefined;
268
+ }
269
+ // Fastify route options: `{ schema: { body: BodySchema } }`, or `{ schema }` naming a const with a `body` key.
270
+ function hasBodySchema(options) {
271
+ const schema = propertyValue(options, 'schema');
272
+ if (schema === undefined)
273
+ return false;
274
+ return propertyValue(constObjectNamed(schema) ?? schema, 'body') !== undefined;
275
+ }
276
+ function containsRouteValidator(middleware) {
277
+ let found = false;
278
+ walkNodes(middleware, (node) => {
279
+ if (!ts.isCallExpression(node))
280
+ return false;
281
+ const callee = ts.skipOuterExpressions(node.expression);
282
+ found = isValidatingCall(node) || (ts.isIdentifier(callee) && ROUTE_VALIDATORS.has(callee.text));
283
+ return found;
284
+ });
285
+ return found;
286
+ }
287
+ // `router.post('/', validate(schema), handler)`, `fastify.post('/', { schema: { body } }, handler)` and
288
+ // `fastify.route({ schema: { body }, handler })` validate the body before the handler runs.
289
+ function routeValidates(handler) {
290
+ const { parent } = handler;
291
+ if (!parent)
292
+ return false;
293
+ if (ts.isPropertyAssignment(parent))
294
+ return hasBodySchema(parent.parent);
295
+ if (!ts.isCallExpression(parent) || !parent.arguments.some((argument) => argument === handler))
296
+ return false;
297
+ return parent.arguments.some((argument) => argument !== handler && (hasBodySchema(argument) || containsRouteValidator(argument)));
298
+ }
299
+ function narrows(condition, castText) {
300
+ const text = condition.getText();
301
+ return NARROWING_CHECK.test(text) && text.includes(castText);
302
+ }
303
+ function exits(statement) {
304
+ if (ts.isBlock(statement)) {
305
+ const last = statement.statements.at(-1);
306
+ return last !== undefined && exits(last);
307
+ }
308
+ return (ts.isReturnStatement(statement) ||
309
+ ts.isThrowStatement(statement) ||
310
+ ts.isContinueStatement(statement) ||
311
+ ts.isBreakStatement(statement));
312
+ }
313
+ // `if (typeof req.body !== 'object') return;` before the cast rejects every value the cast would mistype.
314
+ function hasRejectionGuardBefore(parent, child, castText) {
315
+ if (!ts.isBlock(parent) && !ts.isSourceFile(parent) && !ts.isCaseOrDefaultClause(parent))
316
+ return false;
317
+ const statements = parent.statements;
318
+ const index = statements.findIndex((statement) => statement === child);
319
+ return statements
320
+ .slice(0, index)
321
+ .some((statement) => ts.isIfStatement(statement) &&
322
+ !statement.elseStatement &&
323
+ exits(statement.thenStatement) &&
324
+ narrows(statement.expression, castText));
325
+ }
326
+ // `if (typeof req.body === 'string') return req.body as string` casts a value the condition already checked.
327
+ function isNarrowedBranch(cast) {
328
+ const castText = ts.skipOuterExpressions(cast.expression).getText();
329
+ for (let child = cast, parent = cast.parent; parent; child = parent, parent = parent.parent) {
330
+ if (ts.isFunctionLike(parent))
331
+ return false;
332
+ const condition = (ts.isIfStatement(parent) && parent.thenStatement === child && parent.expression) ||
333
+ (ts.isConditionalExpression(parent) && parent.whenTrue === child && parent.condition);
334
+ if (condition && narrows(condition, castText))
335
+ return true;
336
+ if (hasRejectionGuardBefore(parent, child, castText))
337
+ return true;
338
+ }
339
+ return false;
340
+ }
341
+ function checkJsonCasts(sourceFile, file) {
342
+ if (!TYPESCRIPT_FILE.test(file) || isIgnoredSource(sourceFile, file))
343
+ return [];
344
+ if (!/\bJSON\.parse\b|\.json\(\)|\.body\b/.test(sourceFile.text))
345
+ return [];
346
+ const findings = [];
347
+ walkNodes(sourceFile, (node) => {
348
+ if (!ts.isAsExpression(node) && !ts.isTypeAssertionExpression(node))
349
+ return;
350
+ if (claimsNothing(node.type))
351
+ return;
352
+ const origin = jsonSourceOf(node.expression, node.type);
353
+ if (!origin || isNarrowedBranch(node))
354
+ return;
355
+ const scope = ts.findAncestor(node.parent, ts.isFunctionLike) ?? sourceFile;
356
+ if (scopeValidates(scope) || routeValidates(scope))
357
+ return;
358
+ const finding = findingAt(sourceFile, file, node, RULE_ID, `The ${origin.source} is cast to \`${node.type.getText(sourceFile)}\` without being checked, so a missing or wrongly typed field passes the compiler and fails later, far from here. Validate it with a schema (zod, valibot, joi, typia) or a type guard before use.`);
359
+ const contextualReason = isTypeParameterTarget(node.type, node)
360
+ ? GENERIC_REASON
361
+ : origin.fromRequest
362
+ ? undefined
363
+ : LOCAL_REASON;
364
+ findings.push(contextualReason ? { ...finding, contextualReason } : finding);
365
+ });
366
+ return findings;
367
+ }
368
+ export { checkJsonCasts };