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,218 @@
1
+ import fs from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import ts from 'typescript';
5
+ import { readBoundedFixText } from '../../shared/fix/read-fix-text.js';
6
+ import { isRecord } from '../../shared/system/is-record.js';
7
+ import { isPathInside } from '../../shared/system/path-inside.js';
8
+ import { packageNameOf } from '../../shared/system/text-helpers.js';
9
+ import { maxConsumerBytes } from '../analysis/source-facts.js';
10
+ const manifestFile = 'package.json';
11
+ const packageName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
12
+ const explicitDependencies = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
13
+ const dependencyDeclarations = new Set([...explicitDependencies, 'overrides', 'resolutions']);
14
+ const packageToken = /[@a-zA-Z0-9._-]+(?:\/[@a-zA-Z0-9._-]+)*/g;
15
+ const lockfiles = /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.ya?ml|yarn\.lock|bun\.lockb?)$/i;
16
+ const binaryAssets = /\.(?:png|jpe?g|gif|ico|webp|avif|woff2?|ttf|otf)$/i;
17
+ // These packages can be injected into emitted output without a source-level import.
18
+ const compilerRuntimes = new Set([
19
+ 'tslib',
20
+ '@babel/runtime',
21
+ '@babel/runtime-corejs2',
22
+ '@babel/runtime-corejs3',
23
+ 'core-js',
24
+ 'core-js-pure',
25
+ 'regenerator-runtime',
26
+ '@swc/helpers',
27
+ ]);
28
+ const untrackedLoader = /\bcreateRequire\b|\b(?:import|require(?:\s*\.\s*resolve)?)\s*\(\s*(?:`(?!\.)[^`\\\r\n]*\$\{|(['"])(?!\.)[^'"\r\n]*\1\s*\+)/u;
29
+ const manualReview = 'Check deployment, plug-in and integration usage before removing the dependency.';
30
+ const installedSections = ['dependencies', 'optionalDependencies', 'peerDependencies', 'peerDependenciesMeta'];
31
+ const variablePreload = /(?:--(?:require|import|loader)|(?:^|\s)-r)(?:[=\s]+)["']?(?:\$|%)/;
32
+ function readEvidence(filename) {
33
+ try {
34
+ return readBoundedFixText(filename, maxConsumerBytes);
35
+ }
36
+ catch {
37
+ return;
38
+ }
39
+ }
40
+ function manifestObject(text) {
41
+ if (text === undefined)
42
+ return;
43
+ try {
44
+ const value = JSON.parse(text.replace(/^\uFEFF/u, ''));
45
+ if (isRecord(value))
46
+ return value;
47
+ }
48
+ catch {
49
+ return;
50
+ }
51
+ }
52
+ function declaredNames(manifest, section) {
53
+ const names = manifest[section];
54
+ return isRecord(names) ? Object.keys(names).filter((name) => packageName.test(name)) : [];
55
+ }
56
+ function installedFile(root, directory, name) {
57
+ try {
58
+ const manifest = path.join(directory, name, manifestFile);
59
+ if (!fs.existsSync(manifest))
60
+ return;
61
+ const filename = fs.realpathSync(manifest);
62
+ if (isPathInside(root, filename))
63
+ return filename;
64
+ }
65
+ catch {
66
+ return;
67
+ }
68
+ }
69
+ function candidatesFor(root, manifest, pending) {
70
+ const dependencies = new Set(explicitDependencies.flatMap((section) => declaredNames(manifest, section)));
71
+ const installed = new Map();
72
+ for (const name of dependencies) {
73
+ const filename = installedFile(root, path.join(root, 'node_modules'), name);
74
+ if (!filename)
75
+ continue;
76
+ const metadata = manifestObject(readEvidence(filename));
77
+ if (!metadata)
78
+ return new Set();
79
+ installed.set(name, metadata);
80
+ pending.add(filename);
81
+ }
82
+ const implied = new Set([
83
+ ...declaredNames(manifest, 'optionalDependencies'),
84
+ ...declaredNames(manifest, 'peerDependencies'),
85
+ ]);
86
+ const runtime = isRecord(manifest.dependencies) ? manifest.dependencies : {};
87
+ return new Set(declaredNames(manifest, 'dependencies').filter((name) => {
88
+ const metadata = installed.get(name);
89
+ const target = metadata?.name;
90
+ const range = runtime[name];
91
+ if (typeof target !== 'string' || !metadata)
92
+ return false;
93
+ const alias = typeof range === 'string' && (range === 'npm:' + target || range.startsWith('npm:' + target + '@'));
94
+ // A package providing a CLI can be invoked under a separate executable name or by a deployment script.
95
+ return ((target === name || alias) &&
96
+ !metadata.bin &&
97
+ !compilerRuntimes.has(target) &&
98
+ !implied.has(name) &&
99
+ !target.startsWith('@types/'));
100
+ }));
101
+ }
102
+ function omitInstalledRequirements(root, pending, candidates) {
103
+ for (const filename of pending) {
104
+ if (!candidates.size)
105
+ return;
106
+ const metadata = manifestObject(readEvidence(filename));
107
+ if (!metadata)
108
+ return candidates.clear();
109
+ const directories = (createRequire(filename).resolve.paths('package') ?? []).filter((directory) => isPathInside(root, directory));
110
+ const names = new Set(installedSections.flatMap((section) => declaredNames(metadata, section)));
111
+ for (const name of names) {
112
+ candidates.delete(name);
113
+ const target = firstInstalledFile(root, directories, name);
114
+ if (target)
115
+ pending.add(target);
116
+ }
117
+ }
118
+ }
119
+ function firstInstalledFile(root, directories, name) {
120
+ for (const directory of directories) {
121
+ const target = installedFile(root, directory, name);
122
+ if (target)
123
+ return target;
124
+ }
125
+ }
126
+ function omitTextReferences(candidates, text) {
127
+ for (const [token] of text.matchAll(packageToken)) {
128
+ candidates.delete(packageNameOf(token));
129
+ if (token.includes('node_modules/')) {
130
+ for (const installed of token.split(/(?:^|\/)node_modules\//).slice(1))
131
+ candidates.delete(packageNameOf(installed));
132
+ }
133
+ }
134
+ }
135
+ function hasCompleteEvidence(root, candidates, { inventory, usages, declarations }) {
136
+ if (usages.some(({ dynamicUnresolved }) => dynamicUnresolved.some(({ directory }) => directory === undefined)))
137
+ return false;
138
+ // Type-only, static, and literal runtime imports count, including escaped string literals the text
139
+ // pass would otherwise miss.
140
+ for (const source of [...usages, ...declarations]) {
141
+ for (const { specifier } of [...source.unresolved, ...(source.uncertainTypeImports ?? [])])
142
+ candidates.delete(packageNameOf(specifier));
143
+ }
144
+ for (const file of inventory) {
145
+ if (!candidates.size)
146
+ return false;
147
+ if (file === manifestFile || lockfiles.test(file) || binaryAssets.test(file))
148
+ continue;
149
+ const text = readEvidence(path.join(root, file));
150
+ if (text === undefined ||
151
+ untrackedLoader.test(text) ||
152
+ variablePreload.test(text) ||
153
+ /\bmodule\s*\.\s*require\b/.test(text))
154
+ return false;
155
+ if (file.endsWith('/package.json')) {
156
+ const nested = manifestObject(text);
157
+ if (!nested || nested.workspaces !== undefined)
158
+ return false;
159
+ }
160
+ omitTextReferences(candidates, text);
161
+ }
162
+ return true;
163
+ }
164
+ function manifestFindings(text, names) {
165
+ const source = ts.parseJsonText(manifestFile, text);
166
+ const statement = source.statements[0];
167
+ if (!statement || !ts.isExpressionStatement(statement) || !ts.isObjectLiteralExpression(statement.expression))
168
+ return [];
169
+ const dependencies = statement.expression.properties.find((property) => ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name) && property.name.text === 'dependencies');
170
+ if (!dependencies ||
171
+ !ts.isPropertyAssignment(dependencies) ||
172
+ !ts.isObjectLiteralExpression(dependencies.initializer))
173
+ return [];
174
+ return dependencies.initializer.properties.flatMap((property) => {
175
+ if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name) || !names.has(property.name.text))
176
+ return [];
177
+ const { line, character } = source.getLineAndCharacterOfPosition(property.name.getStart(source));
178
+ return [
179
+ {
180
+ ruleId: 'unused-dependency',
181
+ file: manifestFile,
182
+ line: line + 1,
183
+ column: character + 1,
184
+ message: 'No references to the installed runtime dependency "' + property.name.text + '" were found in this project.',
185
+ suggestion: manualReview,
186
+ },
187
+ ];
188
+ });
189
+ }
190
+ function checkUnusedDependencies(root, inputs) {
191
+ const { inventory } = inputs;
192
+ if (!inventory.includes(manifestFile))
193
+ return [];
194
+ if (inventory.some((file) => /(?:^|\/)(?:pnpm-workspace\.yaml|lerna\.json)$/iu.test(file)))
195
+ return [];
196
+ const manifestText = readEvidence(path.join(root, manifestFile));
197
+ const manifest = manifestObject(manifestText);
198
+ if (manifestText === undefined || manifest?.private !== true || manifest.workspaces !== undefined)
199
+ return [];
200
+ const scripts = isRecord(manifest.scripts) ? Object.values(manifest.scripts) : [];
201
+ if (scripts.some((script) => typeof script === 'string' && (variablePreload.test(script) || /\b(?:require|import)\s*\(/.test(script))))
202
+ return [];
203
+ const directory = fs.realpathSync(root);
204
+ const pending = new Set();
205
+ const candidates = candidatesFor(directory, manifest, pending);
206
+ if (inventory.some((file) => /\.[jt]sx$/i.test(file))) {
207
+ // JSX can load the configured JSX runtime even without a literal React or Preact import.
208
+ for (const name of ['react', 'react-dom', 'preact'])
209
+ candidates.delete(name);
210
+ }
211
+ const usage = Object.entries(manifest).filter(([name]) => !dependencyDeclarations.has(name));
212
+ omitTextReferences(candidates, JSON.stringify(usage));
213
+ if (!candidates.size || !hasCompleteEvidence(root, candidates, inputs))
214
+ return [];
215
+ omitInstalledRequirements(directory, pending, candidates);
216
+ return manifestFindings(manifestText, candidates);
217
+ }
218
+ export { checkUnusedDependencies };
@@ -34,6 +34,7 @@ function shareListRemovals(findings, selectedIds) {
34
34
  }
35
35
  function createUsageIndex(files, usages) {
36
36
  const reexportsByFile = new Map(files.map((file, index) => [file, usages[index].reexports]));
37
+ const thenReadsModule = new Set(files.filter((_file, index) => usages[index].thenReadsModule));
37
38
  const used = new Map();
38
39
  const pending = [];
39
40
  function mark(file, name) {
@@ -45,6 +46,9 @@ function createUsageIndex(files, usages) {
45
46
  if (names.has(everything) || names.has(wanted))
46
47
  continue;
47
48
  names.add(wanted);
49
+ // Using that `then` reads whichever exports it reaches through `this`.
50
+ if (wanted === 'then' && thenReadsModule.has(target))
51
+ pending.push([target, everything]);
48
52
  for (const reexport of reexportsByFile.get(target) ?? []) {
49
53
  queueReexportDependencies(wanted, reexport, pending);
50
54
  }
@@ -97,6 +97,9 @@ const PRISMA_OUTCOME = 'its checks run with reduced precision from schema.prisma
97
97
  function missingOutcome(packageName) {
98
98
  if (packageName === '@prisma/client')
99
99
  return PRISMA_OUTCOME;
100
+ if (packageName === 'mysql2') {
101
+ return 'its type-based checks need `npm install` and were skipped; source checks still run where supported';
102
+ }
100
103
  if (declarationRecognisedPackages.has(packageName)) {
101
104
  return 'its checks run with reduced precision from declarations until `npm install`';
102
105
  }
@@ -43,14 +43,14 @@ function printFullReport(result, values, baseline, print) {
43
43
  function printChangedFindings(findings, fixCommand, print) {
44
44
  for (const finding of findings) {
45
45
  print(`${finding.file}:${finding.line} ${findingLabel(finding)} ${finding.impactLevel}: ${finding.message}`);
46
- if (finding.fixable)
46
+ if (fixCommand && finding.fixable)
47
47
  print(` fix: ${fixCommand} --fix --only ${finding.id}`);
48
48
  print(` dismiss: // loadwise-reviewed ${finding.ruleId} -- <reason>`);
49
49
  }
50
50
  const fixableIds = findings
51
51
  .filter((finding) => finding.fixable && !finding.fix?.requiresReview)
52
52
  .map((finding) => finding.id);
53
- if (fixableIds.length > 1)
53
+ if (fixCommand && fixableIds.length > 1)
54
54
  print(`Fix all: ${fixCommand} --fix --only ${fixableIds.join(',')}`);
55
55
  print(findings.length
56
56
  ? `${findings.length} new finding(s) in changed lines. Apply fixes, then \`git add\` the files and commit again.`
@@ -46,6 +46,7 @@ import { checkPromiseAwait } from './async/awaits.js';
46
46
  import { checkSortExtreme } from './collections/sort-extreme.js';
47
47
  import { checkRebuiltRegExp, fixedRegExpRuleId } from './collections/regex-allocation.js';
48
48
  import { checkNextPageFetches } from './frontend/next-fetch-waterfall.js';
49
+ import { checkSeoFile } from './frontend/seo/seo-rules.js';
49
50
  import { checkNodeBlockingCall, flushBlockingCalls } from './request/node-fs.js';
50
51
  import { checkPoolCreation } from './datastores/pooling.js';
51
52
  import { check as checkLlmMaxTokens } from './request/llm-max-tokens.js';
@@ -277,8 +278,10 @@ function scanFile(program, sourceFile, policy, forEachSourceCandidate) {
277
278
  flushBlockingCalls(pendingBlockingCalls, context);
278
279
  checkWorkbookDecodes(sourceFile, context);
279
280
  }
280
- if (runFullFileRules)
281
+ if (runFullFileRules) {
281
282
  checkNextPageFetches(sourceFile, context);
283
+ checkSeoFile(sourceFile, context);
284
+ }
282
285
  return findings.sort((left, right) => (left.line ?? 0) - (right.line ?? 0) ||
283
286
  (left.column ?? 0) - (right.column ?? 0) ||
284
287
  left.ruleId.localeCompare(right.ruleId));
@@ -1,5 +1,5 @@
1
1
  import { calleeName, skipParentheses } from '../analysis/call-syntax.js';
2
- import { ts } from '../engine/compiler.js';
2
+ import { isDefaultLibrary, ts } from '../engine/compiler.js';
3
3
  import { isAsyncFunction } from '../../shared/analysis/ast-helpers.js';
4
4
  import { isRequestHandler } from '../request/request-handlers.js';
5
5
  import { isStandardArrayCall } from '../collections/repeated.js';
@@ -59,8 +59,29 @@ function returnsReceiverType(call, checker) {
59
59
  const resultSymbol = checker.getTypeAtLocation(call).getSymbol();
60
60
  return Boolean(resultSymbol) && resultSymbol === checker.getTypeAtLocation(callee.expression).getSymbol();
61
61
  }
62
- function runsInAsyncOrHandler(node) {
63
- const owner = ts.findAncestor(node, ts.isFunctionLike);
62
+ // A plain callback passed to `forEach` runs inside the function that calls `forEach`, so a promise it drops is
63
+ // judged by that function: `emails.forEach((email) => { send(email); })` in an async function floats `send()`.
64
+ // A generator callback's body never runs, since `forEach` only creates the generator. A `forEach` that project or
65
+ // package code declares may store the callback for later, so only the standard one (or an untyped call) counts.
66
+ function isForEachCallback(owner, checker) {
67
+ const call = owner.parent;
68
+ return ((ts.isArrowFunction(owner) || (ts.isFunctionExpression(owner) && !owner.asteriskToken)) &&
69
+ !isAsyncFunction(owner) &&
70
+ ts.isCallExpression(call) &&
71
+ call.arguments[0] === owner &&
72
+ calleeName(call, skipParentheses) === 'forEach' &&
73
+ !declaredOutsideDefaultLibrary(call, checker));
74
+ }
75
+ function declaredOutsideDefaultLibrary(call, checker) {
76
+ const callee = skipParentheses(call.expression);
77
+ const name = ts.isPropertyAccessExpression(callee) ? callee.name : callee;
78
+ const declarations = checker.getSymbolAtLocation(name)?.declarations ?? [];
79
+ return declarations.some((declaration) => !isDefaultLibrary(checker, declaration.getSourceFile()));
80
+ }
81
+ function runsInAsyncOrHandler(node, checker) {
82
+ let owner = ts.findAncestor(node, ts.isFunctionLike);
83
+ while (owner && isForEachCallback(owner, checker))
84
+ owner = ts.findAncestor(owner.parent, ts.isFunctionLike);
64
85
  return owner !== undefined && (isAsyncFunction(owner) || isRequestHandler(owner));
65
86
  }
66
87
  function isStatement(call) {
@@ -241,7 +262,7 @@ function check(call, context) {
241
262
  'Use `await Promise.all(items.map(async (item) => ...))` to run them together, or a `for...of` loop with `await` to keep them in order.');
242
263
  return;
243
264
  }
244
- if (!runsInAsyncOrHandler(call))
265
+ if (!runsInAsyncOrHandler(call, context.checker))
245
266
  return;
246
267
  if (!isStatement(call) || (name !== undefined && context.fireAndForgetNames.has(name)))
247
268
  return;
@@ -7,7 +7,7 @@ import { jsonKeyByCommand } from '../analysis/source-pillars.js';
7
7
  import { exitCodeWithSkips } from './scan-outcome.js';
8
8
  import { findProjectRoot } from '../schema/context.js';
9
9
  import { terminalPrinter } from '../../shared/system/terminal-safe.js';
10
- import { reportAutomaticFixes } from '../../shared/reporting/automatic-fix-signal.js';
10
+ import { collectFixSignals, reportTextFindings } from '../../shared/reporting/automatic-fix-signal.js';
11
11
  import { assignFindingIds as assignFindingIdsFindingIds } from './finding-ids.js';
12
12
  import { keepChangedFindings, collectProjectChangedLines, fileKey } from './changed-lines.js';
13
13
  import { attachExample } from './finding-text.js';
@@ -121,7 +121,7 @@ function printSourceOutput(result, values, baseline, print) {
121
121
  if (warningNote && format === 'text' && !values.changedLines)
122
122
  print(warningNote);
123
123
  if (format === 'text')
124
- reportAutomaticFixes(result.findings);
124
+ reportTextFindings(result.findings);
125
125
  }
126
126
  // Finding paths are relative to the working directory.
127
127
  function printStructured(format, result, values, print) {
@@ -168,11 +168,17 @@ export function printEmptyChangedReport(values, commands) {
168
168
  const reports = {};
169
169
  for (const command of commands) {
170
170
  const rendered = output(jsonKeyByCommand[command]);
171
- reports[jsonKeyByCommand[command]] = { code: 0, stdout: rendered ? rendered + '\n' : '' };
171
+ reports[jsonKeyByCommand[command]] = {
172
+ code: 0,
173
+ stdout: rendered ? rendered + '\n' : '',
174
+ ...(format === 'text' && process.env[collectFixSignals] === '1' && { findingCount: 0 }),
175
+ };
172
176
  }
173
177
  console.log(JSON.stringify(reports));
174
178
  }
175
179
  else {
180
+ if (format === 'text')
181
+ reportTextFindings([]);
176
182
  const rendered = output(jsonKeyByCommand[commands[0] ?? 'perf']);
177
183
  if (rendered)
178
184
  console.log(rendered);
@@ -1,13 +1,14 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { loadConfig } from '../../shared/config.js';
4
+ import { conventionalProjects } from '../../shared/conventional-projects.js';
4
5
  import * as ts from 'typescript';
5
6
  import { fileKey } from '../../shared/system/file-key.js';
6
7
  import { isSourceInput, resolveConfig } from '../analysis/source-inputs.js';
7
8
  import { excludedBy } from '../analysis/unscanned-javascript.js';
8
9
  import { isPathInsideOrEqual } from '../../shared/system/path-inside.js';
9
10
  import { validateQueryPolicy, loadQueryPolicy } from '../query-loops/query-policy.js';
10
- import { workspacePackageCoverage, discoverWorkspaces, projectConfig, requireCompleteConfiglessSources, requireCompleteWorkspaceSources, workspaceFileInventory, workspaceRootSources, } from '../../shared/workspaces.js';
11
+ import { workspacePackageCoverage, configlessCoverage, discoverWorkspaces, projectConfig, requireCompleteConfiglessSources, requireCompleteWorkspaceSources, workspaceFileInventory, workspaceRootSources, } from '../../shared/workspaces.js';
11
12
  import { errorMessage } from './cli-arguments.js';
12
13
  import { relativePosix } from '../../shared/system/posix-path.js';
13
14
  // The folder holding loadwise.config.json: the project, or the working directory for files.
@@ -169,6 +170,28 @@ function ownRootConfig(directory, values) {
169
170
  const config = values.workspace.length ? undefined : projectConfig(directory);
170
171
  return { config, alone: Boolean(config && values.watch) };
171
172
  }
173
+ function conventionalTarget(directory, values, rootConfig) {
174
+ if (rootConfig || values.watch || values.fix || values.policy || values['loadwise-config'])
175
+ return;
176
+ const inventory = workspaceFileInventory(directory, true);
177
+ const packages = conventionalProjects(directory, inventory);
178
+ if (!packages.length)
179
+ return;
180
+ const projectFolders = packages.map((project) => relativePosix(directory, project.directory));
181
+ const loose = configlessCoverage(directory, (root, exclude = []) => inventory(root, [...exclude, ...projectFolders]));
182
+ const skippedSources = loose?.skippedSources ?? [];
183
+ noteConfiglessCoverage(directory, skippedSources);
184
+ return {
185
+ directory,
186
+ readOnly: true,
187
+ // Use scopes by directory so a conventional project can load outside types without reporting outside its folder.
188
+ configs: packages.map((project) => project.directory),
189
+ standaloneFiles: loose?.sources ?? [],
190
+ skippedSources,
191
+ standaloneScope: packages.map((project) => project.directory),
192
+ packages: packages.map((project) => ({ name: project.name, directory: relativeToCwd(project.directory) })),
193
+ };
194
+ }
172
195
  // A directory without its own config, or an explicit --workspace, means a monorepo: one config per
173
196
  // package, and the sources of each package without one, checked with the standalone defaults. A root
174
197
  // config that leaves workspace packages out, such as one excluding `packages`, is checked beside them.
@@ -213,7 +236,7 @@ export function workspaceTarget(values, positionals) {
213
236
  if (!chosen.length) {
214
237
  if (values.workspace.length)
215
238
  throw new Error('--workspace found no workspace package with JavaScript or TypeScript.');
216
- return undefined;
239
+ return conventionalTarget(directory, values, rootConfig);
217
240
  }
218
241
  // The root joins as its folder, so its config reports only the files inside the chosen project.
219
242
  if (rootConfig)
@@ -7,12 +7,13 @@ import { configFileName, loadSettings } from '../../shared/config.js';
7
7
  import { baselineForScan } from '../../shared/reporting/baseline.js';
8
8
  import { recordSkippedFile } from '../../shared/reporting/coverage-notes.js';
9
9
  import { resolveFormat } from '../../shared/formats/index.js';
10
+ import { collectFixSignals } from '../../shared/reporting/automatic-fix-signal.js';
10
11
  import { withReviewFixes } from '../../shared/fix/review-fix-mode.js';
11
12
  import { printWatchReport, watchSecurity } from './watch-security.js';
12
13
  import { terminalSafe } from '../../shared/system/terminal-safe.js';
13
14
  import { isEditorScan } from '../../shared/system/environment.js';
14
15
  import { fixPresentation } from '../../shared/fix/fix-presentation.js';
15
- import { editorAnalyzers, exitCodeWithSkips, noteEmptyIgnoredScan, reportSourceResult } from './scan-outcome.js';
16
+ import { editorAnalyzers, exitCodeWithSkips, isolatedPillarOutput, noteEmptyIgnoredScan, reportSourceResult, } from './scan-outcome.js';
16
17
  import { coveringConfig, configlessCoverage, projectConfig, requireCompleteConfiglessSources, } from '../../shared/workspaces.js';
17
18
  import { enableCompileCache } from 'node:module';
18
19
  import { notifyEditor } from '../../shared/agent/notify-editor.js';
@@ -22,8 +23,7 @@ import { loadSnapshot, useSnapshot } from '../schema/context.js';
22
23
  import { appendPrismaSchemaFindings } from './prisma-schema-findings.js';
23
24
  import * as sourceReport from '../../shared/reporting/source-report.js';
24
25
  import * as security from '../../security/cli.js';
25
- import { scanDependencies as scanDependenciesScan } from '../../security/deps/scan.js';
26
- import { noteOffline } from '../../security/deps/cli.js';
26
+ import { sharedSecurityInputs } from './shared-security-inputs.js';
27
27
  import { analyzeSources, performanceAnalyzers, preReadSources, accessibilityAnalyzer, reliabilityAnalyzer, reliabilityAnalyzers, } from '../projects.js';
28
28
  import { accessibilityCommand, jsonKeyByCommand, performanceCommand, pillarOfFinding, reliabilityCommand, takePillar, } from '../analysis/source-pillars.js';
29
29
  import { version as tsVersion } from 'typescript';
@@ -101,6 +101,7 @@ export async function checkCode(args, report = printResult, baselineFlags = {},
101
101
  (pillar.command === 'a11y' || (supportsMarkup && mayHaveVueTemplates(path.resolve(parsedValues.project ?? '.')))));
102
102
  const values = {
103
103
  ...parsedValues,
104
+ readOnly: workspace?.readOnly,
104
105
  // CLI --ignore ids are filtered by selectFindings, so the settings only add the config's own
105
106
  // filters.
106
107
  settings: loadSettings({ directory, explicit: parsedValues['loadwise-config'] }),
@@ -279,6 +280,8 @@ async function scanSource({ values, positionals, workspace, inferredFiles, polic
279
280
  function workspaceSweepRoots(workspace, selectors) {
280
281
  if (!workspace)
281
282
  return undefined;
283
+ if (workspace.standaloneScope)
284
+ return workspace.standaloneScope;
282
285
  // Configless packages already supply their eligible files.
283
286
  if (selectors.length || !workspace.configs.length)
284
287
  return workspace.configs.map((config) => path.dirname(config));
@@ -381,29 +384,22 @@ async function checkWithPillars({ values, positionals, policy, scope, workspace,
381
384
  appendPrismaSchemaFindings(result, workspace?.configs ?? [project ?? '.'], scope);
382
385
  if (workspace)
383
386
  result.packages = workspace.packages;
384
- const securityFiles = withSecurity
385
- ? security.scanFiles(values, securityProjectScope ? positionals : namedFiles, workspace, scope?.isChangedFile)
386
- : undefined;
387
- let dependencies;
388
- let dependencyError;
389
- if (withSecurity && values.online) {
390
- try {
391
- dependencies = await scanDependenciesScan(values.projectDirectory);
392
- }
393
- catch (error) {
394
- dependencyError = error;
395
- }
396
- }
397
- else if (withSecurity && !scope) {
398
- noteOffline(values.projectDirectory);
399
- }
387
+ const securityInputs = withSecurity
388
+ ? await sharedSecurityInputs(values, securityProjectScope ? positionals : namedFiles, workspace, scope)
389
+ : {};
390
+ const collectCounts = resolveFormat(values) === 'text' && process.env[collectFixSignals] === '1';
400
391
  async function reportPillar(command) {
401
392
  const jsonKey = jsonKeyByCommand[command];
402
393
  const isSecurity = command === 'sec';
394
+ const { files: securityFiles, dependencies, dependencyError } = securityInputs;
403
395
  if (isSecurity && dependencyError) {
404
396
  console.error(terminalSafe(errorMessage(dependencyError)));
397
+ if (securityInputs.filesError)
398
+ throw securityInputs.filesError;
405
399
  return { code: 2, stdout: '' };
406
400
  }
401
+ if (isSecurity && securityInputs.filesError)
402
+ throw securityInputs.filesError;
407
403
  const findings = takePillar(result.findings, jsonKey);
408
404
  if (isSecurity)
409
405
  findings.push(...(securityFiles?.findings ?? []), ...(dependencies?.findings ?? []));
@@ -439,18 +435,23 @@ async function checkWithPillars({ values, positionals, policy, scope, workspace,
439
435
  ...(scope && { changedLines: scope.changedLines }),
440
436
  };
441
437
  const lines = [];
442
- const print = (line) => {
443
- lines.push(line);
444
- };
438
+ const print = (line) => lines.push(line);
445
439
  const code = exitCodeWithSkips(reportResult, isSecurity
446
440
  ? await sourceReport.printResult(reportResult, pillarValues, security.pillar, print)
447
441
  : await printResult(reportResult, pillarValues, print));
448
- return { code, stdout: lines.map((line) => line + '\n').join('') };
442
+ return {
443
+ code,
444
+ stdout: lines.map((line) => line + '\n').join(''),
445
+ findingCount: collectCounts ? reportResult.findings.length : undefined,
446
+ };
449
447
  }
450
- const outputs = await Promise.all(commands.map((command) => reportPillar(command)));
448
+ const unexpected = [];
449
+ const outputs = await Promise.all(commands.map((command) => isolatedPillarOutput(jsonKeyByCommand[command], () => reportPillar(command), unexpected)));
451
450
  const reports = Object.fromEntries(commands.map((command, index) => [jsonKeyByCommand[command], outputs[index]]));
452
451
  console.log(JSON.stringify(reports));
453
452
  notifyEditor(values.project ?? process.cwd());
453
+ if (unexpected.length)
454
+ throw unexpected[0];
454
455
  return Math.max(...outputs.map(({ code }) => code));
455
456
  }
456
457
  // The snapshot is optional; without it every rule still reports, using unknown-size wording.
@@ -1,4 +1,7 @@
1
1
  import { fixAllCommand } from '../../shared/fix/fix-command.js';
2
+ import { errorMessage } from '../../shared/system/error-code.js';
3
+ import { terminalSafe } from '../../shared/system/terminal-safe.js';
4
+ import { isExpectedCliError } from '../../shared/system/sentry.js';
2
5
  function noteEmptyIgnoredScan(result, values, scope) {
3
6
  // TypeScript rejects a project with no inputs, but one emptied by ignore globs scans nothing
4
7
  // without complaint.
@@ -19,6 +22,21 @@ function reportSourceResult({ result, usedFallback, values, project, baselineOpt
19
22
  };
20
23
  return report(result, scope ? { ...reportValues, changedLines: scope.changedLines } : reportValues);
21
24
  }
25
+ // The shared `check` pass prints one report per checker. A checker that fails while reporting reports an incomplete
26
+ // scan on its own, so the reports of the checkers that finished are kept. Every failure names its checker. An
27
+ // unexpected error is also collected in `unexpected` for the caller to rethrow once every report is printed, so it
28
+ // still reaches the CLI's crash reporting.
29
+ async function isolatedPillarOutput(checker, produce, unexpected) {
30
+ try {
31
+ return await produce();
32
+ }
33
+ catch (error) {
34
+ console.error(terminalSafe(`The ${checker} checker failed: ${errorMessage(error)}`));
35
+ if (!isExpectedCliError(error))
36
+ unexpected.push(error);
37
+ return { code: invalidInputExitCode, stdout: '' };
38
+ }
39
+ }
22
40
  async function editorAnalyzers() {
23
41
  const [{ reliabilityAnalyzers, accessibilityAnalyzer }, { analyzer }] = await Promise.all([
24
42
  import('../projects.js'),
@@ -26,4 +44,4 @@ async function editorAnalyzers() {
26
44
  ]);
27
45
  return [...reliabilityAnalyzers, analyzer, accessibilityAnalyzer];
28
46
  }
29
- export { editorAnalyzers, exitCodeWithSkips, noteEmptyIgnoredScan, reportSourceResult };
47
+ export { editorAnalyzers, exitCodeWithSkips, isolatedPillarOutput, noteEmptyIgnoredScan, reportSourceResult };
@@ -0,0 +1,27 @@
1
+ // Security's project-file and dependency scans for the shared `check` pass. A failure of either is kept for the
2
+ // security report alone, so the other checkers of the pass still report their results.
3
+ import * as security from '../../security/cli.js';
4
+ import { noteOffline } from '../../security/deps/cli.js';
5
+ import { scanDependencies } from '../../security/deps/scan.js';
6
+ async function sharedSecurityInputs(values, files, workspace, scope) {
7
+ const inputs = {};
8
+ try {
9
+ inputs.files = security.scanFiles(values, files, workspace, scope?.isChangedFile);
10
+ }
11
+ catch (error) {
12
+ inputs.filesError = error;
13
+ }
14
+ if (values.online) {
15
+ try {
16
+ inputs.dependencies = await scanDependencies(values.projectDirectory);
17
+ }
18
+ catch (error) {
19
+ inputs.dependencyError = error;
20
+ }
21
+ }
22
+ else if (!scope) {
23
+ noteOffline(values.projectDirectory);
24
+ }
25
+ return inputs;
26
+ }
27
+ export { sharedSecurityInputs };