loadwise 0.7.0 → 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.
Files changed (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -322,7 +322,7 @@ function collectEdges(sourceFile, file, resolve, compilerOptions = {}) {
322
322
  }
323
323
  if (ts.isExportDeclaration(node))
324
324
  return;
325
- collectDecoratorMetadataUses(compilerOptions, node, metadataUsed);
325
+ collectDecoratorMetadataUses(compilerOptions, node, deferred ? deferredUsed : metadataUsed);
326
326
  if (isClassBase(node)) {
327
327
  pushNode(node.expression, deferred);
328
328
  return;
@@ -363,15 +363,15 @@ function collectEdges(sourceFile, file, resolve, compilerOptions = {}) {
363
363
  if (!memberRead(node))
364
364
  nonMemberReads.add(node.text);
365
365
  }
366
- const read = (binding) => used.has(binding) || deferredUsed.has(binding);
366
+ const read = (binding) => used.has(binding) || deferredUsed.has(binding) || metadataUsed.has(binding);
367
367
  // A binding read only inside function bodies (for example a TypeORM entity callback) is not
368
368
  // evaluated while the module loads, so it cannot close a load-time cycle.
369
369
  for (const item of imports) {
370
370
  let kind;
371
- if (item.bindings.some((binding) => used.has(binding)))
371
+ if (item.bindings.some((binding) => used.has(binding) || metadataUsed.has(binding)))
372
372
  kind = 'eager';
373
373
  else if (item.bindings.some((binding) => deferredUsed.has(binding)))
374
- kind = item.bindings.some((binding) => metadataUsed.has(binding)) ? 'eager' : 'deferred';
374
+ kind = 'deferred';
375
375
  else
376
376
  continue;
377
377
  const constEnumNames = constEnumCandidates(item, read, nonMemberReads, compilerOptions);
@@ -4,7 +4,13 @@ import { spawnSync } from 'node:child_process';
4
4
  import { nonJsLanguages } from '../../../polyglot/maintainability/rules.js';
5
5
  import { unquoteGitPath } from '../../shared/system/git-paths.js';
6
6
  const sourceExtensions = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.cts', ...Object.keys(nonJsLanguages)];
7
- const sourcePathspecs = sourceExtensions.map((extension) => `:(icase)*${extension}`);
7
+ const sourcePathspecs = [
8
+ ...sourceExtensions.map((extension) => `:(icase)*${extension}`),
9
+ ':(icase)tsconfig*.json',
10
+ ':(icase)**/tsconfig*.json',
11
+ ':(icase)jsconfig*.json',
12
+ ':(icase)**/jsconfig*.json',
13
+ ];
8
14
  const declarationFile = /\.d\.[cm]?ts$/i;
9
15
  const hunkHeader = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
10
16
  const wholeFile = [[1, Infinity]];
@@ -43,7 +49,7 @@ function parseChangedRanges(diffText) {
43
49
  let inHeader = false;
44
50
  let addedFile = false;
45
51
  let currentFile;
46
- for (const line of diffText.split('\n')) {
52
+ for (const line of diffText.split(/\r?\n/)) {
47
53
  if (line.startsWith('diff --git ')) {
48
54
  inHeader = true;
49
55
  addedFile = false;
@@ -52,6 +58,12 @@ function parseChangedRanges(diffText) {
52
58
  else if (inHeader && line === '--- /dev/null') {
53
59
  addedFile = true;
54
60
  }
61
+ else if (inHeader && line.startsWith('rename to ')) {
62
+ // A pure rename has no new-side hunk. Preserve the path for file-level checks only.
63
+ const destination = unquoteGitPath(line.slice('rename to '.length));
64
+ if (destination && !changes.has(destination))
65
+ changes.set(destination, []);
66
+ }
55
67
  else if (inHeader && line.startsWith('+++ ')) {
56
68
  currentFile = newSidePath(line);
57
69
  if (currentFile && addedFile)
@@ -86,10 +98,16 @@ function readChangedRanges(root, { staged, since }) {
86
98
  const diffText = runGit(root, [
87
99
  '-c',
88
100
  'core.quotepath=false',
101
+ '-c',
102
+ 'diff.noprefix=false',
103
+ '-c',
104
+ 'diff.mnemonicPrefix=false',
89
105
  'diff',
90
106
  '-U0',
91
107
  '--no-color',
92
108
  '--no-ext-diff',
109
+ '--src-prefix=a/',
110
+ '--dst-prefix=b/',
93
111
  '--diff-filter=ACMR',
94
112
  '--relative',
95
113
  ...target,
@@ -219,7 +219,15 @@ function createResolver(root, fileSet, declarationFiles = []) {
219
219
  }
220
220
  const resolved = ts.resolveModuleName(specifier, filename, options, host, cache, undefined, mode).resolvedModule;
221
221
  if (resolved) {
222
- const local = indexed.get(canonical(path.resolve(resolved.resolvedFileName)));
222
+ let local = indexed.get(canonical(path.resolve(resolved.resolvedFileName)));
223
+ if (!local) {
224
+ try {
225
+ local = indexed.get(canonical(fs.realpathSync.native(resolved.resolvedFileName)));
226
+ }
227
+ catch {
228
+ // Missing symlink target stays unindexed.
229
+ }
230
+ }
223
231
  if (!local && /(?:^|[\\/])node_modules[\\/]/.test(resolved.resolvedFileName))
224
232
  outsideProject?.();
225
233
  return local;
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { configuredLimits } from './quality/limits.js';
3
4
  import { parseArgs } from 'node:util';
4
5
  import { exampleFor } from './examples.js';
5
6
  import { impactByRule } from './rule-ids.js';
@@ -185,6 +186,8 @@ async function scanProject(root, values, { changes, inScope }) {
185
186
  const { loadPolicy, checkImportedGraph } = await import('./project.js');
186
187
  const settings = loadSettings({ directory: root, explicit: values['loadwise-config'], ignore: values.ignore });
187
188
  const policy = loadPolicy(values.config, settings.maintainability);
189
+ if (settings.filename)
190
+ policy.limitsFor = configuredLimits(settings, root, policy.limits);
188
191
  // Ignored files leave file discovery, so duplicates, cycles and boundaries never see them.
189
192
  const { isIgnored } = settings;
190
193
  if (isIgnored)
@@ -236,6 +239,7 @@ async function processBaseline(report, { baselineOptions, root, values, format,
236
239
  options: baselineForScan(baselineOptions, values, values.graph === undefined ? [root] : []),
237
240
  pillar: 'maintainability',
238
241
  findings: report.findings,
242
+ skippedFiles: report.skippedFiles,
239
243
  projectRoot: root,
240
244
  absoluteFileOf: (finding) => path.resolve(root, finding.file ?? ''),
241
245
  idRoot: root,
@@ -169,6 +169,20 @@ function globPattern(rawGlob) {
169
169
  }
170
170
  else if (character === ',' && insideBraces)
171
171
  pattern += '|';
172
+ else if (character === '[') {
173
+ const close = glob.indexOf(']', index + 1);
174
+ // `[!]` has no members, so minimatch treats it as literal text rather than a negated class.
175
+ if (close > index + 1 && glob.slice(index + 1, close) !== '!') {
176
+ const body = glob.slice(index + 1, close);
177
+ // Escape a leading hyphen after the added `/` so it stays a literal, not a range from `/`.
178
+ const negatedBody = body.slice(1).replace(/^-/, String.raw `\-`);
179
+ pattern += `[${body.startsWith('!') ? '^/' + negatedBody : body}]`;
180
+ index = close;
181
+ }
182
+ else {
183
+ pattern += '\\[';
184
+ }
185
+ }
172
186
  else
173
187
  pattern += character.replaceAll(/[.+^$()|[\]\\]/g, '\\$&');
174
188
  }
@@ -392,11 +406,9 @@ function createEntryPoints(root, inventory, sourceFiles, fileFacts) {
392
406
  // Mocha and Jest also read their options from package.json instead of a config file.
393
407
  for (const script of Object.values(manifest.scripts ?? {}))
394
408
  if (typeof script === 'string')
395
- for (const entry of mochaScriptPaths(script))
396
- addConfigPath(directory, entry, true);
409
+ addConfigPaths(directory, mochaScriptPaths(script), true);
397
410
  for (const toolKey of ['mocha', 'jest'])
398
- for (const entry of jsonConfigFilePaths(isRecord(manifest[toolKey]) ? manifest[toolKey] : {}))
399
- addConfigPath(directory, entry, toolKey === 'mocha');
411
+ addConfigPaths(directory, jsonConfigFilePaths(isRecord(manifest[toolKey]) ? manifest[toolKey] : {}), toolKey === 'mocha');
400
412
  for (const entry of stringValues(manifest.exports))
401
413
  if (entry.includes('*'))
402
414
  addWildcardEntry(directory, entry, known, explicit);
@@ -416,32 +428,49 @@ function createEntryPoints(root, inventory, sourceFiles, fileFacts) {
416
428
  }
417
429
  // Mocha loads every file in a folder named as a spec; other tools resolve a folder to its index,
418
430
  // so only mocha paths expand.
419
- function addFolderFiles(directory, entry) {
431
+ function addFolderFiles(directory, entry, excluded = []) {
420
432
  const folder = path.posix.normalize(path.posix.join(directory, entry.replaceAll('\\', '/'))).replace(/\/$/, '');
421
433
  if (folder === '.' || folder.startsWith('..'))
422
434
  return;
423
435
  for (const file of known)
424
- if (file.startsWith(folder + '/'))
436
+ if (file.startsWith(folder + '/') && !excluded.some((pattern) => pattern.test(file)))
425
437
  explicit.add(file);
426
438
  }
427
- function addConfigPath(directory, entry, loadsFolder = false) {
428
- if (!/[*?{]/.test(entry)) {
429
- addEntry(directory, entry);
430
- if (loadsFolder && !sourceExtensions.includes(path.posix.extname(entry)))
431
- addFolderFiles(directory, entry);
439
+ function addConfigPath(directory, entry, loadsFolder = false, excluded = []) {
440
+ const normalized = entry.replaceAll('\\', '/');
441
+ if (normalized.startsWith('!'))
432
442
  return;
443
+ // A bracketed name may be a literal file or a glob class, so it gets both.
444
+ const literalFiles = entryFiles(directory, normalized);
445
+ const bracketed = normalized.includes('[');
446
+ if (!/[*?{]/.test(normalized)) {
447
+ for (const file of literalFiles)
448
+ if (!excluded.some((pattern) => pattern.test(file)))
449
+ explicit.add(file);
450
+ if (loadsFolder && !sourceExtensions.includes(path.posix.extname(normalized)))
451
+ addFolderFiles(directory, normalized, excluded);
452
+ // Mocha also expands the brackets as a glob, so a bracketed name keeps its glob matches too.
453
+ if (!bracketed)
454
+ return;
433
455
  }
434
- const pattern = globPattern(path.posix.normalize(path.posix.join(directory, entry)));
456
+ const pattern = globPattern(path.posix.normalize(path.posix.join(directory, normalized)));
435
457
  for (const file of known)
436
- if (pattern.test(file))
458
+ if (pattern.test(file) && !excluded.some((excludedPattern) => excludedPattern.test(file)))
437
459
  explicit.add(file);
438
460
  }
461
+ function addConfigPaths(directory, entries, loadsFolder = false) {
462
+ const excluded = entries
463
+ .map((entry) => entry.replaceAll('\\', '/'))
464
+ .filter((entry) => entry.startsWith('!') && entry.length > 1)
465
+ .map((entry) => globPattern(path.posix.normalize(path.posix.join(directory, entry.slice(1)))));
466
+ for (const entry of entries)
467
+ addConfigPath(directory, entry, loadsFolder, excluded);
468
+ }
439
469
  function addConfigFiles(file, directory) {
440
470
  const paths = jsonConfigFile.test(file)
441
471
  ? jsonConfigFilePaths(readConfig(root, file))
442
472
  : configFilePaths(parseScript(path.join(root, file)) ?? ts.createSourceFile(file, '', ts.ScriptTarget.Latest));
443
- for (const entry of paths)
444
- addConfigPath(directory, entry, /\.mocharc\./.test(file));
473
+ addConfigPaths(directory, paths, /\.mocharc\./.test(file));
445
474
  }
446
475
  function addEntries(directory, entries) {
447
476
  for (const entry of entries)
@@ -11,6 +11,7 @@ const rawTextTags = new Set([
11
11
  'xmp',
12
12
  ]);
13
13
  const inertTags = new Set(['math', 'svg', 'template']);
14
+ const foreignSelfClosingTags = new Set(['math', 'svg']);
14
15
  const scriptTypes = new Set([
15
16
  '',
16
17
  'module',
@@ -19,6 +20,8 @@ const scriptTypes = new Set([
19
20
  'text/ecmascript',
20
21
  'application/ecmascript',
21
22
  ]);
23
+ // A trailing slash closes the tag only after whitespace, a closing quote or the tag name; in `a=b/` it belongs to the unquoted value.
24
+ const selfClosingDelimiter = /(?:^|[\s"'])\/$/;
22
25
  const localSource = /^(?!\/)[\w./-]+\.[cm]?[jt]sx?$/i;
23
26
  function parseAttributes(text) {
24
27
  const attributes = new Map();
@@ -50,7 +53,8 @@ function htmlScriptEntries(text = '') {
50
53
  inert.pop();
51
54
  continue;
52
55
  }
53
- if (inertTags.has(name))
56
+ const isSelfClosingForeign = foreignSelfClosingTags.has(name) && selfClosingDelimiter.test(attributes.trimEnd());
57
+ if (inertTags.has(name) && !isSelfClosingForeign)
54
58
  inert.push(name);
55
59
  if (name === 'plaintext')
56
60
  break;
@@ -4,8 +4,8 @@ import { nestingAdvice, sectionAdvice, loopGuardComparison } from '../cli/branch
4
4
  import { traversalLeaf } from '../analysis/traversal-context.js';
5
5
  import { checklistContext } from '../analysis/checklist-context.js';
6
6
  import { textChoiceContext, loopGuard, patchMappingContext } from '../analysis/advisory-context.js';
7
- const nestingLimit = 4;
8
- const branchComplexityLimit = 15;
7
+ const defaultNestingLimit = 4;
8
+ const defaultBranchComplexityLimit = 15;
9
9
  // A run of independent `if (...) return;` guards reads straight through, so each counts half toward the
10
10
  // limit. Past this many in one function they count in full again, so a function of twenty guards is
11
11
  // still reported. The reported number stays the plain count of decisions.
@@ -55,7 +55,9 @@ function functionAnchor(node, parent) {
55
55
  return parent.name;
56
56
  return node;
57
57
  }
58
- function analyzeFunctions(sourceFile, relativePath) {
58
+ function analyzeFunctions(sourceFile, relativePath, limits) {
59
+ const nestingLimit = limits?.maxDepth === undefined ? defaultNestingLimit : limits.maxDepth + 1;
60
+ const branchComplexityLimit = limits?.maxComplexity === undefined ? defaultBranchComplexityLimit : limits.maxComplexity + 1;
59
61
  const findings = [];
60
62
  const invokedQueryArrows = new WeakSet();
61
63
  // A function-level finding also records the whole function's lines, so a change anywhere inside
@@ -156,7 +158,8 @@ function analyzeFunctions(sourceFile, relativePath) {
156
158
  inner.complexity < branchComplexityLimit &&
157
159
  'The deepest nested loop branches retain an extreme value or enqueue an unseen item, with optional iteration guards.', nestingAdvice(inner.deepest, sourceFile), loopGuardComparison(inner.deepest, sourceFile), node);
158
160
  }
159
- if (weightedComplexity(inner) >= branchComplexityLimit) {
161
+ const score = weightedComplexity(inner);
162
+ if (limits?.maxComplexity === undefined ? score >= defaultBranchComplexityLimit : score > limits.maxComplexity) {
160
163
  report({
161
164
  node: functionAnchor(node, parent),
162
165
  ruleId: 'high-branch-complexity',
@@ -220,7 +223,7 @@ function analyzeFunctions(sourceFile, relativePath) {
220
223
  function visitNestedStatement(node, nestedBody, scope, depth) {
221
224
  scope.complexity++;
222
225
  const nestedDepth = depth + 1;
223
- classifyNestedTraversal(nestedDepth, scope, node);
226
+ classifyNestedTraversal(nestedDepth, scope, node, nestingLimit);
224
227
  if (nestedDepth > scope.maxDepth) {
225
228
  scope.maxDepth = nestedDepth;
226
229
  scope.deepest = node;
@@ -302,7 +305,7 @@ function analyzeFunctions(sourceFile, relativePath) {
302
305
  visit(sourceFile, undefined, 0);
303
306
  return findings;
304
307
  }
305
- function classifyNestedTraversal(nestedDepth, scope, node) {
308
+ function classifyNestedTraversal(nestedDepth, scope, node, nestingLimit) {
306
309
  if (nestedDepth >= nestingLimit && scope.traversalOnly) {
307
310
  if (nestedDepth > nestingLimit)
308
311
  scope.traversalOnly = false;
@@ -1,3 +1,22 @@
1
+ import path from 'node:path';
1
2
  // Defaults for the size rules; the "maintainability" config section can override each one under "limits".
2
3
  const defaultLimits = { largeModuleLines: 600, largeClassMembers: 30, longParameterCount: 5 };
4
+ export function configuredLimits(settings, root, legacy) {
5
+ const base = settings.filename ? path.dirname(settings.filename) : root;
6
+ return (file) => {
7
+ const relative = path.relative(base, path.resolve(root, file)).split(path.sep).join('/');
8
+ function option(ruleId, key) {
9
+ const value = settings.ruleOptions(ruleId, relative)?.[key];
10
+ return typeof value === 'number' ? value : undefined;
11
+ }
12
+ return {
13
+ largeModuleLines: option('large-module', 'maxLines') ?? legacy.largeModuleLines,
14
+ largeClassMembers: option('large-class', 'maxMethods') ?? legacy.largeClassMembers,
15
+ longParameterCount: option('long-parameter-list', 'maxParams') ?? legacy.longParameterCount,
16
+ maxClassLines: option('large-class', 'maxLines'),
17
+ maxDepth: option('deep-control-flow', 'maxDepth'),
18
+ maxComplexity: option('high-branch-complexity', 'maxComplexity'),
19
+ };
20
+ };
21
+ }
3
22
  export { defaultLimits };
@@ -6,9 +6,9 @@ import { generatedSource } from './duplicates.js';
6
6
  import { isVendoredMinified } from '../../shared/analysis/execution-context.js';
7
7
  import { defaultLimits } from './limits.js';
8
8
  // Lines that hold at least one token, so comments and blank lines are not counted.
9
- function linesOfCode(sourceFile) {
9
+ function linesOfCode(sourceFile, root = sourceFile) {
10
10
  const codeLines = new Set();
11
- const pending = [sourceFile];
11
+ const pending = [root];
12
12
  for (let node = pending.pop(); node; node = pending.pop()) {
13
13
  if (ts.isJSDoc(node) || node.kind === ts.SyntaxKind.EndOfFileToken)
14
14
  continue;
@@ -81,6 +81,12 @@ function checkSizeLimits(sourceFile, file, limits = defaultLimits, isGenerated)
81
81
  if (count > limits.largeClassMembers) {
82
82
  report(node.name ?? node, 'large-class', `This class has ${count} methods and accessors (limit ${limits.largeClassMembers}). A class this wide usually owns several responsibilities. Group the methods that share state into their own classes and have this one delegate to them.`);
83
83
  }
84
+ else if (limits.maxClassLines !== undefined) {
85
+ const lines = linesOfCode(sourceFile, node);
86
+ if (lines > limits.maxClassLines) {
87
+ report(node.name ?? node, 'large-class', `This class has ${lines} lines of code (limit ${limits.maxClassLines}, comments and blank lines excluded). Split responsibilities into smaller classes.`);
88
+ }
89
+ }
84
90
  return;
85
91
  }
86
92
  if (!ts.isFunctionLike(node) || !('body' in node) || !node.body || isInjectionConstructor(node))
@@ -28,13 +28,74 @@ const FIXABLE_METHODS = {
28
28
  error: 'error',
29
29
  };
30
30
  const NEST_METHODS = { log: 'log', info: 'log', debug: 'debug', warn: 'warn', error: 'error' };
31
+ function bindingHasName(name, target) {
32
+ if (ts.isIdentifier(name))
33
+ return name.text === target;
34
+ return name.elements.some((element) => !ts.isOmittedExpression(element) && bindingHasName(element.name, target));
35
+ }
36
+ function statementDeclaresName(statement, target) {
37
+ if (ts.isVariableStatement(statement)) {
38
+ return statement.declarationList.declarations.some((declaration) => bindingHasName(declaration.name, target));
39
+ }
40
+ if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {
41
+ return statement.name.text === target;
42
+ }
43
+ if (ts.isImportDeclaration(statement) && statement.importClause && !statement.importClause.isTypeOnly) {
44
+ return valueBindingNames(statement.importClause).includes(target);
45
+ }
46
+ return false;
47
+ }
48
+ // `var` is hoisted to the enclosing function or file, even from a nested block.
49
+ function declaresHoistedVar(scope, target) {
50
+ const visit = (node) => {
51
+ if (ts.isFunctionLike(node) || ts.isClassStaticBlockDeclaration(node))
52
+ return false;
53
+ if (ts.isVariableDeclaration(node) &&
54
+ ts.isVariableDeclarationList(node.parent) &&
55
+ !(node.parent.flags & ts.NodeFlags.BlockScoped) &&
56
+ bindingHasName(node.name, target)) {
57
+ return true;
58
+ }
59
+ return ts.forEachChild(node, visit) ?? false;
60
+ };
61
+ return ts.forEachChild(scope, visit) ?? false;
62
+ }
63
+ function hasLocalConsoleBinding(node) {
64
+ for (let current = node.parent; current; current = current.parent) {
65
+ if ((ts.isFunctionLike(current) || ts.isClassStaticBlockDeclaration(current) || ts.isSourceFile(current)) &&
66
+ declaresHoistedVar(current, 'console')) {
67
+ return true;
68
+ }
69
+ if ((ts.isBlock(current) || ts.isSourceFile(current)) &&
70
+ current.statements.some((s) => statementDeclaresName(s, 'console'))) {
71
+ return true;
72
+ }
73
+ if (ts.isFunctionLike(current) && current.parameters.some((p) => bindingHasName(p.name, 'console'))) {
74
+ return true;
75
+ }
76
+ if (ts.isCatchClause(current) &&
77
+ current.variableDeclaration &&
78
+ bindingHasName(current.variableDeclaration.name, 'console')) {
79
+ return true;
80
+ }
81
+ if ((ts.isForStatement(current) || ts.isForOfStatement(current) || ts.isForInStatement(current)) &&
82
+ current.initializer &&
83
+ ts.isVariableDeclarationList(current.initializer) &&
84
+ current.initializer.declarations.some((d) => bindingHasName(d.name, 'console'))) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
31
90
  function consoleMethodOf(node) {
32
91
  if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
33
92
  return;
34
93
  const { expression, name } = node.expression;
35
94
  if (!ts.isIdentifier(expression) || expression.text !== 'console')
36
95
  return;
37
- return CONSOLE_METHODS.has(name.text) ? name.text : undefined;
96
+ if (!CONSOLE_METHODS.has(name.text) || hasLocalConsoleBinding(node))
97
+ return undefined;
98
+ return name.text;
38
99
  }
39
100
  function loggerCandidateName(node) {
40
101
  if ((ts.isFunctionDeclaration(node) ||
@@ -39,11 +39,13 @@ function checkTsconfig(root, file) {
39
39
  if (!problem)
40
40
  return [];
41
41
  const { line, character } = sourceFile.getLineAndCharacterOfPosition(problem.getStart(sourceFile));
42
+ const endLine = sourceFile.getLineAndCharacterOfPosition(problem.getEnd()).line;
42
43
  return [
43
44
  {
44
45
  file,
45
46
  line: line + 1,
46
47
  column: character + 1,
48
+ ...(endLine > line ? { rangeEndLine: endLine + 1 } : {}),
47
49
  ruleId: 'tsconfig-strict-disabled',
48
50
  message: 'This tsconfig turns off strict type checking, so null and undefined values and implicit `any` types pass the compiler and fail at runtime. Enable `"strict": true`, or turn it on in steps by fixing the errors per flag.',
49
51
  },
@@ -29,7 +29,10 @@ async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PAR
29
29
  const generated = new Set();
30
30
  const skippedFiles = [];
31
31
  targets.forEach((file, index) => {
32
- const analysis = analyzeSource(root, file, texts[index], resolve, policy);
32
+ const analysis = analyzeSource(root, file, texts[index], resolve, {
33
+ ...policy,
34
+ limits: policy.limitsFor?.(file) ?? policy.limits,
35
+ });
33
36
  if (analysis.parseErrors !== undefined)
34
37
  return reportUnparsable(root, skippedFiles, file, analysis.parseErrors);
35
38
  if (analysis.generated)
@@ -14,12 +14,16 @@ function describeFailure(error) {
14
14
  }
15
15
  // A rejection in an async listener would crash the worker without a reply, so any failure outside
16
16
  // the per-file analysis is reported for every file of the batch instead.
17
- port.on('message', async ({ batch, files }) => {
17
+ port.on('message', async ({ batch, files, limits }) => {
18
18
  try {
19
19
  const entries = await readSourceFiles(root, files);
20
20
  const results = files.map((file, index) => {
21
21
  try {
22
- return analyzeSource(root, file, entries[index].text, resolve, { ...analysisOptions, disk: entries[index] });
22
+ return analyzeSource(root, file, entries[index].text, resolve, {
23
+ ...analysisOptions,
24
+ limits: limits?.[index] ?? analysisOptions.limits,
25
+ disk: entries[index],
26
+ });
23
27
  }
24
28
  catch (error) {
25
29
  return { failure: describeFailure(error) };
@@ -19,9 +19,9 @@ import { noteFlowSkips, recordUnparsedFile } from '../shared/reporting/flow-skip
19
19
  const PARALLEL_FROM_FILES = 600;
20
20
  const MAXIMUM_WORKERS = 8;
21
21
  const BATCH_SIZE = 16;
22
- // Analyses files on worker threads. Results come back in file order, whichever thread finishes
23
- // first.
22
+ // Resolve per-file settings on the main thread; only numeric limits cross the worker boundary.
24
23
  async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
24
+ const { limitsFor, ...workerOptions } = analysisOptions;
25
25
  const results = Array.from({ length: jsFiles.length });
26
26
  let next = 0;
27
27
  const workers = [];
@@ -31,9 +31,16 @@ async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
31
31
  if (next >= jsFiles.length)
32
32
  return resolve();
33
33
  const first = next;
34
- next = Math.min(jsFiles.length, next + BATCH_SIZE);
35
- const request = { batch: first, files: jsFiles.slice(first, next) };
36
- worker.postMessage(request);
34
+ const end = Math.min(jsFiles.length, first + BATCH_SIZE);
35
+ try {
36
+ const files = jsFiles.slice(first, end);
37
+ const request = { batch: first, files, limits: limitsFor && files.map(limitsFor) };
38
+ worker.postMessage(request);
39
+ next = end;
40
+ }
41
+ catch (error) {
42
+ reject(error);
43
+ }
37
44
  }
38
45
  worker.on('message', ({ batch, results: batchResults }) => {
39
46
  batchResults.forEach((result, offset) => (results[batch + offset] = result));
@@ -46,8 +53,9 @@ async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
46
53
  }
47
54
  try {
48
55
  for (let index = 0; index < workerCount; index += 1) {
49
- const workerData = { root, jsFiles, analysisOptions };
50
- workers.push(new Worker(path.join(import.meta.dirname, 'scan-worker.js'), { workerData }));
56
+ const workerData = { root, jsFiles, analysisOptions: workerOptions };
57
+ // The CLI's unbundled scanner and the editor's checker bundle are both one directory below lib/.
58
+ workers.push(new Worker(new URL('../maintainability/scan-worker.js', import.meta.url), { workerData }));
51
59
  }
52
60
  await Promise.all(workers.map(drive));
53
61
  }
@@ -61,7 +69,11 @@ async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
61
69
  async function analyzeSequentially(root, jsFiles, analysisOptions) {
62
70
  const resolve = createResolver(root, new Set(jsFiles));
63
71
  const entries = await readSourceFiles(root, jsFiles);
64
- return jsFiles.map((file, index) => analyzeSource(root, file, entries[index].text, resolve, { ...analysisOptions, disk: entries[index] }));
72
+ return jsFiles.map((file, index) => analyzeSource(root, file, entries[index].text, resolve, {
73
+ ...analysisOptions,
74
+ limits: analysisOptions.limitsFor?.(file) ?? analysisOptions.limits,
75
+ disk: entries[index],
76
+ }));
65
77
  }
66
78
  function analyzeFiles(root, jsFiles, parallelFrom, analysisOptions) {
67
79
  const workerCount = Math.min(MAXIMUM_WORKERS, os.availableParallelism() - 1);
@@ -176,6 +188,7 @@ async function scan(root, policy, { parallelFrom = PARALLEL_FROM_FILES, inScope,
176
188
  const { analyses, polyglot } = await analyzeWithPolyglot(root, jsFiles, otherSources, parallelFrom, {
177
189
  dataAccess: policy.dataAccess,
178
190
  limits: policy.limits,
191
+ limitsFor: policy.limitsFor,
179
192
  indexIdentifiers: identifierIndex !== undefined,
180
193
  });
181
194
  for (const [index, file] of jsFiles.entries()) {
@@ -73,6 +73,22 @@ function isContractReference(identifier) {
73
73
  return false;
74
74
  return Boolean(ts.findAncestor(identifier, ts.isHeritageClause));
75
75
  }
76
+ function declarationSignatures(statement) {
77
+ if (ts.isVariableStatement(statement) &&
78
+ hasModifier(statement, ts.SyntaxKind.ExportKeyword) &&
79
+ !hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) {
80
+ return statement.declarationList.declarations.flatMap((declaration) => {
81
+ const initializer = declaration.initializer && ts.skipOuterExpressions(declaration.initializer);
82
+ const functionParts = initializer && ts.isFunctionLike(initializer) ? functionSignature(initializer) : [];
83
+ const parts = [...(declaration.type ? [declaration.type] : []), ...functionParts];
84
+ if (parts.length === 0)
85
+ return [];
86
+ return bindingNames(declaration.name).map((name) => ({ owner: name.text, parts }));
87
+ });
88
+ }
89
+ const [outer] = declaredExports(statement);
90
+ return outer ? [{ owner: outer.name, parts: signatureParts(statement) }] : [];
91
+ }
76
92
  // For each exported declaration, the other exports whose signature names it.
77
93
  function signatureExposure(statements) {
78
94
  const exportNameByLocal = new Map();
@@ -83,20 +99,19 @@ function signatureExposure(statements) {
83
99
  }
84
100
  const exposedBy = new Map();
85
101
  for (const statement of statements) {
86
- const [outer] = declaredExports(statement);
87
- if (!outer)
88
- continue;
89
- for (const part of signatureParts(statement)) {
90
- walkNodes(part, (node) => {
91
- if (!ts.isIdentifier(node))
92
- return;
93
- const inner = exportNameByLocal.get(node.text);
94
- if (!inner || inner === outer.name || !isContractReference(node))
95
- return;
96
- const owners = exposedBy.get(inner) ?? new Set();
97
- owners.add(outer.name);
98
- exposedBy.set(inner, owners);
99
- });
102
+ for (const { owner, parts } of declarationSignatures(statement)) {
103
+ for (const part of parts) {
104
+ walkNodes(part, (node) => {
105
+ if (!ts.isIdentifier(node))
106
+ return;
107
+ const inner = exportNameByLocal.get(node.text);
108
+ if (!inner || inner === owner || !isContractReference(node))
109
+ return;
110
+ const owners = exposedBy.get(inner) ?? new Set();
111
+ owners.add(owner);
112
+ exposedBy.set(inner, owners);
113
+ });
114
+ }
100
115
  }
101
116
  }
102
117
  return exposedBy;
@@ -205,21 +220,28 @@ function typeReexportRemoval(sourceFile, statement) {
205
220
  return;
206
221
  const lines = sourceFile.text.split(/\r?\n/);
207
222
  const rowOf = (offset) => sourceFile.getLineAndCharacterOfPosition(offset).line;
208
- const first = rowOf(declaration.getStart(sourceFile));
223
+ let first = rowOf(declaration.getStart(sourceFile));
209
224
  const exportRow = rowOf(statement.getStart(sourceFile));
225
+ const exportEndRow = rowOf(statement.end);
210
226
  const removed = new Set();
211
227
  for (let row = first; row <= rowOf(declaration.end); row++)
212
228
  removed.add(row);
213
- removed.add(exportRow);
229
+ for (let row = exportRow; row <= exportEndRow; row++)
230
+ removed.add(row);
214
231
  // Keep one blank line where the re-export sat between two.
215
- if (!lines[exportRow - 1]?.trim() && !lines[exportRow + 1]?.trim() && exportRow + 1 < lines.length)
216
- removed.add(exportRow + 1);
232
+ if (!lines[exportRow - 1]?.trim() && !lines[exportEndRow + 1]?.trim() && exportEndRow + 1 < lines.length)
233
+ removed.add(exportEndRow + 1);
217
234
  let last = Math.max(...removed);
218
- // A line change needs at least one remaining line, so include the next one unchanged.
235
+ // A line change needs at least one remaining line, so include an adjacent line unchanged.
219
236
  if (last + 1 < lines.length)
220
237
  last++;
221
- const span = lines.slice(first, last + 1);
222
- const kept = span.filter((_line, index) => !removed.has(first + index));
238
+ let span = lines.slice(first, last + 1);
239
+ let kept = span.filter((_line, index) => !removed.has(first + index));
240
+ if (!kept.length && first > 0) {
241
+ first--;
242
+ span = lines.slice(first, last + 1);
243
+ kept = span.filter((_line, index) => !removed.has(first + index));
244
+ }
223
245
  if (!kept.length)
224
246
  return;
225
247
  return { name, change: { line: first + 1, before: span.join('\n'), after: kept.join('\n') } };