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
@@ -3,6 +3,7 @@ import { CodeActionKind } from 'vscode-languageserver';
3
3
  import { locateChange } from './apply-fix.js';
4
4
  import { samePosition } from './editor-document.js';
5
5
  import { bulkFixesFor, fixAllEdit, fixEdit, missingFolders } from './fix-edits.js';
6
+ import { mayHaveMovedToLine } from './diagnostics.js';
6
7
  const commands = {
7
8
  scan: 'loadwise.scan',
8
9
  applyFix: 'loadwise.applyFix',
@@ -109,7 +110,7 @@ function fixAllActions(entries, uri, workspace) {
109
110
  }
110
111
  return [{ title: applyAllTitle, kind: fixAllKind, edit }];
111
112
  }
112
- function findingsForAction(entries, range, diagnostics) {
113
+ function findingsForAction(entries, range, diagnostics, workspace) {
113
114
  if (!diagnostics.length)
114
115
  return entries.filter((entry) => onLines(entry.diagnostic.range, range));
115
116
  const selected = new Map();
@@ -119,14 +120,19 @@ function findingsForAction(entries, range, diagnostics) {
119
120
  const matches = entries.filter(({ diagnostic: saved }) => saved.source === diagnostic.source &&
120
121
  saved.code === diagnostic.code &&
121
122
  (diagnostic.data !== undefined ? diagnostic.data === saved.data : diagnostic.message === saved.message));
122
- // Without an echoed identity, identical diagnostics cannot safely identify a moved occurrence.
123
- if (matches.length !== 1)
124
- continue;
125
- const [entry] = matches;
126
- const published = entry.diagnostic.range;
127
- if (diagnostic.data === undefined &&
128
- (!samePosition(published.start, diagnostic.range.start) || !samePosition(published.end, diagnostic.range.end)))
123
+ const candidates = diagnostic.data !== undefined
124
+ ? matches
125
+ : matches.filter(({ diagnostic: saved }) => samePosition(saved.range.start, diagnostic.range.start) &&
126
+ samePosition(saved.range.end, diagnostic.range.end));
127
+ if (candidates.length !== 1)
129
128
  continue;
129
+ const [entry] = candidates;
130
+ // An edit can move one occurrence onto another's published range, even after the buffer is saved.
131
+ if (matches.length > 1) {
132
+ const document = workspace.documentFor(entry.filename);
133
+ if (matches.some((other) => other !== entry && mayHaveMovedToLine(other, document, diagnostic.range.start.line)))
134
+ continue;
135
+ }
130
136
  selected.set(entry, { ...entry, diagnostic: { ...entry.diagnostic, range: diagnostic.range } });
131
137
  }
132
138
  return [...selected.values()];
@@ -134,7 +140,7 @@ function findingsForAction(entries, range, diagnostics) {
134
140
  function codeActions(entries, { range, context: { only, diagnostics }, textDocument: { uri } }, workspace) {
135
141
  const actions = [];
136
142
  if (kindRequested(only, CodeActionKind.QuickFix))
137
- actions.push(...quickFixes(entries, findingsForAction(entries, range, diagnostics), uri, workspace));
143
+ actions.push(...quickFixes(entries, findingsForAction(entries, range, diagnostics, workspace), uri, workspace));
138
144
  // Building the fix-all edit reads files, so it runs only when the editor asks for that kind.
139
145
  if (only && kindRequested(only, fixAllKind))
140
146
  actions.push(...fixAllActions(entries, uri, workspace));
@@ -10,11 +10,13 @@ import { exampleFor as reliabilityExample } from './reliability-examples.js';
10
10
  import { exampleFor as maintainabilityExample } from './maintainability-examples.js';
11
11
  import { exampleFor as securityExample } from './security-examples.js';
12
12
  import { exampleFor as accessibilityExample } from './accessibility-examples.js';
13
- import { getFindingComparison, inlineComparison } from './finding-comparison.js';
13
+ import { getFindingComparison } from './finding-comparison.js';
14
14
  import { isLocatedSite, rangeContains, samePosition, validateRange, wordRangeAt } from './editor-document.js';
15
15
  import { insideRoot, isRealPathInside } from './workspace-paths.js';
16
16
  import { editorSnapshotFileLimit, resolveSourceSnapshot } from '../shared/fix/fix-source-snapshot.js';
17
17
  import { ruleDocUrl } from '../shared/reporting/rule-docs.js';
18
+ import { hoverMarkdown, readable } from './hover-markdown.js';
19
+ import { recommendationLabel, recommendationText } from './inline-recommendation.js';
18
20
  const maintainabilitySource = 'loadwise maint';
19
21
  const severityNames = {
20
22
  error: DiagnosticSeverity.Error,
@@ -72,32 +74,6 @@ function sourceRange(site, document) {
72
74
  const word = wordRangeAt(document, range.start);
73
75
  return word && samePosition(word.start, range.start) ? word : range;
74
76
  }
75
- const sentenceEnds = '.!?';
76
- // Findings are written as short paragraphs; one sentence per line is easier to read in a tooltip.
77
- // Code spans are kept whole, and a break needs a capital, backtick or parenthesis after the space,
78
- // so "e.g. x" stays together.
79
- function sentenceLines(text) {
80
- const lines = [];
81
- let start = 0;
82
- let inCode = false;
83
- for (let index = 0; index < text.length; index++) {
84
- const character = text[index];
85
- if (character === '`')
86
- inCode = !inCode;
87
- else if (!inCode &&
88
- sentenceEnds.includes(character) &&
89
- text[index + 1] === ' ' &&
90
- /[A-Z`(]/.test(text[index + 2] ?? '')) {
91
- lines.push(text.slice(start, index + 1));
92
- start = index + 2;
93
- }
94
- }
95
- lines.push(text.slice(start));
96
- return lines.map((line) => line.trim()).filter(Boolean);
97
- }
98
- function readable(text) {
99
- return text.split('\n').flatMap(sentenceLines).join('\n');
100
- }
101
77
  function dedent(text) {
102
78
  const lines = text.split('\n');
103
79
  const width = Math.min(...lines.filter((line) => line.trim()).map((line) => /^[ \t]*/.exec(line)?.[0].length ?? 0));
@@ -138,14 +114,6 @@ function examplesFor(document, range, anchor) {
138
114
  }, example);
139
115
  return { example, comparison };
140
116
  }
141
- /** The one-line recommendation shown before the finding, or undefined without a comparison. */
142
- function recommendation(document, range, anchor) {
143
- const { comparison } = examplesFor(document, range, anchor);
144
- const preview = comparison && inlineComparison(comparison);
145
- if (!comparison || !preview)
146
- return;
147
- return (comparison.kind === 'source' ? 'Code: ' : '') + preview;
148
- }
149
117
  function defaultUri(filename) {
150
118
  return pathToFileURL(filename).href;
151
119
  }
@@ -186,6 +154,38 @@ function liveLine(document, line, original, root) {
186
154
  if (map.savedEnd === map.prefix + 1 && map.liveEnd === map.prefix + 1)
187
155
  return line;
188
156
  }
157
+ /** Hide a finding only when the live buffer matches its exact single-file edit to the reported snapshot. */
158
+ function findingFixIsApplied(entry, document) {
159
+ const original = publishedSources.get(entry)?.document;
160
+ if (!document || !original || original === document || entry.anchor.fix?.changes.length !== 1)
161
+ return false;
162
+ const [change] = entry.anchor.fix.changes;
163
+ if (change.create || change.filename !== entry.filename || change.before === change.after)
164
+ return false;
165
+ const row = change.line - 1;
166
+ const before = change.before.split(/\r?\n/);
167
+ const after = change.after.split(/\r?\n/);
168
+ if (original.lineCount - before.length + after.length !== document.lineCount)
169
+ return false;
170
+ if (!after.every((line, index) => document.lineAt(row + index).text === line))
171
+ return false;
172
+ const saved = original.getText().split(/\r?\n/);
173
+ if (!before.every((line, index) => saved[row + index] === line))
174
+ return false;
175
+ return (saved
176
+ .slice(0, row)
177
+ .concat(after, saved.slice(row + before.length))
178
+ .join(document.eol) === document.getText());
179
+ }
180
+ function mayHaveMovedToLine(entry, document, editorLine) {
181
+ const original = publishedSources.get(entry);
182
+ if (!original || !document)
183
+ return true;
184
+ if (original.document === document)
185
+ return false;
186
+ const currentLine = liveLine(document, entry.anchor.line, original, original.root);
187
+ return currentLine === undefined || currentLine === editorLine + 1;
188
+ }
189
189
  function location(rootPath, site, options, reported) {
190
190
  if (!isLocatedSite(site))
191
191
  return;
@@ -284,12 +284,12 @@ function relatedInformation(rootPath, finding, options) {
284
284
  return link ? [{ location: { uri: link.uri, range: link.range }, message: label }] : [];
285
285
  });
286
286
  }
287
+ const problemWidth = 160;
287
288
  function buildDiagnostic(site, finding, anchor, options) {
288
- const document = options.documentFor(site.filename);
289
- const preview = document && recommendation(document, site.range, anchor);
289
+ const summary = anchor.message.split('\n', 1)[0];
290
290
  const diagnostic = {
291
291
  range: site.range,
292
- message: preview ? preview + '\n' + anchor.message : anchor.message,
292
+ message: summary.length > problemWidth ? summary.slice(0, problemWidth - 1).trimEnd() + '…' : summary,
293
293
  severity: severityFor(finding, options.severityFor ? options.severityFor(site.filename) : options.severity),
294
294
  source: anchor.source,
295
295
  code: finding.ruleId,
@@ -449,89 +449,92 @@ function buildDiagnostics(rootPath, source, findings, options) {
449
449
  identifyOccurrences(matches, options, savedLines, scopesByFile);
450
450
  return entries.filter(({ anchor }) => !options.isDismissed?.(anchor.dismissal));
451
451
  }
452
- // The editor renders hovers as markdown; finding text is shown literally.
453
- function escapeMarkdown(text) {
454
- return text.replaceAll(/[\\`*_{}[\]()#+\-.!|<>~]/g, '\\$&');
455
- }
456
- function paragraphs(text) {
457
- return readable(text).split('\n').map(escapeMarkdown).join('\n\n');
452
+ function indentation(text) {
453
+ return text.length - text.trimStart().length;
458
454
  }
459
- function codeBlock(code, language) {
460
- const longestFence = Math.max(2, ...[...code.matchAll(/`+/g)].map((match) => match[0].length));
461
- const fence = '`'.repeat(longestFence + 1);
462
- return fence + language + '\n' + code + '\n' + fence;
455
+ function currentIssueRange(document, entry, root, atLine) {
456
+ const original = publishedSources.get(entry);
457
+ if (!document.isDirty && (!original || original.document === document))
458
+ return entry.diagnostic.range;
459
+ const originalText = original?.document.lineAt(entry.anchor.line - 1).text;
460
+ if (originalText === undefined)
461
+ return;
462
+ if (atLine !== undefined && originalText.trim() !== document.lineAt(atLine).text.trim())
463
+ return;
464
+ const line = liveLine(document, entry.anchor.line, original, root);
465
+ if (line === undefined || (atLine !== undefined && line !== atLine + 1))
466
+ return;
467
+ const currentText = document.lineAt(line - 1).text;
468
+ if (originalText.trim() !== currentText.trim())
469
+ return;
470
+ const column = entry.anchor.column + indentation(currentText) - indentation(originalText);
471
+ if (column >= 1)
472
+ return sourceRange({ line, column }, document);
463
473
  }
464
- function comparisonMarkdown(comparison, example, document, ruleId) {
465
- const label = (comparison.kind === 'source' ? 'Current code' : 'Flagged line') + ' (' + ruleId + ')';
466
- const parts = [escapeMarkdown(label), codeBlock(comparison.before, document.languageId)];
467
- if (comparison.kind === 'review')
468
- parts.push(escapeMarkdown('Review: ' + comparison.inline));
469
- else {
470
- parts.push(comparison.kind === 'source' ? 'Suggested rewrite' : 'Illustrative alternative');
471
- parts.push(codeBlock(comparison.after, comparison.language ?? example?.language ?? document.languageId));
472
- }
473
- return parts;
474
+ function fixLabel(fixes, tabAutofix) {
475
+ if (!fixes.length)
476
+ return 'Manual';
477
+ if (fixes.length !== 1)
478
+ return 'Quick Fix';
479
+ const [entry] = fixes;
480
+ // The extension verifies the actual Quick Fix before taking over Tab.
481
+ if (tabAutofix)
482
+ return entry.anchor.fix?.requiresExplicitSelection ? 'Tab to review' : 'Tab to fix';
483
+ return entry.anchor.fix?.requiresReview ? 'Review fix' : 'Quick Fix';
474
484
  }
475
- function hoverMarkdown(document, { anchor, diagnostic }, range) {
476
- const { example, comparison } = examplesFor(document, range, anchor);
477
- if (!comparison && !example && !anchor.message)
478
- return;
479
- const parts = [];
480
- const firstLine = recommendation(document, range, anchor);
481
- if (firstLine)
482
- parts.push('**' + escapeMarkdown(firstLine) + '**');
483
- parts.push(paragraphs(anchor.message));
484
- if (comparison)
485
- parts.push(...comparisonMarkdown(comparison, example, document, anchor.ruleId));
486
- else if (example) {
487
- parts.push(escapeMarkdown('Illustrative alternative (' + anchor.ruleId + ')'), codeBlock(example.code, example.language));
485
+ function inlayHints(document, entries, visible, root, tabAutofix = false) {
486
+ const byLine = new Map();
487
+ for (const entry of entries) {
488
+ const issue = currentIssueRange(document, entry, root);
489
+ if (!issue || issue.start.line >= document.lineCount)
490
+ continue;
491
+ const line = issue.start.line;
492
+ const position = { line, character: document.lineAt(line).text.length };
493
+ const existing = byLine.get(line);
494
+ if (!existing && !rangeContains(visible, position))
495
+ continue;
496
+ const details = examplesFor(document, issue, entry.anchor);
497
+ const text = recommendationText(entry.anchor, details.comparison, details.example, document.isDirty ? undefined : document.lineAt(line).text);
498
+ const markdown = hoverMarkdown(document.languageId, entry.anchor, entry.diagnostic.codeDescription?.href, details);
499
+ if (!text || !markdown)
500
+ continue;
501
+ const row = existing ?? { position, text, sections: new Set(), fixes: [] };
502
+ row.sections.add(markdown);
503
+ if (entry.anchor.fix)
504
+ row.fixes.push(entry);
505
+ if (!existing)
506
+ byLine.set(line, row);
488
507
  }
489
- const note = comparison ? comparison.note : example?.note;
490
- if (note)
491
- parts.push(paragraphs(note));
492
- const docsHref = diagnostic.codeDescription?.href;
493
- if (!comparison && !example && docsHref)
494
- parts.push(`[${escapeMarkdown(anchor.ruleId)}](${docsHref})`);
495
- return parts.join('\n\n');
496
- }
497
- function indentation(text) {
498
- return text.length - text.trimStart().length;
508
+ return [...byLine.values()]
509
+ .sort((left, right) => left.position.line - right.position.line)
510
+ .map(({ position, text, sections, fixes }) => ({
511
+ position,
512
+ label: recommendationLabel(fixLabel(fixes, tabAutofix), text, sections.size - 1),
513
+ paddingLeft: true,
514
+ paddingRight: true,
515
+ tooltip: { kind: 'markdown', value: [...sections].join('\n\n---\n\n') },
516
+ }));
499
517
  }
500
- /** The hover for a position: one section per rule flagged there, or undefined. */
518
+ /** The hover for a position includes each distinct explanation at that site. */
501
519
  function hoverFor(document, entries, position, root) {
502
- const sections = [];
503
- const shown = new Set();
520
+ const sections = new Set();
504
521
  let hoverRange;
505
522
  const word = wordRangeAt(document, position);
506
- const currentLine = document.lineAt(position.line).text.trim();
507
523
  for (const entry of entries) {
508
- let issueRange = entry.diagnostic.range;
509
- const original = publishedSources.get(entry);
510
- if (document.isDirty || (original && original.document !== document)) {
511
- const originalText = original?.document.lineAt(entry.anchor.line - 1).text;
512
- if (originalText?.trim() !== currentLine)
513
- continue;
514
- const line = liveLine(document, entry.anchor.line, original, root);
515
- if (line !== position.line + 1)
516
- continue;
517
- // Indentation edits move the flagged token, so shift the saved column by the indent change.
518
- const column = entry.anchor.column + indentation(document.lineAt(position.line).text) - indentation(originalText);
519
- if (column < 1)
520
- continue;
521
- issueRange = sourceRange({ line, column }, document);
522
- }
524
+ const issueRange = currentIssueRange(document, entry, root, position.line);
525
+ if (!issueRange)
526
+ continue;
523
527
  const range = word && samePosition(word.start, issueRange.start) ? word : issueRange;
524
- if (!rangeContains(range, position) || shown.has(entry.anchor.ruleId))
528
+ if (!rangeContains(range, position))
525
529
  continue;
526
- const markdown = hoverMarkdown(document, entry, issueRange);
530
+ const markdown = hoverMarkdown(document.languageId, entry.anchor, entry.diagnostic.codeDescription?.href, examplesFor(document, issueRange, entry.anchor));
527
531
  if (!markdown)
528
532
  continue;
529
- sections.push(markdown);
530
- shown.add(entry.anchor.ruleId);
533
+ sections.add(markdown);
531
534
  hoverRange ??= range;
532
535
  }
533
- if (!sections.length || !hoverRange)
536
+ if (!sections.size || !hoverRange)
534
537
  return;
535
- return { markdown: sections.join('\n\n---\n\n'), range: hoverRange };
538
+ return { markdown: [...sections].join('\n\n---\n\n'), range: hoverRange };
536
539
  }
537
- export { buildDiagnostics, hoverFor };
540
+ export { buildDiagnostics, findingFixIsApplied, hoverFor, inlayHints, mayHaveMovedToLine };
@@ -1,13 +1,12 @@
1
1
  import { controlFlowComparison } from './control-flow-comparison.js';
2
2
  import { sourceExampleFor } from './source-example.js';
3
3
  const maxExcerptLength = 220;
4
- const maxInlineLength = 150;
5
4
  const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
6
5
  function cleanLine(text) {
7
6
  return typeof text === 'string' ? text.replaceAll(controls, ' ').trim() : '';
8
7
  }
9
- function shorten(text) {
10
- return text.length <= maxInlineLength ? text : text.slice(0, maxInlineLength - 1).trimEnd() + '…';
8
+ function findingReview(suggestion, example) {
9
+ return cleanLine(suggestion) || cleanLine(example?.review);
11
10
  }
12
11
  function flaggedLine(text, column) {
13
12
  if (text.trim().length <= maxExcerptLength)
@@ -36,7 +35,7 @@ function getFindingComparison(document, diagnostic, example) {
36
35
  inline: rewrite.inline,
37
36
  };
38
37
  }
39
- const suggestion = cleanLine(diagnostic.suggestion || example?.review);
38
+ const suggestion = findingReview(diagnostic.suggestion, example);
40
39
  if (suggestion)
41
40
  return { kind: 'review', before: flaggedLine(text, position.character), inline: suggestion };
42
41
  if (!example)
@@ -51,24 +50,4 @@ function getFindingComparison(document, diagnostic, example) {
51
50
  inline: example.inline,
52
51
  };
53
52
  }
54
- function inlineComparison(comparison) {
55
- if (!comparison)
56
- return;
57
- if (comparison.kind === 'review')
58
- return shorten('Review: ' + comparison.inline);
59
- if (comparison.inline)
60
- return shorten(cleanLine(comparison.inline));
61
- if (!/[\r\n\u2028\u2029]/.test(comparison.after)) {
62
- if (comparison.kind === 'source') {
63
- const pair = comparison.before + ' → ' + comparison.after;
64
- if (pair.length <= maxInlineLength && !/[\r\n]/.test(pair))
65
- return cleanLine(pair);
66
- }
67
- return shorten((comparison.kind === 'source' ? 'Use: ' : 'Example: ') + cleanLine(comparison.after));
68
- }
69
- // Multiline code can contain comments, templates or indentation-sensitive blocks. Keep it intact
70
- // in the hover.
71
- const action = comparison.message?.match(/(?:^|[.!?] )((?:Use|Consider|Compile|Reuse|Build|Move|Batch|Fetch|Bind|Pass|Replace|Prefer|Push|Keep|Check|Review)\b[^\n]*?)(?:\.(?:\s|$)|$)/i)?.[1];
72
- return shorten('Review: ' + cleanLine(action || comparison.note || comparison.message || comparison.after.split('\n')[0]));
73
- }
74
- export { getFindingComparison, inlineComparison };
53
+ export { findingReview, getFindingComparison };
@@ -0,0 +1,104 @@
1
+ import { findingReview } from './finding-comparison.js';
2
+ const sentenceEnds = '.!?';
3
+ // Findings are written as short paragraphs; one sentence per line is easier to read in a tooltip.
4
+ // Code spans are kept whole, and a break needs a capital, backtick or parenthesis after the space,
5
+ // so "e.g. x" stays together.
6
+ function sentenceLines(text) {
7
+ const lines = [];
8
+ let start = 0;
9
+ let inCode = false;
10
+ for (let index = 0; index < text.length; index++) {
11
+ const character = text[index];
12
+ if (character === '`')
13
+ inCode = !inCode;
14
+ else if (!inCode &&
15
+ sentenceEnds.includes(character) &&
16
+ text[index + 1] === ' ' &&
17
+ /[A-Z`(]/.test(text[index + 2] ?? '')) {
18
+ lines.push(text.slice(start, index + 1));
19
+ start = index + 2;
20
+ }
21
+ }
22
+ lines.push(text.slice(start));
23
+ return lines.map((line) => line.trim()).filter(Boolean);
24
+ }
25
+ function readable(text) {
26
+ return text.split('\n').flatMap(sentenceLines).join('\n');
27
+ }
28
+ // The editor renders hovers as markdown; finding text is shown literally.
29
+ function escapeMarkdown(text) {
30
+ return text.replaceAll(/[\\`*_{}[\]()#+\-.!|<>~]/g, '\\$&');
31
+ }
32
+ function paragraphs(text) {
33
+ return readable(text).split('\n').map(escapeMarkdown).join('\n\n');
34
+ }
35
+ const previewWidth = 64;
36
+ const previewNote = 'Code wraps for display. Apply the fix to keep the original formatting.';
37
+ // Insert display breaks without dropping whitespace or altering the workspace edit.
38
+ function previewLines(code) {
39
+ const lines = [];
40
+ for (const sourceLine of code.split(/\r?\n/)) {
41
+ const line = sourceLine.replaceAll('\t', ' ');
42
+ let start = 0;
43
+ while (line.length - start > previewWidth) {
44
+ const prefix = line.slice(start, start + previewWidth);
45
+ const separator = prefix.search(/[\s,;)](?=[^\s,;)]*$)/u) + 1;
46
+ const width = /[\uD800-\uDBFF]$/u.test(prefix) ? previewWidth - 1 : previewWidth;
47
+ const end = start + (separator >= previewWidth / 2 ? separator : width);
48
+ lines.push(line.slice(start, end));
49
+ start = end;
50
+ }
51
+ lines.push(line.slice(start));
52
+ }
53
+ return lines.join('\n');
54
+ }
55
+ function codeBlock(code, language) {
56
+ const preview = previewLines(code);
57
+ const longestFence = Math.max(2, ...[...preview.matchAll(/`+/g)].map((match) => match[0].length));
58
+ const fence = '`'.repeat(longestFence + 1);
59
+ const label = /^[\w+.-]+$/u.test(language) ? language : '';
60
+ return { markdown: fence + label + '\n' + preview + '\n' + fence, adjusted: preview !== code };
61
+ }
62
+ function comparisonMarkdown(comparison, example, languageId) {
63
+ const before = codeBlock(comparison.before, languageId);
64
+ const parts = ['**What to change**'];
65
+ if (comparison.inline)
66
+ parts.push(paragraphs(comparison.inline));
67
+ parts.push(comparison.kind === 'source' ? '**Current code**' : '**Flagged line**', before.markdown);
68
+ let adjusted = before.adjusted;
69
+ if (comparison.kind !== 'review') {
70
+ const replacementLanguage = comparison.language ?? (comparison.kind === 'source' ? languageId : (example?.language ?? languageId));
71
+ const after = codeBlock(comparison.after, replacementLanguage);
72
+ parts.push(comparison.kind === 'source' ? '**Suggested replacement**' : '**Illustrative replacement**', after.markdown);
73
+ adjusted ||= after.adjusted;
74
+ }
75
+ if (adjusted)
76
+ parts.push(previewNote);
77
+ return parts;
78
+ }
79
+ function hoverMarkdown(languageId, anchor, docsHref, { example, comparison }) {
80
+ const review = comparison ? undefined : findingReview(anchor.suggestion, example) || example?.inline;
81
+ if (!comparison && !example && !anchor.message && !review)
82
+ return;
83
+ const ruleName = escapeMarkdown(anchor.ruleId);
84
+ const title = docsHref ? '[' + ruleName + '](' + docsHref + ')' : ruleName;
85
+ const parts = ['**' + title + '**', '**Why this was flagged**', paragraphs(anchor.message)];
86
+ if (comparison)
87
+ parts.push(...comparisonMarkdown(comparison, example, languageId));
88
+ else if (example || review) {
89
+ parts.push('**What to change**');
90
+ if (review)
91
+ parts.push(paragraphs(review));
92
+ if (example) {
93
+ const alternative = codeBlock(example.code, example.language);
94
+ parts.push('**Illustrative replacement**', alternative.markdown);
95
+ if (alternative.adjusted)
96
+ parts.push(previewNote);
97
+ }
98
+ }
99
+ const note = comparison ? comparison.note : example?.note;
100
+ if (note)
101
+ parts.push('**Follow-up**', paragraphs(note));
102
+ return parts.join('\n\n');
103
+ }
104
+ export { hoverMarkdown, readable };
@@ -0,0 +1,50 @@
1
+ import { CompletionItemKind } from 'vscode-languageserver';
2
+ import { fileKey } from './workspace-paths.js';
3
+ function exactInlineFix(fix, document, position, original) {
4
+ if (!fix || fix.requiresReview || fix.requiresExplicitSelection || fix.sourceSnapshot || fix.changes.length !== 1)
5
+ return;
6
+ const [change] = fix.changes;
7
+ if (change.create || change.line !== position.line + 1 || change.before !== original)
8
+ return;
9
+ if (fileKey(change.filename) !== fileKey(document.filename))
10
+ return;
11
+ const insertText = change.after.replaceAll(/\r?\n/gu, document.eol);
12
+ if (!insertText || insertText === original)
13
+ return;
14
+ return {
15
+ insertText,
16
+ filterText: original,
17
+ range: { start: { line: position.line, character: 0 }, end: { line: position.line, character: original.length } },
18
+ };
19
+ }
20
+ function inlineFix(document, entries, position) {
21
+ if (document.isDirty || position.line < 0 || position.line >= document.lineCount)
22
+ return;
23
+ const original = document.lineAt(position.line).text;
24
+ if (!original.trim() || position.character < original.length - original.trimStart().length)
25
+ return;
26
+ if (position.character > original.length)
27
+ return;
28
+ let result;
29
+ for (const entry of entries) {
30
+ if (entry.diagnostic.range.start.line !== position.line || entry.anchor.line !== position.line + 1)
31
+ continue;
32
+ const candidate = exactInlineFix(entry.anchor.fix, document, position, original);
33
+ if (!candidate)
34
+ continue;
35
+ if (result && result.insertText !== candidate.insertText)
36
+ return;
37
+ result = candidate;
38
+ }
39
+ return result;
40
+ }
41
+ function suggestFix(fix) {
42
+ return {
43
+ label: 'Apply Loadwise fix',
44
+ kind: CompletionItemKind.Text,
45
+ filterText: fix.filterText,
46
+ sortText: '~loadwise',
47
+ textEdit: { range: fix.range, newText: fix.insertText },
48
+ };
49
+ }
50
+ export { inlineFix, suggestFix };
@@ -0,0 +1,27 @@
1
+ import { findingReview } from './finding-comparison.js';
2
+ const replacementSourceLimit = 1_024;
3
+ function singleLineReplacement(comparison) {
4
+ if (comparison?.kind !== 'source' ||
5
+ comparison.before.includes('\n') ||
6
+ comparison.after.length > replacementSourceLimit)
7
+ return;
8
+ // Generated explanation comments are useful in the full preview. Only show the replacement code inline.
9
+ const lines = comparison.after.trim().split(/\r?\n/u);
10
+ while (lines[0]?.trimStart().startsWith('//'))
11
+ lines.shift();
12
+ const [replacement] = lines;
13
+ if (lines.length === 1 && replacement?.trim())
14
+ return replacement.trim();
15
+ }
16
+ function recommendationText(anchor, comparison, example, currentLine) {
17
+ const replacement = comparison?.before.trim() === currentLine?.trim() ? singleLineReplacement(comparison) : undefined;
18
+ if (replacement && replacement !== currentLine?.trim())
19
+ return replacement;
20
+ return findingReview(anchor.suggestion, example) || comparison?.inline || example?.inline || anchor.message;
21
+ }
22
+ function recommendationLabel(status, text, additional) {
23
+ const suffix = additional > 0 ? ' +' + additional : '';
24
+ // Inlay labels stay on one logical line. The editor can soft-wrap them to fit its viewport.
25
+ return status + ' · ' + findingReview(text, undefined) + suffix;
26
+ }
27
+ export { recommendationText, recommendationLabel };