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
@@ -7,16 +7,22 @@ import * as ts from 'typescript';
7
7
  import { isGeneratedCacheFile, readCacheEntry, trustedCacheDirectory, writeCacheEntry } from './scan-cache-storage.js';
8
8
  import { packageManifest, packagePath, packageRoot } from '../package-root.js';
9
9
  import { defaultCacheDirectory } from '../../security/deps/osv.js';
10
+ import { lockfileNames } from '../../security/deps/lockfiles.js';
10
11
  import { declaredWorkspaceDirectories } from '../workspaces.js';
12
+ import { conventionalProjectGroups } from '../conventional-projects.js';
11
13
  import { isPathInsideOrEqual } from '../system/path-inside.js';
12
- import { runGit } from '../system/git.js';
14
+ import { git, gitFileListing, unmodifiedBlobIds } from './scan-cache-git.js';
13
15
  import { configFileName, loadConfig } from '../config.js';
14
16
  import { noteOnce } from '../reporting/coverage-notes.js';
15
17
  import { parseMaintainabilityArguments } from '../../maintainability/cli/scan-arguments.js';
16
18
  import { rulePackFingerprint } from '../reporting/rule-pack-fingerprint.js';
19
+ import { isFindingCount } from '../reporting/automatic-fix-signal.js';
17
20
  import { normalizeSlashes, relativePosix, toPosixPath } from '../system/posix-path.js';
21
+ import { addAncestorDirectories, hashIgnoredProjectConfigs, insideGitRepository, isLink, linksOutside, fitsKeyedFiles, hashListedFolderInstalls, hashMarkersIn, registryConfigFingerprint, scannedProject, targetsOutside, } from './scan-cache-project-inputs.js';
22
+ import { loadwisePackageVersions } from './scan-cache-loadwise-packages.js';
23
+ import { inheritedSourceWatch, reportOutsideSource } from './scan-cache-sources.js';
18
24
  // Legacy bare reports must not share a filename with the owned record format.
19
- const formatVersion = 3;
25
+ const formatVersion = 4;
20
26
  const defaultMaxEntries = 20;
21
27
  const maximumMaxEntries = 1000;
22
28
  const cacheEnvironment = new Set([
@@ -25,7 +31,6 @@ const cacheEnvironment = new Set([
25
31
  'LOADWISE_SCAN_CACHE_ROOT',
26
32
  'LOADWISE_SCAN_CACHE_MAX_ENTRIES',
27
33
  ]);
28
- const gitListBuffer = 1 << 28;
29
34
  const cacheableCommands = new Set(['check', 'perf', 'rel', 'maint', 'sec', 'a11y']);
30
35
  // Subcommands that read live state (databases, advisories) or write files.
31
36
  const uncachedSubcommands = new Set(['deps', 'db', 'migrations', 'fix']);
@@ -34,6 +39,8 @@ const uncachedFlags = new Set([
34
39
  '--fix',
35
40
  '--watch',
36
41
  '--staged',
42
+ // The key holds no HEAD, so committing staged lines would replay the report from before the commit.
43
+ '--uncommitted',
37
44
  '--changed-since',
38
45
  '--write-baseline',
39
46
  '--online',
@@ -85,7 +92,10 @@ function loadwiseFingerprint() {
85
92
  ...listSources(packagePath('polyglot'), true),
86
93
  ...listSources(packagePath('lib/performance/vendor')),
87
94
  ].sort();
88
- const hash = crypto.createHash('sha1').update(`${packageManifest.version}\n`);
95
+ // Loadwise's TypeScript can be installed apart from it, and its library files are read as sources.
96
+ const hash = crypto.createHash('sha1').update(`${packageManifest.version}\0${ts.version}\n`);
97
+ // The source watch trusts reads inside Loadwise's dependencies, so their versions belong in the key too.
98
+ hash.update(`${loadwisePackageVersions(packageRoot)}\n`);
89
99
  for (let index = 0; index < sources.length; index++) {
90
100
  const file = sources[index];
91
101
  const { size, mtimeMs } = fs.statSync(file);
@@ -103,58 +113,16 @@ function isCacheable(args) {
103
113
  return false;
104
114
  return !args.some((arg) => uncachedFlags.has(arg.split('=')[0]));
105
115
  }
106
- function git(directory, gitArgs, input) {
107
- const run = runGit(directory, gitArgs, { input, maxBuffer: gitListBuffer });
108
- return run.status === 0 ? run.stdout : undefined;
109
- }
110
- // node_modules is ignored by git, but installing or removing a package changes the types the
111
- // checkers see. Package managers rewrite these files on every install, so their size and time stand
112
- // in for the whole tree.
113
- const installMarkers = [
114
- 'node_modules',
115
- 'node_modules/.package-lock.json',
116
- 'node_modules/.yarn-state.yml',
117
- 'node_modules/.modules.yaml',
118
- 'node_modules/.pnpm/lock.yaml',
119
- ];
120
- // Checkers read these from disk to select sources, so their contents count even when Git ignores them.
121
- const projectConfigNames = ['tsconfig.json', 'jsconfig.json', 'pnpm-workspace.yaml', 'lerna.json'];
122
116
  const loadwiseConfigNames = ['loadwise-baseline.json', 'loadwise.config.json'];
123
- const projectInputs = /(?:^|\/)(?:package|[jt]sconfig)\.json$|\.[cm]?[jt]sx?$/i;
124
- function addAncestorDirectories(directories, directory) {
125
- for (let folder = directory; !directories.has(folder); folder = path.posix.dirname(folder)) {
126
- directories.add(folder);
127
- }
128
- }
129
- function projectConfigHash(absolute, readProjectConfig) {
130
- try {
131
- const stat = fs.statSync(absolute, { throwIfNoEntry: false });
132
- if (stat?.isFile())
133
- return fileHash(absolute, stat, false, readProjectConfig);
134
- }
135
- catch {
136
- // An indexed path can have a missing or replaced parent in the working tree.
137
- }
138
- }
139
- // Configless and workspace discovery check source ancestors on disk, including markers Git ignores.
140
- function hashIgnoredProjectConfigs(hash, topLevel, relativeCwd, names, readProjectConfig) {
141
- const directories = new Set(['.']);
142
- addAncestorDirectories(directories, relativeCwd || '.');
143
- for (const name of names) {
144
- if (projectInputs.test(name))
145
- addAncestorDirectories(directories, path.posix.dirname(name));
146
- }
147
- for (const directory of directories) {
148
- for (const configName of projectConfigNames) {
149
- const name = path.posix.join(directory, configName);
150
- if (names.has(name))
151
- continue;
152
- const configHash = projectConfigHash(path.join(topLevel, name), readProjectConfig);
153
- if (configHash !== undefined)
154
- hash.update(`\0project-config\0${name}\0${configHash}`);
155
- }
156
- }
157
- }
117
+ // The dependency checks look for a lockfile in every folder up from the project, so each name counts there too.
118
+ const ancestorManifests = [
119
+ 'package.json',
120
+ 'lerna.json',
121
+ 'pnpm-workspace.yaml',
122
+ '.npmrc',
123
+ 'bunfig.toml',
124
+ ...lockfileNames,
125
+ ];
158
126
  function hashInstallMarkers(topLevel, selectedDirectories) {
159
127
  const directories = new Set(['.']);
160
128
  for (const directory of selectedDirectories) {
@@ -162,14 +130,27 @@ function hashInstallMarkers(topLevel, selectedDirectories) {
162
130
  addAncestorDirectories(directories, relative || '.');
163
131
  }
164
132
  const hash = crypto.createHash('sha256');
165
- for (const directory of directories) {
166
- for (const marker of installMarkers) {
167
- const stat = fs.statSync(path.join(topLevel, directory, marker), { throwIfNoEntry: false });
168
- if (stat)
169
- hash.update(`\0${directory}\0${marker}\0${stat.size}\0${stat.mtimeMs}`);
133
+ for (const directory of directories)
134
+ hashMarkersIn(hash, topLevel, directory);
135
+ return hash.digest('hex');
136
+ }
137
+ // Node, TypeScript and workspace discovery resolve packages and read manifests from every ancestor of the scanned
138
+ // files, so installs and manifests above the repository count too, wherever the scan was launched from. A missing
139
+ // manifest is keyed as well: creating one changes the hash.
140
+ function hashAncestorInputs(hash, topLevel, configFiles) {
141
+ for (let directory = path.resolve(path.dirname(topLevel));; directory = path.dirname(directory)) {
142
+ hash.update(`\0${directory}`);
143
+ hashMarkersIn(hash, directory, '.');
144
+ for (const name of ancestorManifests) {
145
+ const manifest = path.join(directory, name);
146
+ const stat = fs.statSync(manifest, { throwIfNoEntry: false });
147
+ if (stat?.isFile())
148
+ hash.update(`\0${name}\0${fileHash(manifest, stat)}`);
149
+ configFiles.add(manifest);
170
150
  }
151
+ if (path.dirname(directory) === directory)
152
+ break;
171
153
  }
172
- return hash.digest('hex');
173
154
  }
174
155
  // Declared workspace globs can select separate repositories omitted from the outer Git listing.
175
156
  // Only fingerprint their installs once source coverage has been established for all selected packages.
@@ -205,8 +186,10 @@ function workspaceInstalls(topLevel, names) {
205
186
  const manifest = relativePosix(topLevel, path.join(workspace, 'package.json'));
206
187
  return names.has(manifest) && coveredByRepository(workspace);
207
188
  });
208
- if (covered)
209
- fingerprint = hashInstallMarkers(topLevel, [canonical, ...workspaces]);
189
+ // Including an inactive candidate's install is conservative and avoids another source inventory to build a cache key.
190
+ const projects = conventionalProjectGroups(canonical).flatMap(({ projects }) => projects.map(({ directory }) => directory));
191
+ if (covered && projects.every(coveredByRepository))
192
+ fingerprint = hashInstallMarkers(topLevel, [canonical, ...workspaces, ...projects]);
210
193
  }
211
194
  }
212
195
  catch {
@@ -231,97 +214,6 @@ function excludeGeneratedCacheFiles(topLevel, cacheDirectory, names) {
231
214
  if (!trackedNames.has(name))
232
215
  names.delete(name);
233
216
  }
234
- // Checkers may read ancestor configs and repository-level files, so the whole repository is the
235
- // input set. Undefined outside git, where no cache is used.
236
- function gitFileListing(topLevel) {
237
- const listing = git(topLevel, ['ls-files', '-t', '-z', '--cached', '--others', '--exclude-standard']);
238
- if (listing === undefined)
239
- return undefined;
240
- // Security uses tracked files even when identical working-tree bytes also exist untracked.
241
- const tracked = new Set();
242
- const paths = [];
243
- for (const entry of listing.split('\0')) {
244
- if (!entry)
245
- continue;
246
- if (entry[1] !== ' ')
247
- return undefined;
248
- const name = entry.slice(2);
249
- paths.push(name);
250
- if (entry[0] !== '?')
251
- tracked.add(name);
252
- }
253
- return { names: new Set(paths.sort()), tracked };
254
- }
255
- // Git already compares its index with the working tree by stat data (and by content when timestamps are racy),
256
- // so an ordinary tracked file it reports as unmodified is identified by its blob id without reading it again.
257
- // Configs resolved by TypeScript, special modes and entries with assume-unchanged or skip-worktree flags still
258
- // take the full path, because Git is not authoritative for them.
259
- const indexedBlobEntry = /^H (100644|100755) ([0-9a-f]{40,64}) 0\t(.+)$/s;
260
- // A clean filter, ident or re-encoding can leave the blob id unchanged while the working-tree bytes differ,
261
- // and a line-ending conversion makes the two differ by design. Those files must be hashed from disk.
262
- const contentConvertingAttributes = ['filter', 'ident', 'working-tree-encoding'];
263
- const lineEndingAttributes = ['text', 'eol', 'crlf'];
264
- function convertedNames(topLevel, names) {
265
- const attributes = git(topLevel, ['--literal-pathspecs', 'check-attr', '-z', '--stdin', ...contentConvertingAttributes, ...lineEndingAttributes], names.map((name) => `${name}`).join(''));
266
- if (attributes === undefined)
267
- return undefined;
268
- const converted = new Set();
269
- let lineEndingsMayConvert = false;
270
- const fields = attributes.split('');
271
- for (let index = 0; index + 2 < fields.length; index += 3) {
272
- if (fields[index + 2] === 'unspecified')
273
- continue;
274
- if (contentConvertingAttributes.includes(fields[index + 1]))
275
- converted.add(fields[index]);
276
- else
277
- lineEndingsMayConvert = true;
278
- }
279
- // Line-ending conversion needs a text, eol or crlf attribute or core.autocrlf, all of which are metadata.
280
- // Only then is the per-file line-ending listing, which makes Git read every tracked file, worth running.
281
- // An unset key makes a plain --get exit 1, so --default keeps an unconfigured clone on the fast path.
282
- const autocrlf = git(topLevel, ['config', '--default', '', '--get', 'core.autocrlf']);
283
- if (autocrlf === undefined)
284
- return undefined;
285
- if (!lineEndingsMayConvert && autocrlf.trim() === '')
286
- return converted;
287
- const endings = git(topLevel, ['ls-files', '--eol', '-z', '--cached']);
288
- if (endings === undefined)
289
- return undefined;
290
- for (const entry of endings.split('')) {
291
- const match = /^i\/(\S*)\s+w\/(\S*)\s+attr\/[^\t]*\t(.+)$/s.exec(entry);
292
- // A -text file keeps equal classes even when only its CR or CRLF endings changed.
293
- if (match && (match[1] !== match[2] || match[1] === '-text'))
294
- converted.add(match[3]);
295
- }
296
- return converted;
297
- }
298
- function unmodifiedBlobIds(topLevel) {
299
- const blobIds = new Map();
300
- const indexed = git(topLevel, ['ls-files', '-s', '-v', '-z', '--cached']);
301
- const modified = git(topLevel, ['diff-files', '--name-only', '-z']);
302
- // Staging between the two reads would pair an old blob id with a clean check of newer contents.
303
- const indexedAfter = git(topLevel, ['ls-files', '-s', '-v', '-z', '--cached']);
304
- if (indexed === undefined || modified === undefined || indexedAfter !== indexed)
305
- return blobIds;
306
- const modifiedNames = new Set(modified.split('\0'));
307
- const candidates = [];
308
- for (const entry of indexed.split('\0')) {
309
- const match = indexedBlobEntry.exec(entry);
310
- if (!match || /^0+$/.test(match[2]))
311
- continue;
312
- const name = match[3];
313
- if (modifiedNames.has(name) || /^[jt]sconfig(?:\..+)?\.json$/i.test(path.posix.basename(name)))
314
- continue;
315
- candidates.push({ name, blobId: match[2] });
316
- }
317
- const converted = convertedNames(topLevel, candidates.map(({ name }) => name));
318
- if (converted === undefined)
319
- return blobIds;
320
- for (const { name, blobId } of candidates)
321
- if (!converted.has(name))
322
- blobIds.set(name, blobId);
323
- return blobIds;
324
- }
325
217
  function hashUnindexedDirectoryInputs(hash, directories) {
326
218
  const unindexedConfigs = new Set();
327
219
  for (const directory of directories) {
@@ -358,21 +250,48 @@ function inputFingerprint(cwd, cacheDirectory) {
358
250
  return undefined;
359
251
  }
360
252
  const readProjectConfig = projectConfigReader();
253
+ const configFiles = new Set();
254
+ const readKeyedConfig = recordingReader(readProjectConfig, configFiles);
361
255
  const blobIds = unmodifiedBlobIds(topLevel);
256
+ let realTopLevel;
257
+ const resolveTopLevel = () => (realTopLevel ??= fs.realpathSync.native(topLevel));
362
258
  for (const name of names) {
363
259
  const blobId = blobIds.get(name);
364
- const digest = blobId ? `blob:${blobId}` : fileHash(path.join(topLevel, name), undefined, false, readProjectConfig);
260
+ const absolute = path.join(topLevel, name);
261
+ const digest = blobId ? `blob:${blobId}` : fileHash(absolute, undefined, false, readKeyedConfig);
365
262
  // Git lists embedded repositories as a single path, while checkers can read files inside them.
366
263
  if (digest === undefined)
367
264
  return undefined;
265
+ if (digest.startsWith('symlink:') && linksOutside(absolute, resolveTopLevel))
266
+ return undefined;
267
+ // A linked file is keyed by its target's contents, so a checker may read an outside target directly.
268
+ if (digest.startsWith('symlink:') && targetsOutside(absolute, resolveTopLevel))
269
+ configFiles.add(absolute);
368
270
  hash.update(`\0${name}\0${tracked.has(name) ? 'tracked' : 'untracked'}\0${digest}`);
369
271
  }
370
- hashIgnoredProjectConfigs(hash, topLevel, toPosixPath(relativeCwd), names, readProjectConfig);
272
+ try {
273
+ hashIgnoredProjectConfigs(hash, topLevel, toPosixPath(relativeCwd), names, (filename, stat) => fileHash(filename, stat, false, readKeyedConfig));
274
+ hashAncestorInputs(hash, topLevel, configFiles);
275
+ hashListedFolderInstalls(hash, topLevel, names);
276
+ }
277
+ catch {
278
+ // Unreadable or concurrently removed package inputs cannot identify a reusable report.
279
+ return;
280
+ }
371
281
  hashUnindexedDirectoryInputs(hash, new Set([topLevel, path.resolve(cwd)]));
372
282
  return {
283
+ topLevel,
373
284
  fingerprint: hash.digest('hex'),
374
285
  workspaceInstallFingerprint: workspaceInstalls(topLevel, names),
375
286
  readProjectConfig,
287
+ configFiles,
288
+ };
289
+ }
290
+ // Every config file TypeScript read for a fingerprint is keyed by its contents, so a checker may read it freely.
291
+ function recordingReader(read, files) {
292
+ return (filename) => {
293
+ files.add(filename);
294
+ return read(filename);
376
295
  };
377
296
  }
378
297
  const maxHashedFileBytes = 16 * 1024 * 1024;
@@ -419,7 +338,7 @@ function fileHash(absolute, existingStat, namedConfig = false, readProjectConfig
419
338
  return projectFingerprint(absolute, readProjectConfig);
420
339
  }
421
340
  if (stat.isSymbolicLink())
422
- return `symlink:${sha1(fs.readlinkSync(absolute))}`;
341
+ return linkHash(absolute);
423
342
  if (stat.isDirectory())
424
343
  return undefined;
425
344
  if (!stat.isFile())
@@ -434,6 +353,12 @@ function fileHash(absolute, existingStat, namedConfig = false, readProjectConfig
434
353
  return 'missing';
435
354
  }
436
355
  }
356
+ // Checkers read through a link, so a linked file is keyed by its contents as well as by where it points.
357
+ function linkHash(absolute) {
358
+ const link = `symlink:${sha1(fs.readlinkSync(absolute))}`;
359
+ const target = fs.statSync(absolute, { throwIfNoEntry: false });
360
+ return target?.isFile() ? `${link}:${fileHash(absolute, target)}` : link;
361
+ }
437
362
  function configFileEntry(candidate, loadwiseConfig = path.basename(candidate) === configFileName) {
438
363
  let stat;
439
364
  try {
@@ -460,7 +385,7 @@ function configFileEntry(candidate, loadwiseConfig = path.basename(candidate) ==
460
385
  }
461
386
  if (!hash || hash === 'missing')
462
387
  return { unfingerprintable: true };
463
- return { entry: `${candidate}${hash}` };
388
+ return { entry: `${candidate}\0${hash}` };
464
389
  }
465
390
  function directoryConfigFingerprint(directory, stopAt) {
466
391
  const entries = [];
@@ -481,15 +406,15 @@ function directoryConfigFingerprint(directory, stopAt) {
481
406
  break;
482
407
  current = parent;
483
408
  }
484
- return entries.join('');
409
+ return entries.join('\0');
485
410
  }
486
411
  // Returns the fingerprint entries for one argument, or undefined when the cache must be bypassed.
487
- function namedArgumentEntries(args, index, cwd, directory, inputs) {
412
+ function namedArgumentEntries(args, index, directory, inputs, configFiles) {
488
413
  const arg = args[index];
489
414
  const candidate = arg.startsWith('-') && arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : arg;
490
415
  if (!candidate)
491
416
  return [''];
492
- const absolute = path.resolve(cwd, candidate);
417
+ const absolute = path.resolve(directory, candidate);
493
418
  // The checker opens the named input and reads its target when it is a symlink.
494
419
  let stat;
495
420
  try {
@@ -513,7 +438,11 @@ function namedArgumentEntries(args, index, cwd, directory, inputs) {
513
438
  const config = namedLoadwiseConfig ? configFileEntry(absolute, true) : undefined;
514
439
  if (config?.unfingerprintable)
515
440
  return undefined;
516
- const entries = [config?.entry ?? fileHash(absolute, stat, namedProject, inputs.readProjectConfig) ?? ''];
441
+ // The key holds a named config's contents, so the checker may read it, and through it its target.
442
+ if (config)
443
+ configFiles.add(absolute);
444
+ const readProjectConfig = recordingReader(inputs.readProjectConfig, configFiles);
445
+ const entries = [config?.entry ?? fileHash(absolute, stat, namedProject, readProjectConfig) ?? ''];
517
446
  // A selected subproject may read an ignored config or baseline beside its tsconfig.
518
447
  const projectDirectory = path.dirname(absolute);
519
448
  if (!stat?.isFile() || projectDirectory === directory)
@@ -538,28 +467,53 @@ function cacheKey(args, cwd, cacheDirectory) {
538
467
  return;
539
468
  }
540
469
  }
541
- const lookupKey = directory + '\0' + cacheDirectory;
542
- if (launchFingerprints && !launchFingerprints.has(lookupKey)) {
543
- launchFingerprints.set(lookupKey, inputFingerprint(directory, cacheDirectory));
470
+ const snapshotOf = (root) => {
471
+ const lookupKey = root + '\0' + cacheDirectory;
472
+ if (launchFingerprints && !launchFingerprints.has(lookupKey)) {
473
+ launchFingerprints.set(lookupKey, inputFingerprint(root, cacheDirectory));
474
+ }
475
+ return launchFingerprints ? launchFingerprints.get(lookupKey) : inputFingerprint(root, cacheDirectory);
476
+ };
477
+ // Scanning a repository from a folder outside any repository (`loadwise check path/to/app`) snapshots the scanned
478
+ // one. The launch folder's own configs still count, and finding paths stay relative to it through `directory`.
479
+ let inputRoot = directory;
480
+ let inputs = snapshotOf(directory);
481
+ let launchConfigs = '';
482
+ if (!inputs && !insideGitRepository(directory)) {
483
+ const project = scannedProject(args, directory);
484
+ const launch = project && directoryConfigFingerprint(directory, directory);
485
+ if (project && launch !== undefined) {
486
+ inputRoot = project;
487
+ inputs = snapshotOf(project);
488
+ launchConfigs = launch;
489
+ }
544
490
  }
545
- const inputs = launchFingerprints ? launchFingerprints.get(lookupKey) : inputFingerprint(directory, cacheDirectory);
546
491
  if (!inputs)
547
492
  return undefined;
548
- const cwdInstall = inputs.workspaceInstallFingerprint(directory);
493
+ const cwdInstall = inputs.workspaceInstallFingerprint(inputRoot);
549
494
  if (cwdInstall === undefined)
550
495
  return undefined;
496
+ const registryConfig = registryConfigFingerprint();
497
+ if (registryConfig === undefined)
498
+ return undefined;
551
499
  const environment = Object.keys(process.env)
552
500
  .filter((name) => name.startsWith('LOADWISE_') && !cacheEnvironment.has(name))
553
501
  .sort()
554
502
  .map((name) => `${name}=${process.env[name]}`);
555
503
  // A config file named in the args may live outside the repository.
556
504
  const namedFiles = [];
505
+ const configFiles = new Set([...inputs.configFiles, ...registryConfig.files]);
506
+ // launchConfigs keys the launch folder's own configs.
507
+ if (inputRoot !== directory)
508
+ for (const name of loadwiseConfigNames)
509
+ configFiles.add(path.join(directory, name));
557
510
  for (const index of args.keys()) {
558
- const entries = namedArgumentEntries(args, index, cwd, directory, inputs);
511
+ const entries = namedArgumentEntries(args, index, directory, inputs, configFiles);
559
512
  if (!entries)
560
513
  return undefined;
561
514
  namedFiles.push(...entries);
562
515
  }
516
+ const topLevel = inputs.topLevel;
563
517
  const parts = [
564
518
  formatVersion,
565
519
  loadwiseFingerprint(),
@@ -570,8 +524,20 @@ function cacheKey(args, cwd, cacheDirectory) {
570
524
  environment,
571
525
  inputs.fingerprint,
572
526
  cwdInstall,
527
+ launchConfigs,
528
+ registryConfig.fingerprint,
573
529
  ];
574
- return { key: crypto.createHash('sha256').update(JSON.stringify(parts)).digest('hex'), packFingerprint };
530
+ // Files inside the repository are not watched, unless they are links that a checker reads through to an outside target.
531
+ const keyedFiles = [...configFiles].filter((file) => !isPathInsideOrEqual(topLevel, file) || isLink(file));
532
+ // Too many to hand to the checker: scanning uncached beats failing to start it.
533
+ if (!fitsKeyedFiles(keyedFiles))
534
+ return undefined;
535
+ return {
536
+ key: crypto.createHash('sha256').update(JSON.stringify(parts)).digest('hex'),
537
+ packFingerprint,
538
+ topLevel,
539
+ keyedFiles,
540
+ };
575
541
  }
576
542
  function cacheDirectory() {
577
543
  const configured = process.env.LOADWISE_SCAN_CACHE_ROOT;
@@ -600,7 +566,10 @@ function cacheDiagnostic(action, command, unsafeDirectory = false) {
600
566
  function noteUntrustedCache(command) {
601
567
  if (process.env.LOADWISE_EDITOR_SCAN === '1' || command === 'check')
602
568
  return;
603
- return (folder) => noteOnce('scan-cache-untrusted', `Note: the scan cache is off because ${JSON.stringify(folder)} is owned by another user or writable by group or others; remove that write access or set LOADWISE_SCAN_CACHE_ROOT to a private folder.`);
569
+ const reason = process.platform === 'win32'
570
+ ? 'is outside your user profile or is a link; set LOADWISE_SCAN_CACHE_ROOT to a folder in your user profile'
571
+ : 'is owned by another user or writable by group or others; remove that write access or set LOADWISE_SCAN_CACHE_ROOT to a private folder';
572
+ return (folder) => noteOnce('scan-cache-untrusted', `Note: the scan cache is off because ${JSON.stringify(folder)} ${reason}.`);
604
573
  }
605
574
  function isStoredRun(value) {
606
575
  return (typeof value === 'object' &&
@@ -611,7 +580,8 @@ function isStoredRun(value) {
611
580
  typeof value.stdout === 'string' &&
612
581
  'stderr' in value &&
613
582
  typeof value.stderr === 'string' &&
614
- (!('hasAutomaticFixes' in value) || value.hasAutomaticFixes === true));
583
+ (!('hasAutomaticFixes' in value) || value.hasAutomaticFixes === true) &&
584
+ (!('findingCount' in value) || isFindingCount(value.findingCount)));
615
585
  }
616
586
  function trackedCacheEntries(directory) {
617
587
  for (let ancestor = directory;; ancestor = path.dirname(ancestor)) {
@@ -633,7 +603,8 @@ async function cachedRun(args, cwd, run) {
633
603
  if (!directory || !cache) {
634
604
  stats.bypasses++;
635
605
  cacheDiagnostic('bypass', args[0], cacheable && !directory);
636
- return run();
606
+ // A run nested in a watched child still owes that child's parent word of sources read outside the repository.
607
+ return run(undefined, inheritedSourceWatch());
637
608
  }
638
609
  const name = `${cache.key}.json`;
639
610
  const stored = readCacheEntry(path.join(directory, name), isStoredRun);
@@ -651,8 +622,21 @@ async function cachedRun(args, cwd, run) {
651
622
  : (fingerprint) => {
652
623
  usedPackFingerprint = fingerprint;
653
624
  };
654
- const result = await run(receiveFingerprint);
655
- if (cacheableExitCodes.has(result.code) && cache.packFingerprint === usedPackFingerprint)
625
+ // The key covers the repository only, so a report that read sources outside it is not stored.
626
+ let readOutsideSource = false;
627
+ const sourceWatch = {
628
+ topLevel: cache.topLevel,
629
+ keyedFiles: cache.keyedFiles,
630
+ onOutsideSource() {
631
+ readOutsideSource = true;
632
+ reportOutsideSource();
633
+ },
634
+ };
635
+ const result = await run(receiveFingerprint, sourceWatch);
636
+ // Known limit: the key is the inputs' state when the scan started. An input edited during the scan and restored
637
+ // byte for byte before the next one can replay this report; a cheap post-run stat check is the planned follow-up,
638
+ // since re-fingerprinting here would double every cached scan's reads.
639
+ if (cacheableExitCodes.has(result.code) && cache.packFingerprint === usedPackFingerprint && !readOutsideSource)
656
640
  writeCacheEntry(directory, name, result, maxCacheEntries(), trackedCacheEntries);
657
641
  return result;
658
642
  }
@@ -3,6 +3,7 @@ import { watchCheckInputs } from './check-watch-inputs.js';
3
3
  import { stopWatchWorker, verifyClosedWatchWorker } from './check-watch-process.js';
4
4
  import { cliEntryPath } from './package-root.js';
5
5
  import { terminalSafe } from './system/terminal-safe.js';
6
+ import { nextEnvAncestorDependencies } from './analysis/next-env-config.js';
6
7
  const settleMilliseconds = 150;
7
8
  const maximumReportChars = 64 * 1024 * 1024;
8
9
  const stopSignals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
@@ -61,9 +62,8 @@ function watchCheck({ args, directory, format, dependencyFiles, inheritedConfigF
61
62
  if (closing || worker)
62
63
  return;
63
64
  dirty = false;
64
- const inherited = inheritedConfigFiles?.();
65
- if (inherited)
66
- inputs.updateDependencies([...dependencyFiles, ...inherited]);
65
+ const inherited = inheritedConfigFiles?.() ?? [];
66
+ inputs.updateDependencies([...dependencyFiles, ...inherited, ...nextEnvAncestorDependencies(directory)]);
67
67
  let stdout = '';
68
68
  let errorMessage;
69
69
  // No childHeapFlags here: `check` only orchestrates, and it passes them to each checker it spawns.
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
+ import { conventionalProjects } from './conventional-projects.js';
5
6
  import { checkOptions } from './check-options.js';
6
7
  import { configFileName, loadConfig, loadSettings } from './config.js';
7
8
  import { isRecord } from './system/is-record.js';
@@ -44,7 +45,10 @@ function parseCheckArgs(args) {
44
45
  if (values.staged && values['changed-since'] !== undefined) {
45
46
  throw new Error('Choose either --staged or --changed-since.');
46
47
  }
47
- const format = resolveFormat(values, true);
48
+ const defaultReviewJson = values.review && values.format === undefined;
49
+ const format = resolveFormat({ format: values.format, json: values.json || defaultReviewJson }, true);
50
+ if (values.review && format === 'text')
51
+ throw new Error('--review cannot be combined with --format text. Use JSON or a rendered format such as markdown.');
48
52
  if (values.watch) {
49
53
  if (values.review ||
50
54
  values.staged ||
@@ -153,7 +157,7 @@ function printSection(title, run, hideBulkFix) {
153
157
  console.log(styleSectionHeader(title));
154
158
  const noResultNote = `No result: the ${title.toLowerCase()} checker failed (exit code ${run.code}); see the notes below.\n`;
155
159
  const text = hideBulkFix ? run.stdout.replaceAll(perCheckerBulkFix, '') : run.stdout;
156
- const output = styleTerminalText(formatCheckText(terminalSafe(text)));
160
+ const output = styleTerminalText(formatCheckText(terminalSafe(text), undefined, title));
157
161
  process.stdout.write(producedNoResult(run, 'text') ? noResultNote : output || 'Nothing to check.\n');
158
162
  process.stderr.write(terminalSafe(run.stderr));
159
163
  }
@@ -261,6 +265,13 @@ async function scanCheck({ values, format, directory, selected, settings, baseli
261
265
  : await runPillars(selected, optionsFor);
262
266
  return dedupeMissingBaseNotes(runs);
263
267
  }
268
+ const inferredProjectFixGuidance = 'To apply fixes, select an individual project or declare its workspace in the root manifest.';
269
+ function usesReadOnlyProjects({ selected, directory, values }) {
270
+ return (selected.some(({ name }) => name !== 'maint') &&
271
+ !values.config &&
272
+ !values.workspace.length &&
273
+ conventionalProjects(directory).length > 0);
274
+ }
264
275
  function requireFixCoverage(options) {
265
276
  if (options.selected.some(({ name }) => name !== 'maint') && !projectConfig(options.directory)) {
266
277
  // A package the scan skips could hold callers a fix breaks.
@@ -282,6 +293,8 @@ async function scanForFixes(checkers, scopeArgs = [], action, selectedIds) {
282
293
  const options = parseCheckArgs(['--json', ...scopeArgs, ...(checkers ? ['--only', checkers.join(',')] : [])]);
283
294
  if (action)
284
295
  printScanScope(options, action);
296
+ if (usesReadOnlyProjects(options))
297
+ throw new Error(inferredProjectFixGuidance);
285
298
  requireFixCoverage(options);
286
299
  // Tells maint that a fix was requested, so it builds the edits only a fix pays for, scoped to the chosen ids.
287
300
  const runs = await scanCheck(options, ['--fix-selection', selectedIds ? [...selectedIds].join(',') : 'all']);
@@ -339,7 +352,8 @@ function printCheckTextReport(options, runs, exitCode) {
339
352
  const { selected } = options;
340
353
  const hasAutomaticFixes = runs.some((run) => run?.hasAutomaticFixes);
341
354
  let complete = exitCode !== invalidInputCode && runs.every((run) => run !== undefined && run !== null);
342
- let preview = hasAutomaticFixes && complete ? previewCommand(options) : undefined;
355
+ const readOnly = hasAutomaticFixes && usesReadOnlyProjects(options);
356
+ let preview = hasAutomaticFixes && complete && !readOnly ? previewCommand(options) : undefined;
343
357
  if (preview && !hasCompleteFixCoverage(options)) {
344
358
  complete = false;
345
359
  preview = undefined;
@@ -360,12 +374,19 @@ function printCheckTextReport(options, runs, exitCode) {
360
374
  });
361
375
  if (preview)
362
376
  console.log(`\nPreview automatic fixes:\n${preview}`);
377
+ else if (readOnly)
378
+ console.log(`\n${inferredProjectFixGuidance}`);
363
379
  else if (hasAutomaticFixes && complete)
364
380
  console.log('\nUse the fix commands shown above to keep this scan’s filters.');
365
381
  else if (hasAutomaticFixes)
366
382
  console.log('\nResolve the incomplete scan before previewing automatic fixes.');
367
383
  else if (complete && exitCode === thresholdMetCode)
368
384
  console.log('\nReview the findings above. Run npx loadwise explain <rule-id> for rule details.');
385
+ if (selected.length > 1 && !options.baselineOptions.writeBaseline) {
386
+ const count = runs.reduce((sum, run) => sum + (run?.findingCount ?? 0), 0);
387
+ const scope = complete ? '.' : ' reported (scan incomplete).';
388
+ console.log(`\nTotal: ${count} finding${count === 1 ? '' : 's'}${scope}`);
389
+ }
369
390
  }
370
391
  async function runCheck(args, usage, formatReports = renderReports) {
371
392
  const options = parseCheckArgs(args);
@@ -449,7 +470,7 @@ async function runCheck(args, usage, formatReports = renderReports) {
449
470
  }
450
471
  if (values.review)
451
472
  await writeReviewHandoff(directory, 'check', {
452
- format: format === 'text' ? 'text' : 'json',
473
+ format: 'json',
453
474
  args,
454
475
  report,
455
476
  exitCode,
@@ -351,7 +351,7 @@ function createSettings(loaded, cliIgnore) {
351
351
  continue;
352
352
  const relative = relativeToBase(layer.directory, file);
353
353
  for (const override of layer.overrides) {
354
- if (override.matches(relative) && Object.hasOwn(override.rules, ruleId))
354
+ if (Object.hasOwn(override.rules, ruleId) && override.matches(relative))
355
355
  yield override.rules[ruleId];
356
356
  }
357
357
  }