loadwise 0.5.1 → 0.6.1

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 (132) hide show
  1. package/PERFORMANCE.md +31 -6
  2. package/README.md +580 -1024
  3. package/bin/loadwise.js +4 -0
  4. package/lib/accessibility/frontend-detect.js +2 -1
  5. package/lib/accessibility/rule-ids.js +12 -9
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +9 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +6 -0
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +25 -17
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -0,0 +1,111 @@
1
+ // Dismissed findings live in .loadwise/dismissed.json at the workspace folder root, never in the
2
+ // user's code. A finding is matched by file, rule and the trimmed text of its flagged line, so it
3
+ // stays hidden across rescans and line shifts and returns once that line changes. An entry without
4
+ // line text hides the rule for the whole file. Paths are stored relative to the folder, so the file
5
+ // can be shared through version control.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { writeFileAtomic } from '../shared/atomic-write.js';
9
+ import { errorMessage } from '../shared/error-code.js';
10
+ import { isRecord } from '../shared/is-record.js';
11
+ import { isRealPathInside } from './workspace-paths.js';
12
+ const dismissalsPath = path.join('.loadwise', 'dismissed.json');
13
+ // The file is read synchronously on every change to it; a file this large is not a list of
14
+ // dismissals anyone curates, and parsing it would stall the server.
15
+ const maxDismissalBytes = 4 * 1024 * 1024;
16
+ function keyOf({ file, ruleId, lineText }) {
17
+ return JSON.stringify([file, ruleId, lineText ?? null]);
18
+ }
19
+ function storedEntry(root, stored) {
20
+ if (!isRecord(stored) || typeof stored.file !== 'string' || typeof stored.ruleId !== 'string')
21
+ return;
22
+ if (stored.file.includes('\0'))
23
+ return;
24
+ const entry = { file: path.resolve(root, stored.file), ruleId: stored.ruleId };
25
+ if (typeof stored.lineText === 'string')
26
+ entry.lineText = stored.lineText;
27
+ return entry;
28
+ }
29
+ function readEntries(filename, root) {
30
+ let stored;
31
+ try {
32
+ const size = fs.statSync(filename, { throwIfNoEntry: false })?.size;
33
+ if (size === undefined)
34
+ return { entries: [] };
35
+ if (size > maxDismissalBytes)
36
+ return { problem: 'is larger than ' + maxDismissalBytes / 1024 / 1024 + ' MB' };
37
+ stored = JSON.parse(fs.readFileSync(filename, 'utf8'));
38
+ }
39
+ catch (error) {
40
+ return { problem: 'cannot be read: ' + errorMessage(error) };
41
+ }
42
+ if (!Array.isArray(stored))
43
+ return { problem: 'does not hold a list of dismissals' };
44
+ return { entries: stored.flatMap((item) => storedEntry(root, item) ?? []) };
45
+ }
46
+ function serialize(root, entries) {
47
+ const stored = entries.map(({ file, ruleId, lineText }) => ({
48
+ file: path.relative(root, file).split(path.sep).join('/'),
49
+ ruleId,
50
+ ...(typeof lineText === 'string' ? { lineText } : {}),
51
+ }));
52
+ return JSON.stringify(stored, null, 2) + '\n';
53
+ }
54
+ function createDismissals(root, { onProblem }) {
55
+ const filename = path.join(root, dismissalsPath);
56
+ const describe = (problem) => dismissalsPath.split(path.sep).join('/') + ' in ' + root + ' ' + problem + '.';
57
+ let current = [];
58
+ let keys = new Set();
59
+ let pendingWrite = Promise.resolve();
60
+ function replace(next) {
61
+ current = next;
62
+ keys = new Set(current.map(keyOf));
63
+ }
64
+ // A file that does not parse keeps the dismissals already shown: it may be mid-rewrite by a
65
+ // checkout, and an edit the user is still making should not flood the editor with findings.
66
+ function load() {
67
+ const stored = readEntries(filename, root);
68
+ if (stored.entries)
69
+ replace(stored.entries);
70
+ else
71
+ onProblem(describe(stored.problem));
72
+ }
73
+ // Writes run one after another, each on the latest saved entries, so quick dismissals never lose
74
+ // one. The shown state changes only once the file holds it.
75
+ function update(transform) {
76
+ const next = pendingWrite
77
+ .catch(() => { })
78
+ .then(() => {
79
+ const stored = readEntries(filename, root);
80
+ if (stored.entries === undefined) {
81
+ throw new Error(describe(stored.problem) + ' Fix or remove it, then try again; it was left unchanged.');
82
+ }
83
+ if (!isRealPathInside(root, filename)) {
84
+ throw new Error(describe('resolves outside the workspace folder') + ' Nothing was written.');
85
+ }
86
+ const entries = transform(stored.entries);
87
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
88
+ writeFileAtomic(filename, serialize(root, entries));
89
+ replace(entries);
90
+ });
91
+ pendingWrite = next;
92
+ return next;
93
+ }
94
+ load();
95
+ return {
96
+ entries: () => [...current],
97
+ has(site) {
98
+ return keys.has(keyOf(site)) || keys.has(keyOf({ file: site.file, ruleId: site.ruleId }));
99
+ },
100
+ add(entry) {
101
+ const key = keyOf(entry);
102
+ return update((entries) => [...entries.filter((existing) => keyOf(existing) !== key), entry]);
103
+ },
104
+ remove(removed) {
105
+ const gone = new Set(removed.map(keyOf));
106
+ return update((entries) => entries.filter((entry) => !gone.has(keyOf(entry))));
107
+ },
108
+ reload: load,
109
+ };
110
+ }
111
+ export { createDismissals, dismissalsPath };
@@ -0,0 +1,99 @@
1
+ // The text of a source file as the language server sees it: the editor's open buffer when there is
2
+ // one, otherwise the file on disk. Diagnostics, hovers and fixes all read files through this shape.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ const languageBySuffix = {
6
+ ts: 'typescript',
7
+ mts: 'typescript',
8
+ cts: 'typescript',
9
+ tsx: 'typescriptreact',
10
+ js: 'javascript',
11
+ mjs: 'javascript',
12
+ cjs: 'javascript',
13
+ jsx: 'javascriptreact',
14
+ py: 'python',
15
+ go: 'go',
16
+ java: 'java',
17
+ cs: 'csharp',
18
+ rs: 'rust',
19
+ rb: 'ruby',
20
+ php: 'php',
21
+ kt: 'kotlin',
22
+ kts: 'kotlin',
23
+ c: 'c',
24
+ h: 'c',
25
+ cc: 'cpp',
26
+ cpp: 'cpp',
27
+ cxx: 'cpp',
28
+ hpp: 'cpp',
29
+ hh: 'cpp',
30
+ hxx: 'cpp',
31
+ sql: 'sql',
32
+ json: 'json',
33
+ prisma: 'prisma',
34
+ html: 'html',
35
+ vue: 'vue',
36
+ svelte: 'svelte',
37
+ };
38
+ // VS Code's default word definition, so a diagnostic covers the same token in every editor.
39
+ const wordPattern = /(-?\d*\.\d\w*)|([^`~!@#$%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+)/g;
40
+ function languageIdOf(filename) {
41
+ return languageBySuffix[path.extname(filename).slice(1).toLowerCase()] ?? 'plaintext';
42
+ }
43
+ function createEditorDocument(filename, text, { languageId = languageIdOf(filename), version = null, isDirty = false } = {}) {
44
+ const lines = text.split(/\r?\n/);
45
+ return {
46
+ filename,
47
+ languageId,
48
+ version,
49
+ isDirty,
50
+ eol: text.includes('\r\n') ? '\r\n' : '\n',
51
+ lineCount: lines.length,
52
+ lineAt: (line) => ({ text: lines[line] ?? '' }),
53
+ getText: () => text,
54
+ };
55
+ }
56
+ function readDiskDocument(filename) {
57
+ try {
58
+ return createEditorDocument(filename, fs.readFileSync(filename, 'utf8'));
59
+ }
60
+ catch {
61
+ // A file deleted since the scan has no text; its findings disappear on the next scan.
62
+ return undefined;
63
+ }
64
+ }
65
+ function clampPosition(document, position) {
66
+ if (position.line < 0)
67
+ return { line: 0, character: 0 };
68
+ if (position.line >= document.lineCount) {
69
+ const lastLine = document.lineCount - 1;
70
+ return { line: lastLine, character: document.lineAt(lastLine).text.length };
71
+ }
72
+ const length = document.lineAt(position.line).text.length;
73
+ return { line: position.line, character: Math.max(0, Math.min(position.character, length)) };
74
+ }
75
+ function validateRange(document, range) {
76
+ return { start: clampPosition(document, range.start), end: clampPosition(document, range.end) };
77
+ }
78
+ function wordRangeAt(document, position) {
79
+ if (position.line < 0 || position.line >= document.lineCount)
80
+ return;
81
+ const text = document.lineAt(position.line).text;
82
+ for (const match of text.matchAll(wordPattern)) {
83
+ const start = match.index;
84
+ const end = start + match[0].length;
85
+ if (start <= position.character && position.character <= end) {
86
+ return { start: { line: position.line, character: start }, end: { line: position.line, character: end } };
87
+ }
88
+ }
89
+ }
90
+ function samePosition(left, right) {
91
+ return left.line === right.line && left.character === right.character;
92
+ }
93
+ function comparePositions(left, right) {
94
+ return left.line - right.line || left.character - right.character;
95
+ }
96
+ function rangeContains(range, position) {
97
+ return comparePositions(range.start, position) <= 0 && comparePositions(position, range.end) <= 0;
98
+ }
99
+ export { createEditorDocument, rangeContains, readDiskDocument, samePosition, validateRange, wordRangeAt };
@@ -1,9 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getFindingComparison = getFindingComparison;
4
- exports.inlineComparison = inlineComparison;
5
- const control_flow_comparison_cjs_1 = require("./control-flow-comparison.cjs");
6
- const source_example_cjs_1 = require("./source-example.cjs");
1
+ import { controlFlowComparison } from './control-flow-comparison.js';
2
+ import { sourceExampleFor } from './source-example.js';
7
3
  const maxExcerptLength = 220;
8
4
  const maxInlineLength = 150;
9
5
  const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
@@ -29,7 +25,7 @@ function getFindingComparison(document, diagnostic, example) {
29
25
  const text = document.lineAt(position.line).text;
30
26
  if (position.character < 0 || position.character > text.length || !text.trim())
31
27
  return;
32
- const rewrite = (0, control_flow_comparison_cjs_1.controlFlowComparison)(document, diagnostic) ?? (0, source_example_cjs_1.sourceExampleFor)(document, diagnostic);
28
+ const rewrite = controlFlowComparison(document, diagnostic) ?? sourceExampleFor(document, diagnostic);
33
29
  if (rewrite) {
34
30
  return {
35
31
  kind: 'source',
@@ -75,3 +71,4 @@ function inlineComparison(comparison) {
75
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];
76
72
  return shorten('Review: ' + cleanLine(action || comparison.note || comparison.message || comparison.after.split('\n')[0]));
77
73
  }
74
+ export { getFindingComparison, inlineComparison };
@@ -0,0 +1,200 @@
1
+ // Builds the workspace edits that apply scanner fixes. A fix stores the exact original lines, so it
2
+ // applies only where they still exist in the editor's buffer (or the saved file when it is not
3
+ // open); code changed since the scan refuses the fix instead of guessing. The edit goes through the
4
+ // editor, so undo restores the original code.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { isChangeApplied, locateChange } from './apply-fix.js';
8
+ const staleFixMessage = 'The code changed since the last scan. Save the file to rescan, then try again.';
9
+ const noCreateMessage = 'This editor cannot create files through the language server, so the fix was not applied.';
10
+ const overlappingChangesMessage = 'This fix changes the same lines twice, so it was not applied.';
11
+ function normalizeNewlines(text) {
12
+ return text.replaceAll('\r\n', '\n');
13
+ }
14
+ function planCreate(change, workspace) {
15
+ const existing = workspace.documentFor(change.filename);
16
+ // Never overwrite: the file may hold work written since the scan. The same content means it is
17
+ // already applied.
18
+ if (existing === undefined) {
19
+ if (!workspace.canCreateFiles)
20
+ return { error: noCreateMessage };
21
+ return {
22
+ operations: [
23
+ { filename: change.filename, key: workspace.keyOf(change.filename), create: true, text: change.after },
24
+ ],
25
+ };
26
+ }
27
+ if (normalizeNewlines(existing.getText()) !== normalizeNewlines(change.after))
28
+ return { error: change.file + ' already exists, so the fix was not applied.' };
29
+ return 'applied';
30
+ }
31
+ function planReplace(change, workspace) {
32
+ const document = workspace.documentFor(change.filename);
33
+ if (!document)
34
+ return { error: staleFixMessage };
35
+ const lines = document.getText().split(/\r?\n/);
36
+ const row = locateChange(lines, change);
37
+ // The code moved or changed since the scan; applying the stored rewrite could clobber the new
38
+ // code.
39
+ if (row === -1)
40
+ return { error: staleFixMessage };
41
+ if (isChangeApplied(lines, row, change))
42
+ return 'applied';
43
+ const lastRow = row + change.before.split(/\r?\n/).length - 1;
44
+ const range = { start: { line: row, character: 0 }, end: { line: lastRow, character: lines[lastRow].length } };
45
+ const operation = {
46
+ filename: change.filename,
47
+ key: workspace.keyOf(change.filename),
48
+ version: document.version,
49
+ firstRow: row,
50
+ lastRow,
51
+ range,
52
+ text: change.after.split(/\r?\n/).join(document.eol),
53
+ };
54
+ return { operations: [operation] };
55
+ }
56
+ // Resolves every change of one fix against the current files. Any stale change, existing file to
57
+ // create or pair of changes to the same lines rejects the whole fix, so a multi-file fix applies
58
+ // all-or-nothing.
59
+ function planFix(fix, workspace) {
60
+ const operations = [];
61
+ const claimed = new Map();
62
+ let alreadyApplied = 0;
63
+ for (const change of fix.changes) {
64
+ const plan = change.create ? planCreate(change, workspace) : planReplace(change, workspace);
65
+ if (plan === 'applied') {
66
+ alreadyApplied++;
67
+ continue;
68
+ }
69
+ if (plan.operations === undefined)
70
+ return plan;
71
+ // Each change is planned against the unchanged file, so two of them on one line would both apply.
72
+ if (plan.operations.some((operation) => overlaps(claimed, operation)))
73
+ return { error: overlappingChangesMessage };
74
+ for (const operation of plan.operations)
75
+ claim(claimed, operation);
76
+ operations.push(...plan.operations);
77
+ }
78
+ if (!operations.length && alreadyApplied)
79
+ return { error: 'This fix is already applied.' };
80
+ return { operations };
81
+ }
82
+ // New files come first. An editor that aborts on a failed operation keeps the ones before it, and a
83
+ // created file is easier to spot and delete than a half-rewritten existing one.
84
+ function documentChanges(operations, workspace) {
85
+ const changes = [];
86
+ const editsByFile = new Map();
87
+ const ordered = [...operations.filter(({ create }) => create), ...operations.filter(({ create }) => !create)];
88
+ for (const operation of ordered) {
89
+ const uri = workspace.uriFor(operation.filename);
90
+ if (operation.create) {
91
+ changes.push({ kind: 'create', uri, options: { overwrite: false, ignoreIfExists: false } });
92
+ const start = { line: 0, character: 0 };
93
+ changes.push({
94
+ textDocument: { uri, version: null },
95
+ edits: [{ range: { start, end: start }, newText: operation.text }],
96
+ });
97
+ continue;
98
+ }
99
+ const edit = { range: operation.range, newText: operation.text };
100
+ const edits = editsByFile.get(operation.key);
101
+ if (edits) {
102
+ edits.push(edit);
103
+ continue;
104
+ }
105
+ const fileEdits = [edit];
106
+ editsByFile.set(operation.key, fileEdits);
107
+ changes.push({ textDocument: { uri, version: operation.version }, edits: fileEdits });
108
+ }
109
+ return changes;
110
+ }
111
+ function plainChanges(operations, workspace) {
112
+ const changes = {};
113
+ for (const operation of operations) {
114
+ if (operation.create)
115
+ continue;
116
+ const uri = workspace.uriFor(operation.filename);
117
+ (changes[uri] ??= []).push({ range: operation.range, newText: operation.text });
118
+ }
119
+ return changes;
120
+ }
121
+ function workspaceEdit(operations, workspace) {
122
+ const createdFiles = operations.flatMap((operation) => (operation.create ? [operation.filename] : []));
123
+ if (workspace.supportsDocumentChanges) {
124
+ return { edit: { documentChanges: documentChanges(operations, workspace) }, createdFiles };
125
+ }
126
+ return { edit: { changes: plainChanges(operations, workspace) }, createdFiles };
127
+ }
128
+ /** The edit applying one fix, or why it cannot apply. */
129
+ function fixEdit(fix, workspace) {
130
+ const plan = planFix(fix, workspace);
131
+ if (plan.operations === undefined)
132
+ return plan;
133
+ return workspaceEdit(plan.operations, workspace);
134
+ }
135
+ function overlaps(claimed, operation) {
136
+ const taken = claimed.get(operation.key);
137
+ if (!taken)
138
+ return false;
139
+ if (operation.create || taken.created)
140
+ return true;
141
+ return taken.rows.some(([first, last]) => operation.firstRow <= last && first <= operation.lastRow);
142
+ }
143
+ function claim(claimed, operation) {
144
+ let taken = claimed.get(operation.key);
145
+ if (!taken) {
146
+ taken = { created: false, rows: [] };
147
+ claimed.set(operation.key, taken);
148
+ }
149
+ if (operation.create)
150
+ taken.created = true;
151
+ else
152
+ taken.rows.push([operation.firstRow, operation.lastRow]);
153
+ }
154
+ // Identical rewrites can come from several findings. Any request for review applies to the shared
155
+ // rewrite.
156
+ function bulkFixesFor(entries) {
157
+ const unique = new Map();
158
+ for (const { anchor } of entries) {
159
+ const fix = anchor.fix;
160
+ if (!fix)
161
+ continue;
162
+ const key = JSON.stringify(fix.changes);
163
+ if (!unique.has(key) || fix.requiresReview)
164
+ unique.set(key, fix);
165
+ }
166
+ const eligible = [...unique.values()].filter((fix) => !fix.requiresReview);
167
+ return { eligible, reviewCount: unique.size - eligible.length };
168
+ }
169
+ // Every applicable fix in one edit, so one undo reverts them all. Stale fixes, fixes that would
170
+ // create an existing file, and fixes overlapping an earlier one are skipped whole.
171
+ function fixAllEdit(fixes, workspace) {
172
+ const claimed = new Map();
173
+ const operations = [];
174
+ let applied = 0;
175
+ for (const fix of fixes) {
176
+ const plan = planFix(fix, workspace);
177
+ if (plan.operations === undefined || plan.operations.some((operation) => overlaps(claimed, operation)))
178
+ continue;
179
+ for (const operation of plan.operations)
180
+ claim(claimed, operation);
181
+ operations.push(...plan.operations);
182
+ applied++;
183
+ }
184
+ return { ...workspaceEdit(operations, workspace), applied, skipped: fixes.length - applied };
185
+ }
186
+ // A workspace edit can create a file but not a folder, and editors differ on whether they make the
187
+ // missing ones, so the server makes them before it sends such an edit.
188
+ /** The folders of the new files that do not exist yet, outermost first. */
189
+ function missingFolders(createdFiles) {
190
+ const missing = new Set();
191
+ for (const filename of createdFiles) {
192
+ for (let folder = path.dirname(filename); !fs.existsSync(folder); folder = path.dirname(folder)) {
193
+ if (path.dirname(folder) === folder)
194
+ break;
195
+ missing.add(folder);
196
+ }
197
+ }
198
+ return [...missing].sort((left, right) => left.length - right.length);
199
+ }
200
+ export { bulkFixesFor, fixAllEdit, fixEdit, missingFolders };