loadwise 0.6.2 → 0.7.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 (86) hide show
  1. package/README.md +152 -100
  2. package/dist/bin/loadwise.js +126 -49
  3. package/dist/lib/accessibility/frontend-detect.js +6 -5
  4. package/dist/lib/accessibility/usage.js +10 -2
  5. package/dist/lib/editor/configured-setup.js +61 -0
  6. package/dist/lib/editor/editor-launcher.js +165 -0
  7. package/dist/lib/editor/fix-edits.js +19 -0
  8. package/dist/lib/editor/jetbrains-setup.js +53 -0
  9. package/dist/lib/editor/language-server.js +31 -14
  10. package/dist/lib/editor/managed-config.js +37 -0
  11. package/dist/lib/editor/native-setup.js +85 -0
  12. package/dist/lib/editor/release-vsix.js +61 -0
  13. package/dist/lib/editor/server-commands.js +2 -0
  14. package/dist/lib/editor/setup-server.js +87 -0
  15. package/dist/lib/editor/setup-vim.js +61 -0
  16. package/dist/lib/editor/setup.js +131 -0
  17. package/dist/lib/editor/stdio-setup.js +6 -0
  18. package/dist/lib/maintainability/cli/inputs.js +3 -2
  19. package/dist/lib/maintainability/cli.js +14 -5
  20. package/dist/lib/maintainability/examples.js +4 -0
  21. package/dist/lib/maintainability/rule-ids.js +3 -0
  22. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  23. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  24. package/dist/lib/performance/cli/changed-lines.js +8 -1
  25. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  26. package/dist/lib/performance/cli/cli-output.js +3 -0
  27. package/dist/lib/performance/cli.js +8 -4
  28. package/dist/lib/performance/datastores/pg-integrity.js +7 -0
  29. package/dist/lib/performance/datastores/pooling.js +6 -1
  30. package/dist/lib/performance/engine/native-syntax.js +3 -0
  31. package/dist/lib/performance/frontend/frontend-perf.js +80 -20
  32. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  33. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  34. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  35. package/dist/lib/performance/request/mongoose-lean.js +140 -53
  36. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  37. package/dist/lib/performance/request/phase5-ast.js +6 -7
  38. package/dist/lib/performance/request/phase5-rules.js +133 -13
  39. package/dist/lib/performance/request/request-handlers.js +120 -23
  40. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  41. package/dist/lib/performance/site-fixes/collections.js +1 -2
  42. package/dist/lib/performance/site-fixes/frontend-fixes.js +10 -6
  43. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  44. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  45. package/dist/lib/reliability/react-bugs.js +11 -3
  46. package/dist/lib/reliability/usage.js +16 -5
  47. package/dist/lib/security/cli.js +15 -4
  48. package/dist/lib/shared/agent/agent-init.js +26 -4
  49. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  50. package/dist/lib/shared/agent/agent-session.js +6 -1
  51. package/dist/lib/shared/agent/agent-verify.js +54 -10
  52. package/dist/lib/shared/agent/review-delivery.js +1 -1
  53. package/dist/lib/shared/analysis/scan-cache.js +3 -2
  54. package/dist/lib/shared/check.js +172 -20
  55. package/dist/lib/shared/fix/fix-convergence.js +15 -29
  56. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  57. package/dist/lib/shared/fix/fix-imports.js +47 -38
  58. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  59. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  60. package/dist/lib/shared/fix/fix-presentation.js +4 -3
  61. package/dist/lib/shared/fix/fix-safety.js +26 -1
  62. package/dist/lib/shared/fix/fix-scope.js +82 -0
  63. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  64. package/dist/lib/shared/fix/project-file-access.js +17 -26
  65. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  66. package/dist/lib/shared/fix.js +215 -102
  67. package/dist/lib/shared/report-fp.js +93 -0
  68. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  69. package/dist/lib/shared/reporting/check-text.js +50 -0
  70. package/dist/lib/shared/reporting/pillars.js +45 -16
  71. package/dist/lib/shared/reporting/source-report.js +2 -0
  72. package/dist/lib/shared/system/atomic-write.js +5 -2
  73. package/dist/lib/shared/system/sentry.js +203 -0
  74. package/dist/lib/shared/system/shell-argument.js +5 -1
  75. package/dist/lib/shared/system/terminal-safe.js +3 -2
  76. package/dist/lib/shared/system/terminal-style.js +131 -0
  77. package/docs/assets/cli-workflow.gif +0 -0
  78. package/integrations/sublime/plugin.py +22 -0
  79. package/integrations/zed/Cargo.lock +845 -0
  80. package/integrations/zed/Cargo.toml +11 -0
  81. package/integrations/zed/extension.toml +11 -0
  82. package/integrations/zed/src/lib.rs +25 -0
  83. package/package.json +11 -3
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/commands/loadwise.md +11 -6
  86. package/schema/loadwise.config.schema.json +2 -0
@@ -1,11 +1,14 @@
1
1
  import { ts } from '../engine/compiler.js';
2
+ import { isBulkListenerRegistration } from './bulk-listener-registration.js';
3
+ import { isFreshLoopSocket } from './fresh-loop-socket.js';
2
4
  import { enclosingRequestHandler } from './request-handlers.js';
3
5
  import { propertyName } from '../schema/ts-helpers.js';
4
- import { unwrapExpression } from '../../shared/analysis/ast-semantics.js';
5
- import { ARRAY_LOOP_METHODS, containsMatchingNode, enclosingLoop, valueSymbol } from './phase5-ast.js';
6
+ import { resolveImportedBinding, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
7
+ import { ARRAY_LOOP_METHODS, containsMatchingNode, enclosingLoop, isGlobalMethodCall, valueSymbol, } from './phase5-ast.js';
6
8
  const EVENT_ADD_METHODS = new Set(['on', 'addListener', 'addEventListener']);
7
9
  const EVENT_REMOVE_METHODS = new Set(['off', 'removeListener', 'removeEventListener']);
8
10
  const LIFECYCLE_HOOKS = new Set(['useEffect', 'useLayoutEffect', 'onMounted', 'onBeforeMount']);
11
+ const UNMOUNT_HOOKS = new Set(['onBeforeUnmount', 'onUnmounted']);
9
12
  const REQUEST_SCOPED_EMITTERS = new Set([
10
13
  'req',
11
14
  '_req',
@@ -49,10 +52,53 @@ function enclosingHookCallback(node) {
49
52
  }
50
53
  return undefined;
51
54
  }
52
- function hasListenerCleanup(scope) {
55
+ function hasListenerCleanup(scope, registration) {
53
56
  return containsMatchingNode(scope, (node) => ts.isCallExpression(node) &&
54
57
  ts.isPropertyAccessExpression(node.expression) &&
55
- EVENT_REMOVE_METHODS.has(node.expression.name.text), false);
58
+ EVENT_REMOVE_METHODS.has(node.expression.name.text) &&
59
+ (!registration || matchesCleanupTarget(node, registration)), false);
60
+ }
61
+ function matchesCleanupTarget(cleanupCall, registration) {
62
+ const cleanCallee = ts.skipOuterExpressions(cleanupCall.expression);
63
+ const regCallee = ts.skipOuterExpressions(registration.expression);
64
+ if (!ts.isPropertyAccessExpression(cleanCallee) || !ts.isPropertyAccessExpression(regCallee))
65
+ return false;
66
+ if (!EVENT_REMOVE_METHODS.has(cleanCallee.name.text))
67
+ return false;
68
+ const cleanReceiver = ts.skipOuterExpressions(cleanCallee.expression).getText();
69
+ const regReceiver = ts.skipOuterExpressions(regCallee.expression).getText();
70
+ if (cleanReceiver !== regReceiver)
71
+ return false;
72
+ const [cleanEvent, cleanHandler] = cleanupCall.arguments;
73
+ const [regEvent, regHandler] = registration.arguments;
74
+ if (!cleanEvent || !regEvent)
75
+ return false;
76
+ const cleanupEvent = ts.skipOuterExpressions(cleanEvent);
77
+ const registrationEvent = ts.skipOuterExpressions(regEvent);
78
+ const sameEvent = ts.isStringLiteralLike(cleanupEvent) && ts.isStringLiteralLike(registrationEvent)
79
+ ? cleanupEvent.text === registrationEvent.text
80
+ : cleanupEvent.getText() === registrationEvent.getText();
81
+ if (!sameEvent)
82
+ return false;
83
+ if (!cleanHandler || !regHandler)
84
+ return false;
85
+ const cleanupHandler = ts.skipOuterExpressions(cleanHandler);
86
+ const registrationHandler = ts.skipOuterExpressions(regHandler);
87
+ if (ts.isArrowFunction(registrationHandler) || ts.isFunctionExpression(registrationHandler))
88
+ return false;
89
+ return cleanupHandler.getText() === registrationHandler.getText();
90
+ }
91
+ function hasUnmountCleanup(enclosingFn, registration) {
92
+ return containsMatchingNode(enclosingFn, (node) => {
93
+ if (!ts.isCallExpression(node))
94
+ return false;
95
+ const callee = ts.skipOuterExpressions(node.expression);
96
+ if (!ts.isIdentifier(callee) || !UNMOUNT_HOOKS.has(callee.text))
97
+ return false;
98
+ const [callback] = node.arguments;
99
+ return (callback !== undefined &&
100
+ containsMatchingNode(callback, (inner) => ts.isCallExpression(inner) && matchesCleanupTarget(inner, registration), false));
101
+ }, false);
56
102
  }
57
103
  function isLiteralList(node) {
58
104
  const value = unwrapExpression(node);
@@ -134,6 +180,41 @@ function repeatingLoop(node, checker) {
134
180
  loop = enclosingLoop(loop);
135
181
  return loop;
136
182
  }
183
+ function isFreshReceiver(callee, call, hook, handler, checker) {
184
+ const receiver = callee.expression;
185
+ if (!ts.isIdentifier(receiver))
186
+ return false;
187
+ const declaration = valueSymbol(receiver, checker)?.valueDeclaration;
188
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !ts.isVariableStatement(declaration.parent.parent))
189
+ return false;
190
+ if ((declaration.parent.flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const)
191
+ return false;
192
+ const allocation = unwrapExpression(declaration.initializer);
193
+ if (!allocation || !ts.isCallExpression(allocation))
194
+ return false;
195
+ const loop = enclosingLoop(call);
196
+ if (callee.name.text === 'addEventListener') {
197
+ return (!hook &&
198
+ loop !== undefined &&
199
+ enclosingLoop(declaration) === loop &&
200
+ isGlobalMethodCall(allocation, 'document', 'createElement', checker));
201
+ }
202
+ const binding = resolveImportedBinding(unwrapExpression(allocation.expression), checker, {
203
+ includeNamespaceImports: false,
204
+ });
205
+ // Watch mode creates each watcher for the matching configuration's lifetime.
206
+ if (binding?.module === 'rollup' && binding.exported === 'watch') {
207
+ return !hook && !handler && loop !== undefined && enclosingLoop(declaration) === loop;
208
+ }
209
+ // A multipart parser allocated by the request callback handles a single request.
210
+ return (binding?.module === 'busboy' &&
211
+ (binding.exported === 'default' || binding.exported === '*') &&
212
+ !loop &&
213
+ !hook &&
214
+ handler !== undefined &&
215
+ ts.findAncestor(call, ts.isFunctionLike) === handler &&
216
+ ts.findAncestor(declaration, ts.isFunctionLike) === handler);
217
+ }
137
218
  function checkNodeEventListenerLeak(call, context) {
138
219
  const callee = ts.skipOuterExpressions(call.expression);
139
220
  if (!ts.isPropertyAccessExpression(callee) || !EVENT_ADD_METHODS.has(callee.name.text))
@@ -145,6 +226,14 @@ function checkNodeEventListenerLeak(call, context) {
145
226
  const handler = enclosingRequestHandler(call);
146
227
  if (!hook && !loop && !handler)
147
228
  return;
229
+ if (loop && !hook && !handler) {
230
+ if (isBulkListenerRegistration(call, loop, context.checker))
231
+ return;
232
+ if (callee.name.text !== 'addEventListener' && isFreshLoopSocket(callee.expression, call, loop, context.checker))
233
+ return;
234
+ }
235
+ if (isFreshReceiver(callee, call, hook, handler, context.checker))
236
+ return;
148
237
  if (handler &&
149
238
  !loop &&
150
239
  !hook &&
@@ -153,8 +242,13 @@ function checkNodeEventListenerLeak(call, context) {
153
242
  return;
154
243
  }
155
244
  const cleanupScope = hook ?? ts.findAncestor(call, ts.isFunctionLike);
156
- if (cleanupScope && hasListenerCleanup(cleanupScope))
245
+ if (cleanupScope && hasListenerCleanup(cleanupScope, hook ? call : undefined))
157
246
  return;
247
+ if (hook) {
248
+ const enclosingFn = ts.findAncestor(hook.parent, ts.isFunctionLike);
249
+ if (enclosingFn && hasUnmountCleanup(enclosingFn, call))
250
+ return;
251
+ }
158
252
  context.report(call, 'node-event-listener-leak', 'Event listener registered inside a repeated or per-request context without matching cleanup leaks listeners over time.');
159
253
  }
160
254
  export { checkNodeEventListenerLeak };
@@ -70,11 +70,10 @@ function constSource(identifier, checker) {
70
70
  const initializer = unwrapExpression(variable.initializer);
71
71
  return initializer && !ts.isFunctionLike(initializer) ? initializer : undefined;
72
72
  }
73
- // One walk per block, however many of its declarations are looked up. The index holds syntax only,
74
- // so a watch build that reuses the block with a new checker cannot read stale symbols from it.
75
- const blockIdentifiers = new WeakMap();
76
- function identifiersByName(block) {
77
- const known = blockIdentifiers.get(block);
73
+ // Cache syntax only so a watch build that reuses the tree with a new checker sees current symbols.
74
+ const scopeIdentifiers = new WeakMap();
75
+ function identifiersByName(scope) {
76
+ const known = scopeIdentifiers.get(scope);
78
77
  if (known)
79
78
  return known;
80
79
  const byName = new Map();
@@ -88,8 +87,8 @@ function identifiersByName(block) {
88
87
  }
89
88
  ts.forEachChild(node, visit);
90
89
  }
91
- visit(block);
92
- blockIdentifiers.set(block, byName);
90
+ visit(scope);
91
+ scopeIdentifiers.set(scope, byName);
93
92
  return byName;
94
93
  }
95
94
  function valueSymbol(identifier, checker) {
@@ -6,6 +6,8 @@
6
6
  // - node-event-listener-leak
7
7
  // - json-stringify-in-loop
8
8
  import { ts } from '../engine/compiler.js';
9
+ import { standardInterface } from '../collections/repeated.js';
10
+ import { isProjectFunction, signatureDeclaration } from '../query-loops/service-call-resolution.js';
9
11
  import { checkMongooseMissingLean } from './mongoose-lean.js';
10
12
  import { checkNodeEventListenerLeak } from './node-event-listener-leak.js';
11
13
  import { isTestSource } from '../analysis/review-context.js';
@@ -18,10 +20,13 @@ const MAPPING_METHODS = new Set(['map', 'flatMap']);
18
20
  const OUTPUT_METHODS = new Set(['push', 'write']);
19
21
  const GQL_ROOT_TYPES = new Set(['Query', 'Mutation', 'Subscription']);
20
22
  const GQL_DECORATORS = new Set(['ResolveField', 'ResolveProperty']);
23
+ const GQL_PARENT_DECORATORS = new Set(['Parent', 'Root']);
21
24
  const DB_HTTP_METHODS = new Set([
22
25
  'findMany',
23
26
  'findUnique',
27
+ 'findUniqueOrThrow',
24
28
  'findFirst',
29
+ 'findFirstOrThrow',
25
30
  'findOne',
26
31
  'findById',
27
32
  'findByPk',
@@ -35,18 +40,20 @@ const DB_HTTP_METHODS = new Set([
35
40
  'patch',
36
41
  'delete',
37
42
  ]);
43
+ const IN_MEMORY_COLLECTIONS = new Set(['Map', 'ReadonlyMap', 'Set', 'ReadonlySet', 'WeakMap', 'WeakSet']);
38
44
  const HTTP_RECEIVERS = new Set(['axios', 'got', 'ky', 'undici', 'http', 'https']);
45
+ const GET_CLIENT_PACKAGES = ['@nestjs/axios', 'better-sqlite3', '@types/better-sqlite3', 'sqlite3'];
39
46
  // --- Rule 3: graphql-n-plus-one-resolver ---------------------------------------------------------
40
- function hasResolveFieldDecorator(node) {
47
+ function hasGraphqlDecorator(node, names) {
41
48
  if (!node.modifiers)
42
49
  return false;
43
50
  for (const mod of node.modifiers) {
44
51
  if (!ts.isDecorator(mod))
45
52
  continue;
46
53
  const expr = ts.skipOuterExpressions(mod.expression);
47
- if (ts.isIdentifier(expr) && GQL_DECORATORS.has(expr.text))
54
+ if (ts.isIdentifier(expr) && names.has(expr.text))
48
55
  return true;
49
- if (ts.isCallExpression(expr) && ts.isIdentifier(expr.expression) && GQL_DECORATORS.has(expr.expression.text)) {
56
+ if (ts.isCallExpression(expr) && ts.isIdentifier(expr.expression) && names.has(expr.expression.text)) {
50
57
  return true;
51
58
  }
52
59
  }
@@ -83,7 +90,7 @@ function isResolverMapField(fn) {
83
90
  /^(?:parent|root)$/.test(fn.parameters[0].name.text));
84
91
  }
85
92
  function isGraphqlFieldResolver(node) {
86
- if (ts.isMethodDeclaration(node) && hasResolveFieldDecorator(node))
93
+ if (ts.isMethodDeclaration(node) && hasGraphqlDecorator(node, GQL_DECORATORS))
87
94
  return true;
88
95
  if (ts.isMethodDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) {
89
96
  return isResolverMapField(node);
@@ -96,7 +103,7 @@ function usesDataLoader(fn) {
96
103
  ts.isPropertyAccessExpression(node.expression) &&
97
104
  (node.expression.name.text === 'load' || node.expression.name.text === 'loadMany')), false);
98
105
  }
99
- function isDbOrHttpCall(node) {
106
+ function isDbOrHttpCall(node, context) {
100
107
  if (!ts.isCallExpression(node))
101
108
  return false;
102
109
  const callee = ts.skipOuterExpressions(node.expression);
@@ -112,9 +119,64 @@ function isDbOrHttpCall(node) {
112
119
  if (firstArg && (ts.isArrowFunction(firstArg) || ts.isFunctionExpression(firstArg)))
113
120
  return false;
114
121
  }
115
- if (ts.isIdentifier(callee.expression) && HTTP_RECEIVERS.has(callee.expression.text))
122
+ if (method !== 'get' && method !== 'delete')
116
123
  return true;
117
- return true;
124
+ const owner = standardInterface(node, context.checker);
125
+ if (owner !== undefined && IN_MEMORY_COLLECTIONS.has(owner))
126
+ return false;
127
+ if (method === 'delete')
128
+ return true;
129
+ // A generic get can be an in-memory read. Require independent client or return-type evidence.
130
+ const receiver = unwrapExpression(callee.expression);
131
+ const name = ts.isPropertyAccessExpression(receiver) ? receiver.name : receiver;
132
+ return ((ts.isIdentifier(name) && HTTP_RECEIVERS.has(name.text)) ||
133
+ context.isPackageType(receiver, GET_CLIENT_PACKAGES) ||
134
+ context.checker.getTypeAtLocation(node).getProperty('then') !== undefined);
135
+ }
136
+ function callsProjectQuery(call, context) {
137
+ if (!ts.isPropertyAccessExpression(unwrapExpression(call.expression)))
138
+ return false;
139
+ if (!context.checker.getTypeAtLocation(call).getProperty('then'))
140
+ return false;
141
+ const method = signatureDeclaration(call, context.checker);
142
+ if (!isProjectFunction(method) || !ts.isMethodDeclaration(method) || usesDataLoader(method.body))
143
+ return false;
144
+ // Follow one call edge and stop at functions that the service method may never invoke.
145
+ return containsMatchingNode(method.body, (node) => isDbOrHttpCall(node, context));
146
+ }
147
+ function delegatedResolverQuery(resolver, context) {
148
+ if (!resolver.body)
149
+ return;
150
+ const { checker } = context;
151
+ const parents = ts.isMethodDeclaration(resolver) && hasGraphqlDecorator(resolver, GQL_DECORATORS)
152
+ ? resolver.parameters.filter((parameter) => hasGraphqlDecorator(parameter, GQL_PARENT_DECORATORS))
153
+ : resolver.parameters.slice(0, 1);
154
+ const symbols = new Set(parents.flatMap((parameter) => bindingIdentifiers(parameter.name, [])).map((name) => valueSymbol(name, checker)));
155
+ symbols.delete(undefined);
156
+ if (symbols.size === 0)
157
+ return;
158
+ function dependsOnParent(root, depth = 0) {
159
+ if (ts.isFunctionLike(root))
160
+ return false;
161
+ return containsMatchingNode(root, (candidate) => {
162
+ if (!ts.isIdentifier(candidate))
163
+ return false;
164
+ if (symbols.has(valueSymbol(candidate, checker)))
165
+ return true;
166
+ const source = depth < MAX_SOURCE_DEPTH ? constSource(candidate, checker) : undefined;
167
+ return source !== undefined && dependsOnParent(source, depth + 1);
168
+ });
169
+ }
170
+ let query;
171
+ containsMatchingNode(resolver.body, (node) => {
172
+ if (!ts.isCallExpression(node) ||
173
+ !node.arguments.some((argument) => dependsOnParent(argument)) ||
174
+ !callsProjectQuery(node, context))
175
+ return false;
176
+ query = node;
177
+ return true;
178
+ });
179
+ return query;
118
180
  }
119
181
  function checkGraphqlNPlusOneResolver(node, context) {
120
182
  if (!node.body || !isGraphqlFieldResolver(node))
@@ -125,13 +187,14 @@ function checkGraphqlNPlusOneResolver(node, context) {
125
187
  function findQuery(current) {
126
188
  if (queryCall)
127
189
  return;
128
- if (isDbOrHttpCall(current)) {
190
+ if (isDbOrHttpCall(current, context)) {
129
191
  queryCall = current;
130
192
  return;
131
193
  }
132
194
  ts.forEachChild(current, findQuery);
133
195
  }
134
196
  findQuery(node.body);
197
+ queryCall ??= delegatedResolverQuery(node, context);
135
198
  if (queryCall) {
136
199
  context.report(queryCall, 'graphql-n-plus-one-resolver', 'GraphQL field resolver executes a database or HTTP query per parent item without DataLoader batching.');
137
200
  }
@@ -189,8 +252,13 @@ function dependsOnIteration(value, serialize, loop, checker) {
189
252
  return false;
190
253
  function resolvesToIteration(expression, depth = 0, allowObjectLiteral = false) {
191
254
  const origin = unwrapExpression(expression);
192
- if (ts.isPropertyAccessExpression(origin) || ts.isElementAccessExpression(origin))
255
+ if (ts.isPropertyAccessExpression(origin))
193
256
  return resolvesToIteration(origin.expression, depth);
257
+ if (ts.isElementAccessExpression(origin))
258
+ return resolvesToIteration(origin.expression, depth) || resolvesToIteration(origin.argumentExpression, depth);
259
+ if (ts.isCallExpression(origin))
260
+ return (resolvesToIteration(origin.expression, depth) ||
261
+ origin.arguments.some((argument) => resolvesToIteration(argument, depth)));
194
262
  if (allowObjectLiteral && ts.isObjectLiteralExpression(origin)) {
195
263
  const names = origin.properties.map((property) => staticPropertyName(property.name));
196
264
  if (names.includes(undefined) || new Set(names).size !== names.length)
@@ -249,6 +317,26 @@ function isSavedForOutput(declaration, checker) {
249
317
  const references = (identifiersByName(statement.parent).get(name.text) ?? []).filter((candidate) => candidate !== name && valueSymbol(candidate, checker) === symbol);
250
318
  return references.length === 1 && isOutputArgument(enclosingText(references[0]));
251
319
  }
320
+ // Unwraps returned object/array/conditional expressions inside a mapping callback so per-item
321
+ // field serialization like `logs.map(log => ({ body: JSON.stringify(log.body) }))` is recognized.
322
+ function enclosingMappedValue(node) {
323
+ let value = enclosingText(node);
324
+ for (let parent = value.parent; parent; value = parent, parent = parent.parent) {
325
+ if (ts.isParenthesizedExpression(parent) ||
326
+ ts.isPropertyAssignment(parent) ||
327
+ ts.isObjectLiteralExpression(parent) ||
328
+ ts.isArrayLiteralExpression(parent) ||
329
+ ts.isAsExpression(parent) ||
330
+ ts.isSatisfiesExpression(parent) ||
331
+ ts.isTypeAssertionExpression(parent) ||
332
+ ts.isNonNullExpression(parent) ||
333
+ (ts.isConditionalExpression(parent) && (parent.whenTrue === value || parent.whenFalse === value))) {
334
+ continue;
335
+ }
336
+ return value;
337
+ }
338
+ return value;
339
+ }
252
340
  // The value a pass produces: what a `map` or `flatMap` callback returns, or what it pushes or writes.
253
341
  // Serializing each item there cannot move out of the loop.
254
342
  function isPerItemOutput(call, loop, checker) {
@@ -263,25 +351,57 @@ function isPerItemOutput(call, loop, checker) {
263
351
  if (!MAPPING_METHODS.has(loop.expression.name.text))
264
352
  return false;
265
353
  const callback = loop.arguments[0];
266
- if (ts.isArrowFunction(callback) && callback.body === value)
354
+ const mapped = enclosingMappedValue(call);
355
+ if (ts.isArrowFunction(callback) &&
356
+ !ts.isBlock(callback.body) &&
357
+ ts.isExpression(mapped) &&
358
+ unwrapExpression(callback.body) === unwrapExpression(mapped)) {
267
359
  return true;
268
- return ts.isReturnStatement(parent) && ts.findAncestor(parent, ts.isFunctionLike) === callback;
360
+ }
361
+ return ts.isReturnStatement(mapped.parent) && ts.findAncestor(mapped.parent, ts.isFunctionLike) === callback;
269
362
  }
270
363
  // A `for` initializer and a `for...of` iterable are evaluated once, before the first pass.
271
364
  function runsOncePerLoop(node, loop) {
272
365
  const setup = ts.isForStatement(loop) ? loop.initializer : ts.isForOfStatement(loop) ? loop.expression : undefined;
273
366
  return setup !== undefined && node.pos >= setup.pos && node.end <= setup.end;
274
367
  }
368
+ function isEscapingThrow(call, loop) {
369
+ if (ts.isCallExpression(loop))
370
+ return false;
371
+ const statement = ts.findAncestor(call, (node) => ts.isThrowStatement(node) || ts.isFunctionLike(node));
372
+ if (!statement || !ts.isThrowStatement(statement))
373
+ return false;
374
+ for (let child = statement; child.parent && !ts.isFunctionLike(child); child = child.parent) {
375
+ const parent = child.parent;
376
+ if (!ts.isTryStatement(parent))
377
+ continue;
378
+ if ((parent.tryBlock === child && parent.catchClause) || (parent.finallyBlock && parent.finallyBlock !== child))
379
+ return false;
380
+ }
381
+ return true;
382
+ }
383
+ function isJsonEquality(call) {
384
+ const parent = enclosingText(call).parent;
385
+ return (ts.isBinaryExpression(parent) &&
386
+ [
387
+ ts.SyntaxKind.EqualsEqualsEqualsToken,
388
+ ts.SyntaxKind.ExclamationEqualsEqualsToken,
389
+ ts.SyntaxKind.EqualsEqualsToken,
390
+ ts.SyntaxKind.ExclamationEqualsToken,
391
+ ].includes(parent.operatorToken.kind));
392
+ }
275
393
  function checkJsonStringifyInLoop(call, context, cliReason) {
276
394
  if (!isGlobalMethodCall(call, 'JSON', 'stringify', context.checker))
277
395
  return;
278
396
  let loop = enclosingLoop(call);
279
397
  while (loop && runsOncePerLoop(call, loop))
280
398
  loop = enclosingLoop(loop);
281
- if (!loop)
399
+ if (!loop || isEscapingThrow(call, loop))
282
400
  return;
283
401
  const [value] = call.arguments;
284
- if (value && isPerItemOutput(call, loop, context.checker) && dependsOnIteration(value, call, loop, context.checker))
402
+ if (value &&
403
+ (isPerItemOutput(call, loop, context.checker) || isJsonEquality(call)) &&
404
+ dependsOnIteration(value, call, loop, context.checker))
285
405
  return;
286
406
  context.report(call, 'json-stringify-in-loop', 'JSON.stringify runs inside a loop; serialize once outside the loop or stream the output.', cliReason);
287
407
  }
@@ -1,6 +1,7 @@
1
1
  // Shared by the rules that only matter when the work happens for a request: which function is a
2
2
  // request handler, and whether a value ends up in its response.
3
3
  import { ts } from '../engine/compiler.js';
4
+ import { isProvenFastifyReceiver } from './fastify-receivers.js';
4
5
  const ROUTE_DECORATORS = new Set([
5
6
  'Get',
6
7
  'Post',
@@ -30,7 +31,21 @@ const USE_SERVER_DIRECTIVE = 'use server';
30
31
  const HONO_MODULE = /^@?hono(?:[/-]|$)/;
31
32
  const FASTIFY_MODULE = /^(?:fastify|@fastify\/|fastify-)/;
32
33
  const ROUTE_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'all', 'head', 'options', 'on', 'route']);
33
- const FASTIFY_HANDLER_OPTIONS = new Set(['handler', 'preHandler', 'onRequest', 'preValidation', 'preParsing']);
34
+ const LEGACY_FASTIFY_OPTIONS = new Set(['handler', 'preHandler', 'onRequest', 'preValidation', 'preParsing']);
35
+ const FASTIFY_REQUEST_HOOKS = new Set([
36
+ 'onRequest',
37
+ 'preParsing',
38
+ 'preValidation',
39
+ 'preHandler',
40
+ 'preSerialization',
41
+ 'onError',
42
+ 'onSend',
43
+ 'onResponse',
44
+ 'onTimeout',
45
+ 'onRequestAbort',
46
+ ]);
47
+ const FASTIFY_RESPONSE_TRANSFORMS = new Set(['preSerialization', 'onSend']);
48
+ const FASTIFY_HOOKS_WITHOUT_REPLY = new Set(['onError', 'onResponse', 'onTimeout', 'onRequestAbort']);
34
49
  const TYPED_REQUEST_PARAMETERS = new Set(['FastifyRequest', 'NextApiRequest']);
35
50
  const HONO_CONTEXT_NAME = 'c';
36
51
  const HONO_CONTEXT_MEMBERS = new Set(['req', 'json', 'text', 'html']);
@@ -72,11 +87,54 @@ function isFunctionLikeDeclaration(node) {
72
87
  ts.isFunctionExpression(node) ||
73
88
  ts.isArrowFunction(node));
74
89
  }
75
- function hasDecoratorNamed(node, names) {
76
- return !!node.modifiers?.some((modifier) => ts.isDecorator(modifier) &&
77
- ts.isCallExpression(modifier.expression) &&
78
- ts.isIdentifier(modifier.expression.expression) &&
79
- names.has(modifier.expression.expression.text));
90
+ const nestRouteImports = new WeakMap();
91
+ function nestBindings(file) {
92
+ const cached = nestRouteImports.get(file);
93
+ if (cached)
94
+ return cached;
95
+ const aliases = new Set();
96
+ const namespaces = new Set();
97
+ for (const statement of file.statements) {
98
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier))
99
+ continue;
100
+ const module = statement.moduleSpecifier.text;
101
+ if (module !== '@nestjs/common' && module !== '@nestjs/graphql')
102
+ continue;
103
+ const bindings = statement.importClause?.namedBindings;
104
+ if (statement.importClause?.isTypeOnly || !bindings)
105
+ continue;
106
+ if (ts.isNamespaceImport(bindings)) {
107
+ namespaces.add(bindings.name.text);
108
+ continue;
109
+ }
110
+ for (const item of bindings.elements) {
111
+ if (item.isTypeOnly)
112
+ continue;
113
+ if (ROUTE_DECORATORS.has((item.propertyName ?? item.name).text))
114
+ aliases.add(item.name.text);
115
+ }
116
+ }
117
+ const result = { aliases, namespaces };
118
+ nestRouteImports.set(file, result);
119
+ return result;
120
+ }
121
+ function isRouteDecorator(modifier) {
122
+ if (!ts.isDecorator(modifier) || !ts.isCallExpression(modifier.expression))
123
+ return false;
124
+ const callee = modifier.expression.expression;
125
+ if (ts.isIdentifier(callee) && ROUTE_DECORATORS.has(callee.text))
126
+ return true;
127
+ // File-level classes can use renamed or namespaced Nest imports without the packages being installed.
128
+ const declaration = modifier.parent.parent;
129
+ if (!ts.isClassDeclaration(declaration) || !ts.isSourceFile(declaration.parent))
130
+ return false;
131
+ const { aliases, namespaces } = nestBindings(declaration.parent);
132
+ if (ts.isIdentifier(callee))
133
+ return aliases.has(callee.text);
134
+ return (ts.isPropertyAccessExpression(callee) &&
135
+ ts.isIdentifier(callee.expression) &&
136
+ namespaces.has(callee.expression.text) &&
137
+ ROUTE_DECORATORS.has(callee.name.text));
80
138
  }
81
139
  function parameterName(parameter) {
82
140
  return parameter && ts.isIdentifier(parameter.name) ? parameter.name.text : undefined;
@@ -224,26 +282,52 @@ function isHonoHandler(node) {
224
282
  const looksLikeHono = importsModule(node, HONO_MODULE) || contextName === HONO_CONTEXT_NAME;
225
283
  return looksLikeHono && usesHonoContext(node, contextName);
226
284
  }
227
- function isFastifyRouteOption(node) {
228
- const property = ts.isMethodDeclaration(node) ? node : node.parent;
285
+ function fastifyRouteOption(node) {
286
+ let value = ts.isMethodDeclaration(node) ? node : node.parent;
287
+ const array = ts.isArrayLiteralExpression(value);
288
+ if (array)
289
+ value = value.parent;
290
+ const property = value;
229
291
  if (!ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property))
230
- return false;
231
- if (!ts.isIdentifier(property.name) || !FASTIFY_HANDLER_OPTIONS.has(property.name.text))
232
- return false;
292
+ return;
293
+ if (!ts.isIdentifier(property.name) && !ts.isStringLiteralLike(property.name))
294
+ return;
295
+ if (!FASTIFY_REQUEST_HOOKS.has(property.name.text) && (array || property.name.text !== 'handler'))
296
+ return;
233
297
  const options = property.parent;
234
298
  const call = ts.isObjectLiteralExpression(options) && options.parent;
235
299
  if (!call || !isMemberCall(call))
236
- return false;
237
- return ROUTE_METHODS.has(call.expression.name.text) && isFastifyReceiver(call);
300
+ return;
301
+ if (!ROUTE_METHODS.has(call.expression.name.text))
302
+ return;
303
+ const name = property.name.text;
304
+ // New hook shapes need actual receiver evidence. The old route shapes keep their existing coverage.
305
+ const fastify = array || !LEGACY_FASTIFY_OPTIONS.has(name)
306
+ ? isProvenFastifyReceiver(call.expression.expression)
307
+ : isFastifyReceiver(call);
308
+ return fastify ? name : undefined;
238
309
  }
239
310
  function isFastifyReceiver(call) {
240
311
  const receiver = call.expression.expression;
241
312
  return importsModule(call, FASTIFY_MODULE) || (ts.isIdentifier(receiver) && receiver.text === 'fastify');
242
313
  }
314
+ function fastifyHook(node) {
315
+ const call = node.parent;
316
+ if (!isMemberCall(call) || call.expression.name.text !== 'addHook')
317
+ return;
318
+ const [name, callback] = call.arguments;
319
+ return !!name &&
320
+ ts.isStringLiteralLike(name) &&
321
+ FASTIFY_REQUEST_HOOKS.has(name.text) &&
322
+ callback === node &&
323
+ isProvenFastifyReceiver(call.expression.expression)
324
+ ? name.text
325
+ : undefined;
326
+ }
243
327
  function isFastifyHandler(node) {
244
328
  if (!isFunctionLikeDeclaration(node))
245
329
  return false;
246
- if (isFastifyRouteOption(node))
330
+ if (fastifyRouteOption(node) || fastifyHook(node))
247
331
  return true;
248
332
  const call = routeCall(node);
249
333
  if (!call || !node.parameters.length || call.expression.name.text === 'use')
@@ -301,7 +385,7 @@ function computeIsRequestHandler(node) {
301
385
  if (!node.body)
302
386
  return false;
303
387
  if (ts.isMethodDeclaration(node))
304
- return hasDecoratorNamed(node, ROUTE_DECORATORS) || isFastifyRouteOption(node);
388
+ return node.modifiers?.some(isRouteDecorator) === true || fastifyRouteOption(node) !== undefined;
305
389
  const [first, second] = node.parameters.map(parameterName);
306
390
  if (first && REQUEST_PARAMETER.test(first)) {
307
391
  if (second && RESPONSE_PARAMETER.test(second))
@@ -354,16 +438,27 @@ function identifiersNamed(root, name, declaration) {
354
438
  function isTransparent(node) {
355
439
  return TRANSPARENT_KINDS.some((kind) => ts[kind](node));
356
440
  }
441
+ function returnsFromHandler(parent, value, handler) {
442
+ if (ts.isReturnStatement(parent))
443
+ return ts.findAncestor(parent, ts.isFunctionLike) === handler;
444
+ return ts.isArrowFunction(parent) && parent.body === value && parent === handler;
445
+ }
446
+ function reachesResponse(value, handler) {
447
+ const fastify = fastifyRouteOption(handler) ?? fastifyHook(handler);
448
+ if (fastify && FASTIFY_HOOKS_WITHOUT_REPLY.has(fastify))
449
+ return false;
450
+ // Ordinary hooks continue the lifecycle on return. Only payload hooks forward a returned value.
451
+ const sendsReturnValue = !fastify || fastify === 'handler' || FASTIFY_RESPONSE_TRANSFORMS.has(fastify);
452
+ return followsResponse(value, handler, sendsReturnValue, 0);
453
+ }
357
454
  // True when `value` is returned from `handler` or passed to a response call, possibly after being
358
455
  // wrapped in an object or array, mapped, or stored in a local that is then returned. Stops at
359
456
  // nested callbacks.
360
- function reachesResponse(value, handler, depth = 0) {
457
+ function followsResponse(value, handler, sendsReturnValue, depth) {
361
458
  let current = value;
362
459
  for (let parent = current.parent; parent; current = parent, parent = parent.parent) {
363
- if (ts.isReturnStatement(parent))
364
- return ts.findAncestor(parent, ts.isFunctionLike) === handler;
365
- if (ts.isArrowFunction(parent) && parent.body === current)
366
- return parent === handler;
460
+ if (returnsFromHandler(parent, current, handler))
461
+ return sendsReturnValue;
367
462
  if (ts.isFunctionLike(parent))
368
463
  return false;
369
464
  if (isTransparent(parent))
@@ -390,14 +485,16 @@ function reachesResponse(value, handler, depth = 0) {
390
485
  continue;
391
486
  }
392
487
  if (ts.isVariableDeclaration(parent) && parent.initializer === current) {
393
- return ts.isIdentifier(parent.name) && depth < MAX_ALIAS_DEPTH && usesReachResponse(parent.name, handler, depth);
488
+ return (ts.isIdentifier(parent.name) &&
489
+ depth < MAX_ALIAS_DEPTH &&
490
+ usesReachResponse(parent.name, handler, sendsReturnValue, depth));
394
491
  }
395
492
  return false;
396
493
  }
397
494
  return false;
398
495
  }
399
- function usesReachResponse(declaredName, handler, depth) {
400
- return identifiersNamed(handler.body, declaredName.text, declaredName).some((use) => reachesResponse(use, handler, depth + 1));
496
+ function usesReachResponse(declaredName, handler, sendsReturnValue, depth) {
497
+ return identifiersNamed(handler.body, declaredName.text, declaredName).some((use) => followsResponse(use, handler, sendsReturnValue, depth + 1));
401
498
  }
402
499
  const USER_SCOPED_FIELDS = new Set([
403
500
  'userId',
@@ -195,6 +195,7 @@ export function sortExtremeFix({ node }) {
195
195
  text: `${array}.reduce((${best}, value) => (value ${comparison} ${best} ? value : ${best}), ${array}[0])`,
196
196
  },
197
197
  ],
198
- note: 'One pass, no copy and no spread limit; an empty array still gives undefined. Like the sort, this assumes plain numbers without NaN or holes.',
198
+ requiresReview: true,
199
+ note: 'Confirm the array has no holes or NaN values. The reduction can return a different result for either input.',
199
200
  };
200
201
  }
@@ -1,5 +1,4 @@
1
- // Site fixes for collection rules. Each builder returns undefined unless the rewrite provably keeps
2
- // behavior.
1
+ // Site fixes for collection rules.
3
2
  import { membershipFix } from './collection-membership.js';
4
3
  import { findFix } from './collection-find.js';
5
4
  import { filterExistenceFix, sortExtremeFix } from './collection-existence.js';