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,114 @@
1
+ // Reads the repository's file listing and the blob ids Git already vouches for, so the scan cache can key a
2
+ // project by its inputs without hashing every unchanged file.
3
+ import path from 'node:path';
4
+ import { runGit } from '../system/git.js';
5
+ const gitListBuffer = 1 << 28;
6
+ function git(directory, gitArgs, input) {
7
+ const run = runGit(directory, gitArgs, { input, maxBuffer: gitListBuffer });
8
+ return run.status === 0 ? run.stdout : undefined;
9
+ }
10
+ // Checkers may read ancestor configs and repository-level files, so the whole repository is the
11
+ // input set. Undefined outside git, where no cache is used.
12
+ function gitFileListing(topLevel) {
13
+ const listing = git(topLevel, ['ls-files', '-t', '-z', '--cached', '--others', '--exclude-standard']);
14
+ if (listing === undefined)
15
+ return undefined;
16
+ // Security uses tracked files even when identical working-tree bytes also exist untracked.
17
+ const tracked = new Set();
18
+ const paths = [];
19
+ for (const entry of listing.split('\0')) {
20
+ if (!entry)
21
+ continue;
22
+ if (entry[1] !== ' ')
23
+ return undefined;
24
+ const name = entry.slice(2);
25
+ paths.push(name);
26
+ if (entry[0] !== '?')
27
+ tracked.add(name);
28
+ }
29
+ return { names: new Set(paths.sort()), tracked };
30
+ }
31
+ // Git already compares its index with the working tree by stat data (and by content when timestamps are racy),
32
+ // so an ordinary tracked file it reports as unmodified is identified by its blob id without reading it again.
33
+ // Configs resolved by TypeScript, special modes and entries with assume-unchanged or skip-worktree flags still
34
+ // take the full path, because Git is not authoritative for them.
35
+ const indexedBlobEntry = /^H (100644|100755) ([0-9a-f]{40,64}) 0\t(.+)$/s;
36
+ // A clean filter, ident or re-encoding can leave the blob id unchanged while the working-tree bytes differ,
37
+ // and a line-ending conversion makes the two differ by design. Those files must be hashed from disk, except a
38
+ // checkout whose only conversion is LF to CRLF (see crlfCheckouts).
39
+ const contentConvertingAttributes = ['filter', 'ident', 'working-tree-encoding'];
40
+ const lineEndingAttributes = ['text', 'eol', 'crlf'];
41
+ function convertedNames(topLevel, names) {
42
+ const attributes = git(topLevel, ['--literal-pathspecs', 'check-attr', '-z', '--stdin', ...contentConvertingAttributes, ...lineEndingAttributes], names.map((name) => `${name}\0`).join(''));
43
+ if (attributes === undefined)
44
+ return undefined;
45
+ const converted = new Set();
46
+ const crlfCheckouts = new Set();
47
+ let lineEndingsMayConvert = false;
48
+ const fields = attributes.split('\0');
49
+ for (let index = 0; index + 2 < fields.length; index += 3) {
50
+ if (fields[index + 2] === 'unspecified')
51
+ continue;
52
+ if (contentConvertingAttributes.includes(fields[index + 1]))
53
+ converted.add(fields[index]);
54
+ else
55
+ lineEndingsMayConvert = true;
56
+ }
57
+ // Line-ending conversion needs a text, eol or crlf attribute or core.autocrlf, all of which are metadata.
58
+ // Only then is the per-file line-ending listing, which makes Git read every tracked file, worth running.
59
+ // An unset key makes a plain --get exit 1, so --default keeps an unconfigured clone on the fast path.
60
+ const autocrlf = git(topLevel, ['config', '--default', '', '--get', 'core.autocrlf']);
61
+ if (autocrlf === undefined)
62
+ return undefined;
63
+ if (!lineEndingsMayConvert && autocrlf.trim() === '')
64
+ return { converted, crlfCheckouts };
65
+ const endings = git(topLevel, ['ls-files', '--eol', '-z', '--cached']);
66
+ if (endings === undefined)
67
+ return undefined;
68
+ for (const entry of endings.split('\0')) {
69
+ const match = /^i\/(\S*)\s+w\/(\S*)\s+attr\/[^\t]*\t(.+)$/s.exec(entry);
70
+ if (!match || converted.has(match[3]))
71
+ continue;
72
+ // Git classes a blob with any lone CR as -text, so i/lf has no CR at all, and w/crlf has every line ending as
73
+ // CRLF. Git calling such a file unmodified means stripping its CRs gives the blob, so its bytes are exactly the
74
+ // blob with each LF written as CRLF: the blob id and that class identify them without reading the file.
75
+ if (match[1] === 'lf' && match[2] === 'crlf')
76
+ crlfCheckouts.add(match[3]);
77
+ // A -text file keeps equal classes even when only its CR or CRLF endings changed.
78
+ else if (match[1] !== match[2] || match[1] === '-text')
79
+ converted.add(match[3]);
80
+ }
81
+ return { converted, crlfCheckouts };
82
+ }
83
+ // Values are blob ids, suffixed with :crlf for a checkout that differs from its blob only by CRLF line endings.
84
+ function unmodifiedBlobIds(topLevel) {
85
+ const blobIds = new Map();
86
+ const indexed = git(topLevel, ['ls-files', '-s', '-v', '-z', '--cached']);
87
+ const modified = git(topLevel, ['diff-files', '--name-only', '-z']);
88
+ // Staging between the two reads would pair an old blob id with a clean check of newer contents.
89
+ const indexedAfter = git(topLevel, ['ls-files', '-s', '-v', '-z', '--cached']);
90
+ if (indexed === undefined || modified === undefined || indexedAfter !== indexed)
91
+ return blobIds;
92
+ const modifiedNames = new Set(modified.split('\0'));
93
+ const candidates = [];
94
+ for (const entry of indexed.split('\0')) {
95
+ const match = indexedBlobEntry.exec(entry);
96
+ if (!match || /^0+$/.test(match[2]))
97
+ continue;
98
+ const name = match[3];
99
+ if (modifiedNames.has(name) || /^[jt]sconfig(?:\..+)?\.json$/i.test(path.posix.basename(name)))
100
+ continue;
101
+ candidates.push({ name, blobId: match[2] });
102
+ }
103
+ const conversions = convertedNames(topLevel, candidates.map(({ name }) => name));
104
+ if (conversions === undefined)
105
+ return blobIds;
106
+ for (const { name, blobId } of candidates) {
107
+ if (conversions.crlfCheckouts.has(name))
108
+ blobIds.set(name, `${blobId}:crlf`);
109
+ else if (!conversions.converted.has(name))
110
+ blobIds.set(name, blobId);
111
+ }
112
+ return blobIds;
113
+ }
114
+ export { git, gitFileListing, unmodifiedBlobIds };
@@ -0,0 +1,54 @@
1
+ // Which packages make up Loadwise's own install, for the scan cache's key and its source watch.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ // Captured before the wrappers replace it, so finding Loadwise's own packages is not itself watched.
5
+ const readUnwatched = fs.readFileSync;
6
+ function manifestOf(packageFolder) {
7
+ try {
8
+ const manifest = JSON.parse(readUnwatched(path.join(packageFolder, 'package.json'), 'utf8'));
9
+ return manifest !== null && typeof manifest === 'object' ? manifest : undefined;
10
+ }
11
+ catch {
12
+ // A package without a readable manifest adds no dependencies of its own.
13
+ return undefined;
14
+ }
15
+ }
16
+ function dependencyNames(packageFolder) {
17
+ const manifest = manifestOf(packageFolder);
18
+ return Object.keys({ ...manifest?.dependencies, ...manifest?.optionalDependencies, ...manifest?.peerDependencies });
19
+ }
20
+ function installedPackage(from, name) {
21
+ for (let folder = from;; folder = path.dirname(folder)) {
22
+ try {
23
+ return fs.realpathSync.native(path.join(folder, 'node_modules', name));
24
+ }
25
+ catch {
26
+ if (path.dirname(folder) === folder)
27
+ return undefined;
28
+ }
29
+ }
30
+ }
31
+ // Package managers can keep Loadwise's dependencies apart from it, as pnpm, hoisted and linked installs do. Only the
32
+ // packages Loadwise itself depends on count as its install; other packages beside them are not keyed.
33
+ function loadwisePackages(loadwiseRoot) {
34
+ const found = new Set();
35
+ const pending = [loadwiseRoot];
36
+ for (let current = pending.pop(); current !== undefined; current = pending.pop()) {
37
+ for (const name of dependencyNames(current)) {
38
+ const located = installedPackage(current, name);
39
+ if (located === undefined || found.has(located))
40
+ continue;
41
+ found.add(located);
42
+ pending.push(located);
43
+ }
44
+ }
45
+ return [...found];
46
+ }
47
+ /** Where each of Loadwise's packages is installed and at which version, so replacing one changes the cache key. */
48
+ function loadwisePackageVersions(loadwiseRoot) {
49
+ return loadwisePackages(loadwiseRoot)
50
+ .map((folder) => `${folder}\0${String(manifestOf(folder)?.version)}`)
51
+ .sort()
52
+ .join('\n');
53
+ }
54
+ export { loadwisePackages, loadwisePackageVersions };
@@ -0,0 +1,221 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { nextConfigNames } from './next-env-config.js';
6
+ import { isPathInsideOrEqual } from '../system/path-inside.js';
7
+ import { parseMaintainabilityArguments } from '../../maintainability/cli/scan-arguments.js';
8
+ import { lockfileNames } from '../../security/deps/lockfiles.js';
9
+ // Checkers read these from disk to select sources, so their contents count even when Git ignores them.
10
+ // The dependency checks read a lockfile and its registry settings even when Git ignores them.
11
+ const registryConfigNames = ['.npmrc', 'bunfig.toml'];
12
+ const projectConfigNames = [
13
+ 'tsconfig.json',
14
+ 'jsconfig.json',
15
+ 'pnpm-workspace.yaml',
16
+ 'lerna.json',
17
+ ...lockfileNames,
18
+ ...registryConfigNames,
19
+ ];
20
+ const projectInputs = /(?:^|\/)(?:package|[jt]sconfig)\.json$|\.[cm]?[jt]sx?$/i;
21
+ export function addAncestorDirectories(directories, directory) {
22
+ for (let folder = directory; !directories.has(folder); folder = path.posix.dirname(folder)) {
23
+ directories.add(folder);
24
+ }
25
+ }
26
+ function projectConfigHash(absolute, fileHash) {
27
+ try {
28
+ const stat = fs.statSync(absolute, { throwIfNoEntry: false });
29
+ if (stat?.isFile())
30
+ return fileHash(absolute, stat);
31
+ }
32
+ catch {
33
+ // An indexed path can have a missing or replaced parent in the working tree.
34
+ }
35
+ }
36
+ function hashIgnoredPackageInputs(hash, root, directory, names, fileHash) {
37
+ const manifestName = path.posix.join(directory, 'package.json');
38
+ const filename = path.join(root, manifestName);
39
+ const manifest = fs.lstatSync(filename, { throwIfNoEntry: false });
40
+ if (!manifest)
41
+ return;
42
+ if (!names.has(manifestName)) {
43
+ // Other checkers read a linked manifest's contents, but only a regular file can own a Next config.
44
+ const target = manifest.isSymbolicLink() ? fs.statSync(filename, { throwIfNoEntry: false }) : manifest;
45
+ hash.update(`\0manifest\0${manifestName}\0${manifest.mode}\0${target?.isFile() ? fileHash(filename, target) : ''}`);
46
+ }
47
+ if (!manifest.isFile())
48
+ return;
49
+ // Only package directories can own Next configs. A second path of any type makes publication ambiguous.
50
+ for (const config of nextConfigNames) {
51
+ const name = path.posix.join(directory, config);
52
+ if (names.has(name))
53
+ continue;
54
+ const candidate = path.join(root, name);
55
+ const stat = fs.lstatSync(candidate, { throwIfNoEntry: false });
56
+ if (stat)
57
+ hash.update(`\0next-config\0${name}\0${stat.isFile() ? fileHash(candidate, stat) : stat.mode}`);
58
+ }
59
+ }
60
+ // Configless and workspace discovery check source ancestors on disk, including markers Git ignores.
61
+ export function hashIgnoredProjectConfigs(hash, topLevel, relativeCwd, names, fileHash) {
62
+ const directories = new Set(['.']);
63
+ addAncestorDirectories(directories, relativeCwd || '.');
64
+ for (const name of names) {
65
+ if (projectInputs.test(name))
66
+ addAncestorDirectories(directories, path.posix.dirname(name));
67
+ }
68
+ for (const directory of directories) {
69
+ hashIgnoredPackageInputs(hash, topLevel, directory, names, fileHash);
70
+ for (const configName of projectConfigNames) {
71
+ const name = path.posix.join(directory, configName);
72
+ if (names.has(name))
73
+ continue;
74
+ const configHash = projectConfigHash(path.join(topLevel, name), fileHash);
75
+ if (configHash !== undefined)
76
+ hash.update(`\0project-config\0${name}\0${configHash}`);
77
+ }
78
+ }
79
+ }
80
+ // Git lists a linked folder as one entry, so the files it holds outside the repository are missing from the
81
+ // fingerprint while checkers still read them.
82
+ export function linksOutside(absolute, realTopLevel) {
83
+ try {
84
+ if (!fs.statSync(absolute, { throwIfNoEntry: false })?.isDirectory())
85
+ return false;
86
+ return !isPathInsideOrEqual(realTopLevel(), fs.realpathSync.native(absolute));
87
+ }
88
+ catch {
89
+ return true;
90
+ }
91
+ }
92
+ // The dependency checks also read the user's npm and Bun registry settings, from the environment and the home folder.
93
+ const registryVariables = [
94
+ 'BUN_CONFIG_REGISTRY',
95
+ 'NPM_CONFIG_REGISTRY',
96
+ 'npm_config_registry',
97
+ 'NPM_CONFIG_USERCONFIG',
98
+ 'XDG_CONFIG_HOME',
99
+ ];
100
+ /** Undefined when a check could read a registry setting the key cannot name. The files are keyed by their contents. */
101
+ export function registryConfigFingerprint() {
102
+ const home = os.homedir();
103
+ const { NPM_CONFIG_USERCONFIG, XDG_CONFIG_HOME } = process.env;
104
+ // The checks resolve a relative user config from each lockfile's folder, which only the scan finds.
105
+ if (NPM_CONFIG_USERCONFIG && !path.isAbsolute(NPM_CONFIG_USERCONFIG))
106
+ return undefined;
107
+ const configHome = XDG_CONFIG_HOME && path.isAbsolute(XDG_CONFIG_HOME) ? XDG_CONFIG_HOME : home;
108
+ const files = [path.join(home, '.npmrc'), path.join(configHome, '.npmrc'), path.join(configHome, '.bunfig.toml')];
109
+ if (NPM_CONFIG_USERCONFIG)
110
+ files.push(NPM_CONFIG_USERCONFIG);
111
+ const hash = crypto.createHash('sha1');
112
+ for (const name of registryVariables)
113
+ hash.update(`${name}=${process.env[name] ?? ''}\0`);
114
+ for (const file of files) {
115
+ let contents = '\0absent';
116
+ try {
117
+ contents = fs.readFileSync(file, 'utf8');
118
+ }
119
+ catch {
120
+ // A missing or unreadable file leaves the registry unchanged, as the checks read it.
121
+ }
122
+ hash.update(`${file}\0${contents}\0`);
123
+ }
124
+ return { fingerprint: hash.digest('hex'), files };
125
+ }
126
+ // Only a link whose target leaves the repository makes a checker read outside it. A dangling link resolves to itself.
127
+ export function targetsOutside(absolute, realTopLevel) {
128
+ try {
129
+ return !isPathInsideOrEqual(realTopLevel(), fs.realpathSync.native(absolute));
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ }
135
+ // The keyed files travel to the checker in one environment variable, which Windows limits to 32,767 characters.
136
+ const keyedFilesLimit = 30_000;
137
+ export function fitsKeyedFiles(keyedFiles) {
138
+ return JSON.stringify(keyedFiles).length <= keyedFilesLimit;
139
+ }
140
+ export function isLink(file) {
141
+ try {
142
+ return fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink() ?? false;
143
+ }
144
+ catch {
145
+ // An unreadable entry is not followed by the checkers either.
146
+ return false;
147
+ }
148
+ }
149
+ export function insideGitRepository(directory) {
150
+ if (process.env.GIT_DIR)
151
+ return true;
152
+ for (let ancestor = directory;; ancestor = path.dirname(ancestor)) {
153
+ try {
154
+ if (fs.lstatSync(path.join(ancestor, '.git'), { throwIfNoEntry: false }))
155
+ return true;
156
+ }
157
+ catch {
158
+ // Membership cannot be ruled out, so the scan is not keyed from another folder; the caller bypasses the cache.
159
+ return true;
160
+ }
161
+ if (path.dirname(ancestor) === ancestor)
162
+ return false;
163
+ }
164
+ }
165
+ // The folder a checker child scans: its `-p`/`--project` value, or maintainability's positional folder. `check` runs
166
+ // each pillar as such a child with `-p <path>`, so a `check path/to/app` from outside a repository is cached there.
167
+ export function scannedProject(args, cwd) {
168
+ const flagIndex = args.findIndex((arg) => arg === '-p' || arg === '--project');
169
+ let named = flagIndex >= 0 ? args[flagIndex + 1] : args.find((arg) => arg.startsWith('--project='))?.slice('--project='.length);
170
+ if (named === undefined && args[0] === 'maint') {
171
+ try {
172
+ named = parseMaintainabilityArguments(args.slice(1)).positionals[0];
173
+ }
174
+ catch {
175
+ return undefined;
176
+ }
177
+ }
178
+ if (!named)
179
+ return undefined;
180
+ const absolute = path.resolve(cwd, named);
181
+ let stat;
182
+ try {
183
+ stat = fs.statSync(absolute, { throwIfNoEntry: false });
184
+ }
185
+ catch {
186
+ // A looping or unreadable path is the checker's to report; the scan runs uncached.
187
+ return undefined;
188
+ }
189
+ if (stat?.isDirectory())
190
+ return absolute;
191
+ return stat?.isFile() ? path.dirname(absolute) : undefined;
192
+ }
193
+ // node_modules is ignored by git, but installing or removing a package changes the types the
194
+ // checkers see. Package managers rewrite these files on every install, so their size and time stand
195
+ // in for the whole tree.
196
+ const installMarkers = [
197
+ 'node_modules',
198
+ 'node_modules/.package-lock.json',
199
+ 'node_modules/.yarn-state.yml',
200
+ 'node_modules/.modules.yaml',
201
+ 'node_modules/.pnpm/lock.yaml',
202
+ ];
203
+ export function hashMarkersIn(hash, base, directory) {
204
+ for (const marker of installMarkers) {
205
+ const stat = fs.statSync(path.join(base, directory, marker), { throwIfNoEntry: false });
206
+ // The other markers live inside node_modules.
207
+ if (!stat && marker === 'node_modules')
208
+ return;
209
+ if (stat)
210
+ hash.update(`\0${directory}\0${marker}\0${stat.size}\0${stat.mtimeMs}`);
211
+ }
212
+ }
213
+ // A listed file resolves packages from a node_modules in any folder above it, a nested install that is no workspace
214
+ // included, so every such folder's install markers count, and so does the absence of an install there.
215
+ export function hashListedFolderInstalls(hash, topLevel, names) {
216
+ const directories = new Set();
217
+ for (const name of names)
218
+ addAncestorDirectories(directories, path.posix.dirname(name));
219
+ for (const directory of directories)
220
+ hashMarkersIn(hash, topLevel, directory);
221
+ }
@@ -0,0 +1,235 @@
1
+ // The scan cache keys a report by the Git repository's files, but TypeScript follows imports wherever they lead.
2
+ // A checker child whose report may be stored loads this module with --import; it watches file reads, and the
3
+ // first source file read from outside the repository tells the parent not to store the report.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { syncBuiltinESMExports } from 'node:module';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { packageRoot } from '../package-root.js';
9
+ import { realExistingPrefix } from '../project-root.js';
10
+ import { loadwisePackages } from './scan-cache-loadwise-packages.js';
11
+ import { isPathInsideOrEqual } from '../system/path-inside.js';
12
+ const topLevelVariable = 'LOADWISE_INTERNAL_SCAN_CACHE_TOP_LEVEL';
13
+ const keyedFilesVariable = 'LOADWISE_INTERNAL_SCAN_CACHE_KEYED_FILES';
14
+ const outsideSourceSignal = 'loadwise:outside-repository-source';
15
+ // Program sources, the JSON modules they import (manifests and configs too), templates, Prisma schemas and migrations,
16
+ // OpenAPI references and Protobuf imports can change findings. A read outside the repository counts unless the parent
17
+ // keyed that exact file.
18
+ const sourceExtension = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|html?|jsonc?|ya?ml|toml|sql|prisma|proto)$/i;
19
+ function keyedFilesFromEnvironment() {
20
+ let listed;
21
+ try {
22
+ listed = JSON.parse(process.env[keyedFilesVariable] || '[]');
23
+ }
24
+ catch {
25
+ // Keying nothing only means more reads count as outside, which is the safe direction.
26
+ return [];
27
+ }
28
+ return Array.isArray(listed) ? listed.filter((file) => typeof file === 'string') : [];
29
+ }
30
+ function realRoots(topLevel) {
31
+ // The parent names keyed files as Git and TypeScript spell them, which can differ from the child's spelling.
32
+ const keyedFiles = new Set();
33
+ // A missing file is keyed by its absence, and a lookup for it resolves through its nearest existing folder.
34
+ for (const file of keyedFilesFromEnvironment())
35
+ keyedFiles.add(realExistingPrefix(file));
36
+ const loadwiseRoot = fs.realpathSync.native(packageRoot);
37
+ return {
38
+ topLevel: fs.realpathSync.native(topLevel),
39
+ loadwiseRoot,
40
+ loadwisePackages: loadwisePackages(loadwiseRoot),
41
+ keyedFiles,
42
+ };
43
+ }
44
+ // The install markers key node_modules in the repository and in every folder above it. Any other node_modules tree is
45
+ // not keyed, apart from Loadwise's own packages, whose versions the key holds.
46
+ function keyedInstall(resolved, { topLevel }) {
47
+ const segments = resolved.split(/[\\/]/);
48
+ const index = segments.indexOf('node_modules');
49
+ if (index < 1)
50
+ return false;
51
+ const owner = segments.slice(0, index).join(path.sep) + path.sep;
52
+ return isPathInsideOrEqual(owner, topLevel);
53
+ }
54
+ // Read APIs also take file URLs and Buffers; a descriptor was already checked when it was opened.
55
+ function pathText(file) {
56
+ if (typeof file === 'string')
57
+ return file;
58
+ if (file instanceof URL)
59
+ return file.protocol === 'file:' ? fileURLToPath(file) : undefined;
60
+ return Buffer.isBuffer(file) ? file.toString() : undefined;
61
+ }
62
+ // Captured before the wrappers replace it, so resolving a watched path does not watch itself.
63
+ const lstatUnwatched = fs.lstatSync;
64
+ // A link anywhere on the path counts, the file itself included, also inside ignored folders and under node_modules.
65
+ // A missing file resolves through its nearest existing folder, since a later read of it would land there, except
66
+ // under a dangling link, whose target can appear anywhere: that path has no known place.
67
+ function resolvedPath(absolute) {
68
+ const missing = [];
69
+ for (let current = absolute;; current = path.dirname(current)) {
70
+ try {
71
+ return path.join(fs.realpathSync.native(current), ...missing.reverse());
72
+ }
73
+ catch {
74
+ if (lstatUnwatched(current, { throwIfNoEntry: false })?.isSymbolicLink())
75
+ return undefined;
76
+ if (current === path.dirname(current))
77
+ return absolute;
78
+ missing.push(path.basename(current));
79
+ }
80
+ }
81
+ }
82
+ function isOutsideSource(argument, roots) {
83
+ const file = pathText(argument);
84
+ return file !== undefined && sourceExtension.test(file) && isOutside(file, roots);
85
+ }
86
+ // A folder listing, such as a tsconfig `include` walk, finds sources that may not exist yet, so listing any folder
87
+ // outside the repository counts, whatever it holds.
88
+ function isOutsideFolder(argument, roots) {
89
+ const folder = pathText(argument);
90
+ return folder !== undefined && isOutside(folder, roots);
91
+ }
92
+ function isOutside(file, roots) {
93
+ // `path.resolve` would drop a `..` by its text, while POSIX follows a link before the `..` that comes after it.
94
+ const absolute = path.isAbsolute(file) ? file : `${process.cwd()}${path.sep}${file}`;
95
+ const resolved = resolvedPath(absolute);
96
+ if (resolved === undefined)
97
+ return true;
98
+ const watched = roots();
99
+ if (isPathInsideOrEqual(watched.topLevel, resolved) || isLoadwiseInstall(resolved, watched))
100
+ return false;
101
+ return !keyedInstall(resolved, watched) && !watched.keyedFiles.has(resolved);
102
+ }
103
+ const caseInsensitivePaths = process.platform === 'win32' || process.platform === 'darwin';
104
+ // Windows and macOS match a path in any letter case. TypeScript also probes its own path with the case swapped to
105
+ // learn whether the file system is case-sensitive; elsewhere that path does not exist, so a missing path matches in
106
+ // any case too, while an existing file must match exactly. The deepest of Loadwise's packages that holds a path owns
107
+ // it, and a package nested in its node_modules that is not one of Loadwise's own is no part of the install.
108
+ function isLoadwiseInstall(resolved, { loadwiseRoot, loadwisePackages }) {
109
+ const anyCase = caseInsensitivePaths || !lstatUnwatched(resolved, { throwIfNoEntry: false });
110
+ const fold = (text) => (anyCase ? text.toLowerCase() : text);
111
+ const target = fold(resolved);
112
+ let owner;
113
+ for (const installed of [loadwiseRoot, ...loadwisePackages]) {
114
+ const candidate = fold(installed);
115
+ if (isPathInsideOrEqual(candidate, target) && candidate.length > (owner?.length ?? -1))
116
+ owner = candidate;
117
+ }
118
+ return owner !== undefined && !path.relative(owner, target).split(path.sep).includes('node_modules');
119
+ }
120
+ function reportOutsideSource() {
121
+ if (!process.send || !process.connected || !process.env[topLevelVariable])
122
+ return;
123
+ process.send(outsideSourceSignal, undefined, undefined, () => undefined);
124
+ }
125
+ // `fs.open` takes its callback where the flags would be, and opens for reading when they are left out.
126
+ function opensForReading(flags) {
127
+ if (flags === undefined || typeof flags === 'function')
128
+ return true;
129
+ if (typeof flags === 'number')
130
+ return (flags & (fs.constants.O_WRONLY | fs.constants.O_RDWR)) !== fs.constants.O_WRONLY;
131
+ return typeof flags === 'string' && (flags.includes('r') || flags.includes('+'));
132
+ }
133
+ // Set once this process watches its reads.
134
+ let noteRead;
135
+ function watchSourceReads(topLevel) {
136
+ let reported = false;
137
+ // Resolved once, on the first watched read.
138
+ let roots;
139
+ const watchedRoots = () => (roots ??= realRoots(topLevel));
140
+ const noter = (isOutsideRead) => (file) => {
141
+ if (reported)
142
+ return;
143
+ let outside;
144
+ try {
145
+ outside = isOutsideRead(file, watchedRoots);
146
+ }
147
+ catch {
148
+ // The repository or Loadwise's install vanished mid-scan, as a concurrent install can do: the read goes ahead,
149
+ // and the report is not stored.
150
+ outside = true;
151
+ }
152
+ if (!outside)
153
+ return;
154
+ reported = true;
155
+ reportOutsideSource();
156
+ };
157
+ noteRead = noter(isOutsideSource);
158
+ const note = noteRead;
159
+ // Each wrapper forwards every overload unchanged, which its own signature cannot spell out.
160
+ const watched = (read, reads = () => true, noteFile = note) => function watchedRead(...call) {
161
+ if (reads(call[1]))
162
+ noteFile(call[0]);
163
+ return Reflect.apply(read, this, call);
164
+ };
165
+ const noteListing = noter(isOutsideFolder);
166
+ const always = () => true;
167
+ Object.assign(fs, {
168
+ readdirSync: watched(fs.readdirSync, always, noteListing),
169
+ readdir: watched(fs.readdir, always, noteListing),
170
+ opendirSync: watched(fs.opendirSync, always, noteListing),
171
+ opendir: watched(fs.opendir, always, noteListing),
172
+ });
173
+ Object.assign(fs.promises, {
174
+ readdir: watched(fs.promises.readdir, always, noteListing),
175
+ opendir: watched(fs.promises.opendir, always, noteListing),
176
+ });
177
+ // Checkers read sources synchronously (TypeScript) and asynchronously (maintainability) alike.
178
+ Object.assign(fs, { readFileSync: watched(fs.readFileSync), readFile: watched(fs.readFile) });
179
+ Object.assign(fs.promises, { readFile: watched(fs.promises.readFile) });
180
+ // A descriptor or stream read starts with an open, so opening a source to read it counts as reading it.
181
+ Object.assign(fs, {
182
+ openSync: watched(fs.openSync, opensForReading),
183
+ open: watched(fs.open, opensForReading),
184
+ createReadStream: watched(fs.createReadStream),
185
+ });
186
+ Object.assign(fs.promises, { open: watched(fs.promises.open, opensForReading) });
187
+ // Module resolution probes candidates before it reads one, so an outside import that is still missing, and would
188
+ // resolve once created, shows up only as a probe.
189
+ Object.assign(fs, {
190
+ statSync: watched(fs.statSync),
191
+ lstatSync: watched(fs.lstatSync),
192
+ existsSync: watched(fs.existsSync),
193
+ accessSync: watched(fs.accessSync),
194
+ stat: watched(fs.stat),
195
+ lstat: watched(fs.lstat),
196
+ access: watched(fs.access),
197
+ exists: watched(fs.exists),
198
+ });
199
+ Object.assign(fs.promises, {
200
+ stat: watched(fs.promises.stat),
201
+ lstat: watched(fs.promises.lstat),
202
+ access: watched(fs.promises.access),
203
+ });
204
+ // Modules that imported these by name see the wrappers too.
205
+ syncBuiltinESMExports();
206
+ }
207
+ /** Checks sources a reader outside this process loaded, such as the TypeScript 7 native compiler, as if read here. */
208
+ function noteSourcesRead(files) {
209
+ if (noteRead)
210
+ for (const file of files)
211
+ noteRead(file);
212
+ }
213
+ function isOutsideSourceSignal(message) {
214
+ return message === outsideSourceSignal;
215
+ }
216
+ /** The node arguments and environment that make a checker child watch its reads for `watch`. */
217
+ function sourceWatchSpawn(watch) {
218
+ return {
219
+ execArgv: ['--import', pathToFileURL(import.meta.filename).href],
220
+ env: { [topLevelVariable]: watch.topLevel, [keyedFilesVariable]: JSON.stringify(watch.keyedFiles) },
221
+ };
222
+ }
223
+ /** The watch an uncached nested run passes on, so a grandchild's outside read still reaches the caching parent. */
224
+ function inheritedSourceWatch() {
225
+ const topLevel = process.env[topLevelVariable];
226
+ return topLevel
227
+ ? { topLevel, keyedFiles: keyedFilesFromEnvironment(), onOutsideSource: reportOutsideSource }
228
+ : undefined;
229
+ }
230
+ // Only a process with a parent channel installs the wrapper, for the rest of its life. Worker threads have no
231
+ // process.send and stay unwatched; maintainability's scan workers read only the project files listed for them.
232
+ const watchedTopLevel = process.env[topLevelVariable];
233
+ if (watchedTopLevel && process.send)
234
+ watchSourceReads(watchedTopLevel);
235
+ export { inheritedSourceWatch, isOutsideSourceSignal, noteSourcesRead, reportOutsideSource, sourceWatchSpawn };
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import os from 'node:os';
2
3
  import path from 'node:path';
3
4
  import { writeResolvedFileAtomic } from '../system/atomic-write.js';
4
5
  import { errorCode } from '../system/error-code.js';
@@ -41,6 +42,27 @@ function untrustedCacheAncestor(directory) {
41
42
  function trustedCacheAncestors(directory) {
42
43
  return untrustedCacheAncestor(directory) === undefined;
43
44
  }
45
+ function realProfileRoot(root) {
46
+ if (!root || !path.isAbsolute(root))
47
+ return [];
48
+ try {
49
+ return [fs.realpathSync.native(root)];
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ }
55
+ // Windows exposes no owner or permission bits through fs.Stats, so a cache there is trusted only inside the
56
+ // user's own profile, whose default ACL keeps other standard users out. Returns the folder to report otherwise.
57
+ function outsideWindowsProfile(canonical) {
58
+ if (process.platform !== 'win32')
59
+ return;
60
+ const profileRoots = [os.homedir(), process.env.LOCALAPPDATA].flatMap(realProfileRoot);
61
+ // Both sides come from realpath, which spells existing folders as stored, so an exact prefix match also
62
+ // rejects a differently cased sibling in a case-sensitive folder.
63
+ const inside = (root) => canonical.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
64
+ return profileRoots.some(inside) ? undefined : path.dirname(canonical);
65
+ }
44
66
  function createCacheDirectories(parent, missing, canonical) {
45
67
  for (const name of missing) {
46
68
  parent = path.join(parent, name);
@@ -76,6 +98,8 @@ function trustedCacheDirectory(requested, create = false, onUntrusted) {
76
98
  }
77
99
  const parent = fs.realpathSync.native(current);
78
100
  const canonical = path.join(parent, ...missing);
101
+ if (rejectedBy(outsideWindowsProfile(canonical)))
102
+ return;
79
103
  if (canonical !== directory && rejectedBy(untrustedCacheAncestor(canonical)))
80
104
  return;
81
105
  if (create && !createCacheDirectories(parent, missing, canonical))