loadwise 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -0,0 +1,229 @@
1
+ import { ts } from '../../performance/engine/compiler.js';
2
+ import { symbolOf } from '../../shared/analysis/ast-semantics.js';
3
+ import { importedFrom } from '../bindings.js';
4
+ import { isProjectSource } from './summaries.js';
5
+ import { localDeclaration, maxSchemaDepth, objectFields } from './validators.js';
6
+ function priorValidationStatement(use) {
7
+ const statement = ts.findAncestor(use, ts.isStatement);
8
+ if (!statement || !ts.isBlock(statement.parent))
9
+ return;
10
+ const block = statement.parent;
11
+ const index = block.statements.indexOf(statement);
12
+ if (index > 0)
13
+ return block.statements[index - 1];
14
+ // A rejecting validation before a try block must still succeed before the query inside it runs.
15
+ const owner = block.parent;
16
+ if (index === 0 && ts.isTryStatement(owner) && owner.tryBlock === block && ts.isBlock(owner.parent))
17
+ return owner.parent.statements[owner.parent.statements.indexOf(owner) - 1];
18
+ }
19
+ function ordinaryPropertyCall(node) {
20
+ if (!node || !ts.isCallExpression(node) || node.questionDotToken)
21
+ return;
22
+ const member = ts.skipOuterExpressions(node.expression);
23
+ if (ts.isPropertyAccessExpression(member) && !member.questionDotToken)
24
+ return { call: node, member };
25
+ }
26
+ function plainStringModifier(call, name, library) {
27
+ if (library === 'joi' && name === 'required')
28
+ return call.arguments.length === 0;
29
+ return (['min', 'max', 'length'].includes(name) && call.arguments.length === 1 && ts.isNumericLiteral(call.arguments[0]));
30
+ }
31
+ function plainStringSchema(node, library, checker) {
32
+ let current = ts.skipOuterExpressions(node);
33
+ for (let depth = 0; depth < maxSchemaDepth; depth++) {
34
+ const method = ordinaryPropertyCall(current);
35
+ if (!method)
36
+ return false;
37
+ const { call, member } = method;
38
+ const owner = ts.skipOuterExpressions(member.expression);
39
+ const name = member.name.text;
40
+ if (ts.isIdentifier(owner) && originalSchemaLibrary(owner, checker) === library)
41
+ return name === 'string' && call.arguments.length === 0;
42
+ if (!plainStringModifier(call, name, library))
43
+ return false;
44
+ current = owner;
45
+ }
46
+ return false;
47
+ }
48
+ function originalSchemaLibrary(root, checker) {
49
+ const declaration = localDeclaration(root, checker);
50
+ if (declaration && isProjectSource(declaration.getSourceFile()))
51
+ return;
52
+ const binding = importedFrom(root, checker);
53
+ if (!binding)
54
+ return;
55
+ const namespace = binding.exported === '*' || binding.exported === 'default';
56
+ if (binding.module === 'joi' && namespace)
57
+ return 'joi';
58
+ if (binding.module === 'zod' && (namespace || binding.exported === 'z'))
59
+ return 'zod';
60
+ }
61
+ const directValidationMethods = new Set([
62
+ 'parse',
63
+ 'parseAsync',
64
+ 'safeParse',
65
+ 'safeParseAsync',
66
+ 'validate',
67
+ 'validateAsync',
68
+ ]);
69
+ function namedImportAliases(source) {
70
+ const imports = new Map();
71
+ for (const statement of source.statements) {
72
+ if (!ts.isImportDeclaration(statement))
73
+ continue;
74
+ const bindings = statement.importClause?.namedBindings;
75
+ if (!bindings || !ts.isNamedImports(bindings))
76
+ continue;
77
+ for (const specifier of bindings.elements)
78
+ if (specifier.propertyName)
79
+ imports.set(specifier.name.text, specifier.propertyName.text);
80
+ }
81
+ return imports;
82
+ }
83
+ function indexPossibleEscapes(sources) {
84
+ const candidates = new Map();
85
+ for (const source of sources) {
86
+ if (!isProjectSource(source))
87
+ continue;
88
+ const imports = namedImportAliases(source);
89
+ function visit(node) {
90
+ if (!ts.isIdentifier(node))
91
+ return ts.forEachChild(node, visit);
92
+ const parent = node.parent;
93
+ if (ts.isImportSpecifier(parent) || (ts.isVariableDeclaration(parent) && node === parent.name))
94
+ return;
95
+ if (ts.isPropertyAccessExpression(parent) &&
96
+ parent.expression === node &&
97
+ directValidationMethods.has(parent.name.text) &&
98
+ ts.isCallExpression(parent.parent) &&
99
+ parent.parent.expression === parent)
100
+ return;
101
+ // A nested declaration may shadow an imported alias with the same spelling.
102
+ const imported = imports.get(node.text);
103
+ for (const name of imported && imported !== node.text ? [node.text, imported] : [node.text]) {
104
+ const uses = candidates.get(name);
105
+ if (uses)
106
+ uses.push(node);
107
+ else
108
+ candidates.set(name, [node]);
109
+ }
110
+ }
111
+ ts.forEachChild(source, visit);
112
+ }
113
+ return { candidates, escaped: new WeakSet() };
114
+ }
115
+ const schemaEscapes = new WeakMap();
116
+ function schemaUsesAreDirect(receiver, checker, program) {
117
+ const declaration = localDeclaration(receiver, checker);
118
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name))
119
+ return false;
120
+ let index = schemaEscapes.get(checker);
121
+ if (!index) {
122
+ const sources = program?.getSourceFiles?.() ?? program?.getToolingSourceFiles?.();
123
+ if (!sources)
124
+ return false;
125
+ index = indexPossibleEscapes(sources);
126
+ schemaEscapes.set(checker, index);
127
+ }
128
+ // Resolve only the spellings of schemas reaching a query, once for each spelling.
129
+ const name = declaration.name.text;
130
+ for (const candidate of index.candidates.get(name) ?? []) {
131
+ let symbol = symbolOf(candidate, checker);
132
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias)
133
+ symbol = checker.getAliasedSymbol(symbol);
134
+ if (symbol?.valueDeclaration)
135
+ index.escaped.add(symbol.valueDeclaration);
136
+ }
137
+ index.candidates.delete(name);
138
+ return !index.escaped.has(declaration);
139
+ }
140
+ function constantDestructuredBinding(value, checker) {
141
+ if (!ts.isIdentifier(value))
142
+ return;
143
+ const symbol = symbolOf(value, checker);
144
+ const binding = symbol?.valueDeclaration;
145
+ if (!binding || !ts.isBindingElement(binding) || !ts.isObjectBindingPattern(binding.parent))
146
+ return;
147
+ const declaration = binding.parent.parent;
148
+ if (ts.isVariableDeclaration(declaration) && declaration.parent.flags & ts.NodeFlags.Const)
149
+ return symbol;
150
+ }
151
+ function priorValidationCall(value) {
152
+ const statement = priorValidationStatement(value);
153
+ if (!statement || !ts.isExpressionStatement(statement))
154
+ return;
155
+ const expression = ts.skipOuterExpressions(statement.expression);
156
+ const awaited = ts.isAwaitExpression(expression);
157
+ const method = ordinaryPropertyCall(awaited ? ts.skipOuterExpressions(expression.expression) : expression);
158
+ if (!method || method.call.arguments.length !== 1)
159
+ return;
160
+ const input = ts.skipOuterExpressions(method.call.arguments[0]);
161
+ const receiver = ts.skipOuterExpressions(method.member.expression);
162
+ if (ts.isObjectLiteralExpression(input) && ts.isIdentifier(receiver))
163
+ return { input, receiver, awaited, methodName: method.member.name.text };
164
+ }
165
+ function plainStringFields(receiver, checker) {
166
+ const declaration = localDeclaration(receiver, checker);
167
+ if (!declaration ||
168
+ !ts.isVariableDeclaration(declaration) ||
169
+ !(declaration.parent.flags & ts.NodeFlags.Const) ||
170
+ !declaration.initializer)
171
+ return;
172
+ // Only the receiver's own uses are checked for escapes. Following another local alias would
173
+ // leave the original schema's uses unaccounted for.
174
+ const factory = ordinaryPropertyCall(ts.skipOuterExpressions(declaration.initializer));
175
+ if (!factory || factory.member.name.text !== 'object' || factory.call.arguments.length !== 1)
176
+ return;
177
+ const root = ts.skipOuterExpressions(factory.member.expression);
178
+ if (!ts.isIdentifier(root))
179
+ return;
180
+ const library = originalSchemaLibrary(root, checker);
181
+ if (library !== 'joi' && library !== 'zod')
182
+ return;
183
+ const shape = ts.skipOuterExpressions(factory.call.arguments[0]);
184
+ if (!ts.isObjectLiteralExpression(shape))
185
+ return;
186
+ const fields = objectFields(shape, checker);
187
+ if (!fields)
188
+ return;
189
+ // Sibling custom callbacks could rewrite the temporary object before the target is checked.
190
+ for (const [name, field] of fields) {
191
+ if (name === '__proto__' || !plainStringSchema(field, library, checker))
192
+ return;
193
+ }
194
+ return { fields, library };
195
+ }
196
+ function isThrowingValidation(method, awaited, library) {
197
+ if (library === 'joi')
198
+ return awaited && method === 'validateAsync';
199
+ return method === 'parse' || (awaited && method === 'parseAsync');
200
+ }
201
+ function matchesOriginalInput(input, fields, binding, checker) {
202
+ const actual = objectFields(input, checker);
203
+ if (!actual)
204
+ return false;
205
+ let matched = false;
206
+ for (const [name, original] of actual) {
207
+ if (name === '__proto__' || !ts.isIdentifier(original))
208
+ return false;
209
+ if (fields.has(name) && symbolOf(original, checker) === binding)
210
+ matched = true;
211
+ }
212
+ return matched;
213
+ }
214
+ // Throwing validation of a fresh object can prove one original const binding is a string before
215
+ // MongoDB sees it. It does not constrain the string's alphabet for any other type of sink.
216
+ function validatesOriginalString(value, checker, program) {
217
+ const binding = constantDestructuredBinding(value, checker);
218
+ if (!binding)
219
+ return false;
220
+ const validation = priorValidationCall(value);
221
+ if (!validation)
222
+ return false;
223
+ const { input, receiver, methodName, awaited } = validation;
224
+ const schema = plainStringFields(receiver, checker);
225
+ if (!schema || !isThrowingValidation(methodName, awaited, schema.library))
226
+ return false;
227
+ return (matchesOriginalInput(input, schema.fields, binding, checker) && schemaUsesAreDirect(receiver, checker, program));
228
+ }
229
+ export { validatesOriginalString };
@@ -536,4 +536,4 @@ function schemaCall(call, checker) {
536
536
  if (method === 'validate')
537
537
  return { schema: receiver, input, wrapper: library === 'joi' ? 'value' : undefined };
538
538
  }
539
- export { validatedField, schemaCall, schemaShape };
539
+ export { validatedField, schemaCall, schemaShape, localDeclaration, maxSchemaDepth, objectFields };
@@ -16,7 +16,9 @@ async function writeReviewHandoff(directory, command, details) {
16
16
  const event = { version: 1, command, directory, cwd: process.cwd(), ...details };
17
17
  try {
18
18
  const { file, id } = await saveHandoff(event);
19
- const source = id ? 'Use loadwise_read_report with id ' + JSON.stringify(id) + ', or read ' : 'Read ';
19
+ const source = id
20
+ ? `Use loadwise_read_report with id ${JSON.stringify(id)}. For paged results, pass each nextOffset as offset until nextOffset is null. Alternatively, read `
21
+ : 'Read ';
20
22
  console.error('If you need to hand this run to an agent, paste this message:');
21
23
  console.error('Review this Loadwise run without editing files. ' +
22
24
  source +
@@ -456,4 +456,20 @@ function isEffectivelySet(object, key, checker) {
456
456
  }
457
457
  return true;
458
458
  }
459
- export { constInitializer, effectiveProperty, forEachExecutedNode, immediateInvocation, isEffectivelySet, isUnshadowedGlobal, literalKey, neverEvaluatesRight, outermostExpression, resolveImportedBinding, resolveRequiredModule, staticFalsy, staticMemberName, staticNullish, staticPropertyName, symbolOf, unwrapExpression, };
459
+ // The module export a callee names, through aliased, default, namespace and require bindings:
460
+ // exported is a named export, 'default', or '*' for a whole required module. A member of a
461
+ // namespace, required module or default import (`pg.Pool`, `pg['Pool']`) is that module's export.
462
+ function importedMember(target, checker) {
463
+ const callee = unwrapExpression(target);
464
+ if (ts.isIdentifier(callee)) {
465
+ return resolveImportedBinding(callee, checker, { includeNamespaceImports: false, includeDefaultMembers: true });
466
+ }
467
+ if (!ts.isPropertyAccessExpression(callee) && !ts.isElementAccessExpression(callee))
468
+ return;
469
+ const member = staticMemberName(callee);
470
+ const owner = resolveImportedBinding(unwrapExpression(callee.expression), checker, { includeDefaultMembers: true });
471
+ if (member === undefined || !owner || (owner.exported !== '*' && owner.exported !== 'default'))
472
+ return;
473
+ return { module: owner.module, exported: member };
474
+ }
475
+ export { constInitializer, effectiveProperty, forEachExecutedNode, immediateInvocation, importedMember, isEffectivelySet, isUnshadowedGlobal, literalKey, neverEvaluatesRight, outermostExpression, resolveImportedBinding, resolveRequiredModule, staticFalsy, staticMemberName, staticNullish, staticPropertyName, symbolOf, unwrapExpression, };
@@ -4,6 +4,7 @@ import { ts } from '../../performance/engine/compiler.js';
4
4
  import { isRequestHandler } from '../../performance/request/request-handlers.js';
5
5
  import { isTestSource, isSeedSource } from '../../performance/analysis/review-context.js';
6
6
  import { callerNames } from './caller-name-inventory.js';
7
+ import { escapeRegExp } from '../system/text-helpers.js';
7
8
  const MAX_CALL_HOPS = 3;
8
9
  // A name defined in many files (`get`, `save`) cannot be traced cheaply or reliably, so it stays
9
10
  // unknown.
@@ -176,7 +177,7 @@ function callsDeclaration(call, declaration, checker) {
176
177
  symbol = checker.getAliasedSymbol(symbol);
177
178
  return Boolean(symbol?.declarations?.includes(declaration));
178
179
  }
179
- function callersOf(functionNode, program) {
180
+ function findCallers(functionNode, program) {
180
181
  let byFunction = callersCache.get(program);
181
182
  if (byFunction) {
182
183
  const cached = byFunction.get(functionNode);
@@ -187,35 +188,70 @@ function callersOf(functionNode, program) {
187
188
  byFunction = new WeakMap();
188
189
  callersCache.set(program, byFunction);
189
190
  }
191
+ const search = searchCallers(functionNode, program);
192
+ byFunction.set(functionNode, search);
193
+ return search;
194
+ }
195
+ function searchCallers(functionNode, program) {
190
196
  const declaration = declarationOf(functionNode);
191
- if (!declaration) {
192
- byFunction.set(functionNode, []);
193
- return [];
194
- }
197
+ if (!declaration)
198
+ return { calls: [], complete: false };
195
199
  const nameNode = declaration.name;
196
200
  const name = nameNode && 'text' in nameNode ? nameNode.text : undefined;
197
201
  const files = name === undefined ? undefined : callerIndex(program).get(name);
198
- if (!files || files.length > MAX_CALLER_FILES) {
199
- byFunction.set(functionNode, []);
200
- return [];
201
- }
202
+ if (!files)
203
+ return { calls: [], complete: name !== undefined };
204
+ if (files.length > MAX_CALLER_FILES)
205
+ return { calls: [], complete: false };
202
206
  const checker = program.getTypeChecker();
203
207
  const candidates = [];
208
+ let capped = false;
204
209
  for (const source of files) {
205
- const sites = callSites(source).get(name ?? '');
206
- if (!sites)
207
- continue;
210
+ const sites = callSites(source).get(name ?? '') ?? [];
208
211
  for (const site of sites) {
209
- candidates.push(site);
210
- if (candidates.length >= MAX_CALL_SITES)
212
+ if (candidates.length >= MAX_CALL_SITES) {
213
+ capped = true;
211
214
  break;
215
+ }
216
+ candidates.push(site);
212
217
  }
213
- if (candidates.length >= MAX_CALL_SITES)
218
+ if (capped)
214
219
  break;
215
220
  }
216
- const resolved = candidates.filter((call) => callsDeclaration(call, declaration, checker));
217
- byFunction.set(functionNode, resolved);
218
- return resolved;
221
+ const calls = candidates.filter((call) => callsDeclaration(call, declaration, checker));
222
+ const unresolved = candidates.some((call) => !resolvesCallee(call, checker));
223
+ return { calls, complete: !capped && !unresolved };
224
+ }
225
+ function resolvesCallee(call, checker) {
226
+ const nameNode = calleeNameNode(call);
227
+ return Boolean(nameNode && checker.getSymbolAtLocation(nameNode)?.declarations?.length);
228
+ }
229
+ function callersOf(functionNode, program) {
230
+ return findCallers(functionNode, program).calls;
231
+ }
232
+ // Calls are indexed by the declared name, so a default export or an `f as g` import or re-export
233
+ // anywhere in the project hides the calls made through the new name.
234
+ function mayBeRenamed(declaration, program) {
235
+ if (ts.isFunctionDeclaration(declaration) && ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Default)
236
+ return true;
237
+ const nameNode = declaration.name;
238
+ const name = nameNode && 'text' in nameNode ? nameNode.text : undefined;
239
+ if (name === undefined)
240
+ return true;
241
+ // A string-literal method name such as `'a['` can hold any regular-expression metacharacter.
242
+ const escaped = escapeRegExp(name);
243
+ const renamed = new RegExp(`(?<![\\w$])${escaped}\\s+as(?![\\w$])|export\\s+default\\s+${escaped}(?![\\w$])`);
244
+ return projectSources(program).some((source) => source.text.includes(name) && renamed.test(source.text));
245
+ }
246
+ // Every call to a named project function outside tests, or undefined when the search cannot vouch
247
+ // for all of them: a common name, too many call sites, a same-named call the checker cannot resolve,
248
+ // or a rename that hides calls. References that are not calls (a function passed as a callback) are not seen.
249
+ function allProjectCallers(functionNode, program) {
250
+ const search = findCallers(functionNode, program);
251
+ const declaration = declarationOf(functionNode);
252
+ if (!search.complete || !declaration || mayBeRenamed(declaration, program))
253
+ return;
254
+ return search.calls;
219
255
  }
220
256
  // Request when a project function is called, within a few hops, from a request handler; otherwise
221
257
  // background when a job calls it. Callers are found through the type checker, so imports, aliases
@@ -265,4 +301,4 @@ function hotPathOf(node, program) {
265
301
  return result('unknown', 'call graph unavailable');
266
302
  }
267
303
  }
268
- export { hotPathOf };
304
+ export { allProjectCallers, hotPathOf };
@@ -0,0 +1,232 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+ import { readBoundedFixText } from '../fix/read-fix-text.js';
5
+ const nextConfigNames = ['next.config.js', 'next.config.mjs', 'next.config.ts', 'next.config.mts'];
6
+ const configLimit = 256 * 1024;
7
+ const sensitiveName = /secret|password|passwd|token|credential|private.?key|api.?key|database.?url|service.?role/i;
8
+ const reservedName = /^(?:NODE_.+|__.+|NEXT_RUNTIME$)/i;
9
+ const emptyKeys = new Set();
10
+ let inventory;
11
+ function withNextEnvInventory(scan, dependencies) {
12
+ if (inventory)
13
+ return scan();
14
+ inventory = { keys: new Map(), owners: new Map(), dependencies };
15
+ try {
16
+ return scan();
17
+ }
18
+ finally {
19
+ inventory = undefined;
20
+ }
21
+ }
22
+ function owningDirectory(directory, state) {
23
+ if (state?.owners.has(directory))
24
+ return state.owners.get(directory);
25
+ const manifest = path.join(directory, 'package.json');
26
+ state?.dependencies?.add(manifest);
27
+ const boundary = fs.lstatSync(manifest, { throwIfNoEntry: false });
28
+ const parent = path.dirname(directory);
29
+ const owner = boundary
30
+ ? boundary.isFile()
31
+ ? directory
32
+ : undefined
33
+ : parent === directory || fs.lstatSync(path.join(directory, '.git'), { throwIfNoEntry: false })
34
+ ? undefined
35
+ : owningDirectory(parent, state);
36
+ state?.owners.set(directory, owner);
37
+ return owner;
38
+ }
39
+ function unwrap(expression) {
40
+ while (ts.isParenthesizedExpression(expression) ||
41
+ ts.isAsExpression(expression) ||
42
+ ts.isSatisfiesExpression(expression) ||
43
+ ts.isTypeAssertionExpression(expression))
44
+ expression = expression.expression;
45
+ return expression;
46
+ }
47
+ function configBindings(source) {
48
+ const counts = new Map();
49
+ const constants = new Map();
50
+ let onlyProcessEnv = true;
51
+ function visit(node) {
52
+ if (ts.isIdentifier(node)) {
53
+ counts.set(node.text, (counts.get(node.text) ?? 0) + 1);
54
+ if (node.text === 'process') {
55
+ const member = node.parent;
56
+ if (!ts.isPropertyAccessExpression(member) || member.expression !== node || member.name.text !== 'env')
57
+ onlyProcessEnv = false;
58
+ }
59
+ }
60
+ ts.forEachChild(node, visit);
61
+ }
62
+ visit(source);
63
+ for (const statement of source.statements) {
64
+ if (!ts.isVariableStatement(statement))
65
+ continue;
66
+ const list = statement.declarationList;
67
+ for (const declaration of list.declarations) {
68
+ if (!ts.isIdentifier(declaration.name))
69
+ continue;
70
+ const name = declaration.name.text;
71
+ const initializer = !constants.has(name) && list.flags & ts.NodeFlags.Const && declaration.initializer;
72
+ constants.set(name, initializer ? unwrap(initializer) : undefined);
73
+ }
74
+ }
75
+ return { counts, constants, onlyProcessEnv };
76
+ }
77
+ function importedDefault(source, identifier, module) {
78
+ return source.statements.some((statement) => ts.isImportDeclaration(statement) &&
79
+ !statement.importClause?.isTypeOnly &&
80
+ statement.importClause?.name?.text === identifier.text &&
81
+ ts.isStringLiteral(statement.moduleSpecifier) &&
82
+ statement.moduleSpecifier.text === module);
83
+ }
84
+ function exportsConfig(expression) {
85
+ return (ts.isPropertyAccessExpression(expression) &&
86
+ ts.isIdentifier(expression.expression) &&
87
+ expression.expression.text === 'module' &&
88
+ expression.name.text === 'exports');
89
+ }
90
+ function exportedObject(source, { counts, constants }) {
91
+ const exports = [];
92
+ for (const statement of source.statements) {
93
+ if (ts.isExportAssignment(statement)) {
94
+ if (!statement.isExportEquals)
95
+ exports.push(statement.expression);
96
+ }
97
+ else if (ts.isExpressionStatement(statement) && ts.isBinaryExpression(statement.expression)) {
98
+ const { left, right, operatorToken } = statement.expression;
99
+ if (operatorToken.kind === ts.SyntaxKind.EqualsToken && exportsConfig(left) && counts.get('module') === 1)
100
+ exports.push(right);
101
+ }
102
+ }
103
+ if (exports.length !== 1)
104
+ return;
105
+ let value = unwrap(exports[0]);
106
+ if (ts.isCallExpression(value) && ts.isIdentifier(value.expression) && value.arguments.length === 1) {
107
+ const alias = value.expression;
108
+ const factory = constants.get(alias.text);
109
+ if (!factory ||
110
+ !ts.isCallExpression(factory) ||
111
+ !ts.isIdentifier(factory.expression) ||
112
+ counts.get(alias.text) !== 2 ||
113
+ counts.get(factory.expression.text) !== 2 ||
114
+ !importedDefault(source, factory.expression, 'next-intl/plugin'))
115
+ return;
116
+ // The documented next-intl wrapper forwards the provided env object.
117
+ value = unwrap(value.arguments[0]);
118
+ }
119
+ if (ts.isIdentifier(value)) {
120
+ if (counts.get(value.text) !== 2)
121
+ return;
122
+ const initializer = constants.get(value.text);
123
+ if (!initializer)
124
+ return;
125
+ value = initializer;
126
+ }
127
+ return ts.isObjectLiteralExpression(value) ? value : undefined;
128
+ }
129
+ function staticProperties(object) {
130
+ const result = new Map();
131
+ for (const property of object.properties) {
132
+ const key = property.name;
133
+ if (!key || (!ts.isIdentifier(key) && !ts.isStringLiteral(key)) || result.has(key.text))
134
+ return;
135
+ result.set(key.text, property);
136
+ }
137
+ return result;
138
+ }
139
+ function configReadName(value) {
140
+ if (!ts.isPropertyAccessExpression(value) || !ts.isPropertyAccessExpression(value.expression))
141
+ return;
142
+ const receiver = value.expression;
143
+ return receiver.name.text === 'env' && ts.isIdentifier(receiver.expression) && receiver.expression.text === 'process'
144
+ ? value.name.text
145
+ : undefined;
146
+ }
147
+ function publicValue(value, onlyProcessEnv) {
148
+ const candidate = unwrap(value);
149
+ if (ts.isStringLiteralLike(candidate))
150
+ return true;
151
+ if (!ts.isBinaryExpression(candidate) || !ts.isStringLiteralLike(unwrap(candidate.right)))
152
+ return false;
153
+ const operator = candidate.operatorToken.kind;
154
+ if (operator !== ts.SyntaxKind.BarBarToken && operator !== ts.SyntaxKind.QuestionQuestionToken)
155
+ return false;
156
+ const name = configReadName(unwrap(candidate.left));
157
+ return Boolean(name && !sensitiveName.test(name) && onlyProcessEnv);
158
+ }
159
+ function configuredKeys(directory, state) {
160
+ const paths = nextConfigNames.map((name) => path.join(directory, name));
161
+ for (const filename of paths)
162
+ state?.dependencies?.add(filename);
163
+ const existing = paths.filter((filename) => fs.lstatSync(filename, { throwIfNoEntry: false }));
164
+ if (existing.length !== 1)
165
+ return emptyKeys;
166
+ const filename = existing[0];
167
+ // Native Node TypeScript support determines whether Next will load .mts.
168
+ if (filename.endsWith('.mts') || !fs.lstatSync(filename).isFile())
169
+ return emptyKeys;
170
+ const text = readBoundedFixText(filename, configLimit);
171
+ if (!text)
172
+ return emptyKeys;
173
+ const source = ts.createSourceFile(filename, text, ts.ScriptTarget.Latest, true);
174
+ if (source.parseDiagnostics?.length)
175
+ return emptyKeys;
176
+ const bindings = configBindings(source);
177
+ const config = exportedObject(source, bindings);
178
+ const properties = config && staticProperties(config);
179
+ if (!properties || properties.has('webpack') || properties.has('turbopack') || properties.has('__proto__'))
180
+ return emptyKeys;
181
+ const envProperty = properties.get('env');
182
+ if (!envProperty || !ts.isPropertyAssignment(envProperty))
183
+ return emptyKeys;
184
+ const env = unwrap(envProperty.initializer);
185
+ const entries = ts.isObjectLiteralExpression(env) ? staticProperties(env) : undefined;
186
+ const result = new Set();
187
+ for (const [key, entry] of entries ?? []) {
188
+ if (reservedName.test(key) || sensitiveName.test(key))
189
+ continue;
190
+ const value = ts.isPropertyAssignment(entry)
191
+ ? entry.initializer
192
+ : ts.isShorthandPropertyAssignment(entry)
193
+ ? bindings.constants.get(entry.name.text)
194
+ : undefined;
195
+ if (value && publicValue(value, bindings.onlyProcessEnv))
196
+ result.add(key);
197
+ }
198
+ return result;
199
+ }
200
+ function nextPublishedEnvKeys(filename) {
201
+ if (!path.isAbsolute(filename))
202
+ return emptyKeys;
203
+ try {
204
+ const owner = owningDirectory(path.dirname(filename), inventory);
205
+ if (!owner)
206
+ return emptyKeys;
207
+ const cached = inventory?.keys.get(owner);
208
+ if (cached)
209
+ return cached;
210
+ const keys = configuredKeys(owner, inventory);
211
+ inventory?.keys.set(owner, keys);
212
+ return keys;
213
+ }
214
+ catch {
215
+ // An unreadable, unsupported, or concurrently replaced config is not proof of publication.
216
+ return emptyKeys;
217
+ }
218
+ }
219
+ function nextEnvAncestorDependencies(directory) {
220
+ const dependencies = new Set();
221
+ try {
222
+ const owner = owningDirectory(path.resolve(directory), { owners: new Map(), keys: new Map(), dependencies });
223
+ if (owner)
224
+ for (const name of nextConfigNames)
225
+ dependencies.add(path.join(owner, name));
226
+ }
227
+ catch {
228
+ // The watcher still observes ordinary directory events when ancestry cannot be resolved.
229
+ }
230
+ return [...dependencies];
231
+ }
232
+ export { nextConfigNames, nextEnvAncestorDependencies, nextPublishedEnvKeys, withNextEnvInventory };