loadwise 0.6.2 → 0.8.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.
- package/README.md +175 -115
- package/dist/bin/loadwise.js +132 -67
- package/dist/lib/accessibility/analyze.js +5 -3
- package/dist/lib/accessibility/angular-inline.js +9 -11
- package/dist/lib/accessibility/angular-literal.js +39 -0
- package/dist/lib/accessibility/form-context.js +36 -0
- package/dist/lib/accessibility/frame-head.js +92 -0
- package/dist/lib/accessibility/frame-viewport.js +149 -0
- package/dist/lib/accessibility/frontend-detect.js +6 -5
- package/dist/lib/accessibility/jsx-elements.js +13 -3
- package/dist/lib/accessibility/markup-files.js +7 -2
- package/dist/lib/accessibility/rule-ids.js +3 -0
- package/dist/lib/accessibility/rules.js +128 -41
- package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
- package/dist/lib/accessibility/template-attributes.js +5 -3
- package/dist/lib/accessibility/template-elements.js +25 -6
- package/dist/lib/accessibility/template-file.js +40 -25
- package/dist/lib/accessibility/usage.js +10 -2
- package/dist/lib/editor/accessibility-examples.js +6 -1
- package/dist/lib/editor/actions.js +46 -7
- package/dist/lib/editor/apply-fix.js +69 -4
- package/dist/lib/editor/configured-setup.js +63 -0
- package/dist/lib/editor/diagnostics.js +206 -17
- package/dist/lib/editor/dismissals.js +85 -26
- package/dist/lib/editor/editor-document.js +5 -2
- package/dist/lib/editor/editor-launcher.js +170 -0
- package/dist/lib/editor/fix-edits.js +19 -0
- package/dist/lib/editor/jetbrains-setup.js +53 -0
- package/dist/lib/editor/language-server.js +80 -24
- package/dist/lib/editor/managed-config.js +37 -0
- package/dist/lib/editor/native-setup.js +86 -0
- package/dist/lib/editor/perf-watch.js +8 -6
- package/dist/lib/editor/release-vsix.js +61 -0
- package/dist/lib/editor/reliability-examples.js +15 -0
- package/dist/lib/editor/scan-session.js +29 -8
- package/dist/lib/editor/server-commands.js +38 -9
- package/dist/lib/editor/setup-server.js +87 -0
- package/dist/lib/editor/setup-vim.js +63 -0
- package/dist/lib/editor/setup.js +131 -0
- package/dist/lib/editor/stdio-setup.js +6 -0
- package/dist/lib/editor/workspace-files.js +61 -7
- package/dist/lib/editor/workspace-paths.js +41 -1
- package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
- package/dist/lib/maintainability/architecture/architecture.js +4 -4
- package/dist/lib/maintainability/cli/changed-lines.js +20 -2
- package/dist/lib/maintainability/cli/inputs.js +12 -3
- package/dist/lib/maintainability/cli.js +18 -5
- package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
- package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
- package/dist/lib/maintainability/examples.js +4 -0
- package/dist/lib/maintainability/quality/functions.js +9 -6
- package/dist/lib/maintainability/quality/limits.js +19 -0
- package/dist/lib/maintainability/quality/size-limits.js +8 -2
- package/dist/lib/maintainability/quality/stray-console.js +62 -1
- package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
- package/dist/lib/maintainability/rule-ids.js +3 -0
- package/dist/lib/maintainability/scan-changed.js +4 -1
- package/dist/lib/maintainability/scan-worker.js +6 -2
- package/dist/lib/maintainability/scan.js +21 -8
- package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
- package/dist/lib/maintainability/unused/module-usage.js +43 -21
- package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
- package/dist/lib/maintainability/unused/unused-modules.js +5 -10
- package/dist/lib/performance/analysis/source-inputs.js +7 -2
- package/dist/lib/performance/analysis/source-options.js +7 -6
- package/dist/lib/performance/analyze.js +16 -3
- package/dist/lib/performance/cli/changed-lines.js +8 -1
- package/dist/lib/performance/cli/cli-arguments.js +19 -8
- package/dist/lib/performance/cli/cli-output.js +4 -0
- package/dist/lib/performance/cli/cli-scan.js +21 -2
- package/dist/lib/performance/cli.js +16 -7
- package/dist/lib/performance/collections/memory-growth.js +55 -12
- package/dist/lib/performance/contracts/openapi.js +13 -4
- package/dist/lib/performance/datastores/pg-integrity.js +68 -22
- package/dist/lib/performance/datastores/pg-session-release.js +114 -0
- package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
- package/dist/lib/performance/datastores/pooling.js +62 -3
- package/dist/lib/performance/datastores/redis.js +94 -18
- package/dist/lib/performance/datastores/session-store.js +2 -1
- package/dist/lib/performance/db/checks.js +19 -8
- package/dist/lib/performance/db/gateway.js +3 -1
- package/dist/lib/performance/db/plan-estimates.js +4 -4
- package/dist/lib/performance/engine/native-syntax.js +3 -0
- package/dist/lib/performance/engine/native.js +11 -7
- package/dist/lib/performance/evidence/plans.js +7 -5
- package/dist/lib/performance/evidence/traces.js +21 -1
- package/dist/lib/performance/frontend/angular-teardown.js +96 -0
- package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
- package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
- package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
- package/dist/lib/performance/frontend/frontend-perf.js +149 -74
- package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
- package/dist/lib/performance/migrations/extract-code.js +13 -5
- package/dist/lib/performance/migrations/extract-sql.js +82 -38
- package/dist/lib/performance/migrations/operations.js +56 -13
- package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
- package/dist/lib/performance/migrations/postgres-registry.js +127 -26
- package/dist/lib/performance/migrations/postgres-settings.js +78 -0
- package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
- package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
- package/dist/lib/performance/migrations/rules-postgres.js +88 -39
- package/dist/lib/performance/orm/offset-pagination.js +6 -4
- package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
- package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
- package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
- package/dist/lib/performance/polyglot.js +111 -14
- package/dist/lib/performance/projects.js +3 -3
- package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
- package/dist/lib/performance/request/backend-mastery.js +151 -42
- package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
- package/dist/lib/performance/request/fastify-receivers.js +93 -0
- package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
- package/dist/lib/performance/request/mongoose-lean.js +298 -46
- package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
- package/dist/lib/performance/request/phase5-ast.js +6 -7
- package/dist/lib/performance/request/phase5-rules.js +204 -23
- package/dist/lib/performance/request/request-handlers.js +120 -23
- package/dist/lib/performance/request/sql-select-star.js +150 -0
- package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
- package/dist/lib/performance/request/upload-limits.js +5 -1
- package/dist/lib/performance/site-fix.js +4 -4
- package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
- package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
- package/dist/lib/performance/site-fixes/collections.js +1 -2
- package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
- package/dist/lib/performance/site-fixes/helpers.js +3 -4
- package/dist/lib/performance/site-fixes/integrity.js +2 -4
- package/dist/lib/performance/site-fixes/migration-context.js +8 -1
- package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
- package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
- package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
- package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
- package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
- package/dist/lib/performance/sql/mysql-tokens.js +38 -12
- package/dist/lib/reliability/boundary-access.js +114 -57
- package/dist/lib/reliability/react-bugs.js +29 -7
- package/dist/lib/reliability/resource-leak-intervals.js +258 -0
- package/dist/lib/reliability/resource-leaks.js +209 -195
- package/dist/lib/reliability/rule-ids.js +10 -1
- package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
- package/dist/lib/reliability/swallowed-errors.js +107 -21
- package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
- package/dist/lib/reliability/usage.js +16 -5
- package/dist/lib/reliability/walk.js +3 -2
- package/dist/lib/security/auth-crypto/hashing.js +24 -8
- package/dist/lib/security/auth-crypto/jwt.js +21 -6
- package/dist/lib/security/auth-crypto/secrets.js +44 -1
- package/dist/lib/security/auth-crypto/shared.js +3 -1
- package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
- package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
- package/dist/lib/security/cli.js +21 -6
- package/dist/lib/security/cookie-credentials.js +115 -0
- package/dist/lib/security/cookie-csrf.js +241 -0
- package/dist/lib/security/deps/advisory.js +50 -109
- package/dist/lib/security/deps/cli.js +1 -1
- package/dist/lib/security/deps/cvss-score.js +14 -0
- package/dist/lib/security/deps/fixed-version.js +97 -0
- package/dist/lib/security/deps/lockfiles.js +135 -74
- package/dist/lib/security/deps/osv.js +11 -3
- package/dist/lib/security/deps/scan.js +47 -20
- package/dist/lib/security/deps/yarn-lock.js +158 -0
- package/dist/lib/security/examples/injection.cjs +4 -0
- package/dist/lib/security/exposure/cookies.js +17 -2
- package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
- package/dist/lib/security/exposure/frontend-security.js +21 -14
- package/dist/lib/security/exposure/jsx-url.js +18 -33
- package/dist/lib/security/exposure/logging.js +49 -10
- package/dist/lib/security/exposure/prototype-pollution.js +126 -56
- package/dist/lib/security/exposure/react-html.js +26 -0
- package/dist/lib/security/exposure/reflected-xss.js +34 -5
- package/dist/lib/security/files/compose.js +126 -1
- package/dist/lib/security/files/dockerfile.js +62 -4
- package/dist/lib/security/files/index.js +1 -1
- package/dist/lib/security/injection/command.js +46 -18
- package/dist/lib/security/injection/index.js +2 -0
- package/dist/lib/security/injection/ldap.js +86 -0
- package/dist/lib/security/injection/nosql.js +28 -4
- package/dist/lib/security/injection/redos.js +1 -1
- package/dist/lib/security/injection/rule-ids.js +1 -0
- package/dist/lib/security/injection/shared.js +5 -1
- package/dist/lib/security/injection/sql.js +28 -13
- package/dist/lib/security/lexical-declaration.js +113 -0
- package/dist/lib/security/pg-dynamic-query.js +28 -1
- package/dist/lib/security/pg-identifier-guards.js +107 -3
- package/dist/lib/security/phase5-rules.js +26 -135
- package/dist/lib/security/polyglot.js +2 -2
- package/dist/lib/security/redirect-settings.js +98 -0
- package/dist/lib/security/request-forgery/open-redirect.js +18 -5
- package/dist/lib/security/request-forgery/path-traversal.js +84 -6
- package/dist/lib/security/request-forgery/shared.js +1 -7
- package/dist/lib/security/request-forgery/ssrf.js +176 -14
- package/dist/lib/security/rule-descriptions.js +5 -1
- package/dist/lib/security/rule-ids.js +7 -0
- package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
- package/dist/lib/security/site-fixes/exposure.js +21 -3
- package/dist/lib/security/site-fixes/files.js +11 -13
- package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
- package/dist/lib/security/site-fixes/injection.js +17 -4
- package/dist/lib/security/site-fixes/jwt.js +1 -20
- package/dist/lib/security/site-fixes/request-forgery.js +37 -29
- package/dist/lib/security/taint/binding-inputs.js +236 -0
- package/dist/lib/security/taint/filename-guard.js +45 -45
- package/dist/lib/security/taint/guards.js +14 -8
- package/dist/lib/security/taint/index.js +126 -154
- package/dist/lib/security/taint/propagate.js +43 -9
- package/dist/lib/security/taint/record-writes.js +161 -0
- package/dist/lib/security/taint/resolution-cache.js +13 -7
- package/dist/lib/security/taint/sanitizers.js +89 -5
- package/dist/lib/security/taint/trace-nodes.js +61 -0
- package/dist/lib/security/taint/validators.js +89 -9
- package/dist/lib/shared/agent/agent-init.js +28 -5
- package/dist/lib/shared/agent/agent-prompt.js +74 -0
- package/dist/lib/shared/agent/agent-session.js +6 -1
- package/dist/lib/shared/agent/agent-verify.js +58 -11
- package/dist/lib/shared/agent/git-hook.js +17 -6
- package/dist/lib/shared/agent/review-delivery.js +1 -1
- package/dist/lib/shared/agent/review-mcp.js +8 -2
- package/dist/lib/shared/analysis/ast-semantics.js +2 -2
- package/dist/lib/shared/analysis/scan-cache.js +99 -14
- package/dist/lib/shared/check.js +172 -20
- package/dist/lib/shared/cli-dispatch.js +17 -0
- package/dist/lib/shared/config.js +27 -10
- package/dist/lib/shared/explain.js +1 -1
- package/dist/lib/shared/fix/fix-convergence.js +19 -31
- package/dist/lib/shared/fix/fix-handoff.js +16 -11
- package/dist/lib/shared/fix/fix-imports.js +4 -162
- package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
- package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
- package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
- package/dist/lib/shared/fix/fix-presentation.js +9 -6
- package/dist/lib/shared/fix/fix-safety.js +32 -1
- package/dist/lib/shared/fix/fix-scope.js +82 -0
- package/dist/lib/shared/fix/fix-terminal.js +28 -1
- package/dist/lib/shared/fix/fix-typecheck.js +8 -4
- package/dist/lib/shared/fix/import-text-edits.js +148 -0
- package/dist/lib/shared/fix/project-file-access.js +17 -26
- package/dist/lib/shared/fix/read-fix-text.js +20 -0
- package/dist/lib/shared/fix.js +241 -104
- package/dist/lib/shared/formats/finding-location.js +4 -1
- package/dist/lib/shared/formats/github.js +3 -3
- package/dist/lib/shared/formats/sarif.js +9 -3
- package/dist/lib/shared/report-fp.js +97 -0
- package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
- package/dist/lib/shared/reporting/baseline.js +7 -5
- package/dist/lib/shared/reporting/check-text.js +50 -0
- package/dist/lib/shared/reporting/pillars.js +54 -19
- package/dist/lib/shared/reporting/source-report.js +3 -0
- package/dist/lib/shared/system/atomic-write.js +5 -2
- package/dist/lib/shared/system/glob.js +34 -8
- package/dist/lib/shared/system/sentry.js +222 -0
- package/dist/lib/shared/system/shell-argument.js +5 -1
- package/dist/lib/shared/system/terminal-safe.js +3 -2
- package/dist/lib/shared/system/terminal-style.js +131 -0
- package/dist/lib/shared/workspaces.js +15 -3
- package/docs/assets/cli-workflow.gif +0 -0
- package/integrations/sublime/plugin.py +22 -0
- package/integrations/zed/Cargo.lock +845 -0
- package/integrations/zed/Cargo.toml +11 -0
- package/integrations/zed/extension.toml +11 -0
- package/integrations/zed/src/lib.rs +25 -0
- package/package.json +15 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/loadwise.md +11 -6
- package/plugin/hooks/check-edited-file.mjs +27 -5
- package/polyglot/performance/rules/csharp.yml +34 -5
- package/polyglot/performance/rules/java.yml +24 -1
- package/polyglot/performance/rules/python.yml +74 -2
- package/polyglot/performance/sgconfig.yml +1 -0
- package/polyglot/reliability/rules/csharp.yml +12 -6
- package/polyglot/reliability/rules/go.yml +86 -6
- package/polyglot/reliability/rules/java.yml +22 -1
- package/polyglot/reliability/sgconfig.yml +1 -0
- package/polyglot/security/rules/go.yml +100 -22
- package/polyglot/security/rules/python.yml +74 -6
- package/polyglot/security/rules/rust.yml +65 -0
- package/polyglot/security/sgconfig.yml +1 -0
- package/schema/loadwise.config.schema.json +556 -76
- /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const automaticFixSignal = 'loadwise:automatic-fixes-available';
|
|
2
|
+
const collectFixSignals = 'LOADWISE_INTERNAL_COLLECT_FIX_SIGNALS';
|
|
3
|
+
function reportAutomaticFixes(findings) {
|
|
4
|
+
if (!process.send || !process.connected || process.env[collectFixSignals] !== '1')
|
|
5
|
+
return;
|
|
6
|
+
if (findings.some(({ fix }) => fix?.changes.length && !fix.requiresReview)) {
|
|
7
|
+
process.send(automaticFixSignal, undefined, undefined, () => undefined);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export { automaticFixSignal, collectFixSignals, reportAutomaticFixes };
|
|
@@ -130,14 +130,16 @@ function createOutsideScan(baselineFile, pillar, scope, projectRoot) {
|
|
|
130
130
|
// Replaces one pillar's section and keeps the others, so pillars can be baselined one at a time.
|
|
131
131
|
// Entries outside a partial scan's scope are kept, so baselining one workspace or rule set leaves
|
|
132
132
|
// the rest recorded.
|
|
133
|
-
function writePillarBaseline(baselineFile, pillar, findings, findingKeys, isOutsideScan) {
|
|
133
|
+
function writePillarBaseline(baselineFile, pillar, findings, findingKeys, { isOutsideScan, skippedFiles }) {
|
|
134
|
+
const document = readDocument(baselineFile);
|
|
135
|
+
if (document && skippedFiles.length && (document.pillars[pillar] || recordedEntries(document, pillar).length))
|
|
136
|
+
throw new Error(`Cannot refresh the ${pillar} baseline because the scan skipped ${skippedFiles[0].file}. Resolve skipped files and retry.`);
|
|
134
137
|
const counts = new Map();
|
|
135
138
|
for (const { key } of findingKeys(findings)) {
|
|
136
139
|
const entry = counts.get(keyText(key)) ?? { ...key, count: 0 };
|
|
137
140
|
entry.count++;
|
|
138
141
|
counts.set(keyText(key), entry);
|
|
139
142
|
}
|
|
140
|
-
const document = readDocument(baselineFile);
|
|
141
143
|
for (const entry of document?.pillars[pillar]?.findings ?? []) {
|
|
142
144
|
if (isOutsideScan(entry) && !counts.has(keyText(entry)))
|
|
143
145
|
counts.set(keyText(entry), entry);
|
|
@@ -195,7 +197,7 @@ function filterPillarBaseline(baselineFile, pillar, findings, findingKeys, parti
|
|
|
195
197
|
// Returns undefined without baseline flags, { written, file } after --write-baseline, or the
|
|
196
198
|
// filtered result.
|
|
197
199
|
// `idRoot` is the folder the finding ids were computed against.
|
|
198
|
-
function applyBaselineOptions({ options, pillar, findings, projectRoot, absoluteFileOf, idRoot, }) {
|
|
200
|
+
function applyBaselineOptions({ options, pillar, findings, skippedFiles = [], projectRoot, absoluteFileOf, idRoot, }) {
|
|
199
201
|
if (options.baseline && options.writeBaseline)
|
|
200
202
|
throw new Error('Choose either --baseline or --write-baseline.');
|
|
201
203
|
const option = options.writeBaseline ?? options.baseline;
|
|
@@ -205,9 +207,9 @@ function applyBaselineOptions({ options, pillar, findings, projectRoot, absolute
|
|
|
205
207
|
const findingKeys = createFindingKeys(file, absoluteFileOf, idRoot);
|
|
206
208
|
if (options.writeBaseline) {
|
|
207
209
|
const isOutsideScan = createOutsideScan(file, pillar, options.scope, projectRoot);
|
|
208
|
-
return { written: writePillarBaseline(file, pillar, findings, findingKeys, isOutsideScan), file };
|
|
210
|
+
return { written: writePillarBaseline(file, pillar, findings, findingKeys, { isOutsideScan, skippedFiles }), file };
|
|
209
211
|
}
|
|
210
|
-
const partialScan = options.partialScan || limitedToPaths(file, options.scope);
|
|
212
|
+
const partialScan = options.partialScan || skippedFiles.length > 0 || limitedToPaths(file, options.scope);
|
|
211
213
|
return filterPillarBaseline(file, pillar, findings, findingKeys, partialScan);
|
|
212
214
|
}
|
|
213
215
|
// `scannedPaths` are the absolute files or folders the scan was limited to, if any.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { wrapWords } from '../fix/fix-terminal.js';
|
|
2
|
+
const findingLine = /^((?:\S.*:\d+(?::\d+)? )?\[[a-z][a-z0-9-]*(?: #[0-9a-f-]+)?\] (?:critical|high|medium|low)): (.*)$/;
|
|
3
|
+
const groupedCount = /^(.*) \((\d+ findings)\)$/;
|
|
4
|
+
const packageHeading = /^-- .+ --$/;
|
|
5
|
+
const summaryLine = /^\d+ (?:(?:source |graph )?file\(s\)(?: checked| compared)?, \d+ |(?:new |contextual )?finding\(s\) )/;
|
|
6
|
+
const countedWord = /(\d+) ((?:(?:source|graph|new|contextual|contract|breaking) )?(?:file|finding|change))\(s\)/g;
|
|
7
|
+
const singleWarning = '1 finding(s) are warnings and do not affect the exit code.';
|
|
8
|
+
const explanationLabel = ' Why: ';
|
|
9
|
+
const maximumWidth = 100;
|
|
10
|
+
function explainLines(message, columns) {
|
|
11
|
+
const width = Math.max(1, Math.min(columns, maximumWidth) - explanationLabel.length);
|
|
12
|
+
const hangingIndent = ' '.repeat(explanationLabel.length);
|
|
13
|
+
return wrapWords(message, width).map((line, index) => (index ? hangingIndent : explanationLabel) + line);
|
|
14
|
+
}
|
|
15
|
+
/** Lay out the combined report while passing through checker-specific details and commands. */
|
|
16
|
+
function formatCheckText(text, columns = process.stdout.columns || maximumWidth) {
|
|
17
|
+
const lines = [];
|
|
18
|
+
let reportedFindings = false;
|
|
19
|
+
for (const line of text.split('\n')) {
|
|
20
|
+
const finding = findingLine.exec(line);
|
|
21
|
+
if (finding) {
|
|
22
|
+
if (reportedFindings && lines.at(-1))
|
|
23
|
+
lines.push('');
|
|
24
|
+
const [, heading, explanation] = finding;
|
|
25
|
+
const group = heading.startsWith('[') ? groupedCount.exec(explanation) : null;
|
|
26
|
+
lines.push(group ? `${heading} (${group[2]})` : heading);
|
|
27
|
+
lines.push(...explainLines(group ? group[1] : explanation, columns));
|
|
28
|
+
reportedFindings = true;
|
|
29
|
+
}
|
|
30
|
+
else if (packageHeading.test(line)) {
|
|
31
|
+
if (lines.at(-1))
|
|
32
|
+
lines.push('');
|
|
33
|
+
lines.push(line);
|
|
34
|
+
reportedFindings = false;
|
|
35
|
+
}
|
|
36
|
+
else if (summaryLine.test(line)) {
|
|
37
|
+
if (reportedFindings && lines.at(-1))
|
|
38
|
+
lines.push('');
|
|
39
|
+
lines.push(line === singleWarning
|
|
40
|
+
? '1 finding is a warning and does not affect the exit code.'
|
|
41
|
+
: line.replaceAll(countedWord, (_match, count, word) => `${count} ${word}${count === '1' ? '' : 's'}`));
|
|
42
|
+
reportedFindings = false;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
lines.push(line);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return lines.join('\n');
|
|
49
|
+
}
|
|
50
|
+
export { formatCheckText };
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// The checkers `loadwise check` can run, in report order. Each runs as a child process of the loadwise CLI, so it keeps
|
|
2
2
|
// its own process-wide state and output. A new checker registers by adding one entry here.
|
|
3
|
-
import path from 'node:path';
|
|
4
3
|
import { spawn } from 'node:child_process';
|
|
4
|
+
import { packagePath } from '../package-root.js';
|
|
5
5
|
import { allowedHeapMegabytes, childHeapFlags, isHeapExhaustion } from '../system/heap-limit.js';
|
|
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';
|
|
@@ -28,7 +29,7 @@ function titleList(names) {
|
|
|
28
29
|
const titles = names.map((name) => pillars.find((pillar) => pillar.name === name)?.title.toLowerCase() ?? name);
|
|
29
30
|
return titles.length < 2 ? titles.join('') : `${titles.slice(0, -1).join(', ')} and ${titles[titles.length - 1]}`;
|
|
30
31
|
}
|
|
31
|
-
const cli =
|
|
32
|
+
const cli = packagePath('dist/bin/loadwise.js');
|
|
32
33
|
const invalidInputCode = 2;
|
|
33
34
|
// An unchanged project replays the stored report; see scan-cache.cjs for what invalidates it.
|
|
34
35
|
function runChecker(args, cwd = process.cwd()) {
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
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({
|
|
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
|
-
|
|
152
|
-
|
|
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(
|
|
273
|
+
const names = new Set();
|
|
274
|
+
for (const selector of list
|
|
252
275
|
.split(',')
|
|
253
|
-
.map((
|
|
254
|
-
.filter(Boolean))
|
|
255
|
-
|
|
256
|
-
if (!
|
|
257
|
-
throw new Error(`Unknown ${flag} name "${
|
|
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
|
}
|
|
@@ -361,15 +385,26 @@ async function runSharedSourceCheck(shared, options) {
|
|
|
361
385
|
}
|
|
362
386
|
catch {
|
|
363
387
|
return {
|
|
364
|
-
reports: Object.fromEntries(
|
|
388
|
+
reports: Object.fromEntries(shared.map((pillar, index) => {
|
|
389
|
+
const base = index ? { ...failed, stderr: '' } : failed;
|
|
390
|
+
return [
|
|
391
|
+
pillar.jsonKey,
|
|
392
|
+
pillar.name === 'rel' ? mergeContractReport(base, contracts, contractOptions?.contractFlags) : base,
|
|
393
|
+
];
|
|
394
|
+
})),
|
|
365
395
|
};
|
|
366
396
|
}
|
|
367
|
-
// The child's warnings belong to the run once
|
|
397
|
+
// The child's warnings and combined fix signal belong to the run once.
|
|
368
398
|
const reports = shared.map((pillar, index) => {
|
|
369
399
|
const report = envelope[pillar.jsonKey];
|
|
370
400
|
if (!report)
|
|
371
401
|
return undefined;
|
|
372
|
-
const own = {
|
|
402
|
+
const own = {
|
|
403
|
+
code: report.code,
|
|
404
|
+
stdout: report.stdout,
|
|
405
|
+
stderr: index ? '' : run.stderr,
|
|
406
|
+
...(!index && run.hasAutomaticFixes && { hasAutomaticFixes: true }),
|
|
407
|
+
};
|
|
373
408
|
return pillar.name === 'rel' ? mergeContractReport(own, contracts, contractOptions?.contractFlags) : own;
|
|
374
409
|
});
|
|
375
410
|
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';
|
|
@@ -61,6 +62,7 @@ async function printResult(result, values, pillar, print = console.log) {
|
|
|
61
62
|
options: values.baselineOptions ?? {},
|
|
62
63
|
pillar: 'security',
|
|
63
64
|
findings: result.findings,
|
|
65
|
+
skippedFiles: result.skippedFiles,
|
|
64
66
|
projectRoot: values.projectDirectory,
|
|
65
67
|
absoluteFileOf: (finding) => path.resolve(finding.file ?? ''),
|
|
66
68
|
idRoot,
|
|
@@ -108,6 +110,7 @@ function printSourceReport(result, values, baseline, format, print) {
|
|
|
108
110
|
else
|
|
109
111
|
printTextSummary(result, values, terminalPrinter(print));
|
|
110
112
|
if (format === 'text') {
|
|
113
|
+
reportAutomaticFixes(result.findings);
|
|
111
114
|
if (baseline)
|
|
112
115
|
for (const line of baselineNoteLines(baseline))
|
|
113
116
|
print(line);
|
|
@@ -24,8 +24,11 @@ function retryTransientErrors(operation) {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
function renameWithRetry(from, to) {
|
|
28
|
-
retryTransientErrors(() =>
|
|
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) {
|
|
@@ -1,9 +1,35 @@
|
|
|
1
1
|
// One glob dialect for every loadwise pattern (config ignore and overrides, workspace package lists): `*` matches
|
|
2
2
|
// within a folder, `**` any depth, `?` one character and `{a,b}` alternatives.
|
|
3
|
+
const MAX_BRACE_DEPTH = 8;
|
|
4
|
+
// Maps each opening brace that has a closing brace to whether it is a real alternation group. Braces nested
|
|
5
|
+
// deeper than MAX_BRACE_DEPTH stay paired but literal, so their commas and closers never alter an outer group.
|
|
6
|
+
function pairBraces(pattern) {
|
|
7
|
+
const closeOfOpen = new Map();
|
|
8
|
+
const openIndexes = [];
|
|
9
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
10
|
+
if (pattern[index] === '{')
|
|
11
|
+
openIndexes.push(index);
|
|
12
|
+
else if (pattern[index] === '}' && openIndexes.length)
|
|
13
|
+
closeOfOpen.set(openIndexes.pop() ?? index, index);
|
|
14
|
+
}
|
|
15
|
+
// Unmatched openings stay literal and must not count toward the nesting depth of real pairs.
|
|
16
|
+
const pairs = new Map();
|
|
17
|
+
const pairedCloses = [];
|
|
18
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
19
|
+
if (closeOfOpen.has(index)) {
|
|
20
|
+
pairs.set(index, pairedCloses.length < MAX_BRACE_DEPTH);
|
|
21
|
+
pairedCloses.push(closeOfOpen.get(index) ?? index);
|
|
22
|
+
}
|
|
23
|
+
else if (pairedCloses.at(-1) === index)
|
|
24
|
+
pairedCloses.pop();
|
|
25
|
+
}
|
|
26
|
+
return pairs;
|
|
27
|
+
}
|
|
3
28
|
function globSource(rawPattern) {
|
|
4
29
|
const pattern = rawPattern.replaceAll(/(?:\*\*\/)+/g, '**/').replaceAll(/\*{3,}/g, '**');
|
|
5
30
|
let source = '';
|
|
6
|
-
|
|
31
|
+
const bracePairs = pairBraces(pattern);
|
|
32
|
+
const openBraceIsGroup = [];
|
|
7
33
|
for (let index = 0; index < pattern.length; index++) {
|
|
8
34
|
const character = pattern[index];
|
|
9
35
|
if (character === '*' && pattern[index + 1] === '*') {
|
|
@@ -15,15 +41,15 @@ function globSource(rawPattern) {
|
|
|
15
41
|
source += '[^/]*';
|
|
16
42
|
else if (character === '?')
|
|
17
43
|
source += '[^/]';
|
|
18
|
-
else if (character === '{' &&
|
|
19
|
-
|
|
20
|
-
|
|
44
|
+
else if (character === '{' && bracePairs.has(index)) {
|
|
45
|
+
const isGroup = bracePairs.get(index) === true;
|
|
46
|
+
openBraceIsGroup.push(isGroup);
|
|
47
|
+
source += isGroup ? '(?:' : String.raw `\{`;
|
|
21
48
|
}
|
|
22
|
-
else if (character === ',' &&
|
|
49
|
+
else if (character === ',' && openBraceIsGroup.at(-1))
|
|
23
50
|
source += '|';
|
|
24
|
-
else if (character === '}' &&
|
|
25
|
-
|
|
26
|
-
source += ')';
|
|
51
|
+
else if (character === '}' && openBraceIsGroup.length) {
|
|
52
|
+
source += openBraceIsGroup.pop() ? ')' : String.raw `\}`;
|
|
27
53
|
}
|
|
28
54
|
else
|
|
29
55
|
source += character.replaceAll(/[.+^$[\]\\(){}|]/g, '\\$&');
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// Opt-in Sentry crash reporting sends diagnostic metadata about Loadwise itself.
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import { errorMessage } from './error-code.js';
|
|
4
|
+
import { terminalSafe } from './terminal-safe.js';
|
|
5
|
+
import { isIP } from 'node:net';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { packageManifest, packageRoot } from '../package-root.js';
|
|
8
|
+
const SEND_TIMEOUT_MS = 3_000;
|
|
9
|
+
const DEFAULT_SENTRY_HOST = 'o4512506230603776.ingest.de.sentry.io';
|
|
10
|
+
const DEFAULT_SENTRY_PROJECT_ID = '4512506234273872';
|
|
11
|
+
// Public write-only client ingest key for loadwise-cli (EU); rate-limited via Sentry Spike Protection.
|
|
12
|
+
const DEFAULT_SENTRY_CLIENT_ID = '0230b9fb3fe7211d2f647690dd92f6c2';
|
|
13
|
+
const STACK_LOC_RE = /^(.*):(\d+):(\d+)$/;
|
|
14
|
+
const NORMALIZED_PACKAGE_ROOT = `${packageRoot.replaceAll('\\', '/').replace(/\/+$/, '')}/`;
|
|
15
|
+
const PACKAGE_FRAME_RE = /^(?:dist|lib|bin)\/(?:[\w-]+\/)*[\w.-]+\.[cm]?[jt]s$/;
|
|
16
|
+
const BUILT_IN_ERROR_NAMES = new Set([
|
|
17
|
+
'AggregateError',
|
|
18
|
+
'EvalError',
|
|
19
|
+
'RangeError',
|
|
20
|
+
'ReferenceError',
|
|
21
|
+
'SyntaxError',
|
|
22
|
+
'TypeError',
|
|
23
|
+
'URIError',
|
|
24
|
+
]);
|
|
25
|
+
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\.|Project directory ".*" (?:does not exist|is not a directory)\.|Workspace packages are missing|Trace file contains invalid JSON|The Sublime package link at .* has a missing target.|Initialize local review history|The (?:Performance|Reliability|Maintainability|Security|Accessibility) scan did not complete|.*\.findings contains a finding)/;
|
|
26
|
+
/**
|
|
27
|
+
* Parses a Sentry DSN into its Envelope endpoint URL and X-Sentry-Auth header.
|
|
28
|
+
* Returns null when the DSN is empty or malformed.
|
|
29
|
+
*/
|
|
30
|
+
function parseSentryDsn(dsn) {
|
|
31
|
+
const trimmed = dsn.trim();
|
|
32
|
+
if (!trimmed)
|
|
33
|
+
return null;
|
|
34
|
+
let url;
|
|
35
|
+
try {
|
|
36
|
+
url = new URL(trimmed);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const { hostname, protocol } = url;
|
|
42
|
+
const loopback = hostname === 'localhost' || hostname === '[::1]' || (isIP(hostname) === 4 && hostname.startsWith('127.'));
|
|
43
|
+
if ((protocol !== 'https:' && !(protocol === 'http:' && loopback)) || !url.username || !hostname)
|
|
44
|
+
return null;
|
|
45
|
+
const segments = url.pathname.split('/').filter(Boolean);
|
|
46
|
+
const projectId = segments.pop();
|
|
47
|
+
if (!projectId || !/^\d+$/.test(projectId))
|
|
48
|
+
return null;
|
|
49
|
+
const prefix = segments.length > 0 ? `/${segments.join('/')}` : '';
|
|
50
|
+
return {
|
|
51
|
+
envelopeUrl: `${url.protocol}//${url.host}${prefix}/api/${projectId}/envelope/`,
|
|
52
|
+
authHeader: `Sentry sentry_version=7, sentry_client=loadwise/${packageManifest.version}, sentry_key=${url.username}`,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
class CliUsageError extends Error {
|
|
56
|
+
constructor(message) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = 'CliUsageError';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Returns true for expected CLI usage, flag, or input validation errors that should not page Sentry.
|
|
63
|
+
*/
|
|
64
|
+
function isExpectedCliError(error) {
|
|
65
|
+
if (error instanceof CliUsageError)
|
|
66
|
+
return true;
|
|
67
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
68
|
+
return EXPECTED_CLI_ERROR_RE.test(message.trim());
|
|
69
|
+
}
|
|
70
|
+
function normalizeLocationPath(raw) {
|
|
71
|
+
let candidate = raw.trim();
|
|
72
|
+
if (candidate.startsWith('file://')) {
|
|
73
|
+
try {
|
|
74
|
+
candidate = fileURLToPath(candidate);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return candidate;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return candidate.replaceAll('\\', '/');
|
|
81
|
+
}
|
|
82
|
+
function parseFrame(line) {
|
|
83
|
+
const trimmed = line.trim();
|
|
84
|
+
if (!trimmed.startsWith('at '))
|
|
85
|
+
return null;
|
|
86
|
+
const body = trimmed.slice(3);
|
|
87
|
+
const parenIndex = body.indexOf(' (');
|
|
88
|
+
const rawLocation = parenIndex === -1 ? body : body.slice(parenIndex + 2, body.endsWith(')') ? -1 : undefined);
|
|
89
|
+
const locMatch = STACK_LOC_RE.exec(rawLocation);
|
|
90
|
+
if (!locMatch)
|
|
91
|
+
return null;
|
|
92
|
+
const normalized = normalizeLocationPath(locMatch[1]);
|
|
93
|
+
const rootMatch = process.platform === 'win32'
|
|
94
|
+
? normalized.toLowerCase().startsWith(NORMALIZED_PACKAGE_ROOT.toLowerCase())
|
|
95
|
+
: normalized.startsWith(NORMALIZED_PACKAGE_ROOT);
|
|
96
|
+
if (!rootMatch)
|
|
97
|
+
return null;
|
|
98
|
+
const relative = normalized.slice(NORMALIZED_PACKAGE_ROOT.length);
|
|
99
|
+
if (!PACKAGE_FRAME_RE.test(relative))
|
|
100
|
+
return null;
|
|
101
|
+
return {
|
|
102
|
+
filename: relative,
|
|
103
|
+
abs_path: 'app:///' + relative,
|
|
104
|
+
in_app: true,
|
|
105
|
+
lineno: Number(locMatch[2]),
|
|
106
|
+
colno: Number(locMatch[3]),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Keeps only package-relative Loadwise locations and drops arbitrary stack labels.
|
|
111
|
+
*/
|
|
112
|
+
function sanitizeStack(stack) {
|
|
113
|
+
if (!stack)
|
|
114
|
+
return [];
|
|
115
|
+
const frames = [];
|
|
116
|
+
for (const line of stack.split(/\r?\n/)) {
|
|
117
|
+
const frame = parseFrame(line);
|
|
118
|
+
if (frame)
|
|
119
|
+
frames.push(frame);
|
|
120
|
+
}
|
|
121
|
+
// Sentry expects stack frames ordered oldest-to-newest.
|
|
122
|
+
return frames.reverse();
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Builds a 3-line Sentry Envelope without free-form exception data.
|
|
126
|
+
*/
|
|
127
|
+
function buildEnvelope(error, command, version, options = {}) {
|
|
128
|
+
const eventId = options.eventId ?? crypto.randomUUID().replaceAll('-', '');
|
|
129
|
+
const sentAt = new Date().toISOString();
|
|
130
|
+
const errorName = error instanceof Error ? error.name : 'Error';
|
|
131
|
+
const type = BUILT_IN_ERROR_NAMES.has(errorName) ? errorName : 'Error';
|
|
132
|
+
const frames = error instanceof Error ? sanitizeStack(error.stack) : [];
|
|
133
|
+
const header = JSON.stringify({ event_id: eventId, sent_at: sentAt });
|
|
134
|
+
const itemHeader = JSON.stringify({ type: 'event' });
|
|
135
|
+
const payload = JSON.stringify({
|
|
136
|
+
event_id: eventId,
|
|
137
|
+
timestamp: sentAt,
|
|
138
|
+
platform: 'node',
|
|
139
|
+
level: 'error',
|
|
140
|
+
release: `loadwise@${version}`,
|
|
141
|
+
environment: options.environment ?? (process.env.CI ? 'ci' : 'local'),
|
|
142
|
+
tags: {
|
|
143
|
+
command: command || 'check',
|
|
144
|
+
node: process.version,
|
|
145
|
+
platform: process.platform,
|
|
146
|
+
},
|
|
147
|
+
exception: {
|
|
148
|
+
values: [
|
|
149
|
+
{
|
|
150
|
+
type,
|
|
151
|
+
value: 'Unexpected Loadwise error',
|
|
152
|
+
...(frames.length > 0 ? { stacktrace: { frames } } : {}),
|
|
153
|
+
},
|
|
154
|
+
],
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
return `${header}\n${itemHeader}\n${payload}\n`;
|
|
158
|
+
}
|
|
159
|
+
function resolveCrashReportTarget(options = {}) {
|
|
160
|
+
const env = options.env ?? process.env;
|
|
161
|
+
if (!options.env && env.NODE_TEST_CONTEXT)
|
|
162
|
+
return null;
|
|
163
|
+
if (env.LOADWISE_SENTRY_DSN)
|
|
164
|
+
return parseSentryDsn(env.LOADWISE_SENTRY_DSN);
|
|
165
|
+
const envEnabled = env.LOADWISE_CRASH_REPORTS === '1' || env.LOADWISE_CRASH_REPORTS === 'true';
|
|
166
|
+
if (!options.flagEnabled && !envEnabled)
|
|
167
|
+
return null;
|
|
168
|
+
return {
|
|
169
|
+
envelopeUrl: `https://${DEFAULT_SENTRY_HOST}/api/${DEFAULT_SENTRY_PROJECT_ID}/envelope/`,
|
|
170
|
+
authHeader: `Sentry sentry_version=7, sentry_client=loadwise/${packageManifest.version}, sentry_key=${DEFAULT_SENTRY_CLIENT_ID}`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Sends a sanitized crash envelope when crash reporting is enabled. Never throws or blocks exit.
|
|
175
|
+
*/
|
|
176
|
+
async function reportCrash(error, command, dsnOrTarget = resolveCrashReportTarget() ?? undefined) {
|
|
177
|
+
if (!dsnOrTarget)
|
|
178
|
+
return false;
|
|
179
|
+
const parsed = typeof dsnOrTarget === 'string' ? parseSentryDsn(dsnOrTarget) : dsnOrTarget;
|
|
180
|
+
if (!parsed)
|
|
181
|
+
return false;
|
|
182
|
+
try {
|
|
183
|
+
const body = buildEnvelope(error, command, packageManifest.version);
|
|
184
|
+
const response = await fetch(parsed.envelopeUrl, {
|
|
185
|
+
method: 'POST',
|
|
186
|
+
redirect: 'error',
|
|
187
|
+
headers: {
|
|
188
|
+
'Content-Type': 'application/x-sentry-envelope',
|
|
189
|
+
'X-Sentry-Auth': parsed.authHeader,
|
|
190
|
+
},
|
|
191
|
+
body,
|
|
192
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
193
|
+
});
|
|
194
|
+
return response.ok;
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** Formats a thrown value for stderr; unprintable values (e.g. Object.create(null)) must not stop the exit-2 path. */
|
|
201
|
+
function describeCrash(error) {
|
|
202
|
+
try {
|
|
203
|
+
return terminalSafe(errorMessage(error));
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return 'unprintable error value';
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Installs uncaughtException / unhandledRejection listeners when crash reporting is enabled.
|
|
211
|
+
*/
|
|
212
|
+
function installGlobalCrashHandlers(command, target = resolveCrashReportTarget()) {
|
|
213
|
+
if (!target)
|
|
214
|
+
return;
|
|
215
|
+
const handleCrash = (error) => {
|
|
216
|
+
console.error('Unexpected Loadwise error: ' + describeCrash(error));
|
|
217
|
+
void reportCrash(error, command, target).finally(() => process.exit(2));
|
|
218
|
+
};
|
|
219
|
+
process.once('uncaughtException', handleCrash);
|
|
220
|
+
process.once('unhandledRejection', handleCrash);
|
|
221
|
+
}
|
|
222
|
+
export { CliUsageError, 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
|
-
|
|
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 };
|