loadwise 0.5.0 → 0.6.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 (132) hide show
  1. package/README.md +543 -628
  2. package/bin/loadwise.js +5 -1
  3. package/lib/accessibility/frontend-detect.js +2 -1
  4. package/lib/accessibility/rule-ids.js +12 -9
  5. package/lib/accessibility/template-attributes.js +4 -2
  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 +16 -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 +20 -3
  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 +12 -19
  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
@@ -0,0 +1,78 @@
1
+ import { spawn } from 'node:child_process';
2
+ // Runs `loadwise perf -p <config> --watch --json`. The TypeScript watch compiler re-analyzes only
3
+ // what changed, including edits from git, other editors or code generators, and prints one compact
4
+ // JSON report per line.
5
+ function startPerfWatch({ script, project, cwd, env, onFindings, onError, onExit }) {
6
+ const child = spawn(process.execPath, [script, 'perf', '-p', project, '--watch', '--json'], {
7
+ cwd,
8
+ env,
9
+ windowsHide: true,
10
+ stdio: ['ignore', 'pipe', 'pipe'],
11
+ });
12
+ const maxPendingBytes = 64 * 1024 * 1024;
13
+ let pending = '';
14
+ let stopped = false;
15
+ function readReport(line) {
16
+ let report;
17
+ try {
18
+ report = JSON.parse(line);
19
+ }
20
+ catch (error) {
21
+ onError(new Error('Watch mode printed an unreadable report: ' + (error instanceof Error ? error.message : String(error))));
22
+ return;
23
+ }
24
+ if (report && Array.isArray(report.findings))
25
+ onFindings(report.findings);
26
+ else
27
+ onError(new Error('Watch mode returned an invalid findings report.'));
28
+ }
29
+ child.stdout.setEncoding('utf8');
30
+ child.stdout.on('data', (chunk) => {
31
+ if (child.killed)
32
+ return;
33
+ if (pending.length + chunk.length > maxPendingBytes) {
34
+ pending = '';
35
+ onError(new Error('Watch mode output exceeded maximum buffer size.'));
36
+ child.kill('SIGKILL');
37
+ return;
38
+ }
39
+ pending += chunk;
40
+ let newline;
41
+ while ((newline = pending.indexOf('\n')) !== -1) {
42
+ const line = pending.slice(0, newline).trim();
43
+ pending = pending.slice(newline + 1);
44
+ if (line)
45
+ readReport(line);
46
+ }
47
+ });
48
+ child.stderr.setEncoding('utf8');
49
+ child.stderr.on('data', (text) => {
50
+ if (child.killed)
51
+ return;
52
+ if (text.trim())
53
+ onError(new Error(text.trim()));
54
+ });
55
+ function finish(error) {
56
+ if (stopped)
57
+ return;
58
+ stopped = true;
59
+ onExit(error);
60
+ }
61
+ child.on('error', finish);
62
+ child.on('exit', (code, signal) => finish(new Error('Watch mode exited with ' + (signal ?? 'code ' + code) + '.')));
63
+ return {
64
+ pid: child.pid,
65
+ stop() {
66
+ if (stopped)
67
+ return;
68
+ stopped = true;
69
+ child.kill();
70
+ const killTimer = setTimeout(() => {
71
+ if (child.exitCode === null && child.signalCode === null)
72
+ child.kill('SIGKILL');
73
+ }, 2000);
74
+ killTimer.unref();
75
+ },
76
+ };
77
+ }
78
+ export { startPerfWatch };
@@ -1,101 +1,59 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.exampleFor = exampleFor;
4
- const standalone_performance_examples_cjs_1 = require("./standalone-performance-examples.cjs");
1
+ import { standaloneExamples } from './standalone-performance-examples.js';
5
2
  // Examples are illustrative fragments. The scanner knows the site, but cannot choose a
6
3
  // business-preserving rewrite.
4
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
7
5
  const examples = {
8
- 'known-reads-awaited-serially': [
9
- 'const [profile, preferences] = await Promise.all([readProfile(), readPreferences()]);',
10
- 'Use this for independent reads whose ordering, failure behavior and concurrency budget allow it.',
11
- ],
12
- 'array-repeated-membership': [
13
- 'const allowed = new Set(allowedIds);\nconst visible = rows.filter(row => allowed.has(row.id));',
14
- 'Build the set once while allowedIds is stable.',
15
- ],
16
6
  'array-repeated-find': [
17
7
  'const firstById = new Map();\nfor (const row of rows) {\n if (!firstById.has(row.id)) firstById.set(row.id, row);\n}\nconst matches = ids.map(id => firstById.get(id));',
18
8
  'For stable string IDs this preserves the first match, duplicate requests and undefined for missing IDs. Check equality semantics for other key types.',
19
9
  ],
20
- 'reduce-copy-accumulator': [
21
- 'const labels = [];\nfor (const row of rows) labels.push(row.label);',
22
- 'Mutate only a fresh result whose intermediate versions are never observed.',
23
- ],
24
- 'loop-copy-accumulator': [
25
- 'const result = [];\nfor (const batch of batches) {\n for (const item of batch) result.push(item);\n}',
26
- 'For dense arrays, build one fresh result if nothing observes intermediate copies.',
27
- ],
28
- 'filter-for-existence': [
29
- 'const hasPending = rows.some(row => row.status === pendingStatus);',
30
- 'Use for a pure predicate when the consumer needs only a yes/no answer.',
31
- ],
32
- 'pg-query-in-loop': [
33
- "const { rows } = await client.query(\n 'SELECT id, name FROM users WHERE organization_id = $1 AND id = ANY($2::uuid[])',\n [authorizedOrganizationId, ids]\n);\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id));",
34
- 'For independent reads with unique UUID keys. Preserve every original scope predicate, the transaction client, missing-row behavior and query batch limits.',
10
+ 'array-repeated-membership': [
11
+ 'const allowed = new Set(allowedIds);\nconst visible = rows.filter(row => allowed.has(row.id));',
12
+ 'Build the set once while allowedIds is stable.',
35
13
  ],
36
- 'prisma-query-in-loop': [
37
- 'const rows = await prisma.user.findMany({ where: { AND: [scope, { id: { in: ids } }] } });\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id) ?? null);',
38
- 'For independent findUnique-style reads on unique IDs. Keep projection, authorization scope, transaction and original missing-row behavior.',
14
+ 'drizzle-last-insert-id': [
15
+ 'const [result] = await db.insert(orders).values(order);\nconst id = result.insertId;',
16
+ 'For one row with an auto-increment key, verify that the mysql2 result has the ID type expected by the caller.',
39
17
  ],
40
18
  'drizzle-query-in-loop': [
41
19
  'const rows = ids.length\n ? await db.select().from(users).where(and(scope, inArray(users.id, ids)))\n : [];\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id));',
42
20
  'and and inArray come from drizzle-orm. This example batches independent reads by a unique key.',
43
21
  ],
44
- 'pg-count-materialization': [
45
- "const { rows } = await client.query(\n 'SELECT count(*) AS total FROM orders WHERE status = $1', [status]\n);\nconst total = BigInt(rows[0].total);",
46
- 'PostgreSQL COUNT returns bigint. If your API returns a JavaScript number, convert only within its safe integer range.',
47
- ],
48
- 'prisma-count-materialization': [
49
- 'const total = await prisma.order.count({ where });',
50
- 'Keep the original filters and verify that pagination or distinct rows do not change the count.',
51
- ],
52
- 'prisma-count-for-existence': [
53
- 'const hasOrder = (await prisma.order.findFirst({ where, select: { id: true } })) !== null;',
54
- 'Keep the original filter and select a small field from the actual model when you only need to know whether a row exists.',
55
- ],
56
- 'typeorm-unused-count': [
57
- 'const orders = await orderRepository.find({ where, order, skip, take });',
58
- 'When only the rows are used, keep the original filters, ordering and pagination and choose the equivalent method that returns rows alone.',
22
+ 'drizzle-unfiltered-write': [
23
+ 'await db.update(orders).set(changes).where(and(scope, eq(orders.id, orderId)));',
24
+ 'Use the intended filter for this operation. Confirm explicitly if a whole-table mutation is intentional.',
59
25
  ],
60
26
  'drizzle-write-preflight': [
61
27
  'const [result] = await db.delete(items).where(eq(items.id, id));\nif (result.affectedRows === 0) throw new NotFoundError();',
62
28
  'For MySQL deletes, preserve the original scope and error contract. For inserts, check for a matching unique constraint and translate only its duplicate-key error.',
63
29
  ],
64
- 'drizzle-last-insert-id': [
65
- 'const [result] = await db.insert(orders).values(order);\nconst id = result.insertId;',
66
- 'For one row with an auto-increment key, verify that the mysql2 result has the ID type expected by the caller.',
67
- ],
68
- 'repeated-workbook-decode': [
69
- 'const workbook = new Workbook();\nawait workbook.xlsx.load(bytes);\nconst rows = readRows(workbook);\nconst images = readImages(workbook);',
70
- 'Share a workbook only when both readers can use the same decoded data and preserve each other’s view of the sheets.',
71
- ],
72
- 'pg-first-materialization': [
73
- "const { rows: [first] } = await client.query(\n 'SELECT id FROM orders WHERE status = $1 ORDER BY id LIMIT 1', [status]\n);",
74
- 'Preserve the intended ordering, filters and projection. An empty result leaves first undefined.',
30
+ 'filter-for-existence': [
31
+ 'const hasPending = rows.some(row => row.status === pendingStatus);',
32
+ 'Use for a pure predicate when the consumer needs only a yes/no answer.',
75
33
  ],
76
- 'prisma-first-materialization': [
77
- 'const first = (await prisma.order.findFirst({ where, orderBy, select })) ?? undefined;',
78
- 'Carry over the original filters, ordering and projection. Here null is converted to match array indexing.',
34
+ 'graphql-n-plus-one-resolver': [
35
+ 'const resolvers = {\n Order: {\n items: (order, _args, ctx) => ctx.itemsLoader.load(order.id),\n },\n};',
36
+ 'Batch per-parent field queries through a request-scoped DataLoader.',
79
37
  ],
80
- 'pg-filter-materialization': [
81
- "const { rows } = await client.query(\n 'SELECT id, status FROM orders WHERE status = $1', [status]\n);",
82
- 'Combine the filter with all existing predicates. Check collation and NULL handling against the JavaScript comparison.',
38
+ 'json-stringify-in-loop': [
39
+ 'const serialized = JSON.stringify(items);\nlogger.info(serialized);',
40
+ 'Serialize once outside the loop or stream NDJSON instead of stringifying per iteration.',
83
41
  ],
84
- 'prisma-filter-materialization': [
85
- 'const rows = await prisma.order.findMany({\n where: { AND: [where, { status }] }, orderBy, select\n});',
86
- 'For an unbounded read with an equivalent database equality comparison. Check collation and NULL handling.',
42
+ 'known-reads-awaited-serially': [
43
+ 'const [profile, preferences] = await Promise.all([readProfile(), readPreferences()]);',
44
+ 'Use this for independent reads whose ordering, failure behavior and concurrency budget allow it.',
87
45
  ],
88
- 'pg-top-k-materialization': [
89
- "const { rows } = await client.query(\n 'SELECT id, score FROM entries WHERE category = $1 ORDER BY score DESC, id ASC LIMIT $2',\n [category, limit]\n);",
90
- 'Use the original ordering and tie-break rule, including NULL handling. Here ties are ordered by ID.',
46
+ 'loop-copy-accumulator': [
47
+ 'const result = [];\nfor (const batch of batches) {\n for (const item of batch) result.push(item);\n}',
48
+ 'For dense arrays, build one fresh result if nothing observes intermediate copies.',
91
49
  ],
92
- 'prisma-top-k-materialization': [
93
- "const top = await prisma.entry.findMany({\n where, orderBy: [{ score: 'desc' }, { id: 'asc' }], take: limit, select\n});",
94
- 'Use a nonnegative limit and preserve the previous sort direction, tie behavior and NULL handling.',
50
+ 'mongoose-missing-lean': [
51
+ 'const users = await UserModel.find({ active: true }).lean();',
52
+ 'Add .lean() on read-only queries when Document methods (.save, .markModified) are not needed.',
95
53
  ],
96
- 'node-sync-fs-in-async': [
97
- "const { readFile } = require('node:fs/promises');\nconst contents = await readFile(filename, 'utf8');",
98
- 'readFile example. Choose the asynchronous counterpart of the original operation and preserve its options and errors.',
54
+ 'node-event-listener-leak': [
55
+ "useEffect(() => {\n window.addEventListener('resize', onResize);\n return () => window.removeEventListener('resize', onResize);\n}, []);",
56
+ 'Remove listeners on cleanup, or use .once() / { once: true } / AbortSignal.',
99
57
  ],
100
58
  'node-sync-compression-in-async': [
101
59
  "const { promisify } = require('node:util');\nconst gzip = promisify(require('node:zlib').gzip);\nconst compressed = await gzip(contents, options);",
@@ -105,98 +63,139 @@ const examples = {
105
63
  "const { promisify } = require('node:util');\nconst scrypt = promisify(require('node:crypto').scrypt);\nconst key = await scrypt(password, salt, keyLength, options);",
106
64
  'scrypt example. Preserve the selected algorithm and cost parameters, and bound concurrent work.',
107
65
  ],
66
+ 'node-sync-fs-in-async': [
67
+ "const { readFile } = require('node:fs/promises');\nconst contents = await readFile(filename, 'utf8');",
68
+ 'readFile example. Choose the asynchronous counterpart of the original operation and preserve its options and errors.',
69
+ ],
108
70
  'node-sync-process-in-async': [
109
71
  "const { promisify } = require('node:util');\nconst execFile = promisify(require('node:child_process').execFile);\nconst { stdout } = await execFile(executable, args, options);",
110
72
  'Use a trusted executable and pass arguments separately. For streaming output use spawn and handle completion and errors.',
111
73
  ],
112
- 'pool-created-per-request-or-item': [
113
- "const { Pool } = require('pg');\nconst pool = new Pool(databaseOptions); // module scope\nasync function loadOrders(status) {\n return pool.query('SELECT id FROM orders WHERE status = $1', [status]);\n}",
114
- 'PostgreSQL example. Share the client only across compatible credentials, endpoint and lifecycle. Close it at application shutdown.',
74
+ 'pg-count-materialization': [
75
+ "const { rows } = await client.query(\n 'SELECT count(*) AS total FROM orders WHERE status = $1', [status]\n);\nconst total = BigInt(rows[0].total);",
76
+ 'PostgreSQL COUNT returns bigint. If your API returns a JavaScript number, convert only within its safe integer range.',
115
77
  ],
116
- 'pg-unreleased-checkout': [
117
- "const { rows } = await pool.query('SELECT id FROM orders WHERE status = $1', [status]);",
118
- 'For a single statement, the pool borrows and returns the client. A multi-statement transaction needs its own checked-out client.',
78
+ 'pg-filter-materialization': [
79
+ "const { rows } = await client.query(\n 'SELECT id, status FROM orders WHERE status = $1', [status]\n);",
80
+ 'Combine the filter with all existing predicates. Check collation and NULL handling against the JavaScript comparison.',
81
+ ],
82
+ 'pg-first-materialization': [
83
+ "const { rows: [first] } = await client.query(\n 'SELECT id FROM orders WHERE status = $1 ORDER BY id LIMIT 1', [status]\n);",
84
+ 'Preserve the intended ordering, filters and projection. An empty result leaves first undefined.',
85
+ ],
86
+ 'pg-query-in-loop': [
87
+ "const { rows } = await client.query(\n 'SELECT id, name FROM users WHERE organization_id = $1 AND id = ANY($2::uuid[])',\n [authorizedOrganizationId, ids]\n);\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id));",
88
+ 'For independent reads with unique UUID keys. Preserve every original scope predicate, the transaction client, missing-row behavior and query batch limits.',
89
+ ],
90
+ 'pg-top-k-materialization': [
91
+ "const { rows } = await client.query(\n 'SELECT id, score FROM entries WHERE category = $1 ORDER BY score DESC, id ASC LIMIT $2',\n [category, limit]\n);",
92
+ 'Use the original ordering and tie-break rule, including NULL handling. Here ties are ordered by ID.',
119
93
  ],
120
94
  'pg-transaction-on-pool': [
121
95
  "const client = await pool.connect();\ntry {\n await client.query('BEGIN'); await updateOrders(client); await client.query('COMMIT');\n} catch (error) { await client.query('ROLLBACK'); throw error; }\nfinally { client.release(); }",
122
96
  'Send every operation in the transaction through this client; discard an unusable connection if rollback itself fails.',
123
97
  ],
124
- 'prisma-transaction-client-escape': [
125
- 'await prisma.$transaction(async tx => {\n await tx.order.create({ data: orderData });\n await tx.auditEntry.create({ data: auditData });\n});',
126
- 'Pass tx to any helper that participates in this transaction.',
98
+ 'pg-unreleased-checkout': [
99
+ "const { rows } = await pool.query('SELECT id FROM orders WHERE status = $1', [status]);",
100
+ 'For a single statement, the pool borrows and returns the client. A multi-statement transaction needs its own checked-out client.',
127
101
  ],
128
- 'prisma-read-modify-write': [
129
- 'await prisma.counter.update({\n where: uniqueCounterFilter, data: { value: { increment: delta } }\n});',
130
- 'For a non-null counter and a simple addition. Conditional business rules may require a guarded update or version check.',
102
+ 'pool-created-per-request-or-item': [
103
+ "const { Pool } = require('pg');\nconst pool = new Pool(databaseOptions); // module scope\nasync function loadOrders(status) {\n return pool.query('SELECT id FROM orders WHERE status = $1', [status]);\n}",
104
+ 'PostgreSQL example. Share the client only across compatible credentials, endpoint and lifecycle. Close it at application shutdown.',
105
+ ],
106
+ 'prisma-count-for-existence': [
107
+ 'const hasOrder = (await prisma.order.findFirst({ where, select: { id: true } })) !== null;',
108
+ 'Keep the original filter and select a small field from the actual model when you only need to know whether a row exists.',
109
+ ],
110
+ 'prisma-count-materialization': [
111
+ 'const total = await prisma.order.count({ where });',
112
+ 'Keep the original filters and verify that pagination or distinct rows do not change the count.',
131
113
  ],
132
114
  'prisma-dependent-writes': [
133
115
  'await prisma.$transaction(async tx => {\n const order = await tx.order.create({ data: orderData });\n await tx.lineItem.create({ data: { ...lineData, orderId: order.id } });\n});',
134
116
  'Use when the writes must succeed or fail together. A nested write is another option for an existing relation.',
135
117
  ],
136
- 'drizzle-unfiltered-write': [
137
- 'await db.update(orders).set(changes).where(and(scope, eq(orders.id, orderId)));',
138
- 'Use the intended filter for this operation. Confirm explicitly if a whole-table mutation is intentional.',
118
+ 'prisma-filter-materialization': [
119
+ 'const rows = await prisma.order.findMany({\n where: { AND: [where, { status }] }, orderBy, select\n});',
120
+ 'For an unbounded read with an equivalent database equality comparison. Check collation and NULL handling.',
139
121
  ],
140
- 'unbounded-promise-all': [
141
- "import pLimit from 'p-limit';\nconst limit = pLimit(10);\nawait Promise.all(items.map((item) => limit(() => processItem(item))));",
142
- 'Cap concurrency with p-limit, p-map, PromisePool, or chunked batches.',
122
+ 'prisma-first-materialization': [
123
+ 'const first = (await prisma.order.findFirst({ where, orderBy, select })) ?? undefined;',
124
+ 'Carry over the original filters, ordering and projection. Here null is converted to match array indexing.',
143
125
  ],
144
- 'mongoose-missing-lean': [
145
- 'const users = await UserModel.find({ active: true }).lean();',
146
- 'Add .lean() on read-only queries when Document methods (.save, .markModified) are not needed.',
126
+ 'prisma-query-in-loop': [
127
+ 'const rows = await prisma.user.findMany({ where: { AND: [scope, { id: { in: ids } }] } });\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id) ?? null);',
128
+ 'For independent findUnique-style reads on unique IDs. Keep projection, authorization scope, transaction and original missing-row behavior.',
147
129
  ],
148
- 'graphql-n-plus-one-resolver': [
149
- 'const resolvers = {\n Order: {\n items: (order, _args, ctx) => ctx.itemsLoader.load(order.id),\n },\n};',
150
- 'Batch per-parent field queries through a request-scoped DataLoader.',
130
+ 'prisma-read-modify-write': [
131
+ 'await prisma.counter.update({\n where: uniqueCounterFilter, data: { value: { increment: delta } }\n});',
132
+ 'For a non-null counter and a simple addition. Conditional business rules may require a guarded update or version check.',
133
+ ],
134
+ 'prisma-top-k-materialization': [
135
+ "const top = await prisma.entry.findMany({\n where, orderBy: [{ score: 'desc' }, { id: 'asc' }], take: limit, select\n});",
136
+ 'Use a nonnegative limit and preserve the previous sort direction, tie behavior and NULL handling.',
137
+ ],
138
+ 'prisma-transaction-client-escape': [
139
+ 'await prisma.$transaction(async tx => {\n await tx.order.create({ data: orderData });\n await tx.auditEntry.create({ data: auditData });\n});',
140
+ 'Pass tx to any helper that participates in this transaction.',
151
141
  ],
152
142
  'react-context-value-recreated': [
153
143
  'const value = useMemo(() => ({ user, logout }), [user, logout]);\nreturn <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;',
154
144
  'Memoize Context.Provider values so consumers do not re-render on every parent render.',
155
145
  ],
156
- 'node-event-listener-leak': [
157
- "useEffect(() => {\n window.addEventListener('resize', onResize);\n return () => window.removeEventListener('resize', onResize);\n}, []);",
158
- 'Remove listeners on cleanup, or use .once() / { once: true } / AbortSignal.',
146
+ 'reduce-copy-accumulator': [
147
+ 'const labels = [];\nfor (const row of rows) labels.push(row.label);',
148
+ 'Mutate only a fresh result whose intermediate versions are never observed.',
159
149
  ],
160
- 'json-stringify-in-loop': [
161
- 'const serialized = JSON.stringify(items);\nlogger.info(serialized);',
162
- 'Serialize once outside the loop or stream NDJSON instead of stringifying per iteration.',
150
+ 'repeated-workbook-decode': [
151
+ 'const workbook = new Workbook();\nawait workbook.xlsx.load(bytes);\nconst rows = readRows(workbook);\nconst images = readImages(workbook);',
152
+ 'Share a workbook only when both readers can use the same decoded data and preserve each other’s view of the sheets.',
153
+ ],
154
+ 'typeorm-unused-count': [
155
+ 'const orders = await orderRepository.find({ where, order, skip, take });',
156
+ 'When only the rows are used, keep the original filters, ordering and pagination and choose the equivalent method that returns rows alone.',
157
+ ],
158
+ 'unbounded-promise-all': [
159
+ "import pLimit from 'p-limit';\nconst limit = pLimit(10);\nawait Promise.all(items.map((item) => limit(() => processItem(item))));",
160
+ 'Cap concurrency with p-limit, p-map, PromisePool, or chunked batches.',
163
161
  ],
164
162
  };
163
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
165
164
  const polyglot = {
166
- 'python-copy-growing-list': [
167
- 'python',
168
- 'items = []\nfor value in values:\n items.append(value)',
169
- 'For a list with no observers depending on intermediate copies.',
165
+ 'csharp-fixed-regex-in-loop': [
166
+ 'csharp',
167
+ 'var digits = new Regex("^[0-9]+$");\nforeach (var value in values) {\n if (digits.IsMatch(value)) Collect(value);\n}',
168
+ 'Preserve the original options and timeout.',
170
169
  ],
171
- 'python-sync-requests-in-async': [
172
- 'python',
173
- 'async def fetch(client, url):\n return await client.get(url)',
174
- 'For an httpx.AsyncClient or aiohttp session.',
170
+ 'go-fixed-regexp-in-loop': [
171
+ 'go',
172
+ 'pattern := regexp.MustCompile(`^[0-9]+$`)\nfor _, value := range values {\n if pattern.MatchString(value) { collect(value) }\n}',
173
+ 'For a known valid constant pattern. Keep error handling if the original used regexp.Compile.',
174
+ ],
175
+ 'java-fixed-regex-in-loop': [
176
+ 'java',
177
+ 'Pattern digits = Pattern.compile("^[0-9]+$");\nfor (String value : values) {\n if (digits.matcher(value).matches()) collect(value);\n}',
178
+ 'Reuse the Pattern and create a matcher per input. Preserve the original matching method and flags.',
175
179
  ],
176
180
  'python-blocking-sleep-in-async': [
177
181
  'python',
178
182
  'async def wait():\n await asyncio.sleep(1)',
179
183
  'For code running on the asyncio event loop.',
180
184
  ],
185
+ 'python-copy-growing-list': [
186
+ 'python',
187
+ 'items = []\nfor value in values:\n items.append(value)',
188
+ 'For a list with no observers depending on intermediate copies.',
189
+ ],
181
190
  'python-fixed-regex-in-loop': [
182
191
  'python',
183
192
  'pattern = re.compile(r"^[0-9]+$")\nfor value in values:\n pattern.match(value)',
184
193
  'For a constant pattern; hoist the compile out of the loop.',
185
194
  ],
186
- 'go-fixed-regexp-in-loop': [
187
- 'go',
188
- 'pattern := regexp.MustCompile(`^[0-9]+$`)\nfor _, value := range values {\n if pattern.MatchString(value) { collect(value) }\n}',
189
- 'For a known valid constant pattern. Keep error handling if the original used regexp.Compile.',
190
- ],
191
- 'java-fixed-regex-in-loop': [
192
- 'java',
193
- 'Pattern digits = Pattern.compile("^[0-9]+$");\nfor (String value : values) {\n if (digits.matcher(value).matches()) collect(value);\n}',
194
- 'Reuse the Pattern and create a matcher per input. Preserve the original matching method and flags.',
195
- ],
196
- 'csharp-fixed-regex-in-loop': [
197
- 'csharp',
198
- 'var digits = new Regex("^[0-9]+$");\nforeach (var value in values) {\n if (digits.IsMatch(value)) Collect(value);\n}',
199
- 'Preserve the original options and timeout.',
195
+ 'python-sync-requests-in-async': [
196
+ 'python',
197
+ 'async def fetch(client, url):\n return await client.get(url)',
198
+ 'For an httpx.AsyncClient or aiohttp session.',
200
199
  ],
201
200
  'rust-fixed-regex-in-loop': [
202
201
  'rust',
@@ -392,6 +391,7 @@ function specializedExample(ruleId, message, language) {
392
391
  }
393
392
  // A Mongoose finding's message names a `schema.index(...)` fix; the SQL example would point at the
394
393
  // wrong database.
394
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
395
395
  const mongooseIndexExamples = {
396
396
  'index-missing-filter': {
397
397
  language: 'javascript',
@@ -409,8 +409,8 @@ const mongooseIndexExamples = {
409
409
  function exampleFor(ruleId, languageId, message = '') {
410
410
  if (Object.hasOwn(mongooseIndexExamples, ruleId) && message.includes('.index({'))
411
411
  return { ...mongooseIndexExamples[ruleId] };
412
- if (Object.hasOwn(standalone_performance_examples_cjs_1.standaloneExamples, ruleId))
413
- return { ...standalone_performance_examples_cjs_1.standaloneExamples[ruleId] };
412
+ if (Object.hasOwn(standaloneExamples, ruleId))
413
+ return { ...standaloneExamples[ruleId] };
414
414
  if (Object.hasOwn(polyglot, ruleId)) {
415
415
  const [language, code, note] = polyglot[ruleId];
416
416
  return languageId === language ? { language, code, note } : undefined;
@@ -436,3 +436,4 @@ function exampleFor(ruleId, languageId, message = '') {
436
436
  return { language: snippetLanguage, code, note };
437
437
  }
438
438
  }
439
+ export { exampleFor };