loadwise 0.5.1 → 0.6.1

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 (132) hide show
  1. package/PERFORMANCE.md +31 -6
  2. package/README.md +580 -1024
  3. package/bin/loadwise.js +4 -0
  4. package/lib/accessibility/frontend-detect.js +2 -1
  5. package/lib/accessibility/rule-ids.js +12 -9
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +9 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +6 -0
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +25 -17
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -1,6 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.standaloneExamples = void 0;
4
1
  const sqlExample = (before, after, note) => ({
5
2
  language: 'sql',
6
3
  before,
@@ -23,78 +20,54 @@ const contractExample = (language, before, after, note) => ({
23
20
  code: after,
24
21
  note,
25
22
  });
23
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
26
24
  const standaloneExamples = {
27
- 'duplicate-key-read': {
28
- language: 'javascript',
29
- before: 'const user = await cache.get(key);\nconst again = await cache.get(key); // same key, same request',
30
- code: 'const user = await cache.get(key);\n// reuse `user` for the rest of this request',
31
- note: 'Reuse the first result only when freshness, ordering and authorization allow it; otherwise keep the separate read.',
32
- },
33
- 'repeated-db-span': {
34
- language: 'javascript',
35
- before: "for (const id of ids) await db.query('SELECT * FROM users WHERE id = $1', [id]);",
36
- code: "const { rows } = await db.query('SELECT * FROM users WHERE id = ANY($1)', [ids]);",
37
- note: 'Batch repeated lookups into one statement and keep the original scope predicates.',
38
- },
39
- 'redis-keys-scan': {
40
- language: 'javascript',
41
- before: "const keys = await redis.keys('session:*');",
42
- code: "for await (const key of redis.scanIterator({ MATCH: 'session:*', COUNT: 100 })) await handle(key);",
43
- note: 'KEYS blocks Redis while it walks the whole keyspace; SCAN is incremental. ioredis offers scanStream.',
44
- },
45
- 'redis-repeated-read': {
46
- language: 'javascript',
47
- before: "for (const id of ids) values.push(await redis.get('user:' + id));",
48
- code: "const values = await redis.mGet(ids.map((id) => 'user:' + id));",
49
- note: 'One MGET replaces one round trip per key. ioredis spells it mget; use a pipeline for HGET.',
50
- },
51
- 'redis-command-in-loop': {
52
- language: 'javascript',
53
- before: "for (const id of ids) await redis.get('user:' + id);",
54
- code: "const values = await redis.mGet(ids.map((id) => 'user:' + id));",
55
- note: 'Use a multi-key command or a pipeline. Ignore if each command depends on the previous reply.',
56
- },
57
- 'password-hash-sync-in-async': {
58
- language: 'javascript',
59
- before: 'const hash = bcrypt.hashSync(password, 10);',
60
- code: 'const hash = await bcrypt.hash(password, 10);\nconst matches = await bcrypt.compare(password, hash);',
61
- note: 'The synchronous hash blocks the event loop for every other request. Keep the same cost factor.',
25
+ 'angular-default-change-detection': {
26
+ language: 'typescript',
27
+ before: "@Component({ selector: 'x' })\nclass X {}",
28
+ code: "@Component({ selector: 'x', changeDetection: ChangeDetectionStrategy.OnPush })\nclass X {}",
29
+ note: 'Check inputs are not mutated in place first.',
62
30
  },
63
- 'serial-awaits-in-literal': {
64
- language: 'javascript',
65
- before: 'const [posts, accounts] = [await syncPosts(), await syncAccounts()];',
66
- code: 'const [posts, accounts] = await Promise.all([syncPosts(), syncAccounts()]);',
67
- note: 'Awaits inside a literal still run one after the other, so the wait is the sum. Keep them serial if one depends on the other.',
31
+ 'angular-ngfor-missing-trackby': {
32
+ language: 'typescript',
33
+ before: '@Component({ template: \'<li *ngFor="let item of items"></li>\' })\nclass List {}',
34
+ code: '@Component({ template: \'<li *ngFor="let item of items; trackBy: trackById"></li>\' })\nclass List { trackById(index: number, item: { id: string }) { return item.id; } }',
35
+ note: 'Return a stable identifier from trackBy.',
68
36
  },
69
- 'typeorm-load-then-save': {
70
- language: 'javascript',
71
- before: 'const user = await users.findOneBy({ id });\nuser.lastLoginAt = new Date();\nuser.tokenVersion += 1;\nawait users.save(user);',
72
- code: "await users.increment({ id }, 'tokenVersion', 1);\nawait users.update({ id }, { lastLoginAt: new Date() });",
73
- note: 'save() of a loaded entity costs a SELECT, an UPDATE and a transaction. update() skips entity listeners.',
37
+ 'angular-subscribe-without-cleanup': {
38
+ language: 'typescript',
39
+ before: 'interval(1000).subscribe(tick);',
40
+ code: 'interval(1000).pipe(takeUntilDestroyed()).subscribe(tick);',
41
+ note: 'End the subscription with the component.',
74
42
  },
75
- 'queue-add-in-loop': {
43
+ 'api-enum-value-removed': contractExample('typescript', "type Status = 'open' | 'closed' | 'archived';", "type Status = 'open' | 'closed' | 'archived'; // keep accepting 'archived'", 'Keep accepting the old value (map it to the new one) until clients stop sending it.'),
44
+ 'api-removed-field': contractExample('typescript', 'class UserDto {\n name: string;\n}', 'class UserDto {\n name: string;\n /** @deprecated read name */\n fullName?: string;\n}', 'Deprecate a response field first and remove it after clients stop reading it.'),
45
+ 'api-removed-operation': contractExample('graphql', 'type Query {\n user(id: ID!): User\n}', 'type Query {\n user(id: ID!): User\n userV2(id: ID!): User\n}', 'Keep the old operation (or serve /v1 beside a new /v2) until no deployed client calls it.'),
46
+ 'api-required-input': contractExample('typescript', 'class CreateUserDto {\n nickname?: string;\n}', 'class CreateUserDto {\n nickname?: string;\n}\n// make it required only in a new API version', 'A newly required input rejects every client that has not been updated; give it a default or version the API.'),
47
+ 'api-type-changed': contractExample('typescript', 'class OrderDto {\n total: number;\n}', 'class OrderDto {\n total: number;\n totalText: string;\n}', 'Add a new field for the new type and keep the old one until clients migrate.'),
48
+ 'async-callback-unhandled-rejection': {
76
49
  language: 'javascript',
77
- before: "for (const id of ids) await queue.add('render', { id });",
78
- code: "await queue.addBulk(ids.map((id) => ({ name: 'render', data: { id } })));",
79
- note: 'addBulk sends every job in one Redis call instead of one round trip per job.',
50
+ before: 'setInterval(async () => {\n await syncAccounts();\n}, 60_000);',
51
+ code: 'setInterval(async () => {\n try {\n await syncAccounts();\n } catch (error) { logger.error(error); }\n}, 60_000);',
52
+ note: 'Nothing awaits a callback timers and emitters call, so its rejection is unhandled unless the callback catches it.',
80
53
  },
81
- 'prisma-distinct-in-memory': {
54
+ 'async-route-unhandled-rejection': {
82
55
  language: 'javascript',
83
- before: "await prisma.product.findMany({ where, select: { storeId: true }, distinct: ['storeId'] });",
84
- code: "await prisma.product.groupBy({ by: ['storeId'], where });",
85
- note: 'Prisma applies distinct after reading every matching row; groupBy dedupes in SQL. Not needed with the nativeDistinct preview feature.',
56
+ before: "app.get('/users', async (req, res) => {\n res.json(await loadUsers());\n});",
57
+ code: "app.get('/users', async (req, res, next) => {\n try {\n res.json(await loadUsers());\n } catch (error) { next(error); }\n});",
58
+ note: 'Express 4 ignores the promise a handler returns; passing the error to next reaches the error middleware.',
86
59
  },
87
- 'prisma-relation-count-in-list': {
60
+ 'await-before-early-exit': {
88
61
  language: 'javascript',
89
- before: 'await prisma.brand.findMany({ take: 20, include: { _count: { select: { products: true } } } });',
90
- code: "const brands = await prisma.brand.findMany({ take: 20 });\nconst counts = await prisma.product.groupBy({\n by: ['brandId'],\n where: { brandId: { in: brands.map((brand) => brand.id) } },\n _count: { _all: true },\n});",
91
- note: 'The _count join groups the whole related table, not just the page. Counting only the page ids keeps the cost tied to take.',
62
+ before: "const user = await prisma.user.findUnique({ where: { id } });\nif (!dto.name) throw new BadRequestException('name required');",
63
+ code: "if (!dto.name) throw new BadRequestException('name required');\nconst user = await prisma.user.findUnique({ where: { id } });",
64
+ note: 'Run the guard before the read it does not use. Keep the order when the read is there for its own error or timing.',
92
65
  },
93
- 'guard-query-per-request': {
94
- language: 'javascript',
95
- before: 'async function canActivate(context) {\n const user = await this.users.findOne({ where: { id } });\n}',
96
- code: 'async function canActivate(context) {\n const user = await this.userCache.wrap(id, () => this.users.findOne({ where: { id } }), 60_000);\n}',
97
- note: 'A global guard runs this query before every handler. Cache it by id with a short TTL and invalidate it when the user changes.',
66
+ 'check-then-update-race': {
67
+ language: 'typescript',
68
+ before: 'account.balance -= amount; await account.save();',
69
+ code: 'await Account.updateOne({ _id: id, balance: { $gte: amount } }, { $inc: { balance: -amount } });',
70
+ note: 'Let the database apply the change atomically.',
98
71
  },
99
72
  'count-then-page-serial': {
100
73
  language: 'javascript',
@@ -102,41 +75,63 @@ const standaloneExamples = {
102
75
  code: 'const [rows, total] = await qb.skip(offset).take(limit).getManyAndCount();',
103
76
  note: 'The page waits for the count, so one list costs two round trips. Prisma has no combined call; run both with Promise.all.',
104
77
  },
105
- 'await-before-early-exit': {
106
- language: 'javascript',
107
- before: "const user = await prisma.user.findUnique({ where: { id } });\nif (!dto.name) throw new BadRequestException('name required');",
108
- code: "if (!dto.name) throw new BadRequestException('name required');\nconst user = await prisma.user.findUnique({ where: { id } });",
109
- note: 'Run the guard before the read it does not use. Keep the order when the read is there for its own error or timing.',
110
- },
78
+ 'db-duplicate-index': sqlExample('CREATE INDEX a_idx ON orders (customer_id);\nCREATE INDEX b_idx ON orders (customer_id);', 'DROP INDEX CONCURRENTLY b_idx;', 'Keep one of two identical indexes. An index that is a prefix of another is also redundant.'),
79
+ 'db-missing-index': sqlExample('SELECT id FROM orders WHERE customer_id = $1;', foreignKeyIndex, 'Check that the write cost of one more index is acceptable for this table.'),
80
+ 'db-seq-scan-heavy-table': sqlExample('SELECT relname, seq_scan, idx_scan FROM pg_stat_user_tables ORDER BY seq_scan DESC;', foreignKeyIndex, 'Find the queries scanning this table (pg_stat_statements) and index their filter columns.'),
81
+ 'db-slow-query-plan': sqlExample('EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = $1;', foreignKeyIndex, 'Add the index the plan lacks, or rewrite the query, then compare the plan.'),
82
+ 'db-unindexed-foreign-key': sqlExample(foreignKeyBefore, foreignKeyIndex, foreignKeyNote),
83
+ 'db-unused-index': sqlExample('SELECT indexrelname FROM pg_stat_user_indexes WHERE idx_scan = 0;', 'DROP INDEX CONCURRENTLY orders_legacy_idx;', 'Confirm on every replica over a full business cycle, and that no constraint depends on the index.'),
111
84
  'discarded-error-result': {
112
85
  language: 'javascript',
113
86
  before: 'await updateProvider();',
114
87
  code: "const result = await updateProvider();\nif (result._tag === 'Left') return result;",
115
88
  note: 'This fp-ts Either example forwards the failure to a caller that handles it. Keep the success path after the guard.',
116
89
  },
117
- 'promise-return-escapes-catch': {
118
- language: 'javascript',
119
- before: 'try {\n return loadProfile();\n} catch (error) {\n return respondToFailure(error);\n}',
120
- code: 'try {\n return await loadProfile();\n} catch (error) {\n return respondToFailure(error);\n}',
121
- note: 'Await inside the protected try block when its catch is responsible for handling the rejection.',
90
+ 'dom-layout-thrashing': {
91
+ language: 'typescript',
92
+ before: "for (const el of els) { const w = el.offsetWidth; el.style.width = w + 1 + 'px'; }",
93
+ code: "const widths = els.map((el) => el.offsetWidth); els.forEach((el, i) => { el.style.width = widths[i] + 1 + 'px'; });",
94
+ note: 'Batch reads before writes.',
122
95
  },
123
- 'return-in-finally': {
96
+ 'dom-listener-without-cleanup': {
97
+ language: 'typescript',
98
+ before: "window.addEventListener('online', () => sync());",
99
+ code: "window.addEventListener('online', () => sync(), { signal: controller.signal });",
100
+ note: 'Make the listener removable.',
101
+ },
102
+ 'dom-unthrottled-scroll-resize': {
103
+ language: 'typescript',
104
+ before: "window.addEventListener('wheel', onWheel);",
105
+ code: "window.addEventListener('wheel', onWheel, { passive: true });",
106
+ note: 'Passive listeners, and throttle work with requestAnimationFrame.',
107
+ },
108
+ 'duplicate-key-read': {
124
109
  language: 'javascript',
125
- before: 'try {\n return readValue();\n} finally {\n return release();\n}',
126
- code: 'try {\n return readValue();\n} finally {\n release();\n}',
127
- note: 'Keep cleanup in finally so the caller receives the original return value or error.',
110
+ before: 'const user = await cache.get(key);\nconst again = await cache.get(key); // same key, same request',
111
+ code: 'const user = await cache.get(key);\n// reuse `user` for the rest of this request',
112
+ note: 'Reuse the first result only when freshness, ordering and authorization allow it; otherwise keep the separate read.',
128
113
  },
129
- 'return-newline': {
114
+ 'express-missing-compression': {
130
115
  language: 'javascript',
131
- before: 'function read() {\n return\n ({ value: 1 });\n}',
132
- code: 'function read() {\n return { value: 1 };\n}',
133
- note: 'Start the expression on the same line as return to prevent automatic semicolon insertion.',
116
+ before: 'const app = express(); app.listen(3000);',
117
+ code: "import compression from 'compression';\nconst app = express();\napp.use(compression());\napp.listen(3000);",
118
+ note: 'Compresses JSON and HTML responses on the wire; skip if your reverse proxy already compresses responses.',
134
119
  },
135
- 'floating-promise': {
120
+ 'external-call-in-transaction': {
136
121
  language: 'javascript',
137
- before: 'sendWelcomeEmail(user.email);',
138
- code: 'await sendWelcomeEmail(user.email);\n// or, on purpose in the background:\nvoid sendWelcomeEmail(user.email).catch((error) => logger.error(error));',
139
- note: 'An unawaited rejection is unhandled and can stop the process. List deliberate background helpers under fireAndForget in the policy.',
122
+ before: [
123
+ 'await prisma.$transaction(async (tx) => {',
124
+ ' await tx.order.create({ data });',
125
+ ' await fetch(webhookUrl, { method: "POST" });',
126
+ '});',
127
+ ].join('\n'),
128
+ code: [
129
+ 'await prisma.$transaction(async (tx) => {',
130
+ ' await tx.order.create({ data });',
131
+ '});',
132
+ 'await fetch(webhookUrl, { method: "POST" }); // after commit',
133
+ ].join('\n'),
134
+ note: 'The transaction holds a pool connection and its locks for the whole network call. Make the call after commit, or before the transaction when the write needs its result.',
140
135
  },
141
136
  'find-then-create-race': {
142
137
  language: 'javascript',
@@ -144,47 +139,53 @@ const standaloneExamples = {
144
139
  code: 'await prisma.user.upsert({ where: { email }, update: {}, create: { email } });',
145
140
  note: 'Needs a unique constraint on email; two requests can otherwise both find nothing and both insert. Or insert and catch P2002.',
146
141
  },
147
- 'redis-keys-command': {
142
+ 'floating-promise': {
148
143
  language: 'javascript',
149
- before: "const keys = await redis.keys('session:*');",
150
- code: "const keys = [];\nfor await (const batch of redis.scanStream({ match: 'session:*', count: 100 })) keys.push(...batch);",
151
- note: 'KEYS blocks every Redis client while it walks the whole keyspace; SCAN works in small steps.',
144
+ before: 'sendWelcomeEmail(user.email);',
145
+ code: 'await sendWelcomeEmail(user.email);\n// or, on purpose in the background:\nvoid sendWelcomeEmail(user.email).catch((error) => logger.error(error));',
146
+ note: 'An unawaited rejection is unhandled and can stop the process. List deliberate background helpers under fireAndForget in the policy.',
152
147
  },
153
- 'redis-incr-then-expire': {
154
- language: 'javascript',
155
- before: 'const hits = await redis.incr(key);\nif (hits === 1) await redis.expire(key, 60);',
156
- code: "const [[, hits]] = await redis.multi().incr(key).expire(key, 60, 'NX').exec();",
157
- note: 'Two round trips, and a crash between them leaves the counter with no TTL. One MULTI sends both; NX needs Redis 7+.',
148
+ 'frontend-barrel-heavy-import': {
149
+ language: 'tsx',
150
+ before: "import _ from 'lodash';",
151
+ code: "import debounce from 'lodash/debounce';",
152
+ note: 'Import subpaths.',
158
153
  },
159
- 'unbounded-list-query': {
154
+ 'guard-query-per-request': {
160
155
  language: 'javascript',
161
- before: 'return prisma.order.findMany({ where: { userId } });',
162
- code: 'return prisma.order.findMany({ where: { userId }, orderBy: { id: "desc" }, take: 50, cursor });',
163
- note: 'The response grows with the table. Page the list with a stable order and cap the page size.',
156
+ before: 'async function canActivate(context) {\n const user = await this.users.findOne({ where: { id } });\n}',
157
+ code: 'async function canActivate(context) {\n const user = await this.userCache.wrap(id, () => this.users.findOne({ where: { id } }), 60_000);\n}',
158
+ note: 'A global guard runs this query before every handler. Cache it by id with a short TTL and invalidate it when the user changes.',
164
159
  },
165
- 'unbounded-module-cache': {
160
+ 'heavy-media-in-request-handler': {
166
161
  language: 'javascript',
167
- before: 'const cache = new Map();\nfunction load(id) {\n if (!cache.has(id)) cache.set(id, read(id));\n return cache.get(id);\n}',
168
- code: 'const cache = new LRUCache({ max: 5000, ttl: 60_000 });\nfunction load(id) {\n if (!cache.has(id)) cache.set(id, read(id));\n return cache.get(id);\n}',
169
- note: 'A cache keyed by request data with no eviction grows until the process runs out of memory. Cap it by size or age.',
162
+ before: "app.post('/avatar', async (req, res) => { res.send(await sharp(req.body).resize(256).toBuffer()); });",
163
+ code: "app.post('/avatar', async (req, res) => { await mediaQueue.add('resize', { fileId }); res.status(202).json({ queued: true }); });",
164
+ note: 'Move CPU-intensive sharp or PDF rendering to a background worker queue to protect request latency.',
170
165
  },
171
- 'whole-payload-in-memory': {
166
+ 'http-call-without-timeout': {
172
167
  language: 'javascript',
173
- before: 'const body = Buffer.from(await response.arrayBuffer());\nawait writeFile(path, body);',
174
- code: 'await pipeline(Readable.fromWeb(response.body), createWriteStream(path));',
175
- note: 'Streaming keeps memory flat however large the payload is.',
168
+ before: "const response = await fetch(url, { method: 'POST', body });",
169
+ code: "const response = await fetch(url, { method: 'POST', body, signal: AbortSignal.timeout(10_000) });",
170
+ note: 'Without a timeout a hung upstream holds this request and its socket for up to 5 minutes (undici defaults). Tune the limit per API.',
176
171
  },
177
- 'list-query-overfetch': {
172
+ 'index-missing-filter': sqlExample('SELECT id FROM orders WHERE status = $1;', 'CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);', 'Skip it for a column with very few distinct values unless the query also filters further.'),
173
+ 'index-missing-foreign-key': sqlExample(foreignKeyBefore, foreignKeyIndex, foreignKeyNote),
174
+ 'index-missing-order': sqlExample('SELECT id FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20;', 'CREATE INDEX CONCURRENTLY orders_customer_created_idx ON orders (customer_id, created_at DESC);', 'Equality columns first, then the sort column, so the index returns rows already ordered.'),
175
+ 'index-redundant-prefix': sqlExample('CREATE INDEX orders_tenant_idx ON orders (tenant_id);\nCREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at);', 'CREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at);', 'The composite index already serves lookups on tenant_id alone. Drop the shorter one with DROP INDEX orders_tenant_idx; in a new migration.'),
176
+ 'index-unusable-expression': sqlExample('SELECT id FROM users WHERE lower(email) = $1;', 'CREATE INDEX CONCURRENTLY users_email_lower_idx ON users (lower(email));', 'Index the exact expression the query uses, or compare the plain column.'),
177
+ 'index-unusable-pattern': sqlExample("SELECT id FROM users WHERE name LIKE '%smith';", 'CREATE INDEX CONCURRENTLY users_name_trgm_idx ON users USING gin (name gin_trgm_ops);', 'A leading wildcard defeats a btree index. A trigram index (pg_trgm extension) serves it.'),
178
+ 'json-parse-unguarded': {
178
179
  language: 'javascript',
179
- before: 'const posts = await prisma.post.findMany({ include: { author: { include: { team: true } } } });',
180
- code: 'const posts = await prisma.post.findMany({ select: { id: true, title: true, author: { select: { name: true } } } });',
181
- note: 'Each row drags large columns or nested relations along. Select the fields the list shows and load the rest on demand.',
180
+ before: 'const settings = JSON.parse(req.body.settings);',
181
+ code: "let settings;\ntry {\n settings = JSON.parse(req.body.settings);\n} catch {\n return res.status(400).json({ error: 'Invalid settings' });\n}",
182
+ note: 'Malformed input becomes a 400 instead of an unhandled throw.',
182
183
  },
183
- 'orm-deep-offset': {
184
+ 'json-roundtrip-clone': {
184
185
  language: 'javascript',
185
- before: 'const rows = await prisma.order.findMany({ skip: Number(req.query.page) * 50, take: 50 });',
186
- code: "const rows = await prisma.order.findMany({ take: 50, ...(cursor && { cursor: { id: cursor }, skip: 1 }), orderBy: { id: 'asc' } });",
187
- note: 'A deep offset makes the database read and discard every earlier row. Page by the last seen key instead.',
186
+ before: 'items.map((item) => JSON.parse(JSON.stringify(item)))',
187
+ code: 'items.map((item) => structuredClone(item))',
188
+ note: 'structuredClone is faster and keeps Dates and Maps, which a JSON round trip drops.',
188
189
  },
189
190
  'list-count-per-request': {
190
191
  language: 'javascript',
@@ -192,115 +193,76 @@ const standaloneExamples = {
192
193
  code: 'const rows = await prisma.order.findMany({ skip, take: take + 1 });\nconst hasMore = rows.length > take;',
193
194
  note: 'A full count scans the table on every page. Fetch one extra row for "has more", or count once and cache it.',
194
195
  },
195
- 'notification-send-in-loop': {
196
- language: 'javascript',
197
- before: 'for (const token of tokens) await messaging.send({ token, notification });',
198
- code: 'await messaging.sendEach(tokens.map((token) => ({ token, notification })));',
199
- note: 'One request per recipient multiplies latency and rate-limit use. Keep per-recipient sends only when each message is personalised.',
200
- },
201
- 'session-memory-store': {
202
- language: 'javascript',
203
- before: 'app.use(session({ secret, resave: false }));',
204
- code: 'app.use(session({ secret, resave: false, store: new RedisStore({ client: redisClient }) }));',
205
- note: 'A shared store keeps sessions across restarts and instances and does not grow process memory.',
206
- },
207
- 'orm-cartesian-include': {
196
+ 'list-query-overfetch': {
208
197
  language: 'javascript',
209
- before: "repo.createQueryBuilder('u').leftJoinAndSelect('u.posts', 'p').leftJoinAndSelect('u.tags', 't').getMany();",
210
- code: "repo.find({ relations: ['posts', 'tags'], relationLoadStrategy: 'query' });",
211
- note: 'Each collection loads in its own query, so no row is repeated for every combination.',
198
+ before: 'const posts = await prisma.post.findMany({ include: { author: { include: { team: true } } } });',
199
+ code: 'const posts = await prisma.post.findMany({ select: { id: true, title: true, author: { select: { name: true } } } });',
200
+ note: 'Each row drags large columns or nested relations along. Select the fields the list shows and load the rest on demand.',
212
201
  },
213
- 'retry-without-backoff': {
202
+ 'llm-call-without-max-tokens': {
214
203
  language: 'javascript',
215
- before: 'for (let attempt = 0; attempt < 3; attempt++) {\n try { return await fetch(url); } catch {}\n}',
216
- code: 'for (let attempt = 0; attempt < 3; attempt++) {\n try { return await fetch(url); } catch { await sleep(2 ** attempt * 100 + Math.random() * 100); }\n}',
217
- note: 'Waiting longer after each failure keeps retries from hammering a struggling service.',
204
+ before: 'await openai.chat.completions.create({ model, messages });',
205
+ code: 'await openai.chat.completions.create({ model, messages, max_completion_tokens: 1024 });',
206
+ note: 'Without a cap a long or runaway completion is billed in full. Pick a limit the feature can justify.',
218
207
  },
219
- 'json-roundtrip-clone': {
220
- language: 'javascript',
221
- before: 'items.map((item) => JSON.parse(JSON.stringify(item)))',
222
- code: 'items.map((item) => structuredClone(item))',
223
- note: 'structuredClone is faster and keeps Dates and Maps, which a JSON round trip drops.',
224
- },
225
- 'async-route-unhandled-rejection': {
226
- language: 'javascript',
227
- before: "app.get('/users', async (req, res) => {\n res.json(await loadUsers());\n});",
228
- code: "app.get('/users', async (req, res, next) => {\n try {\n res.json(await loadUsers());\n } catch (error) { next(error); }\n});",
229
- note: 'Express 4 ignores the promise a handler returns; passing the error to next reaches the error middleware.',
230
- },
231
- 'async-callback-unhandled-rejection': {
232
- language: 'javascript',
233
- before: 'setInterval(async () => {\n await syncAccounts();\n}, 60_000);',
234
- code: 'setInterval(async () => {\n try {\n await syncAccounts();\n } catch (error) { logger.error(error); }\n}, 60_000);',
235
- note: 'Nothing awaits a callback timers and emitters call, so its rejection is unhandled unless the callback catches it.',
236
- },
237
- 'stream-pipe-unhandled-error': {
238
- language: 'javascript',
239
- before: 'fs.createReadStream(file).pipe(zlib.createGzip()).pipe(res);',
240
- code: "import { pipeline } from 'node:stream/promises';\n\nawait pipeline(fs.createReadStream(file), zlib.createGzip(), res);",
241
- note: 'pipeline forwards an error from any stage and closes every stream; .pipe() does neither.',
242
- },
243
- 'json-parse-unguarded': {
208
+ 'migration-breaking-drop': sqlExample('ALTER TABLE users DROP COLUMN legacy_name;', '-- release 1: stop reading and writing legacy_name\n-- release 2:\nALTER TABLE users DROP COLUMN legacy_name;', 'Dropping while old application versions still run breaks them. Drop after the code no longer uses it.'),
209
+ 'migration-breaking-rename': sqlExample('ALTER TABLE users RENAME COLUMN name TO full_name;', 'ALTER TABLE users ADD COLUMN full_name text;\n-- dual-write, backfill, switch reads, then drop name', 'A rename breaks every running application version that still uses the old name.'),
210
+ 'migration-column-type-rewrite': sqlExample('ALTER TABLE payments ALTER COLUMN amount TYPE bigint;', 'ALTER TABLE payments ADD COLUMN amount_big bigint;\n-- backfill in batches, switch reads and writes, then drop amount', 'A type change that is not binary compatible rewrites the table under an exclusive lock.'),
211
+ 'migration-concurrent-in-transaction': sqlExample('BEGIN;\nCREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);\nCOMMIT;', 'CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status); -- no transaction', 'Run it in its own migration with the runner transaction disabled.'),
212
+ 'migration-constraint-not-valid': sqlExample('ALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id);', 'ALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;', 'NOT VALID skips the blocking scan; VALIDATE CONSTRAINT checks existing rows with a weaker lock.'),
213
+ 'migration-constraint-without-index': sqlExample(foreignKeyBefore, foreignKeyIndex, 'Index the referencing column in the same release so parent deletes and joins do not scan the table.'),
214
+ 'migration-index-not-concurrent': sqlExample('CREATE INDEX orders_status_idx ON orders (status);', 'CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);', 'Plain CREATE INDEX blocks writes for the whole build. CONCURRENTLY cannot run inside a transaction.'),
215
+ 'migration-missing-lock-timeout': sqlExample('ALTER TABLE orders ADD COLUMN note text;', "SET lock_timeout = '5s';\nALTER TABLE orders ADD COLUMN note text;", 'Without a timeout the DDL queues behind a long transaction and blocks every later query on the table.'),
216
+ 'migration-mysql-lock-unspecified': sqlExample('ALTER TABLE orders ADD COLUMN note TEXT;', 'ALTER TABLE orders ADD COLUMN note TEXT, ALGORITHM=INSTANT;', 'State ALGORITHM (and LOCK) so MySQL refuses a statement that would silently lock or copy the table.'),
217
+ 'migration-mysql-table-copy': sqlExample('ALTER TABLE orders MODIFY status VARCHAR(20);', 'ALTER TABLE orders MODIFY status VARCHAR(20), ALGORITHM=INPLACE, LOCK=NONE;', 'MySQL fails instead of copying the table if the change cannot run online; use gh-ost for those.'),
218
+ 'migration-not-null-without-default': sqlExample('ALTER TABLE users ADD COLUMN plan text NOT NULL;', "ALTER TABLE users ADD COLUMN plan text NOT NULL DEFAULT 'free';", 'Existing rows need a value. A constant default is cheap on PostgreSQL 11 and later.'),
219
+ 'migration-set-not-null-scan': sqlExample('ALTER TABLE users ALTER COLUMN email SET NOT NULL;', 'ALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_email_nn;\nALTER TABLE users ALTER COLUMN email SET NOT NULL;', 'On PostgreSQL 12 and later the validated CHECK lets SET NOT NULL skip its scan. Drop the CHECK afterwards.'),
220
+ 'migration-table-rewrite-command': sqlExample('VACUUM FULL orders;', 'VACUUM orders; -- or pg_repack for an online rewrite', 'VACUUM FULL and CLUSTER hold an exclusive lock while they rewrite the table.'),
221
+ 'migration-unparsed': sqlExample("DO $$ BEGIN EXECUTE format('CREATE INDEX ON %I (id)', tbl); END $$;", 'CREATE INDEX CONCURRENTLY orders_id_idx ON orders (id);', 'Plain static statements can be analyzed; dynamic SQL cannot, so it is not checked.'),
222
+ 'migration-volatile-default': sqlExample('ALTER TABLE users ADD COLUMN token uuid DEFAULT gen_random_uuid();', 'ALTER TABLE users ADD COLUMN token uuid;\n-- backfill in batches, then:\nALTER TABLE users ALTER COLUMN token SET DEFAULT gen_random_uuid();', 'A volatile default rewrites the whole table under an exclusive lock.'),
223
+ 'mongo-collection-scan': collectionScan,
224
+ 'mongo-collection-scan-observed': collectionScan,
225
+ 'mongo-deep-skip': {
244
226
  language: 'javascript',
245
- before: 'const settings = JSON.parse(req.body.settings);',
246
- code: "let settings;\ntry {\n settings = JSON.parse(req.body.settings);\n} catch {\n return res.status(400).json({ error: 'Invalid settings' });\n}",
247
- note: 'Malformed input becomes a 400 instead of an unhandled throw.',
227
+ before: 'orders.find(filter).sort({ _id: 1 }).skip(page * size).limit(size);',
228
+ code: 'orders.find({ ...filter, _id: { $gt: lastSeenId } }).sort({ _id: 1 }).limit(size);',
229
+ note: 'Keyset pagination: return the last _id with each page. It fits sequential navigation, not random page jumps.',
248
230
  },
249
- 'request-number-unvalidated': {
231
+ 'mongo-disk-sort': {
250
232
  language: 'javascript',
251
- before: 'const page = Number(req.query.page);\nconst rows = await db.order.findMany({ skip: page * 20, take: 20 });',
252
- code: "const page = Number(req.query.page);\nif (!Number.isInteger(page) || page < 0) return res.status(400).json({ error: 'Invalid page' });\nconst rows = await db.order.findMany({ skip: page * 20, take: 20 });",
253
- note: 'NaN or a negative number reaching the query errors or returns the wrong rows; reject it first.',
233
+ before: "orders.find({ status: 'open' }).sort({ createdAt: -1 });",
234
+ code: "await orders.createIndex({ status: 1, createdAt: -1 });\norders.find({ status: 'open' }).sort({ createdAt: -1 });",
235
+ note: 'An index in sort order lets MongoDB skip the in-memory sort. Equality fields come first in the index.',
254
236
  },
255
- 'service-query-in-loop': {
237
+ 'mongoose-aggregate-uncast-id': {
256
238
  language: 'javascript',
257
- before: 'for (const id of ids) await this.approve(id); // approve() runs findOne + save',
258
- code: 'await this.approveMany(ids); // one In(ids) read and one bulk save',
259
- note: 'The helper hides queries that run once per item. Add a batch variant and keep per-item validation and transaction needs.',
239
+ before: 'await Order.aggregate([{ $match: { _id: id } }]);',
240
+ code: 'await Order.aggregate([{ $match: { _id: new Types.ObjectId(id) } }]);',
241
+ note: 'Mongoose does not auto-cast strings inside aggregate() pipelines; wrap string ids in Types.ObjectId.',
260
242
  },
261
- 'http-call-without-timeout': {
243
+ 'mongoose-hydrate-for-to-object': {
262
244
  language: 'javascript',
263
- before: "const response = await fetch(url, { method: 'POST', body });",
264
- code: "const response = await fetch(url, { method: 'POST', body, signal: AbortSignal.timeout(10_000) });",
265
- note: 'Without a timeout a hung upstream holds this request and its socket for up to 5 minutes (undici defaults). Tune the limit per API.',
245
+ before: 'const doc = await User.findById(id); return doc.toObject();',
246
+ code: 'return await User.findById(id).lean();',
247
+ note: 'Using .lean() returns a plain JavaScript object directly without hydrating a Mongoose Document.',
266
248
  },
267
- 'upload-without-size-limit': {
249
+ 'notification-send-in-loop': {
268
250
  language: 'javascript',
269
- before: "FileInterceptor('file')",
270
- code: "FileInterceptor('file', { limits: { fileSize: 10 * 1024 * 1024 } })",
271
- note: '10 MiB is an example. Verify the endpoint’s accepted file sizes and preserve any inherited upload limits.',
251
+ before: 'for (const token of tokens) await messaging.send({ token, notification });',
252
+ code: 'await messaging.sendEach(tokens.map((token) => ({ token, notification })));',
253
+ note: 'One request per recipient multiplies latency and rate-limit use. Keep per-recipient sends only when each message is personalised.',
272
254
  },
273
- 'external-call-in-transaction': {
255
+ 'orm-cartesian-include': {
274
256
  language: 'javascript',
275
- before: [
276
- 'await prisma.$transaction(async (tx) => {',
277
- ' await tx.order.create({ data });',
278
- ' await fetch(webhookUrl, { method: "POST" });',
279
- '});',
280
- ].join('\n'),
281
- code: [
282
- 'await prisma.$transaction(async (tx) => {',
283
- ' await tx.order.create({ data });',
284
- '});',
285
- 'await fetch(webhookUrl, { method: "POST" }); // after commit',
286
- ].join('\n'),
287
- note: 'The transaction holds a pool connection and its locks for the whole network call. Make the call after commit, or before the transaction when the write needs its result.',
257
+ before: "repo.createQueryBuilder('u').leftJoinAndSelect('u.posts', 'p').leftJoinAndSelect('u.tags', 't').getMany();",
258
+ code: "repo.find({ relations: ['posts', 'tags'], relationLoadStrategy: 'query' });",
259
+ note: 'Each collection loads in its own query, so no row is repeated for every combination.',
288
260
  },
289
- 'typeorm-transaction-client-escape': {
261
+ 'orm-deep-offset': {
290
262
  language: 'javascript',
291
- before: [
292
- 'await dataSource.transaction(async (manager) => {',
293
- ' await manager.save(order);',
294
- " await this.usageRepository.increment({ organizationId }, 'orders', 1);",
295
- '});',
296
- ].join('\n'),
297
- code: [
298
- 'await dataSource.transaction(async (manager) => {',
299
- ' await manager.save(order);',
300
- " await manager.getRepository(Usage).increment({ organizationId }, 'orders', 1);",
301
- '});',
302
- ].join('\n'),
303
- note: 'An injected repository runs on its own pooled connection and autocommits. Use the callback manager, or pass it to helpers that write.',
263
+ before: 'const rows = await prisma.order.findMany({ skip: Number(req.query.page) * 50, take: 50 });',
264
+ code: "const rows = await prisma.order.findMany({ take: 50, ...(cursor && { cursor: { id: cursor }, skip: 1 }), orderBy: { id: 'asc' } });",
265
+ note: 'A deep offset makes the database read and discard every earlier row. Page by the last seen key instead.',
304
266
  },
305
267
  'password-hash-pure-js': {
306
268
  language: 'javascript',
@@ -308,89 +270,50 @@ const standaloneExamples = {
308
270
  code: "import { hash } from 'bcrypt';",
309
271
  note: 'bcryptjs hashes in pure JavaScript on the main thread and blocks every request for 50-400 ms. Native bcrypt runs on the libuv threadpool with the same API and hash format; install bcrypt and @types/bcrypt.',
310
272
  },
311
- 'mongo-collection-scan': collectionScan,
312
- 'mongo-collection-scan-observed': collectionScan,
313
- 'mongo-disk-sort': {
273
+ 'password-hash-sync-in-async': {
314
274
  language: 'javascript',
315
- before: "orders.find({ status: 'open' }).sort({ createdAt: -1 });",
316
- code: "await orders.createIndex({ status: 1, createdAt: -1 });\norders.find({ status: 'open' }).sort({ createdAt: -1 });",
317
- note: 'An index in sort order lets MongoDB skip the in-memory sort. Equality fields come first in the index.',
275
+ before: 'const hash = bcrypt.hashSync(password, 10);',
276
+ code: 'const hash = await bcrypt.hash(password, 10);\nconst matches = await bcrypt.compare(password, hash);',
277
+ note: 'The synchronous hash blocks the event loop for every other request. Keep the same cost factor.',
318
278
  },
319
- 'mongo-deep-skip': {
320
- language: 'javascript',
321
- before: 'orders.find(filter).sort({ _id: 1 }).skip(page * size).limit(size);',
322
- code: 'orders.find({ ...filter, _id: { $gt: lastSeenId } }).sort({ _id: 1 }).limit(size);',
323
- note: 'Keyset pagination: return the last _id with each page. It fits sequential navigation, not random page jumps.',
279
+ 'payment-missing-idempotency-key': {
280
+ language: 'typescript',
281
+ before: 'await stripe.paymentIntents.create({ amount, currency });',
282
+ code: 'await stripe.paymentIntents.create({ amount, currency }, { idempotencyKey: `order-${orderId}` });',
283
+ note: 'Derive the key from a stable order or attempt id.',
324
284
  },
325
- 'pg-sequential-scan': missingIndex,
326
- 'pg-disk-sort': sqlExample('SELECT * FROM events ORDER BY created_at DESC LIMIT 50;', 'CREATE INDEX CONCURRENTLY events_created_at_idx ON events (created_at DESC);\nSELECT id, created_at FROM events ORDER BY created_at DESC LIMIT 50;', 'An index in the requested order removes the sort. Selecting fewer columns also shrinks it.'),
327
285
  'pg-deep-offset': sqlExample('SELECT id FROM orders ORDER BY id LIMIT 50 OFFSET 100000;', 'SELECT id FROM orders WHERE id > $1 ORDER BY id LIMIT 50;', 'Keyset pagination with the last id of the previous page. Needs a unique, indexed sort key.'),
328
- 'index-missing-foreign-key': sqlExample(foreignKeyBefore, foreignKeyIndex, foreignKeyNote),
329
- 'index-missing-filter': sqlExample('SELECT id FROM orders WHERE status = $1;', 'CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);', 'Skip it for a column with very few distinct values unless the query also filters further.'),
330
- 'index-missing-order': sqlExample('SELECT id FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20;', 'CREATE INDEX CONCURRENTLY orders_customer_created_idx ON orders (customer_id, created_at DESC);', 'Equality columns first, then the sort column, so the index returns rows already ordered.'),
331
- 'index-unusable-pattern': sqlExample("SELECT id FROM users WHERE name LIKE '%smith';", 'CREATE INDEX CONCURRENTLY users_name_trgm_idx ON users USING gin (name gin_trgm_ops);', 'A leading wildcard defeats a btree index. A trigram index (pg_trgm extension) serves it.'),
332
- 'index-unusable-expression': sqlExample('SELECT id FROM users WHERE lower(email) = $1;', 'CREATE INDEX CONCURRENTLY users_email_lower_idx ON users (lower(email));', 'Index the exact expression the query uses, or compare the plain column.'),
333
- 'index-redundant-prefix': sqlExample('CREATE INDEX orders_tenant_idx ON orders (tenant_id);\nCREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at);', 'CREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at);', 'The composite index already serves lookups on tenant_id alone. Drop the shorter one with DROP INDEX orders_tenant_idx; in a new migration.'),
334
- 'migration-index-not-concurrent': sqlExample('CREATE INDEX orders_status_idx ON orders (status);', 'CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);', 'Plain CREATE INDEX blocks writes for the whole build. CONCURRENTLY cannot run inside a transaction.'),
335
- 'migration-concurrent-in-transaction': sqlExample('BEGIN;\nCREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);\nCOMMIT;', 'CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status); -- no transaction', 'Run it in its own migration with the runner transaction disabled.'),
336
- 'migration-not-null-without-default': sqlExample('ALTER TABLE users ADD COLUMN plan text NOT NULL;', "ALTER TABLE users ADD COLUMN plan text NOT NULL DEFAULT 'free';", 'Existing rows need a value. A constant default is cheap on PostgreSQL 11 and later.'),
337
- 'migration-volatile-default': sqlExample('ALTER TABLE users ADD COLUMN token uuid DEFAULT gen_random_uuid();', 'ALTER TABLE users ADD COLUMN token uuid;\n-- backfill in batches, then:\nALTER TABLE users ALTER COLUMN token SET DEFAULT gen_random_uuid();', 'A volatile default rewrites the whole table under an exclusive lock.'),
338
- 'migration-column-type-rewrite': sqlExample('ALTER TABLE payments ALTER COLUMN amount TYPE bigint;', 'ALTER TABLE payments ADD COLUMN amount_big bigint;\n-- backfill in batches, switch reads and writes, then drop amount', 'A type change that is not binary compatible rewrites the table under an exclusive lock.'),
339
- 'migration-set-not-null-scan': sqlExample('ALTER TABLE users ALTER COLUMN email SET NOT NULL;', 'ALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_email_nn;\nALTER TABLE users ALTER COLUMN email SET NOT NULL;', 'On PostgreSQL 12 and later the validated CHECK lets SET NOT NULL skip its scan. Drop the CHECK afterwards.'),
340
- 'migration-constraint-not-valid': sqlExample('ALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id);', 'ALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;', 'NOT VALID skips the blocking scan; VALIDATE CONSTRAINT checks existing rows with a weaker lock.'),
341
- 'migration-constraint-without-index': sqlExample(foreignKeyBefore, foreignKeyIndex, 'Index the referencing column in the same release so parent deletes and joins do not scan the table.'),
342
- 'migration-breaking-drop': sqlExample('ALTER TABLE users DROP COLUMN legacy_name;', '-- release 1: stop reading and writing legacy_name\n-- release 2:\nALTER TABLE users DROP COLUMN legacy_name;', 'Dropping while old application versions still run breaks them. Drop after the code no longer uses it.'),
343
- 'migration-breaking-rename': sqlExample('ALTER TABLE users RENAME COLUMN name TO full_name;', 'ALTER TABLE users ADD COLUMN full_name text;\n-- dual-write, backfill, switch reads, then drop name', 'A rename breaks every running application version that still uses the old name.'),
344
- 'migration-missing-lock-timeout': sqlExample('ALTER TABLE orders ADD COLUMN note text;', "SET lock_timeout = '5s';\nALTER TABLE orders ADD COLUMN note text;", 'Without a timeout the DDL queues behind a long transaction and blocks every later query on the table.'),
345
- 'migration-table-rewrite-command': sqlExample('VACUUM FULL orders;', 'VACUUM orders; -- or pg_repack for an online rewrite', 'VACUUM FULL and CLUSTER hold an exclusive lock while they rewrite the table.'),
346
- 'migration-unparsed': sqlExample("DO $$ BEGIN EXECUTE format('CREATE INDEX ON %I (id)', tbl); END $$;", 'CREATE INDEX CONCURRENTLY orders_id_idx ON orders (id);', 'Plain static statements can be analyzed; dynamic SQL cannot, so it is not checked.'),
347
- 'migration-mysql-table-copy': sqlExample('ALTER TABLE orders MODIFY status VARCHAR(20);', 'ALTER TABLE orders MODIFY status VARCHAR(20), ALGORITHM=INPLACE, LOCK=NONE;', 'MySQL fails instead of copying the table if the change cannot run online; use gh-ost for those.'),
348
- 'migration-mysql-lock-unspecified': sqlExample('ALTER TABLE orders ADD COLUMN note TEXT;', 'ALTER TABLE orders ADD COLUMN note TEXT, ALGORITHM=INSTANT;', 'State ALGORITHM (and LOCK) so MySQL refuses a statement that would silently lock or copy the table.'),
349
- 'api-removed-operation': contractExample('graphql', 'type Query {\n user(id: ID!): User\n}', 'type Query {\n user(id: ID!): User\n userV2(id: ID!): User\n}', 'Keep the old operation (or serve /v1 beside a new /v2) until no deployed client calls it.'),
350
- 'api-removed-field': contractExample('typescript', 'class UserDto {\n name: string;\n}', 'class UserDto {\n name: string;\n /** @deprecated read name */\n fullName?: string;\n}', 'Deprecate a response field first and remove it after clients stop reading it.'),
351
- 'api-required-input': contractExample('typescript', 'class CreateUserDto {\n nickname?: string;\n}', 'class CreateUserDto {\n nickname?: string;\n}\n// make it required only in a new API version', 'A newly required input rejects every client that has not been updated; give it a default or version the API.'),
352
- 'api-type-changed': contractExample('typescript', 'class OrderDto {\n total: number;\n}', 'class OrderDto {\n total: number;\n totalText: string;\n}', 'Add a new field for the new type and keep the old one until clients migrate.'),
353
- 'api-enum-value-removed': contractExample('typescript', "type Status = 'open' | 'closed' | 'archived';", "type Status = 'open' | 'closed' | 'archived'; // keep accepting 'archived'", 'Keep accepting the old value (map it to the new one) until clients stop sending it.'),
354
- 'db-unindexed-foreign-key': sqlExample(foreignKeyBefore, foreignKeyIndex, foreignKeyNote),
355
- 'db-unused-index': sqlExample('SELECT indexrelname FROM pg_stat_user_indexes WHERE idx_scan = 0;', 'DROP INDEX CONCURRENTLY orders_legacy_idx;', 'Confirm on every replica over a full business cycle, and that no constraint depends on the index.'),
356
- 'db-duplicate-index': sqlExample('CREATE INDEX a_idx ON orders (customer_id);\nCREATE INDEX b_idx ON orders (customer_id);', 'DROP INDEX CONCURRENTLY b_idx;', 'Keep one of two identical indexes. An index that is a prefix of another is also redundant.'),
357
- 'db-seq-scan-heavy-table': sqlExample('SELECT relname, seq_scan, idx_scan FROM pg_stat_user_tables ORDER BY seq_scan DESC;', foreignKeyIndex, 'Find the queries scanning this table (pg_stat_statements) and index their filter columns.'),
358
- 'db-slow-query-plan': sqlExample('EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = $1;', foreignKeyIndex, 'Add the index the plan lacks, or rewrite the query, then compare the plan.'),
359
- 'mongoose-aggregate-uncast-id': {
286
+ 'pg-disk-sort': sqlExample('SELECT * FROM events ORDER BY created_at DESC LIMIT 50;', 'CREATE INDEX CONCURRENTLY events_created_at_idx ON events (created_at DESC);\nSELECT id, created_at FROM events ORDER BY created_at DESC LIMIT 50;', 'An index in the requested order removes the sort. Selecting fewer columns also shrinks it.'),
287
+ 'pg-sequential-scan': missingIndex,
288
+ 'prisma-distinct-in-memory': {
360
289
  language: 'javascript',
361
- before: 'await Order.aggregate([{ $match: { _id: id } }]);',
362
- code: 'await Order.aggregate([{ $match: { _id: new Types.ObjectId(id) } }]);',
363
- note: 'Mongoose does not auto-cast strings inside aggregate() pipelines; wrap string ids in Types.ObjectId.',
290
+ before: "await prisma.product.findMany({ where, select: { storeId: true }, distinct: ['storeId'] });",
291
+ code: "await prisma.product.groupBy({ by: ['storeId'], where });",
292
+ note: 'Prisma applies distinct after reading every matching row; groupBy dedupes in SQL. Not needed with the nativeDistinct preview feature.',
364
293
  },
365
- 'mongoose-hydrate-for-to-object': {
294
+ 'prisma-relation-count-in-list': {
366
295
  language: 'javascript',
367
- before: 'const doc = await User.findById(id); return doc.toObject();',
368
- code: 'return await User.findById(id).lean();',
369
- note: 'Using .lean() returns a plain JavaScript object directly without hydrating a Mongoose Document.',
296
+ before: 'await prisma.brand.findMany({ take: 20, include: { _count: { select: { products: true } } } });',
297
+ code: "const brands = await prisma.brand.findMany({ take: 20 });\nconst counts = await prisma.product.groupBy({\n by: ['brandId'],\n where: { brandId: { in: brands.map((brand) => brand.id) } },\n _count: { _all: true },\n});",
298
+ note: 'The _count join groups the whole related table, not just the page. Counting only the page ids keeps the cost tied to take.',
370
299
  },
371
- 'express-missing-compression': {
300
+ 'promise-return-escapes-catch': {
372
301
  language: 'javascript',
373
- before: 'const app = express(); app.listen(3000);',
374
- code: "import compression from 'compression';\nconst app = express();\napp.use(compression());\napp.listen(3000);",
375
- note: 'Compresses JSON and HTML responses on the wire; skip if your reverse proxy already compresses responses.',
302
+ before: 'try {\n return loadProfile();\n} catch (error) {\n return respondToFailure(error);\n}',
303
+ code: 'try {\n return await loadProfile();\n} catch (error) {\n return respondToFailure(error);\n}',
304
+ note: 'Await inside the protected try block when its catch is responsible for handling the rejection.',
376
305
  },
377
- 'heavy-media-in-request-handler': {
306
+ 'queue-add-in-loop': {
378
307
  language: 'javascript',
379
- before: "app.post('/avatar', async (req, res) => { res.send(await sharp(req.body).resize(256).toBuffer()); });",
380
- code: "app.post('/avatar', async (req, res) => { await mediaQueue.add('resize', { fileId }); res.status(202).json({ queued: true }); });",
381
- note: 'Move CPU-intensive sharp or PDF rendering to a background worker queue to protect request latency.',
382
- },
383
- 'react-missing-cleanup': {
384
- language: 'tsx',
385
- before: "useEffect(() => { window.addEventListener('resize', onResize); }, []);",
386
- code: "useEffect(() => { window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, []);",
387
- note: 'Return a cleanup that removes what the effect added.',
308
+ before: "for (const id of ids) await queue.add('render', { id });",
309
+ code: "await queue.addBulk(ids.map((id) => ({ name: 'render', data: { id } })));",
310
+ note: 'addBulk sends every job in one Redis call instead of one round trip per job.',
388
311
  },
389
- 'react-index-as-key': {
312
+ 'react-component-defined-in-component': {
390
313
  language: 'tsx',
391
- before: 'rows.map((r, i) => <li key={i}>{r.name}</li>)',
392
- code: 'rows.map((r) => <li key={r.id}>{r.name}</li>)',
393
- note: 'Use a stable id from the item.',
314
+ before: 'function List() { const Row = () => <li />; return <Row />; }',
315
+ code: 'const Row = () => <li />;\nfunction List() { return <Row />; }',
316
+ note: 'Declare the component at module scope and pass props.',
394
317
  },
395
318
  'react-fetch-in-effect-no-abort': {
396
319
  language: 'tsx',
@@ -398,59 +321,107 @@ const standaloneExamples = {
398
321
  code: 'useEffect(() => { const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(); }, [url]);',
399
322
  note: 'Abort the request on cleanup.',
400
323
  },
324
+ 'react-index-as-key': {
325
+ language: 'tsx',
326
+ before: 'rows.map((r, i) => <li key={i}>{r.name}</li>)',
327
+ code: 'rows.map((r) => <li key={r.id}>{r.name}</li>)',
328
+ note: 'Use a stable id from the item.',
329
+ },
401
330
  'react-inline-object-in-jsx-prop': {
402
331
  language: 'tsx',
403
332
  before: '<Row options={{ dense: true }} />',
404
333
  code: 'const options = { dense: true };\n<Row options={options} />',
405
334
  note: 'Hoist the object or memoise it.',
406
335
  },
407
- 'angular-subscribe-without-cleanup': {
408
- language: 'typescript',
409
- before: 'interval(1000).subscribe(tick);',
410
- code: 'interval(1000).pipe(takeUntilDestroyed()).subscribe(tick);',
411
- note: 'End the subscription with the component.',
336
+ 'react-missing-cleanup': {
337
+ language: 'tsx',
338
+ before: "useEffect(() => { window.addEventListener('resize', onResize); }, []);",
339
+ code: "useEffect(() => { window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, []);",
340
+ note: 'Return a cleanup that removes what the effect added.',
412
341
  },
413
- 'angular-default-change-detection': {
414
- language: 'typescript',
415
- before: "@Component({ selector: 'x' })\nclass X {}",
416
- code: "@Component({ selector: 'x', changeDetection: ChangeDetectionStrategy.OnPush })\nclass X {}",
417
- note: 'Check inputs are not mutated in place first.',
342
+ 'redis-command-in-loop': {
343
+ language: 'javascript',
344
+ before: "for (const id of ids) await redis.get('user:' + id);",
345
+ code: "const values = await redis.mGet(ids.map((id) => 'user:' + id));",
346
+ note: 'Use a multi-key command or a pipeline. Ignore if each command depends on the previous reply.',
418
347
  },
419
- 'vue-watch-missing-cleanup': {
420
- language: 'typescript',
421
- before: "onMounted(() => { window.addEventListener('resize', f); });",
422
- code: "onMounted(() => window.addEventListener('resize', f)); onUnmounted(() => window.removeEventListener('resize', f));",
423
- note: 'Pair each mount resource with unmount cleanup.',
348
+ 'redis-incr-then-expire': {
349
+ language: 'javascript',
350
+ before: 'const hits = await redis.incr(key);\nif (hits === 1) await redis.expire(key, 60);',
351
+ code: "const [[, hits]] = await redis.multi().incr(key).expire(key, 60, 'NX').exec();",
352
+ note: 'Two round trips, and a crash between them leaves the counter with no TTL. One MULTI sends both; NX needs Redis 7+.',
424
353
  },
425
- 'vue-v-for-missing-key': {
426
- language: 'typescript',
427
- before: "rows.map((r) => h('li', r.name))",
428
- code: "rows.map((r) => h('li', { key: r.id }, r.name))",
429
- note: 'Give each item a stable key.',
354
+ 'redis-keys-command': {
355
+ language: 'javascript',
356
+ before: "const keys = await redis.keys('session:*');",
357
+ code: "const keys = [];\nfor await (const batch of redis.scanStream({ match: 'session:*', count: 100 })) keys.push(...batch);",
358
+ note: 'KEYS blocks every Redis client while it walks the whole keyspace; SCAN works in small steps.',
430
359
  },
431
- 'dom-layout-thrashing': {
432
- language: 'typescript',
433
- before: "for (const el of els) { const w = el.offsetWidth; el.style.width = w + 1 + 'px'; }",
434
- code: "const widths = els.map((el) => el.offsetWidth); els.forEach((el, i) => { el.style.width = widths[i] + 1 + 'px'; });",
435
- note: 'Batch reads before writes.',
360
+ 'redis-keys-scan': {
361
+ language: 'javascript',
362
+ before: "const keys = await redis.keys('session:*');",
363
+ code: "for await (const key of redis.scanIterator({ MATCH: 'session:*', COUNT: 100 })) await handle(key);",
364
+ note: 'KEYS blocks Redis while it walks the whole keyspace; SCAN is incremental. ioredis offers scanStream.',
436
365
  },
437
- 'dom-listener-without-cleanup': {
438
- language: 'typescript',
439
- before: "window.addEventListener('online', () => sync());",
440
- code: "window.addEventListener('online', () => sync(), { signal: controller.signal });",
441
- note: 'Make the listener removable.',
366
+ 'redis-repeated-read': {
367
+ language: 'javascript',
368
+ before: "for (const id of ids) values.push(await redis.get('user:' + id));",
369
+ code: "const values = await redis.mGet(ids.map((id) => 'user:' + id));",
370
+ note: 'One MGET replaces one round trip per key. ioredis spells it mget; use a pipeline for HGET.',
442
371
  },
443
- 'dom-unthrottled-scroll-resize': {
372
+ 'repeated-db-span': {
373
+ language: 'javascript',
374
+ before: "for (const id of ids) await db.query('SELECT * FROM users WHERE id = $1', [id]);",
375
+ code: "const { rows } = await db.query('SELECT * FROM users WHERE id = ANY($1)', [ids]);",
376
+ note: 'Batch repeated lookups into one statement and keep the original scope predicates.',
377
+ },
378
+ 'request-number-unvalidated': {
379
+ language: 'javascript',
380
+ before: 'const page = Number(req.query.page);\nconst rows = await db.order.findMany({ skip: page * 20, take: 20 });',
381
+ code: "const page = Number(req.query.page);\nif (!Number.isInteger(page) || page < 0) return res.status(400).json({ error: 'Invalid page' });\nconst rows = await db.order.findMany({ skip: page * 20, take: 20 });",
382
+ note: 'NaN or a negative number reaching the query errors or returns the wrong rows; reject it first.',
383
+ },
384
+ 'retry-without-backoff': {
385
+ language: 'javascript',
386
+ before: 'for (let attempt = 0; attempt < 3; attempt++) {\n try { return await fetch(url); } catch {}\n}',
387
+ code: 'for (let attempt = 0; attempt < 3; attempt++) {\n try { return await fetch(url); } catch { await sleep(2 ** attempt * 100 + Math.random() * 100); }\n}',
388
+ note: 'Waiting longer after each failure keeps retries from hammering a struggling service.',
389
+ },
390
+ 'return-in-finally': {
391
+ language: 'javascript',
392
+ before: 'try {\n return readValue();\n} finally {\n return release();\n}',
393
+ code: 'try {\n return readValue();\n} finally {\n release();\n}',
394
+ note: 'Keep cleanup in finally so the caller receives the original return value or error.',
395
+ },
396
+ 'return-newline': {
397
+ language: 'javascript',
398
+ before: 'function read() {\n return\n ({ value: 1 });\n}',
399
+ code: 'function read() {\n return { value: 1 };\n}',
400
+ note: 'Start the expression on the same line as return to prevent automatic semicolon insertion.',
401
+ },
402
+ 'sequential-http-in-loop': {
444
403
  language: 'typescript',
445
- before: "window.addEventListener('wheel', onWheel);",
446
- code: "window.addEventListener('wheel', onWheel, { passive: true });",
447
- note: 'Passive listeners, and throttle work with requestAnimationFrame.',
404
+ before: 'for (const url of urls) { await fetch(url); }',
405
+ code: 'await Promise.all(urls.map((url) => fetch(url)));',
406
+ note: 'Bound concurrency (p-limit) for large lists or rate-limited APIs.',
448
407
  },
449
- 'frontend-barrel-heavy-import': {
450
- language: 'tsx',
451
- before: "import _ from 'lodash';",
452
- code: "import debounce from 'lodash/debounce';",
453
- note: 'Import subpaths.',
408
+ 'serial-awaits-in-literal': {
409
+ language: 'javascript',
410
+ before: 'const [posts, accounts] = [await syncPosts(), await syncAccounts()];',
411
+ code: 'const [posts, accounts] = await Promise.all([syncPosts(), syncAccounts()]);',
412
+ note: 'Awaits inside a literal still run one after the other, so the wait is the sum. Keep them serial if one depends on the other.',
413
+ },
414
+ 'service-query-in-loop': {
415
+ language: 'javascript',
416
+ before: 'for (const id of ids) await this.approve(id); // approve() runs findOne + save',
417
+ code: 'await this.approveMany(ids); // one In(ids) read and one bulk save',
418
+ note: 'The helper hides queries that run once per item. Add a batch variant and keep per-item validation and transaction needs.',
419
+ },
420
+ 'session-memory-store': {
421
+ language: 'javascript',
422
+ before: 'app.use(session({ secret, resave: false }));',
423
+ code: 'app.use(session({ secret, resave: false, store: new RedisStore({ client: redisClient }) }));',
424
+ note: 'A shared store keeps sessions across restarts and instances and does not grow process memory.',
454
425
  },
455
426
  'sql-select-star-in-query': {
456
427
  language: 'typescript',
@@ -458,23 +429,63 @@ const standaloneExamples = {
458
429
  code: "await pool.query('SELECT id, total, status FROM orders WHERE status = $1', [s]);",
459
430
  note: 'List the columns the caller uses.',
460
431
  },
461
- 'sequential-http-in-loop': {
462
- language: 'typescript',
463
- before: 'for (const url of urls) { await fetch(url); }',
464
- code: 'await Promise.all(urls.map((url) => fetch(url)));',
465
- note: 'Bound concurrency (p-limit) for large lists or rate-limited APIs.',
432
+ 'stream-pipe-unhandled-error': {
433
+ language: 'javascript',
434
+ before: 'fs.createReadStream(file).pipe(zlib.createGzip()).pipe(res);',
435
+ code: "import { pipeline } from 'node:stream/promises';\n\nawait pipeline(fs.createReadStream(file), zlib.createGzip(), res);",
436
+ note: 'pipeline forwards an error from any stage and closes every stream; .pipe() does neither.',
466
437
  },
467
- 'check-then-update-race': {
438
+ 'typeorm-load-then-save': {
439
+ language: 'javascript',
440
+ before: 'const user = await users.findOneBy({ id });\nuser.lastLoginAt = new Date();\nuser.tokenVersion += 1;\nawait users.save(user);',
441
+ code: "await users.increment({ id }, 'tokenVersion', 1);\nawait users.update({ id }, { lastLoginAt: new Date() });",
442
+ note: 'save() of a loaded entity costs a SELECT, an UPDATE and a transaction. update() skips entity listeners.',
443
+ },
444
+ 'typeorm-transaction-client-escape': {
445
+ language: 'javascript',
446
+ before: [
447
+ 'await dataSource.transaction(async (manager) => {',
448
+ ' await manager.save(order);',
449
+ " await this.usageRepository.increment({ organizationId }, 'orders', 1);",
450
+ '});',
451
+ ].join('\n'),
452
+ code: [
453
+ 'await dataSource.transaction(async (manager) => {',
454
+ ' await manager.save(order);',
455
+ " await manager.getRepository(Usage).increment({ organizationId }, 'orders', 1);",
456
+ '});',
457
+ ].join('\n'),
458
+ note: 'An injected repository runs on its own pooled connection and autocommits. Use the callback manager, or pass it to helpers that write.',
459
+ },
460
+ 'unbounded-list-query': {
461
+ language: 'javascript',
462
+ before: 'return prisma.order.findMany({ where: { userId } });',
463
+ code: 'return prisma.order.findMany({ where: { userId }, orderBy: { id: "desc" }, take: 50, cursor });',
464
+ note: 'The response grows with the table. Page the list with a stable order and cap the page size.',
465
+ },
466
+ 'unbounded-module-cache': {
467
+ language: 'javascript',
468
+ before: 'const cache = new Map();\nfunction load(id) {\n if (!cache.has(id)) cache.set(id, read(id));\n return cache.get(id);\n}',
469
+ code: 'const cache = new LRUCache({ max: 5000, ttl: 60_000 });\nfunction load(id) {\n if (!cache.has(id)) cache.set(id, read(id));\n return cache.get(id);\n}',
470
+ note: 'A cache keyed by request data with no eviction grows until the process runs out of memory. Cap it by size or age.',
471
+ },
472
+ 'upload-without-size-limit': {
473
+ language: 'javascript',
474
+ before: "FileInterceptor('file')",
475
+ code: "FileInterceptor('file', { limits: { fileSize: 10 * 1024 * 1024 } })",
476
+ note: '10 MiB is an example. Verify the endpoint’s accepted file sizes and preserve any inherited upload limits.',
477
+ },
478
+ 'vue-v-for-missing-key': {
468
479
  language: 'typescript',
469
- before: 'account.balance -= amount; await account.save();',
470
- code: 'await Account.updateOne({ _id: id, balance: { $gte: amount } }, { $inc: { balance: -amount } });',
471
- note: 'Let the database apply the change atomically.',
480
+ before: "rows.map((r) => h('li', r.name))",
481
+ code: "rows.map((r) => h('li', { key: r.id }, r.name))",
482
+ note: 'Give each item a stable key.',
472
483
  },
473
- 'payment-missing-idempotency-key': {
484
+ 'vue-watch-missing-cleanup': {
474
485
  language: 'typescript',
475
- before: 'await stripe.paymentIntents.create({ amount, currency });',
476
- code: 'await stripe.paymentIntents.create({ amount, currency }, { idempotencyKey: `order-${orderId}` });',
477
- note: 'Derive the key from a stable order or attempt id.',
486
+ before: "onMounted(() => { window.addEventListener('resize', f); });",
487
+ code: "onMounted(() => window.addEventListener('resize', f)); onUnmounted(() => window.removeEventListener('resize', f));",
488
+ note: 'Pair each mount resource with unmount cleanup.',
478
489
  },
479
490
  'webhook-missing-idempotency-check': {
480
491
  language: 'typescript',
@@ -482,6 +493,11 @@ const standaloneExamples = {
482
493
  code: "app.post('/webhooks/stripe', async (req, res) => { await ProcessedEvent.create({ eventId: req.body.id }); /* unique index rejects redelivery */ });",
483
494
  note: 'Record the event id under a unique constraint before applying the effect.',
484
495
  },
485
- 'db-missing-index': sqlExample('SELECT id FROM orders WHERE customer_id = $1;', foreignKeyIndex, 'Check that the write cost of one more index is acceptable for this table.'),
496
+ 'whole-payload-in-memory': {
497
+ language: 'javascript',
498
+ before: 'const body = Buffer.from(await response.arrayBuffer());\nawait writeFile(path, body);',
499
+ code: 'await pipeline(Readable.fromWeb(response.body), createWriteStream(path));',
500
+ note: 'Streaming keeps memory flat however large the payload is.',
501
+ },
486
502
  };
487
- exports.standaloneExamples = standaloneExamples;
503
+ export { standaloneExamples };