loadwise 0.5.1 → 0.6.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 (131) hide show
  1. package/README.md +542 -627
  2. package/bin/loadwise.js +4 -0
  3. package/lib/accessibility/frontend-detect.js +2 -1
  4. package/lib/accessibility/rule-ids.js +12 -9
  5. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  6. package/lib/editor/actions.js +117 -0
  7. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  8. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  9. package/lib/editor/diagnostics.js +365 -0
  10. package/lib/editor/dismissals.js +111 -0
  11. package/lib/editor/editor-document.js +99 -0
  12. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  13. package/lib/editor/fix-edits.js +200 -0
  14. package/lib/editor/language-server.js +437 -0
  15. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  16. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  17. package/lib/editor/perf-watch.js +78 -0
  18. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  19. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  20. package/lib/editor/scan-session.js +334 -0
  21. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  22. package/lib/editor/server-commands.js +232 -0
  23. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  24. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  25. package/lib/editor/types/dismissal.js +1 -0
  26. package/lib/editor/types/fix-example.js +1 -0
  27. package/lib/editor/types/source-document.js +1 -0
  28. package/lib/editor/workspace-files.js +78 -0
  29. package/lib/editor/workspace-paths.js +22 -0
  30. package/lib/maintainability/analyze-source.js +2 -0
  31. package/lib/maintainability/apply-fix.js +1 -1
  32. package/lib/maintainability/cli.js +1 -1
  33. package/lib/maintainability/examples.js +58 -41
  34. package/lib/maintainability/rule-ids.js +29 -14
  35. package/lib/maintainability/scan-changed.js +3 -0
  36. package/lib/maintainability/scan.js +13 -9
  37. package/lib/maintainability/tsconfig-strict.js +69 -0
  38. package/lib/maintainability/type-safety-hygiene.js +204 -0
  39. package/lib/performance/analyze.js +2 -0
  40. package/lib/performance/cli-arguments.js +0 -2
  41. package/lib/performance/cli-policy.js +17 -9
  42. package/lib/performance/cli-scan.js +10 -8
  43. package/lib/performance/cli.js +4 -23
  44. package/lib/performance/editor-signal.js +1 -1
  45. package/lib/performance/finding-text.js +3 -3
  46. package/lib/performance/fix-cli.js +1 -1
  47. package/lib/performance/frontend-perf.js +7 -0
  48. package/lib/performance/frontend-render-perf.js +200 -0
  49. package/lib/performance/llm-max-tokens.js +56 -0
  50. package/lib/performance/native.js +46 -26
  51. package/lib/performance/polyglot.js +22 -1
  52. package/lib/performance/pooling.js +38 -23
  53. package/lib/performance/projects.js +42 -21
  54. package/lib/performance/rule-ids.js +236 -222
  55. package/lib/performance/site-fixes/database.js +3 -1
  56. package/lib/performance/site-fixes/integrity.js +15 -1
  57. package/lib/performance/source-inputs.js +18 -6
  58. package/lib/performance/unscanned-javascript.js +66 -19
  59. package/lib/reliability/analyze.js +12 -0
  60. package/lib/reliability/child-process.js +106 -0
  61. package/lib/reliability/error-values.js +177 -0
  62. package/lib/reliability/pool-timeout.js +79 -0
  63. package/lib/reliability/react-bugs.js +602 -0
  64. package/lib/reliability/resource-leaks.js +3 -6
  65. package/lib/reliability/rule-ids.js +169 -127
  66. package/lib/reliability/switch-exhaustive.js +284 -0
  67. package/lib/reliability/uncaught-exception.js +223 -0
  68. package/lib/security/auth-crypto/rule-ids.js +3 -2
  69. package/lib/security/cli.js +6 -5
  70. package/lib/security/deps/rule-ids.js +1 -0
  71. package/lib/security/examples/auth-crypto.cjs +5 -4
  72. package/lib/security/examples/deps.cjs +1 -0
  73. package/lib/security/examples/exposure.cjs +55 -42
  74. package/lib/security/examples/files.cjs +1 -0
  75. package/lib/security/examples/injection.cjs +1 -0
  76. package/lib/security/examples/moved.cjs +5 -4
  77. package/lib/security/examples/request-forgery.cjs +1 -0
  78. package/lib/security/exposure/client-env.js +113 -0
  79. package/lib/security/exposure/frontend-security.js +12 -10
  80. package/lib/security/exposure/index.js +14 -3
  81. package/lib/security/exposure/jsx-url.js +267 -0
  82. package/lib/security/exposure/next-image-config.js +34 -0
  83. package/lib/security/exposure/package-manifest.js +45 -0
  84. package/lib/security/exposure/react-version.js +45 -0
  85. package/lib/security/exposure/rule-ids.js +16 -12
  86. package/lib/security/files/index.js +1 -1
  87. package/lib/security/files/rule-ids.js +1 -0
  88. package/lib/security/injection/code.js +24 -10
  89. package/lib/security/injection/command.js +81 -28
  90. package/lib/security/injection/nosql.js +109 -22
  91. package/lib/security/injection/redos.js +152 -308
  92. package/lib/security/injection/regex-pattern.js +290 -0
  93. package/lib/security/injection/regex.js +30 -11
  94. package/lib/security/injection/rule-ids.js +2 -1
  95. package/lib/security/injection/shared.js +19 -1
  96. package/lib/security/injection/sql.js +83 -2
  97. package/lib/security/request-forgery/rule-ids.js +1 -0
  98. package/lib/security/rule-descriptions.js +36 -32
  99. package/lib/security/rule-ids.js +74 -67
  100. package/lib/security/taint/filename-guard.js +3 -1
  101. package/lib/security/taint/guards.js +84 -10
  102. package/lib/security/taint/index.js +124 -13
  103. package/lib/security/taint/propagate.js +10 -7
  104. package/lib/security/taint/sanitizers.js +7 -3
  105. package/lib/security/taint/sources.js +6 -3
  106. package/lib/security/taint/summaries.js +13 -1
  107. package/lib/security/taint/url-parts.js +14 -5
  108. package/lib/shared/agent-session.js +2 -2
  109. package/lib/shared/check.js +9 -6
  110. package/lib/shared/explain.js +5 -5
  111. package/lib/shared/fix-convergence.js +1 -1
  112. package/lib/shared/formats/finding-location.js +6 -2
  113. package/lib/shared/formats/sarif.js +3 -3
  114. package/lib/shared/heap-limit.js +6 -0
  115. package/lib/shared/pillars.js +7 -7
  116. package/lib/shared/rule-docs.js +12 -0
  117. package/lib/shared/scan-cache.js +0 -1
  118. package/lib/shared/workspaces.js +31 -9
  119. package/package.json +9 -16
  120. package/plugin/.claude-plugin/plugin.json +1 -1
  121. package/schema/loadwise.config.schema.json +44 -0
  122. package/editor/README.md +0 -47
  123. package/examples/redis-keys.otlp.json +0 -22
  124. package/lib/maintainability/notify-editor.js +0 -1
  125. package/lib/performance/editor-report.js +0 -191
  126. package/lib/performance/editor-setup.js +0 -189
  127. package/lib/performance/editor-watch-supervisor.js +0 -104
  128. package/lib/performance/editor-watch.js +0 -193
  129. package/lib/performance/notify-editor.js +0 -1
  130. package/lib/performance/recursive-watch.js +0 -181
  131. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
package/bin/loadwise.js CHANGED
@@ -13,6 +13,7 @@ const usage = `Usage:
13
13
  loadwise fix --all [performance] [reliability] [maintainability] [security] [accessibility] [--json]
14
14
  loadwise fix --handoff [performance] [reliability] [maintainability] [security] [accessibility]
15
15
  loadwise explain <rule-id>
16
+ loadwise lsp [--stdio]
16
17
  loadwise --version
17
18
  loadwise agent init [--mode ask|auto] [--hook [block|warn|off]]
18
19
  loadwise agent instructions
@@ -35,6 +36,7 @@ fix --yes applies automatic edits. fix --all also applies edits marked for revie
35
36
  fix --json with --yes or --all records the applied hunks and outstanding findings in its output for review.
36
37
  perf, rel, maint, sec and a11y run one checker with its full command set; \`loadwise perf --help\`, \`loadwise rel --help\`, \`loadwise maint --help\` \`loadwise sec --help\` and \`loadwise a11y --help\` list their commands and flags.
37
38
  explain prints the rule's default impact, description and an illustrative change when available.
39
+ lsp runs the language server on stdin and stdout for any editor with a Language Server Protocol client: findings from every checker as diagnostics, with hovers, fixes, dismissals and code lenses.
38
40
  Recognized coding-agent sessions receive review instructions automatically. agent instructions prints the review workflow. Optional agent init writes it into AGENTS.md and imports it from CLAUDE.md.
39
41
  An active agent can run check --json directly or use the loadwise_check MCP tool for a fresh offline report.
40
42
  Add --review to a combined check or bulk fix to keep its original report and print the same handoff for any coding agent. agent pending lists saved handoffs for this project.
@@ -58,6 +60,8 @@ async function main(args) {
58
60
  return (await import('../lib/shared/fix.js')).runFix(rest);
59
61
  if (command === 'explain')
60
62
  return (await import('../lib/shared/explain.js')).runExplain(rest);
63
+ if (command === 'lsp')
64
+ return (await import('../lib/editor/language-server.js')).runLanguageServer(rest);
61
65
  if (command === '--version' || command === '-v') {
62
66
  if (rest.length)
63
67
  throw new Error('Usage: loadwise --version');
@@ -87,7 +87,8 @@ function hasFrontendSourcesInWorkspaces(directory, selectors) {
87
87
  if (!selectors.length)
88
88
  return hasFrontendSources(directory);
89
89
  try {
90
- const chosen = selectWorkspaces(discoverWorkspaces(directory).packages, path.resolve(directory), selectors);
90
+ const { packages, withoutConfig } = discoverWorkspaces(directory);
91
+ const chosen = selectWorkspaces([...packages, ...withoutConfig], path.resolve(directory), selectors);
91
92
  return chosen.some((workspace) => hasFrontendSources(workspace.directory));
92
93
  }
93
94
  catch {
@@ -1,35 +1,38 @@
1
1
  // Rules about markup that people using screen readers, keyboards or zoom cannot use. JSX is read from the shared
2
2
  // TypeScript pass; HTML files and Vue, Svelte and Angular templates are read as markup files beside it.
3
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
3
4
  const knownRules = new Set([
4
- 'a11y-img-missing-alt',
5
5
  'a11y-button-missing-type',
6
6
  'a11y-clickable-non-interactive',
7
- 'a11y-invalid-aria',
8
- 'a11y-missing-form-label',
9
7
  'a11y-html-missing-lang',
10
8
  'a11y-iframe-missing-title',
9
+ 'a11y-img-missing-alt',
10
+ 'a11y-invalid-aria',
11
+ 'a11y-missing-form-label',
11
12
  'a11y-positive-tabindex',
12
13
  'a11y-viewport-zoom-disabled',
13
14
  ]);
15
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
14
16
  const impactByRule = {
15
- 'a11y-img-missing-alt': 'high',
16
17
  'a11y-button-missing-type': 'medium',
17
18
  'a11y-clickable-non-interactive': 'high',
18
- 'a11y-invalid-aria': 'high',
19
- 'a11y-missing-form-label': 'high',
20
19
  'a11y-html-missing-lang': 'medium',
21
20
  'a11y-iframe-missing-title': 'medium',
21
+ 'a11y-img-missing-alt': 'high',
22
+ 'a11y-invalid-aria': 'high',
23
+ 'a11y-missing-form-label': 'high',
22
24
  'a11y-positive-tabindex': 'medium',
23
25
  'a11y-viewport-zoom-disabled': 'high',
24
26
  };
27
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
25
28
  const descriptionByRule = {
26
- 'a11y-img-missing-alt': 'An image has no alt text, so screen readers announce its file name or nothing.',
27
29
  'a11y-button-missing-type': 'A button inside a form has no type, so it submits the form even when it only meant to run a handler.',
28
30
  'a11y-clickable-non-interactive': 'A click handler sits on a non-interactive element without a role and keyboard support, so keyboard users cannot activate it.',
29
- 'a11y-invalid-aria': 'An ARIA attribute or role is misspelled or invalid, so assistive technology ignores it.',
30
- 'a11y-missing-form-label': 'A form control has no label, so screen readers announce it without its purpose.',
31
31
  'a11y-html-missing-lang': 'The html element has no lang attribute, so screen readers guess the pronunciation.',
32
32
  'a11y-iframe-missing-title': 'An iframe has no title, so screen readers cannot say what it contains.',
33
+ 'a11y-img-missing-alt': 'An image has no alt text, so screen readers announce its file name or nothing.',
34
+ 'a11y-invalid-aria': 'An ARIA attribute or role is misspelled or invalid, so assistive technology ignores it.',
35
+ 'a11y-missing-form-label': 'A form control has no label, so screen readers announce it without its purpose.',
33
36
  'a11y-positive-tabindex': 'A positive tabindex reorders keyboard focus away from the visual order.',
34
37
  'a11y-viewport-zoom-disabled': 'The viewport meta tag disables zoom, so people with low vision cannot enlarge the page.',
35
38
  };
@@ -1,12 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.exampleFor = exampleFor;
1
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
4
2
  const examples = {
5
- 'a11y-img-missing-alt': {
6
- jsx: { before: '<img src={logo} />', code: '<img src={logo} alt="Company logo" />' },
7
- html: { before: '<img src="logo.png">', code: '<img src="logo.png" alt="Company logo">' },
8
- note: 'Describe the image, or use alt="" if it is decorative.',
9
- },
10
3
  'a11y-button-missing-type': {
11
4
  jsx: {
12
5
  before: '<button onClick={save}>Save</button>',
@@ -29,6 +22,24 @@ const examples = {
29
22
  },
30
23
  note: 'A button works with the keyboard and screen readers without extra attributes.',
31
24
  },
25
+ 'a11y-html-missing-lang': {
26
+ jsx: { before: '<html>', code: '<html lang="en">' },
27
+ html: { before: '<html>', code: '<html lang="en">' },
28
+ note: 'Set the language of the page content.',
29
+ },
30
+ 'a11y-iframe-missing-title': {
31
+ jsx: { before: '<iframe src={mapUrl} />', code: '<iframe src={mapUrl} title="Store location map" />' },
32
+ html: {
33
+ before: '<iframe src="/map"></iframe>',
34
+ code: '<iframe src="/map" title="Store location map"></iframe>',
35
+ },
36
+ note: 'The title is what screen readers announce for the frame.',
37
+ },
38
+ 'a11y-img-missing-alt': {
39
+ jsx: { before: '<img src={logo} />', code: '<img src={logo} alt="Company logo" />' },
40
+ html: { before: '<img src="logo.png">', code: '<img src="logo.png" alt="Company logo">' },
41
+ note: 'Describe the image, or use alt="" if it is decorative.',
42
+ },
32
43
  'a11y-invalid-aria': {
33
44
  jsx: { before: '<div aria-lable="Close" />', code: '<div aria-label="Close" />' },
34
45
  html: { before: '<div aria-lable="Close"></div>', code: '<div aria-label="Close"></div>' },
@@ -45,19 +56,6 @@ const examples = {
45
56
  },
46
57
  note: 'A placeholder is not a label; wrap the input, or use label for, or aria-label.',
47
58
  },
48
- 'a11y-html-missing-lang': {
49
- jsx: { before: '<html>', code: '<html lang="en">' },
50
- html: { before: '<html>', code: '<html lang="en">' },
51
- note: 'Set the language of the page content.',
52
- },
53
- 'a11y-iframe-missing-title': {
54
- jsx: { before: '<iframe src={mapUrl} />', code: '<iframe src={mapUrl} title="Store location map" />' },
55
- html: {
56
- before: '<iframe src="/map"></iframe>',
57
- code: '<iframe src="/map" title="Store location map"></iframe>',
58
- },
59
- note: 'The title is what screen readers announce for the frame.',
60
- },
61
59
  'a11y-positive-tabindex': {
62
60
  jsx: { before: '<div tabIndex={2} />', code: '<div tabIndex={0} />' },
63
61
  html: { before: '<div tabindex="2"></div>', code: '<div tabindex="0"></div>' },
@@ -88,3 +86,4 @@ function exampleFor(ruleId, languageId) {
88
86
  return;
89
87
  return { language: 'html', ...html, note };
90
88
  }
89
+ export { exampleFor };
@@ -0,0 +1,117 @@
1
+ // Code actions and code lenses for the published findings of one file.
2
+ import { CodeActionKind } from 'vscode-languageserver';
3
+ import { bulkFixesFor, fixAllEdit, fixEdit, missingFolders } from './fix-edits.js';
4
+ const commands = {
5
+ scan: 'loadwise.scan',
6
+ applyFix: 'loadwise.applyFix',
7
+ applyAllFixes: 'loadwise.applyAllFixes',
8
+ dismiss: 'loadwise.dismiss',
9
+ showDismissed: 'loadwise.showDismissed',
10
+ restoreDismissed: 'loadwise.restoreDismissed',
11
+ };
12
+ const fixAllKind = CodeActionKind.SourceFixAll + '.loadwise';
13
+ const applyAllTitle = 'Apply all Loadwise fixes in this file';
14
+ // `only` asks for a kind and everything below it: source.fixAll covers source.fixAll.loadwise.
15
+ function kindRequested(only, kind) {
16
+ if (!only)
17
+ return kind !== fixAllKind;
18
+ return only.some((requested) => kind === requested || kind.startsWith(requested + '.'));
19
+ }
20
+ // The lightbulb appears with the cursor anywhere on a flagged line, not only on the reported token.
21
+ function onLines(entry, range) {
22
+ const flagged = entry.diagnostic.range;
23
+ return flagged.start.line <= range.end.line && flagged.end.line >= range.start.line;
24
+ }
25
+ function command(title, name, argument) {
26
+ return { title, command: name, arguments: [argument] };
27
+ }
28
+ function applyFixAction(entry, fix, workspace) {
29
+ const title = 'Apply fix: ' + entry.anchor.ruleId;
30
+ const action = {
31
+ title,
32
+ kind: CodeActionKind.QuickFix,
33
+ diagnostics: [entry.diagnostic],
34
+ isPreferred: !fix.requiresReview,
35
+ };
36
+ const result = fixEdit(fix, workspace);
37
+ if (result.edit === undefined)
38
+ action.disabled = { reason: result.error };
39
+ // A new file in a missing folder goes through the command, which makes the folder first.
40
+ else if (missingFolders(result.createdFiles).length)
41
+ action.command = command(title, commands.applyFix, fix);
42
+ else
43
+ action.edit = result.edit;
44
+ return action;
45
+ }
46
+ function dismissAction(entry, title, dismissal) {
47
+ return {
48
+ title,
49
+ kind: CodeActionKind.QuickFix,
50
+ diagnostics: [entry.diagnostic],
51
+ command: command(title, commands.dismiss, dismissal),
52
+ };
53
+ }
54
+ function quickFixes(entries, range, uri, workspace) {
55
+ const actions = [];
56
+ const fileWide = new Set();
57
+ for (const entry of entries.filter((candidate) => onLines(candidate, range))) {
58
+ const { fix, dismissal, ruleId } = entry.anchor;
59
+ if (fix)
60
+ actions.push(applyFixAction(entry, fix, workspace));
61
+ actions.push(dismissAction(entry, 'Dismiss this finding (' + ruleId + ')', dismissal));
62
+ if (fileWide.has(ruleId))
63
+ continue;
64
+ fileWide.add(ruleId);
65
+ actions.push(dismissAction(entry, 'Dismiss ' + ruleId + ' in this file', { file: dismissal.file, ruleId: dismissal.ruleId }));
66
+ }
67
+ if (actions.length && bulkFixesFor(entries).eligible.length > 1) {
68
+ actions.push({
69
+ title: applyAllTitle,
70
+ kind: CodeActionKind.QuickFix,
71
+ command: command(applyAllTitle, commands.applyAllFixes, uri),
72
+ });
73
+ }
74
+ return actions;
75
+ }
76
+ // Runs for "Fix All" and code actions on save, so it carries the edit itself instead of a command.
77
+ function fixAllActions(entries, uri, workspace) {
78
+ const { eligible } = bulkFixesFor(entries);
79
+ if (!eligible.length)
80
+ return [];
81
+ const { edit, applied, createdFiles } = fixAllEdit(eligible, workspace);
82
+ if (!applied)
83
+ return [];
84
+ if (missingFolders(createdFiles).length) {
85
+ return [{ title: applyAllTitle, kind: fixAllKind, command: command(applyAllTitle, commands.applyAllFixes, uri) }];
86
+ }
87
+ return [{ title: applyAllTitle, kind: fixAllKind, edit }];
88
+ }
89
+ function codeActions(entries, range, only, uri, workspace) {
90
+ const actions = [];
91
+ if (kindRequested(only, CodeActionKind.QuickFix))
92
+ actions.push(...quickFixes(entries, range, uri, workspace));
93
+ // Building the fix-all edit reads files, so it runs only when the editor asks for that kind.
94
+ if (only && kindRequested(only, fixAllKind))
95
+ actions.push(...fixAllActions(entries, uri, workspace));
96
+ return actions;
97
+ }
98
+ // One-click buttons above each fixable line, so applying a fix does not need the code action menu.
99
+ function codeLenses(entries, uri) {
100
+ const fixable = entries.filter((entry) => entry.anchor.fix);
101
+ const lenses = [];
102
+ const bulkCount = bulkFixesFor(fixable).eligible.length;
103
+ const top = { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } };
104
+ if (bulkCount > 1) {
105
+ const title = 'Apply all ' + bulkCount + ' Loadwise fixes in this file';
106
+ lenses.push({ range: top, command: command(title, commands.applyAllFixes, uri) });
107
+ }
108
+ for (const { anchor, diagnostic } of fixable) {
109
+ if (!anchor.fix)
110
+ continue;
111
+ const line = diagnostic.range.start.line;
112
+ const range = { start: { line, character: 0 }, end: { line, character: 0 } };
113
+ lenses.push({ range, command: command('Apply fix: ' + anchor.ruleId, commands.applyFix, anchor.fix) }, { range, command: command('Dismiss', commands.dismiss, anchor.dismissal) });
114
+ }
115
+ return lenses;
116
+ }
117
+ export { codeActions, codeLenses, commands, fixAllKind };
@@ -1,9 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.applyChangesToText = applyChangesToText;
4
- exports.applyFix = applyFix;
5
- exports.isChangeApplied = isChangeApplied;
6
- exports.locateChange = locateChange;
7
1
  // Applies a site fix to file text. A fix stores the exact original lines, so it is applied only
8
2
  // where those lines still exist; an edit made since the scan moves or removes them and the fix then
9
3
  // refuses instead of guessing.
@@ -185,3 +179,4 @@ function applyFix(fix, { readFile, writeFile }, options) {
185
179
  writeFile(file, text);
186
180
  return { files: updates.map(([file]) => file) };
187
181
  }
182
+ export { applyChangesToText, applyFix, isChangeApplied, locateChange };
@@ -1,6 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.controlFlowComparison = controlFlowComparison;
4
1
  const scriptLanguages = new Set(['javascript', 'javascriptreact', 'typescript', 'typescriptreact']);
5
2
  const maximumSnippetLength = 200;
6
3
  const maximumBindingDistance = 12;
@@ -131,3 +128,4 @@ function matchesSavedExcerpt(document, row, comparison) {
131
128
  return actual === indent + line || (!line && !actual);
132
129
  });
133
130
  }
131
+ export { controlFlowComparison };
@@ -0,0 +1,365 @@
1
+ // Turns checker reports into language server diagnostics and hovers. Each published diagnostic keeps
2
+ // an anchor with what the code actions, code lenses and hovers need: the reported site, the
3
+ // scanner's fix and the dismissal entry.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { DiagnosticSeverity } from 'vscode-languageserver';
8
+ import { exampleFor as reliabilityExample } from './reliability-examples.js';
9
+ import { exampleFor as maintainabilityExample } from './maintainability-examples.js';
10
+ import { exampleFor as securityExample } from './security-examples.js';
11
+ import { exampleFor as accessibilityExample } from './accessibility-examples.js';
12
+ import { getFindingComparison, inlineComparison } from './finding-comparison.js';
13
+ import { rangeContains, samePosition, validateRange, wordRangeAt } from './editor-document.js';
14
+ import { isRealPathInside } from './workspace-paths.js';
15
+ import { ruleDocUrl } from '../shared/rule-docs.js';
16
+ const maintainabilitySource = 'loadwise maint';
17
+ const severityNames = {
18
+ error: DiagnosticSeverity.Error,
19
+ warning: DiagnosticSeverity.Warning,
20
+ information: DiagnosticSeverity.Information,
21
+ hint: DiagnosticSeverity.Hint,
22
+ };
23
+ const polyglotLanguages = new Set(['python', 'go', 'java', 'csharp', 'rust', 'php', 'ruby', 'kotlin', 'c', 'cpp']);
24
+ const contracts = new Set([
25
+ 'pg-transaction-on-pool',
26
+ 'folder-boundary',
27
+ 'file-placement',
28
+ 'query-mutates-state',
29
+ 'data-access-boundary',
30
+ ]);
31
+ const advice = new Map([
32
+ [
33
+ 'dependency-cycle',
34
+ 'Follow the imports in the reported cycle. Move a shared dependency into a module that both sides can import, or pass it to the caller explicitly.',
35
+ ],
36
+ [
37
+ 'folder-boundary',
38
+ 'Use an API the importing layer is allowed to call, or move the code that needs this dependency into the layer that owns it.',
39
+ ],
40
+ ['file-placement', 'Move the file to one of the configured folders and update its imports.'],
41
+ ]);
42
+ function sourceExample(ruleId, languageId, message) {
43
+ // Reliability examples fall back to the performance ones, so one lookup covers the shared source pass.
44
+ return (reliabilityExample(ruleId, languageId, message) ??
45
+ securityExample(ruleId, languageId) ??
46
+ accessibilityExample(ruleId, languageId));
47
+ }
48
+ // ast-grep counts Unicode code points; editor positions and TypeScript use UTF-16.
49
+ function utf16Column(document, line, codePoints) {
50
+ let remaining = codePoints;
51
+ let column = 0;
52
+ for (const character of document.lineAt(line).text) {
53
+ if (remaining === 0)
54
+ break;
55
+ column += character.length;
56
+ remaining--;
57
+ }
58
+ return column;
59
+ }
60
+ function sourceRange(site, document) {
61
+ const line = site.line - 1;
62
+ let column = site.column - 1;
63
+ if (document && polyglotLanguages.has(document.languageId) && line < document.lineCount && column > 0) {
64
+ column = utf16Column(document, line, column);
65
+ }
66
+ const anchor = { start: { line, character: column }, end: { line, character: column + 1 } };
67
+ if (!document)
68
+ return anchor;
69
+ const range = validateRange(document, anchor);
70
+ const word = wordRangeAt(document, range.start);
71
+ return word && samePosition(word.start, range.start) ? word : range;
72
+ }
73
+ const sentenceEnds = '.!?';
74
+ // Findings are written as short paragraphs; one sentence per line is easier to read in a tooltip.
75
+ // Code spans are kept whole, and a break needs a capital, backtick or parenthesis after the space,
76
+ // so "e.g. x" stays together.
77
+ function sentenceLines(text) {
78
+ const lines = [];
79
+ let start = 0;
80
+ let inCode = false;
81
+ for (let index = 0; index < text.length; index++) {
82
+ const character = text[index];
83
+ if (character === '`')
84
+ inCode = !inCode;
85
+ else if (!inCode &&
86
+ sentenceEnds.includes(character) &&
87
+ text[index + 1] === ' ' &&
88
+ /[A-Z`(]/.test(text[index + 2] ?? '')) {
89
+ lines.push(text.slice(start, index + 1));
90
+ start = index + 2;
91
+ }
92
+ }
93
+ lines.push(text.slice(start));
94
+ return lines.map((line) => line.trim()).filter(Boolean);
95
+ }
96
+ function readable(text) {
97
+ return text.split('\n').flatMap(sentenceLines).join('\n');
98
+ }
99
+ function dedent(text) {
100
+ const lines = text.split('\n');
101
+ const width = Math.min(...lines.filter((line) => line.trim()).map((line) => /^[ \t]*/.exec(line)?.[0].length ?? 0));
102
+ return lines.map((line) => line.slice(width)).join('\n');
103
+ }
104
+ // The scanner's rewrite of this exact code; the generic rule example is only a fallback.
105
+ function fixComparison(fix) {
106
+ const shown = fix.changes.find((change) => !change.create) ?? fix.changes[0];
107
+ const others = fix.changes.filter((change) => change !== shown);
108
+ const created = others.filter((change) => change.create).map((change) => change.file);
109
+ const edited = others.length - created.length;
110
+ const more = (edited ? ' Also changes ' + edited + ' more place(s).' : '') +
111
+ (created.length ? ' Also creates ' + created.join(', ') + '.' : '');
112
+ return {
113
+ kind: 'source',
114
+ before: shown.create ? '(new file ' + shown.file + ')' : dedent(shown.before),
115
+ after: shown.create ? shown.after.trimEnd() : dedent(shown.after),
116
+ note: ((fix.note ?? '') +
117
+ more +
118
+ (fix.requiresReview ? ' Review this change and apply it individually.' : '') +
119
+ ' Use the Apply fix code action or the code lens above the line.').trim(),
120
+ };
121
+ }
122
+ function examplesFor(document, range, anchor) {
123
+ // Every source checker but maintainability shares the source examples, which fall back to the
124
+ // security ones.
125
+ const lookup = anchor.source === maintainabilitySource ? maintainabilityExample : sourceExample;
126
+ const example = lookup(anchor.ruleId, document.languageId, anchor.message);
127
+ if (anchor.fix)
128
+ return { example, comparison: fixComparison(anchor.fix) };
129
+ const comparison = getFindingComparison(document, {
130
+ source: anchor.source,
131
+ code: anchor.ruleId,
132
+ message: anchor.message,
133
+ suggestion: anchor.suggestion,
134
+ comparison: anchor.comparison,
135
+ range,
136
+ }, example);
137
+ return { example, comparison };
138
+ }
139
+ /** The one-line recommendation shown before the finding, or undefined without a comparison. */
140
+ function recommendation(document, range, anchor) {
141
+ const { comparison } = examplesFor(document, range, anchor);
142
+ const preview = comparison && inlineComparison(comparison);
143
+ if (!comparison || !preview)
144
+ return;
145
+ return (comparison.kind === 'source' ? 'Code: ' : '') + preview;
146
+ }
147
+ function isLocatedSite(site) {
148
+ if (typeof site !== 'object' || site === null)
149
+ return false;
150
+ if (!('file' in site) || !('line' in site) || !('column' in site))
151
+ return false;
152
+ return (typeof site.file === 'string' &&
153
+ site.file !== '' &&
154
+ !site.file.includes('\0') &&
155
+ typeof site.line === 'number' &&
156
+ Number.isSafeInteger(site.line) &&
157
+ site.line >= 1 &&
158
+ typeof site.column === 'number' &&
159
+ Number.isSafeInteger(site.column) &&
160
+ site.column >= 1);
161
+ }
162
+ function insideRoot(rootPath, file) {
163
+ const filename = path.resolve(rootPath, file);
164
+ const relative = path.relative(rootPath, filename);
165
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
166
+ return;
167
+ return filename;
168
+ }
169
+ function defaultUri(filename) {
170
+ return pathToFileURL(filename).href;
171
+ }
172
+ function location(rootPath, site, options) {
173
+ if (!isLocatedSite(site))
174
+ return;
175
+ const filename = insideRoot(rootPath, site.file);
176
+ if (filename === undefined)
177
+ return;
178
+ const uri = (options.uriFor ?? defaultUri)(filename);
179
+ return { filename, uri, range: sourceRange(site, options.documentFor(filename)) };
180
+ }
181
+ // Resolves each change of a site fix inside the workspace folder; a path outside it, also through a
182
+ // symbolic link, drops the whole fix.
183
+ function workspaceFix(rootPath, fix) {
184
+ if (!fix || !Array.isArray(fix.changes) || !fix.changes.length)
185
+ return;
186
+ const changes = [];
187
+ for (const change of fix.changes) {
188
+ if (typeof change?.file !== 'string' ||
189
+ change.file.includes('\0') ||
190
+ typeof change.before !== 'string' ||
191
+ typeof change.after !== 'string')
192
+ return;
193
+ if (!Number.isSafeInteger(change.line) || change.line < 1)
194
+ return;
195
+ const filename = insideRoot(rootPath, change.file);
196
+ if (filename === undefined || !isRealPathInside(rootPath, filename))
197
+ return;
198
+ changes.push({ ...change, filename });
199
+ }
200
+ return {
201
+ changes,
202
+ note: typeof fix.note === 'string' ? fix.note : undefined,
203
+ requiresReview: fix.requiresReview === true,
204
+ };
205
+ }
206
+ // Every finding is an optional suggestion: a warning by default, an error for a declared contract,
207
+ // unless the loadwise.severity setting picks one level for all of them.
208
+ function severityFor(finding, setting) {
209
+ const isError = finding.level === 'error' || (finding.level !== 'warn' && contracts.has(finding.ruleId));
210
+ const chosen = setting === undefined ? undefined : severityNames[setting];
211
+ return chosen ?? (isError ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning);
212
+ }
213
+ function readSavedLines(filename) {
214
+ try {
215
+ return fs.readFileSync(filename, 'utf8').split(/\r?\n/);
216
+ }
217
+ catch {
218
+ // A file deleted since the scan has no line text; its findings disappear on the next scan.
219
+ return [];
220
+ }
221
+ }
222
+ // The trimmed text of the reported line identifies a dismissed finding. An edited buffer no longer
223
+ // matches the scan, so its line is read from the saved file.
224
+ function flaggedLineText(filename, line, options, savedLines) {
225
+ const document = options.documentFor(filename);
226
+ if (document && !document.isDirty)
227
+ return line <= document.lineCount ? document.lineAt(line - 1).text.trim() : '';
228
+ if (!savedLines.has(filename))
229
+ savedLines.set(filename, readSavedLines(filename));
230
+ return ((savedLines.get(filename) ?? [])[line - 1] ?? '').trim();
231
+ }
232
+ // A live-database finding names a table, not a file. It is shown on the first line of the project's
233
+ // package.json, prefixed by the table, and dismissed by table name.
234
+ function databaseFinding(finding) {
235
+ if (finding.file !== undefined || typeof finding.target !== 'string' || typeof finding.message !== 'string')
236
+ return finding;
237
+ return { ...finding, file: 'package.json', line: 1, column: 1, message: finding.target + ': ' + finding.message };
238
+ }
239
+ function relatedInformation(rootPath, finding, options) {
240
+ if (!Array.isArray(finding.related))
241
+ return;
242
+ const label = finding.ruleId === 'dependency-cycle' ? 'Import in this cycle' : 'Matching implementation';
243
+ return finding.related.flatMap((item) => {
244
+ const link = location(rootPath, item, options);
245
+ return link ? [{ location: { uri: link.uri, range: link.range }, message: label }] : [];
246
+ });
247
+ }
248
+ function buildDiagnostic(site, finding, anchor, options) {
249
+ const document = options.documentFor(site.filename);
250
+ const preview = document && recommendation(document, site.range, anchor);
251
+ const diagnostic = {
252
+ range: site.range,
253
+ message: preview ? preview + '\n' + anchor.message : anchor.message,
254
+ severity: severityFor(finding, options.severity),
255
+ source: anchor.source,
256
+ code: finding.ruleId,
257
+ };
258
+ const documentation = ruleDocUrl(finding.ruleId);
259
+ if (documentation)
260
+ diagnostic.codeDescription = { href: documentation };
261
+ return diagnostic;
262
+ }
263
+ function publishedFinding(rootPath, source, reported, options, savedLines) {
264
+ const finding = databaseFinding(reported);
265
+ if (!isLocatedSite(finding) || typeof finding.message !== 'string' || typeof finding.ruleId !== 'string')
266
+ return;
267
+ const site = location(rootPath, finding, options);
268
+ if (!site)
269
+ return;
270
+ const lineText = finding === reported
271
+ ? flaggedLineText(site.filename, finding.line, options, savedLines)
272
+ : typeof finding.target === 'string'
273
+ ? finding.target
274
+ : undefined;
275
+ const dismissal = { file: site.filename, ruleId: finding.ruleId, lineText };
276
+ if (options.isDismissed?.(dismissal))
277
+ return;
278
+ const anchor = {
279
+ source,
280
+ ruleId: finding.ruleId,
281
+ line: finding.line,
282
+ column: finding.column,
283
+ message: readable([finding.message, advice.get(finding.ruleId), finding.contextualReason].filter(Boolean).join('\n')),
284
+ suggestion: finding.suggestion,
285
+ comparison: finding.comparison,
286
+ fix: workspaceFix(rootPath, finding.fix),
287
+ dismissal,
288
+ };
289
+ const diagnostic = buildDiagnostic(site, finding, anchor, options);
290
+ const related = relatedInformation(rootPath, finding, options);
291
+ if (related)
292
+ diagnostic.relatedInformation = related;
293
+ return { filename: site.filename, uri: site.uri, diagnostic, anchor };
294
+ }
295
+ /** The diagnostics of one checker report, skipping findings outside the folder or dismissed. */
296
+ function buildDiagnostics(rootPath, source, findings, options) {
297
+ const savedLines = new Map();
298
+ return findings.flatMap((finding) => publishedFinding(rootPath, source, finding, options, savedLines) ?? []);
299
+ }
300
+ // The editor renders hovers as markdown; finding text is shown literally.
301
+ function escapeMarkdown(text) {
302
+ return text.replaceAll(/[\\`*_{}[\]()#+\-.!|<>~]/g, '\\$&');
303
+ }
304
+ function paragraphs(text) {
305
+ return readable(text).split('\n').map(escapeMarkdown).join('\n\n');
306
+ }
307
+ function codeBlock(code, language) {
308
+ const longestFence = Math.max(2, ...[...code.matchAll(/`+/g)].map((match) => match[0].length));
309
+ const fence = '`'.repeat(longestFence + 1);
310
+ return fence + language + '\n' + code + '\n' + fence;
311
+ }
312
+ function comparisonMarkdown(comparison, example, document, ruleId) {
313
+ const label = (comparison.kind === 'source' ? 'Current code' : 'Flagged line') + ' (' + ruleId + ')';
314
+ const parts = [escapeMarkdown(label), codeBlock(comparison.before, document.languageId)];
315
+ if (comparison.kind === 'review')
316
+ parts.push(escapeMarkdown('Review: ' + comparison.inline));
317
+ else {
318
+ parts.push(comparison.kind === 'source' ? 'Suggested rewrite' : 'Illustrative alternative');
319
+ parts.push(codeBlock(comparison.after, comparison.language ?? example?.language ?? document.languageId));
320
+ }
321
+ return parts;
322
+ }
323
+ function hoverMarkdown(document, entry) {
324
+ const { anchor, diagnostic } = entry;
325
+ const { example, comparison } = examplesFor(document, diagnostic.range, anchor);
326
+ if (!comparison && !example)
327
+ return;
328
+ const parts = [];
329
+ const firstLine = recommendation(document, diagnostic.range, anchor);
330
+ if (firstLine)
331
+ parts.push('**' + escapeMarkdown(firstLine) + '**');
332
+ parts.push(paragraphs(anchor.message));
333
+ if (comparison)
334
+ parts.push(...comparisonMarkdown(comparison, example, document, anchor.ruleId));
335
+ else if (example) {
336
+ parts.push(escapeMarkdown('Illustrative alternative (' + anchor.ruleId + ')'), codeBlock(example.code, example.language));
337
+ }
338
+ const note = comparison ? comparison.note : example?.note;
339
+ if (note)
340
+ parts.push(paragraphs(note));
341
+ return parts.join('\n\n');
342
+ }
343
+ /** The hover for a position: one section per rule flagged there, or undefined. */
344
+ function hoverFor(document, entries, position) {
345
+ const sections = [];
346
+ const shown = new Set();
347
+ let hoverRange;
348
+ const word = wordRangeAt(document, position);
349
+ for (const entry of entries) {
350
+ const issueRange = entry.diagnostic.range;
351
+ const range = word && samePosition(word.start, issueRange.start) ? word : issueRange;
352
+ if (!rangeContains(range, position) || shown.has(entry.anchor.ruleId))
353
+ continue;
354
+ const markdown = hoverMarkdown(document, entry);
355
+ if (!markdown)
356
+ continue;
357
+ sections.push(markdown);
358
+ shown.add(entry.anchor.ruleId);
359
+ hoverRange ??= range;
360
+ }
361
+ if (!sections.length || !hoverRange)
362
+ return;
363
+ return { markdown: sections.join('\n\n---\n\n'), range: hoverRange };
364
+ }
365
+ export { buildDiagnostics, hoverFor };