loadwise 0.6.2 → 0.7.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 (86) hide show
  1. package/README.md +152 -100
  2. package/dist/bin/loadwise.js +126 -49
  3. package/dist/lib/accessibility/frontend-detect.js +6 -5
  4. package/dist/lib/accessibility/usage.js +10 -2
  5. package/dist/lib/editor/configured-setup.js +61 -0
  6. package/dist/lib/editor/editor-launcher.js +165 -0
  7. package/dist/lib/editor/fix-edits.js +19 -0
  8. package/dist/lib/editor/jetbrains-setup.js +53 -0
  9. package/dist/lib/editor/language-server.js +31 -14
  10. package/dist/lib/editor/managed-config.js +37 -0
  11. package/dist/lib/editor/native-setup.js +85 -0
  12. package/dist/lib/editor/release-vsix.js +61 -0
  13. package/dist/lib/editor/server-commands.js +2 -0
  14. package/dist/lib/editor/setup-server.js +87 -0
  15. package/dist/lib/editor/setup-vim.js +61 -0
  16. package/dist/lib/editor/setup.js +131 -0
  17. package/dist/lib/editor/stdio-setup.js +6 -0
  18. package/dist/lib/maintainability/cli/inputs.js +3 -2
  19. package/dist/lib/maintainability/cli.js +14 -5
  20. package/dist/lib/maintainability/examples.js +4 -0
  21. package/dist/lib/maintainability/rule-ids.js +3 -0
  22. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  23. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  24. package/dist/lib/performance/cli/changed-lines.js +8 -1
  25. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  26. package/dist/lib/performance/cli/cli-output.js +3 -0
  27. package/dist/lib/performance/cli.js +8 -4
  28. package/dist/lib/performance/datastores/pg-integrity.js +7 -0
  29. package/dist/lib/performance/datastores/pooling.js +6 -1
  30. package/dist/lib/performance/engine/native-syntax.js +3 -0
  31. package/dist/lib/performance/frontend/frontend-perf.js +80 -20
  32. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  33. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  34. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  35. package/dist/lib/performance/request/mongoose-lean.js +140 -53
  36. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  37. package/dist/lib/performance/request/phase5-ast.js +6 -7
  38. package/dist/lib/performance/request/phase5-rules.js +133 -13
  39. package/dist/lib/performance/request/request-handlers.js +120 -23
  40. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  41. package/dist/lib/performance/site-fixes/collections.js +1 -2
  42. package/dist/lib/performance/site-fixes/frontend-fixes.js +10 -6
  43. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  44. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  45. package/dist/lib/reliability/react-bugs.js +11 -3
  46. package/dist/lib/reliability/usage.js +16 -5
  47. package/dist/lib/security/cli.js +15 -4
  48. package/dist/lib/shared/agent/agent-init.js +26 -4
  49. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  50. package/dist/lib/shared/agent/agent-session.js +6 -1
  51. package/dist/lib/shared/agent/agent-verify.js +54 -10
  52. package/dist/lib/shared/agent/review-delivery.js +1 -1
  53. package/dist/lib/shared/analysis/scan-cache.js +3 -2
  54. package/dist/lib/shared/check.js +172 -20
  55. package/dist/lib/shared/fix/fix-convergence.js +15 -29
  56. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  57. package/dist/lib/shared/fix/fix-imports.js +47 -38
  58. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  59. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  60. package/dist/lib/shared/fix/fix-presentation.js +4 -3
  61. package/dist/lib/shared/fix/fix-safety.js +26 -1
  62. package/dist/lib/shared/fix/fix-scope.js +82 -0
  63. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  64. package/dist/lib/shared/fix/project-file-access.js +17 -26
  65. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  66. package/dist/lib/shared/fix.js +215 -102
  67. package/dist/lib/shared/report-fp.js +93 -0
  68. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  69. package/dist/lib/shared/reporting/check-text.js +50 -0
  70. package/dist/lib/shared/reporting/pillars.js +45 -16
  71. package/dist/lib/shared/reporting/source-report.js +2 -0
  72. package/dist/lib/shared/system/atomic-write.js +5 -2
  73. package/dist/lib/shared/system/sentry.js +203 -0
  74. package/dist/lib/shared/system/shell-argument.js +5 -1
  75. package/dist/lib/shared/system/terminal-safe.js +3 -2
  76. package/dist/lib/shared/system/terminal-style.js +131 -0
  77. package/docs/assets/cli-workflow.gif +0 -0
  78. package/integrations/sublime/plugin.py +22 -0
  79. package/integrations/zed/Cargo.lock +845 -0
  80. package/integrations/zed/Cargo.toml +11 -0
  81. package/integrations/zed/extension.toml +11 -0
  82. package/integrations/zed/src/lib.rs +25 -0
  83. package/package.json +11 -3
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/commands/loadwise.md +11 -6
  86. package/schema/loadwise.config.schema.json +2 -0
@@ -6,6 +6,7 @@ import { allowedHeapMegabytes, childHeapFlags, isHeapExhaustion } from '../syste
6
6
  import { configlessSources, coveringConfig, hasWorkspaceSources, missingSourcesDetail, projectConfig, } from '../workspaces.js';
7
7
  import { cachedRun, withSharedInputFingerprint } from '../analysis/scan-cache.js';
8
8
  import { isRecord } from '../system/is-record.js';
9
+ import { automaticFixSignal, collectFixSignals } from './automatic-fix-signal.js';
9
10
  import { rulesByPillar } from '../rule-registry.js';
10
11
  import { hasInfrastructureFiles } from '../../security/files/index.js';
11
12
  import { hasFrontendSourcesInWorkspaces } from '../../accessibility/frontend-detect.js';
@@ -51,16 +52,29 @@ function spawnChecker(args, cwd) {
51
52
  // The parent owns the review and its scope, including when several checkers run in child
52
53
  // processes.
53
54
  const heapFlags = childHeapFlags();
55
+ const collect = pillarNames.includes(args[0]) && !args.includes('--json');
54
56
  const child = spawn(process.execPath, [...heapFlags, cli, ...args], {
55
57
  cwd,
56
58
  windowsHide: true,
57
- env: { ...process.env, LOADWISE_AGENT: '0' },
59
+ stdio: ['pipe', 'pipe', 'pipe', collect ? 'ipc' : 'ignore'],
60
+ env: {
61
+ ...process.env,
62
+ LOADWISE_AGENT: '0',
63
+ NO_COLOR: '1',
64
+ FORCE_COLOR: '0',
65
+ [collectFixSignals]: collect ? '1' : '0',
66
+ },
58
67
  });
59
68
  const maxOutputBytes = 64 * 1024 * 1024;
60
69
  let stdout = '';
61
70
  let stderr = '';
62
71
  let overflowed = false;
63
- child.stdout.setEncoding('utf8').on('data', (text) => {
72
+ let hasAutomaticFixes = false;
73
+ child.on('message', (message) => {
74
+ if (message === automaticFixSignal)
75
+ hasAutomaticFixes = true;
76
+ });
77
+ child.stdout?.setEncoding('utf8').on('data', (text) => {
64
78
  if (stdout.length + text.length > maxOutputBytes) {
65
79
  overflowed = true;
66
80
  child.kill('SIGKILL');
@@ -68,7 +82,7 @@ function spawnChecker(args, cwd) {
68
82
  }
69
83
  stdout += text;
70
84
  });
71
- child.stderr.setEncoding('utf8').on('data', (text) => {
85
+ child.stderr?.setEncoding('utf8').on('data', (text) => {
72
86
  if (stderr.length + text.length <= maxOutputBytes)
73
87
  stderr += text;
74
88
  });
@@ -82,7 +96,12 @@ function spawnChecker(args, cwd) {
82
96
  resolve({ code: invalidInputCode, stdout: '', stderr: heapExhaustionMessage(args, heapFlags) });
83
97
  return;
84
98
  }
85
- resolve({ code: code ?? invalidInputCode, stdout, stderr });
99
+ resolve({
100
+ code: code ?? invalidInputCode,
101
+ stdout,
102
+ stderr,
103
+ ...(hasAutomaticFixes && { hasAutomaticFixes: true }),
104
+ });
86
105
  });
87
106
  });
88
107
  }
@@ -105,7 +124,7 @@ function mergeContractReport(source, contracts, contractFlags) {
105
124
  if (contracts.code === invalidInputCode)
106
125
  return { ...source, code, stderr };
107
126
  if (!contractFlags?.includes('--json'))
108
- return { code, stdout: source.stdout + contracts.stdout, stderr };
127
+ return { ...source, code, stdout: source.stdout + contracts.stdout, stderr };
109
128
  let sourceReport;
110
129
  let contractReport;
111
130
  try {
@@ -148,8 +167,12 @@ const noFrontendNote = (directory) => `Note: no frontend sources (JSX, HTML, Vue
148
167
  // A project of plain markup has no tsconfig.json; the checker then reads its markup files alone.
149
168
  function runAccessibilityChecker(options) {
150
169
  if (!hasFrontendSourcesInWorkspaces(options.directory, options.workspaces)) {
151
- console.error(noFrontendNote(options.directory));
152
- return Promise.resolve(undefined);
170
+ return Promise.resolve({
171
+ code: 0,
172
+ stdout: '',
173
+ stderr: noFrontendNote(options.directory) + '\n',
174
+ notApplicable: 'no-frontend-sources',
175
+ });
153
176
  }
154
177
  const { directory, flags, workspaces, relative } = options;
155
178
  const workspaceFlags = workspaces.flatMap((selector) => ['--workspace', selector]);
@@ -240,7 +263,6 @@ const pillars = [
240
263
  name: 'a11y',
241
264
  title: 'Accessibility',
242
265
  jsonKey: 'accessibility',
243
- optional: true,
244
266
  ruleIds: () => rulesByPillar.accessibility.knownRules,
245
267
  findingRoot: () => process.cwd(),
246
268
  run: (options) => runAccessibilityChecker(options),
@@ -248,13 +270,15 @@ const pillars = [
248
270
  ];
249
271
  const pillarNames = pillars.map(({ name }) => name);
250
272
  function namesIn(list, flag) {
251
- const names = new Set(list
273
+ const names = new Set();
274
+ for (const selector of list
252
275
  .split(',')
253
- .map((name) => name.trim())
254
- .filter(Boolean));
255
- for (const name of names) {
256
- if (!pillarNames.includes(name))
257
- throw new Error(`Unknown ${flag} name "${name}"; use ${pillarNames.join(', ')}.`);
276
+ .map((item) => item.trim())
277
+ .filter(Boolean)) {
278
+ const checker = pillars.find(({ name, jsonKey }) => selector === name || selector === jsonKey);
279
+ if (!checker)
280
+ throw new Error(`Unknown ${flag} name "${selector}"; use ${pillarNames.join(', ')}.`);
281
+ names.add(checker.name);
258
282
  }
259
283
  return names;
260
284
  }
@@ -364,12 +388,17 @@ async function runSharedSourceCheck(shared, options) {
364
388
  reports: Object.fromEntries(keys.map((key, index) => [key, index ? { ...failed, stderr: '' } : failed])),
365
389
  };
366
390
  }
367
- // The child's warnings belong to the run once, so they print with the first report.
391
+ // The child's warnings and combined fix signal belong to the run once.
368
392
  const reports = shared.map((pillar, index) => {
369
393
  const report = envelope[pillar.jsonKey];
370
394
  if (!report)
371
395
  return undefined;
372
- const own = { ...report, stderr: index ? '' : run.stderr };
396
+ const own = {
397
+ code: report.code,
398
+ stdout: report.stdout,
399
+ stderr: index ? '' : run.stderr,
400
+ ...(!index && run.hasAutomaticFixes && { hasAutomaticFixes: true }),
401
+ };
373
402
  return pillar.name === 'rel' ? mergeContractReport(own, contracts, contractOptions?.contractFlags) : own;
374
403
  });
375
404
  return { reports: Object.fromEntries(keys.map((key, index) => [key, reports[index]])) };
@@ -9,6 +9,7 @@ import { resolveFormat, renderReports } from '../formats/index.js';
9
9
  import { impactByRule } from '../../security/rule-ids.js';
10
10
  import { findProjectRoot } from '../../performance/schema/context.js';
11
11
  import { terminalPrinter } from '../system/terminal-safe.js';
12
+ import { reportAutomaticFixes } from './automatic-fix-signal.js';
12
13
  import { assignFindingIds as assignFindingIdsFindingIds } from '../../performance/cli/finding-ids.js';
13
14
  import { keepChangedFindings } from '../../performance/cli/changed-lines.js';
14
15
  import { attachExample, printFindings, findingLabel } from '../../performance/cli/finding-text.js';
@@ -108,6 +109,7 @@ function printSourceReport(result, values, baseline, format, print) {
108
109
  else
109
110
  printTextSummary(result, values, terminalPrinter(print));
110
111
  if (format === 'text') {
112
+ reportAutomaticFixes(result.findings);
111
113
  if (baseline)
112
114
  for (const line of baselineNoteLines(baseline))
113
115
  print(line);
@@ -24,8 +24,11 @@ function retryTransientErrors(operation) {
24
24
  }
25
25
  }
26
26
  }
27
- function renameWithRetry(from, to) {
28
- retryTransientErrors(() => fs.renameSync(from, to));
27
+ function renameWithRetry(from, to, assertStillReplaceable) {
28
+ retryTransientErrors(() => {
29
+ assertStillReplaceable?.();
30
+ fs.renameSync(from, to);
31
+ });
29
32
  }
30
33
  // The file can change during a backoff, so `assertStillRemovable` runs before every retry and throws to keep it.
31
34
  function unlinkWithRetry(filename, assertStillRemovable) {
@@ -0,0 +1,203 @@
1
+ // Opt-in Sentry crash reporting sends diagnostic metadata about Loadwise itself.
2
+ import crypto from 'node:crypto';
3
+ import { isIP } from 'node:net';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { packageManifest, packageRoot } from '../package-root.js';
6
+ const SEND_TIMEOUT_MS = 3_000;
7
+ const DEFAULT_SENTRY_HOST = 'o4512506230603776.ingest.de.sentry.io';
8
+ const DEFAULT_SENTRY_PROJECT_ID = '4512506234273872';
9
+ // Public write-only client ingest key for loadwise-cli (EU); rate-limited via Sentry Spike Protection.
10
+ const DEFAULT_SENTRY_CLIENT_ID = '0230b9fb3fe7211d2f647690dd92f6c2';
11
+ const STACK_LOC_RE = /^(.*):(\d+):(\d+)$/;
12
+ const NORMALIZED_PACKAGE_ROOT = `${packageRoot.replaceAll('\\', '/').replace(/\/+$/, '')}/`;
13
+ const PACKAGE_FRAME_RE = /^(?:dist|lib|bin)\/(?:[\w-]+\/)*[\w.-]+\.[cm]?[jt]s$/;
14
+ const BUILT_IN_ERROR_NAMES = new Set([
15
+ 'AggregateError',
16
+ 'EvalError',
17
+ 'RangeError',
18
+ 'ReferenceError',
19
+ 'SyntaxError',
20
+ 'TypeError',
21
+ 'URIError',
22
+ ]);
23
+ const EXPECTED_CLI_ERROR_RE = /^(?:Usage:|Unknown (?:option|.*rule|--)|Choose (?:either |one of )|Option '[^']+' argument|Pass one checker name|Expected (?:an existing|a project directory|a project-relative path|a nonempty)|--[a-z][a-z-]* (?:must be|is only valid|cannot be combined|supports|accepts|is read-only|apply to)|Invalid |Cannot (?:combine|load) |Cannot find (?:tsconfig|jsconfig|config|project|file|directory)\b|No (?:tsconfig|inputs were found|supported source files|package-lock\.json)|Baseline not found:|ENOENT:|error TS\d+:|Option '[^']+' must be|Unsupported |.* must be an array\.|check never changes (?:source )?files\.|--uncommitted requires a Git repository|fix accepts at most one project directory\.|Workspace packages are missing|Trace file contains invalid JSON|Initialize local review history|The (?:Performance|Reliability|Maintainability|Security|Accessibility) scan did not complete|.*\.findings contains a finding)/;
24
+ /**
25
+ * Parses a Sentry DSN into its Envelope endpoint URL and X-Sentry-Auth header.
26
+ * Returns null when the DSN is empty or malformed.
27
+ */
28
+ function parseSentryDsn(dsn) {
29
+ const trimmed = dsn.trim();
30
+ if (!trimmed)
31
+ return null;
32
+ let url;
33
+ try {
34
+ url = new URL(trimmed);
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ const { hostname, protocol } = url;
40
+ const loopback = hostname === 'localhost' || hostname === '[::1]' || (isIP(hostname) === 4 && hostname.startsWith('127.'));
41
+ if ((protocol !== 'https:' && !(protocol === 'http:' && loopback)) || !url.username || !hostname)
42
+ return null;
43
+ const segments = url.pathname.split('/').filter(Boolean);
44
+ const projectId = segments.pop();
45
+ if (!projectId || !/^\d+$/.test(projectId))
46
+ return null;
47
+ const prefix = segments.length > 0 ? `/${segments.join('/')}` : '';
48
+ return {
49
+ envelopeUrl: `${url.protocol}//${url.host}${prefix}/api/${projectId}/envelope/`,
50
+ authHeader: `Sentry sentry_version=7, sentry_client=loadwise/${packageManifest.version}, sentry_key=${url.username}`,
51
+ };
52
+ }
53
+ /**
54
+ * Returns true for expected CLI usage, flag, or input validation errors that should not page Sentry.
55
+ */
56
+ function isExpectedCliError(error) {
57
+ const message = error instanceof Error ? error.message : String(error);
58
+ return EXPECTED_CLI_ERROR_RE.test(message.trim());
59
+ }
60
+ function normalizeLocationPath(raw) {
61
+ let candidate = raw.trim();
62
+ if (candidate.startsWith('file://')) {
63
+ try {
64
+ candidate = fileURLToPath(candidate);
65
+ }
66
+ catch {
67
+ return candidate;
68
+ }
69
+ }
70
+ return candidate.replaceAll('\\', '/');
71
+ }
72
+ function parseFrame(line) {
73
+ const trimmed = line.trim();
74
+ if (!trimmed.startsWith('at '))
75
+ return null;
76
+ const body = trimmed.slice(3);
77
+ const parenIndex = body.indexOf(' (');
78
+ const rawLocation = parenIndex === -1 ? body : body.slice(parenIndex + 2, body.endsWith(')') ? -1 : undefined);
79
+ const locMatch = STACK_LOC_RE.exec(rawLocation);
80
+ if (!locMatch)
81
+ return null;
82
+ const normalized = normalizeLocationPath(locMatch[1]);
83
+ const rootMatch = process.platform === 'win32'
84
+ ? normalized.toLowerCase().startsWith(NORMALIZED_PACKAGE_ROOT.toLowerCase())
85
+ : normalized.startsWith(NORMALIZED_PACKAGE_ROOT);
86
+ if (!rootMatch)
87
+ return null;
88
+ const relative = normalized.slice(NORMALIZED_PACKAGE_ROOT.length);
89
+ if (!PACKAGE_FRAME_RE.test(relative))
90
+ return null;
91
+ return {
92
+ filename: relative,
93
+ abs_path: 'app:///' + relative,
94
+ in_app: true,
95
+ lineno: Number(locMatch[2]),
96
+ colno: Number(locMatch[3]),
97
+ };
98
+ }
99
+ /**
100
+ * Keeps only package-relative Loadwise locations and drops arbitrary stack labels.
101
+ */
102
+ function sanitizeStack(stack) {
103
+ if (!stack)
104
+ return [];
105
+ const frames = [];
106
+ for (const line of stack.split(/\r?\n/)) {
107
+ const frame = parseFrame(line);
108
+ if (frame)
109
+ frames.push(frame);
110
+ }
111
+ // Sentry expects stack frames ordered oldest-to-newest.
112
+ return frames.reverse();
113
+ }
114
+ /**
115
+ * Builds a 3-line Sentry Envelope without free-form exception data.
116
+ */
117
+ function buildEnvelope(error, command, version, options = {}) {
118
+ const eventId = options.eventId ?? crypto.randomUUID().replaceAll('-', '');
119
+ const sentAt = new Date().toISOString();
120
+ const errorName = error instanceof Error ? error.name : 'Error';
121
+ const type = BUILT_IN_ERROR_NAMES.has(errorName) ? errorName : 'Error';
122
+ const frames = error instanceof Error ? sanitizeStack(error.stack) : [];
123
+ const header = JSON.stringify({ event_id: eventId, sent_at: sentAt });
124
+ const itemHeader = JSON.stringify({ type: 'event' });
125
+ const payload = JSON.stringify({
126
+ event_id: eventId,
127
+ timestamp: sentAt,
128
+ platform: 'node',
129
+ level: 'error',
130
+ release: `loadwise@${version}`,
131
+ environment: options.environment ?? (process.env.CI ? 'ci' : 'local'),
132
+ tags: {
133
+ command: command || 'check',
134
+ node: process.version,
135
+ platform: process.platform,
136
+ },
137
+ exception: {
138
+ values: [
139
+ {
140
+ type,
141
+ value: 'Unexpected Loadwise error',
142
+ ...(frames.length > 0 ? { stacktrace: { frames } } : {}),
143
+ },
144
+ ],
145
+ },
146
+ });
147
+ return `${header}\n${itemHeader}\n${payload}\n`;
148
+ }
149
+ function resolveCrashReportTarget(options = {}) {
150
+ const env = options.env ?? process.env;
151
+ if (!options.env && env.NODE_TEST_CONTEXT)
152
+ return null;
153
+ if (env.LOADWISE_SENTRY_DSN)
154
+ return parseSentryDsn(env.LOADWISE_SENTRY_DSN);
155
+ const envEnabled = env.LOADWISE_CRASH_REPORTS === '1' || env.LOADWISE_CRASH_REPORTS === 'true';
156
+ if (!options.flagEnabled && !envEnabled)
157
+ return null;
158
+ return {
159
+ envelopeUrl: `https://${DEFAULT_SENTRY_HOST}/api/${DEFAULT_SENTRY_PROJECT_ID}/envelope/`,
160
+ authHeader: `Sentry sentry_version=7, sentry_client=loadwise/${packageManifest.version}, sentry_key=${DEFAULT_SENTRY_CLIENT_ID}`,
161
+ };
162
+ }
163
+ /**
164
+ * Sends a sanitized crash envelope when crash reporting is enabled. Never throws or blocks exit.
165
+ */
166
+ async function reportCrash(error, command, dsnOrTarget = resolveCrashReportTarget() ?? undefined) {
167
+ if (!dsnOrTarget)
168
+ return false;
169
+ const parsed = typeof dsnOrTarget === 'string' ? parseSentryDsn(dsnOrTarget) : dsnOrTarget;
170
+ if (!parsed)
171
+ return false;
172
+ try {
173
+ const body = buildEnvelope(error, command, packageManifest.version);
174
+ const response = await fetch(parsed.envelopeUrl, {
175
+ method: 'POST',
176
+ redirect: 'error',
177
+ headers: {
178
+ 'Content-Type': 'application/x-sentry-envelope',
179
+ 'X-Sentry-Auth': parsed.authHeader,
180
+ },
181
+ body,
182
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
183
+ });
184
+ return response.ok;
185
+ }
186
+ catch {
187
+ return false;
188
+ }
189
+ }
190
+ /**
191
+ * Installs uncaughtException / unhandledRejection listeners when crash reporting is enabled.
192
+ */
193
+ function installGlobalCrashHandlers(command, target = resolveCrashReportTarget()) {
194
+ if (!target)
195
+ return;
196
+ process.once('uncaughtException', (error) => {
197
+ void reportCrash(error, command, target).finally(() => process.exit(2));
198
+ });
199
+ process.once('unhandledRejection', (reason) => {
200
+ void reportCrash(reason, command, target).finally(() => process.exit(2));
201
+ });
202
+ }
203
+ export { parseSentryDsn, resolveCrashReportTarget, buildEnvelope, reportCrash, isExpectedCliError, installGlobalCrashHandlers, };
@@ -6,4 +6,8 @@ function quoteArgument(argument) {
6
6
  const escaped = process.platform === 'win32' ? argument.replaceAll(/['\u2018-\u201B]/g, "'$&") : argument.replaceAll("'", "'\\''");
7
7
  return "'" + escaped + "'";
8
8
  }
9
- export { quoteArgument };
9
+ // parseArgs treats a separate token starting with a dash as another option.
10
+ function optionArguments(flag, value) {
11
+ return value.startsWith('-') ? [`${flag}=${value}`] : [flag, value];
12
+ }
13
+ export { optionArguments, quoteArgument };
@@ -1,6 +1,7 @@
1
1
  // Text output quotes scanned code: messages, file names and fix diffs. A control character in it, such as an escape
2
2
  // sequence in a pull request's file, would be run by the terminal instead of shown, so text output prints a
3
3
  // placeholder for each one. JSON, SARIF and saved reports keep the exact text.
4
+ import { styleTerminalLine } from './terminal-style.js';
4
5
  // Every control character except a newline, a tab and the carriage return that ends a CRLF line. A carriage return
5
6
  // inside a line would let the rest of the line overwrite what precedes it.
6
7
  const controlCharacters = /\r(?!\n|$)|[^\P{Cc}\n\t\r]/gu;
@@ -8,9 +9,9 @@ function terminalSafe(text) {
8
9
  return text.replaceAll(controlCharacters, '\uFFFD');
9
10
  }
10
11
  function terminalPrinter(print) {
11
- return (line) => print(terminalSafe(line));
12
+ return (line) => print(styleTerminalLine(terminalSafe(line)));
12
13
  }
13
14
  function printTerminalLine(line) {
14
- console.log(terminalSafe(line));
15
+ console.log(styleTerminalLine(terminalSafe(line)));
15
16
  }
16
17
  export { printTerminalLine, terminalPrinter, terminalSafe };
@@ -0,0 +1,131 @@
1
+ // TTY-aware ANSI styling for Loadwise terminal output.
2
+ // Always runs AFTER `terminalSafe()` so untrusted source code cannot inject escape sequences.
3
+ // When stdout is not a TTY, NO_COLOR is set, or an AI agent session is active, output stays plain text.
4
+ import { isAgentSession } from '../agent/agent-session.js';
5
+ const ansi = {
6
+ reset: '\x1b[0m',
7
+ bold: '\x1b[1m',
8
+ dim: '\x1b[2m',
9
+ red: '\x1b[31m',
10
+ green: '\x1b[32m',
11
+ yellow: '\x1b[33m',
12
+ cyan: '\x1b[36m',
13
+ magenta: '\x1b[35m',
14
+ boldRed: '\x1b[1;31m',
15
+ boldGreen: '\x1b[1;32m',
16
+ boldYellow: '\x1b[1;33m',
17
+ boldCyan: '\x1b[1;36m',
18
+ boldWhite: '\x1b[1;37m',
19
+ dimCyan: '\x1b[2;36m',
20
+ };
21
+ /** True when interactive ANSI color should be emitted for `stream`. */
22
+ function supportsColor(stream = process.stdout) {
23
+ if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '')
24
+ return false;
25
+ if (process.env.TERM === 'dumb')
26
+ return false;
27
+ const forced = process.env.FORCE_COLOR;
28
+ if (forced !== undefined)
29
+ return forced !== '0' && forced.toLowerCase() !== 'false';
30
+ if (isAgentSession())
31
+ return false;
32
+ return Boolean(stream.isTTY);
33
+ }
34
+ /** Formats a checker section header (`== Performance ==` in plain text, bold cyan rule in TTY). */
35
+ function styleSectionHeader(title, enabled = supportsColor()) {
36
+ if (!enabled)
37
+ return `== ${title} ==`;
38
+ const bar = '━'.repeat(Math.max(4, 52 - title.length));
39
+ return `${ansi.boldCyan}━━ ${title} ${ansi.dimCyan}${bar}${ansi.reset}`;
40
+ }
41
+ function styleSeverity(severity) {
42
+ if (severity === 'critical')
43
+ return `${ansi.boldRed}critical${ansi.reset}`;
44
+ if (severity === 'high')
45
+ return `${ansi.red}${ansi.bold}high${ansi.reset}`;
46
+ if (severity === 'medium')
47
+ return `${ansi.boldYellow}medium${ansi.reset}`;
48
+ return `${ansi.dimCyan}${severity}${ansi.reset}`;
49
+ }
50
+ function styleFindingHeader(line) {
51
+ // Single finding: `path:line:col [rule #id] severity: message`
52
+ const single = /^(\S.*:\d+(?::\d+)?) (\[[^\]]+\]) (critical|high|medium|low)(?:: (.*))?$/.exec(line);
53
+ if (single) {
54
+ const [, loc, rule, severity, message] = single;
55
+ const explanation = message === undefined ? '' : `${ansi.dim}:${ansi.reset} ${message}`;
56
+ return `${ansi.cyan}${loc}${ansi.reset} ${ansi.boldWhite}${rule}${ansi.reset} ${styleSeverity(severity)}${explanation}`;
57
+ }
58
+ // Grouped finding header: `[rule] severity: message (N findings)`
59
+ const grouped = /^(\[[^\]]+\]) (critical|high|medium|low)(?: (\(\d+ findings\)))?(?:: (.*))?$/.exec(line);
60
+ if (grouped) {
61
+ const [, rule, severity, count, message] = grouped;
62
+ const explanation = message === undefined ? '' : `${ansi.dim}:${ansi.reset} ${message}`;
63
+ const total = count ? ` ${ansi.dim}${count}${ansi.reset}` : '';
64
+ return `${ansi.boldWhite}${rule}${ansi.reset} ${styleSeverity(severity)}${total}${explanation}`;
65
+ }
66
+ return undefined;
67
+ }
68
+ /** Applies TTY color to a single already-sanitized output line. */
69
+ function styleTerminalLine(line, enabled = supportsColor()) {
70
+ if (!enabled || !line)
71
+ return line;
72
+ const header = styleFindingHeader(line);
73
+ if (header)
74
+ return header;
75
+ // Grouped finding location line: ` path:line:col #id`
76
+ const groupedLoc = /^( {2})(\S.*:\d+:\d+)( #[a-f0-9-]+)?$/.exec(line);
77
+ if (groupedLoc) {
78
+ const [, indent, loc, id = ''] = groupedLoc;
79
+ return `${indent}${ansi.cyan}${loc}${ansi.reset}${ansi.magenta}${id}${ansi.reset}`;
80
+ }
81
+ // Diff lines in Fix blocks
82
+ if (/^\s+\+ /.test(line))
83
+ return `${ansi.green}${line}${ansi.reset}`;
84
+ if (/^\s+- /.test(line))
85
+ return `${ansi.red}${line}${ansi.reset}`;
86
+ // Actionable fix commands
87
+ const reviewCmd = /^(\s*)(After individual review:|Fix all:) (.+)$/.exec(line);
88
+ if (reviewCmd) {
89
+ const [, indent, prefix, cmd] = reviewCmd;
90
+ return `${indent}${ansi.dim}${prefix}${ansi.reset} ${ansi.boldCyan}${cmd}${ansi.reset}`;
91
+ }
92
+ // Labels (` Fix (...)`, ` Example (...)`, ` Hot path: ...`, ` Note: ...`)
93
+ const labelLine = /^(\s*)(Fix \([^)]+\):|Example \([^)]+\):|Hot path:|Note:|Impact:|Why:)(.*)$/.exec(line);
94
+ if (labelLine) {
95
+ const [, indent, label, rest] = labelLine;
96
+ return `${indent}${ansi.dimCyan}${label}${ansi.reset}${rest}`;
97
+ }
98
+ // Checker summary lines
99
+ if (/^\d+ (?:(?:source|graph) )?file(?:s|\(s\))?\b.*\b0 finding(?:s|\(s\))/.test(line)) {
100
+ return `${ansi.boldGreen}✓ ${line}${ansi.reset}`;
101
+ }
102
+ if (/^\d+ (?:(?:source|graph) )?file(?:s|\(s\))?\b.*\b[1-9]\d* finding(?:s|\(s\))?/.test(line)) {
103
+ return `${ansi.boldYellow}${line}${ansi.reset}`;
104
+ }
105
+ return line;
106
+ }
107
+ /** Colors a sanitized unified diff. Paths and source keep their markers in plain-text output. */
108
+ function stylePatchLine(line, enabled = supportsColor()) {
109
+ if (!enabled)
110
+ return line;
111
+ let color = ansi.dim;
112
+ if (line.startsWith('--- ') || line.startsWith('+++ '))
113
+ color = ansi.boldWhite;
114
+ else if (line.startsWith('@@ '))
115
+ color = ansi.cyan;
116
+ else if (line.startsWith('+'))
117
+ color = ansi.green;
118
+ else if (line.startsWith('-'))
119
+ color = ansi.red;
120
+ return color + line + ansi.reset;
121
+ }
122
+ /** Applies TTY color to a multi-line already-sanitized text block, preserving trailing newline. */
123
+ function styleTerminalText(text, enabled = supportsColor()) {
124
+ if (!enabled || !text)
125
+ return text;
126
+ const endsWithNewline = text.endsWith('\n');
127
+ const lines = (endsWithNewline ? text.slice(0, -1) : text).split('\n');
128
+ const styled = lines.map((line) => styleTerminalLine(line, true)).join('\n');
129
+ return endsWithNewline ? styled + '\n' : styled;
130
+ }
131
+ export { stylePatchLine, styleSectionHeader, styleTerminalLine, styleTerminalText };
Binary file
@@ -0,0 +1,22 @@
1
+ import json
2
+
3
+ import sublime
4
+ from LSP.plugin import AbstractPlugin, register_plugin, unregister_plugin
5
+
6
+
7
+ class LoadwisePlugin(AbstractPlugin):
8
+ @classmethod
9
+ def name(cls):
10
+ return "loadwise"
11
+
12
+ @classmethod
13
+ def additional_variables(cls):
14
+ return json.loads(sublime.load_resource("Packages/LSP-loadwise/runtime.json"))
15
+
16
+
17
+ def plugin_loaded():
18
+ register_plugin(LoadwisePlugin)
19
+
20
+
21
+ def plugin_unloaded():
22
+ unregister_plugin(LoadwisePlugin)