@blundergoat/gruff-ts 0.4.0 → 0.6.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 (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -2,21 +2,9 @@
2
2
  * Provides lightweight source text scanners that separate executable TypeScript
3
3
  * from comments, strings, and regex bodies before rule matching runs.
4
4
  */
5
- import { createRequire } from "node:module";
5
+ import { parseScript } from "./parsed-script.ts";
6
6
  import type { RunDiagnostic } from "./types.ts";
7
7
 
8
- const require = createRequire(import.meta.url);
9
- const typescriptSyntax = require("typescript") as typeof import("typescript");
10
-
11
- type TsDiagnostic = import("typescript").Diagnostic;
12
- type TsSourceFile = import("typescript").SourceFile;
13
-
14
- // TypeScript's public SourceFile shape exposes parseDiagnostics at runtime; this interface gives
15
- // the syntax-only parser result the diagnostic field without requiring a full Program.
16
- interface ParsedSourceFileWithDiagnostics extends TsSourceFile {
17
- parseDiagnostics: readonly TsDiagnostic[];
18
- }
19
-
20
8
  // Just enough of `SourceFile` to keep `parseDiagnostics` decoupled from the full project type:
21
9
  // `isScript` gates whether parser diagnostics run; `displayPath` is the report-path anchor.
22
10
  interface DiagnosticSourceFile {
@@ -26,44 +14,14 @@ interface DiagnosticSourceFile {
26
14
 
27
15
  /**
28
16
  * Syntax-only TypeScript parser diagnostics for script files; non-script inputs stay unparsed.
17
+ * Uses the shared parser so callers that only need diagnostics get the same summary as the analyser.
29
18
  *
30
19
  * @param file - Source metadata used to skip non-script inputs and report paths.
31
20
  * @param source - Raw file text to parse for syntax diagnostics.
21
+ * @returns One summarized parse-error diagnostic when the script fails to parse; empty for non-script inputs and clean parses.
32
22
  */
33
23
  function parseDiagnostics(file: DiagnosticSourceFile, source: string): RunDiagnostic[] {
34
- if (!file.isScript) {
35
- return [];
36
- }
37
- const parsed = typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath)) as ParsedSourceFileWithDiagnostics;
38
- return parsed.parseDiagnostics.map((diagnostic) => parseErrorDiagnostic(file, diagnosticLine(parsed, diagnostic), diagnosticMessage(diagnostic)));
39
- }
40
-
41
- // Maps extensions onto the matching TypeScript parser mode so TSX/JSX syntax is parsed as syntax.
42
- function scriptKindFor(path: string): import("typescript").ScriptKind {
43
- if (path.endsWith(".tsx")) {
44
- return typescriptSyntax.ScriptKind.TSX;
45
- }
46
- if (path.endsWith(".jsx")) {
47
- return typescriptSyntax.ScriptKind.JSX;
48
- }
49
- if (path.endsWith(".js") || path.endsWith(".mjs") || path.endsWith(".cjs")) {
50
- return typescriptSyntax.ScriptKind.JS;
51
- }
52
- return typescriptSyntax.ScriptKind.TS;
53
- }
54
-
55
- // Parser diagnostics may omit a start offset; line 1 is the stable fallback for malformed files.
56
- function diagnosticLine(sourceFile: TsSourceFile, diagnostic: TsDiagnostic): number {
57
- if (diagnostic.start === undefined) {
58
- return 1;
59
- }
60
- return sourceFile.getLineAndCharacterOfPosition(diagnostic.start).line + 1;
61
- }
62
-
63
- // Prefixes the TypeScript parser message while preserving the existing parse-error diagnostic shape.
64
- // Chained messages flatten with a space separator so text-format diagnostic rows stay single-line.
65
- function diagnosticMessage(diagnostic: TsDiagnostic): string {
66
- return `TypeScript syntax error: ${typescriptSyntax.flattenDiagnosticMessageText(diagnostic.messageText, " ")}`;
24
+ return parseScript(file, source)?.diagnostics ?? [];
67
25
  }
68
26
 
69
27
  // Running totals for `{}`, `()`, and `[]`. A negative count means a closer appeared with no opener
@@ -74,11 +32,10 @@ interface DelimiterCounts {
74
32
  brackets: number;
75
33
  }
76
34
 
77
- // Lexer state for the delimiter scanner. `previousCode` is the last non-whitespace executable
78
- // character - required because `/` may start a regex or a division depending on what came before.
79
- // `templateInterpolationStack` records the brace count at each `${` so a matching `}` can re-enter
80
- // template literal mode; without it, nested-template-literal files like `\`\${x.map(n => \`\${n}\`)}\``
81
- // flip out of quote mode early and start counting code-level braces inside the string body.
35
+ // Lexer state for the delimiter and masking scanner across quotes, comments, regex literals, and nested templates.
36
+ //
37
+ // - `previousCode` tracks the last non-whitespace code character so `/` disambiguates regex literals from division;
38
+ // - `templateInterpolationStack` records the brace depth at each `${` so matching `}` re-enters template text cleanly.
82
39
  interface DelimiterScanState {
83
40
  quote: string | undefined;
84
41
  isEscaped: boolean;
@@ -103,8 +60,12 @@ interface ScanStep {
103
60
  shouldStopLine: boolean;
104
61
  }
105
62
 
106
- // All flags begin false / quote unset. `previousCode` starts empty so the first `/` in a file
107
- // is treated as a regex opener (matches the JS grammar at program start).
63
+ /**
64
+ * Builds fresh delimiter-scan state for a new file with no active literal or comment and no prior code character.
65
+ * An empty `previousCode` lets a slash at the start of code open a regex; later code updates that context.
66
+ *
67
+ * @returns Initialized `DelimiterScanState` with cleared literal, comment, and escape flags.
68
+ */
108
69
  function defaultDelimiterScanState(): DelimiterScanState {
109
70
  return {
110
71
  quote: undefined,
@@ -118,8 +79,15 @@ function defaultDelimiterScanState(): DelimiterScanState {
118
79
  };
119
80
  }
120
81
 
121
- // Walks one line, mutating `ctx.counts` and `ctx.scan` in place. The `shouldStopLine` step is the only
122
- // way out before line end; comment, string, and regex bodies merely advance offset without counting.
82
+ /**
83
+ * Updates the supplied delimiter totals and scanner state across one source line.
84
+ * Stops at a line comment because the rest of the line is comment text; block comments, string text, and regex
85
+ * bodies leave counts unchanged while template interpolations resume counting.
86
+ *
87
+ * @param line - Source line text to scan from left to right.
88
+ * @param ctx - Mutable delimiter counts and lexer state updated in place for `line`.
89
+ * @returns Nothing. Mutates `ctx.counts` and `ctx.scan` for each scanned character until EOL or a line comment.
90
+ */
123
91
  function scanDelimiterLine(line: string, ctx: DelimiterScanContext): void {
124
92
  for (let offset = 0; offset < line.length; offset += 1) {
125
93
  const step = scanDelimiterCharacter(line, offset, ctx);
@@ -130,8 +98,14 @@ function scanDelimiterLine(line: string, ctx: DelimiterScanContext): void {
130
98
  }
131
99
  }
132
100
 
133
- // State-machine dispatch: block-comment, string, regex, or code. Order matters - once inside a
134
- // block comment, characters must not be re-interpreted as a quote or regex opener.
101
+ /**
102
+ * Scans `line` at `offset` according to the lexical mode stored in `ctx`, mutating its counts and scan state.
103
+ *
104
+ * @param line - Source line text containing the character to inspect.
105
+ * @param offset - Zero-based index of the current character within `line`.
106
+ * @param ctx - Mutable delimiter counts and lexer state carried across characters.
107
+ * @returns Step telling the line walker whether to continue, skip a character, or stop at a line comment.
108
+ */
135
109
  function scanDelimiterCharacter(line: string, offset: number, ctx: DelimiterScanContext): ScanStep {
136
110
  const character = line[offset] ?? "";
137
111
  const next = line[offset + 1] ?? "";
@@ -148,8 +122,15 @@ function scanDelimiterCharacter(line: string, offset: number, ctx: DelimiterScan
148
122
  return scanCodeDelimiter(line, offset, character, next, ctx);
149
123
  }
150
124
 
151
- // Inside `/* ... */`. Returns `skip: 1` to swallow the `/` of the closing `*/`, then the next
152
- // step resumes in code mode. Block-comment contents do not affect delimiter counts.
125
+ /**
126
+ * Scans inside a block comment, leaving delimiter counts unchanged until the closing delimiter.
127
+ * Mutates `scan.isInBlockComment` to false on the closer so the next step resumes in code mode.
128
+ *
129
+ * @param character - Current character inside the block comment.
130
+ * @param next - Lookahead character immediately following `character`.
131
+ * @param scan - Mutable lexer state updated when the closing delimiter is matched.
132
+ * @returns Step with `skip: 1` to swallow the trailing `/` on a closer, or a continuing step otherwise.
133
+ */
153
134
  function scanBlockCommentDelimiter(character: string, next: string, scan: DelimiterScanState): ScanStep {
154
135
  if (character === "*" && next === "/") {
155
136
  scan.isInBlockComment = false;
@@ -158,11 +139,15 @@ function scanBlockCommentDelimiter(character: string, next: string, scan: Delimi
158
139
  return continueScan();
159
140
  }
160
141
 
161
- // Inside a string or template literal. `\` arms `isEscaped` so the next character (including a
162
- // closing quote) is treated as literal text. Necessary to handle `"\\\""` and similar correctly.
163
- // Template literals also recognise `${` as an interpolation opener - the scanner pushes the current
164
- // brace count onto a stack, exits quote mode, and counts the opening `{` so a matching `}` re-enters
165
- // template literal mode. Without this, nested-template files mis-attribute later `\`` as the closer.
142
+ /**
143
+ * Scans inside a quoted literal, mutating quote, escape, and template-interpolation state in `ctx`.
144
+ * Escapes protect the next character; template interpolation saves brace depth and resumes code until its closing brace.
145
+ *
146
+ * @param character - Current character inside the quoted literal.
147
+ * @param next - Lookahead character immediately following `character`.
148
+ * @param ctx - Mutable delimiter counts and lexer state updated on escapes, quotes, or `${`.
149
+ * @returns Continuing step, or a skip step after `${` so the opening brace is not re-counted.
150
+ */
166
151
  function scanQuotedDelimiter(character: string, next: string, ctx: DelimiterScanContext): ScanStep {
167
152
  const scan = ctx.scan;
168
153
  if (scan.isEscaped) {
@@ -186,8 +171,14 @@ function scanQuotedDelimiter(character: string, next: string, ctx: DelimiterScan
186
171
  return continueScan();
187
172
  }
188
173
 
189
- // Inside `/regex/`. `[...]` character classes can legally contain `/`, so the closing slash
190
- // is only honoured when `isInRegexCharClass` is false; otherwise `/[/]/` would terminate early.
174
+ /**
175
+ * Scans inside a regex literal, mutating `scan` for escapes, character classes, and the closing slash.
176
+ * Closing slash is only honoured when `isInRegexCharClass` is false because `[...]` can contain `/`.
177
+ *
178
+ * @param character - Current character inside the regex literal body.
179
+ * @param scan - Mutable lexer state updated for escapes, `[` / `]` class boundaries, and regex exit.
180
+ * @returns Nothing. Mutates `scan` in place and sets `scan.previousCode` to `"x"` when the regex closes.
181
+ */
191
182
  function scanRegexDelimiter(character: string, scan: DelimiterScanState): void {
192
183
  if (scan.isRegexEscaped) {
193
184
  scan.isRegexEscaped = false;
@@ -203,8 +194,17 @@ function scanRegexDelimiter(character: string, scan: DelimiterScanState): void {
203
194
  }
204
195
  }
205
196
 
206
- // In executable code. The chain order (line comment → block comment → quote → regex → plain) is
207
- // deliberate: line comments must win over block-comment openers because `/* /* */` is one comment.
197
+ /**
198
+ * Classifies `character` and lookahead `next` in executable code, using `line` and `offset` for regex detection.
199
+ * Mutates delimiter counts and lexical state in `ctx` according to the matched token handler.
200
+ *
201
+ * @param line - Source line text providing preceding context for the regex-opening heuristic.
202
+ * @param offset - Zero-based index of `character` in `line`.
203
+ * @param character - Current character in executable code.
204
+ * @param next - Lookahead character immediately following `character`.
205
+ * @param ctx - Mutable delimiter counts and lexer state updated by the matching token handler.
206
+ * @returns Matched token's scan step, or the ordinary-code step when no opener matches.
207
+ */
208
208
  function scanCodeDelimiter(line: string, offset: number, character: string, next: string, ctx: DelimiterScanContext): ScanStep {
209
209
  return (
210
210
  scanLineCommentStart(character, next) ??
@@ -215,7 +215,13 @@ function scanCodeDelimiter(line: string, offset: number, character: string, next
215
215
  );
216
216
  }
217
217
 
218
- // `//` ends the line for delimiter purposes - anything to the right is comment text.
218
+ /**
219
+ * Detects a `//` line-comment opener that ends delimiter scanning for the remainder of the line.
220
+ *
221
+ * @param character - Current character in executable code.
222
+ * @param next - Lookahead character immediately following `character`.
223
+ * @returns Stopping step when `//` is matched, or `undefined` to try another token kind.
224
+ */
219
225
  function scanLineCommentStart(character: string, next: string): ScanStep | undefined {
220
226
  if (character === "/" && next === "/") {
221
227
  return stopLineScan();
@@ -223,7 +229,15 @@ function scanLineCommentStart(character: string, next: string): ScanStep | undef
223
229
  return undefined;
224
230
  }
225
231
 
226
- // `/*` flips the scanner into block-comment mode; `skip: 1` swallows the `*` so it isn't re-evaluated.
232
+ /**
233
+ * Detects a block-comment opener (`/*`) and mutates `scan.isInBlockComment` so following text is skipped.
234
+ * Uses `skip: 1` to swallow the `*` so it is not re-evaluated as part of a closer.
235
+ *
236
+ * @param character - Current character in executable code.
237
+ * @param next - Lookahead character immediately following `character`.
238
+ * @param scan - Mutable lexer state updated when a block comment opens.
239
+ * @returns Skip step when a block comment opens, or `undefined` to try another token handler.
240
+ */
227
241
  function scanBlockCommentStart(character: string, next: string, scan: DelimiterScanState): ScanStep | undefined {
228
242
  if (character === "/" && next === "*") {
229
243
  scan.isInBlockComment = true;
@@ -232,7 +246,13 @@ function scanBlockCommentStart(character: string, next: string, scan: DelimiterS
232
246
  return undefined;
233
247
  }
234
248
 
235
- // Records which quote character opened the literal so the scanner closes on the same kind.
249
+ /**
250
+ * Recognises a string or template quote opener and stores it in `scan.quote`.
251
+ *
252
+ * @param character - Current character in executable code.
253
+ * @param scan - Mutable lexer state updated with the active quote delimiter on match.
254
+ * @returns Continuing step when `character` is a quote, or `undefined` to try another token kind.
255
+ */
236
256
  function scanQuoteStart(character: string, scan: DelimiterScanState): ScanStep | undefined {
237
257
  if (isQuote(character)) {
238
258
  scan.quote = character;
@@ -241,9 +261,16 @@ function scanQuoteStart(character: string, scan: DelimiterScanState): ScanStep |
241
261
  return undefined;
242
262
  }
243
263
 
244
- // `/` is ambiguous in JS - it can start a regex or be division. `isRegexLiteralStart` decides based
245
- // on the previous non-whitespace token; getting this wrong would let division `a / b / c` enter
246
- // regex mode and absorb everything to the next slash.
264
+ /**
265
+ * Distinguishes a regex literal opener from division using `scan.previousCode` and the line prefix before `offset`.
266
+ * Mutates `scan` regex flags when `/` opens a regex literal.
267
+ *
268
+ * @param line - Source line text containing the candidate slash.
269
+ * @param offset - Zero-based index of `character` in `line`.
270
+ * @param character - Current character in executable code.
271
+ * @param scan - Mutable lexer state supplying `previousCode` and receiving updated regex flags.
272
+ * @returns Continuing step on a regex opener, or `undefined` for the next token handler.
273
+ */
247
274
  function scanRegexStart(line: string, offset: number, character: string, scan: DelimiterScanState): ScanStep | undefined {
248
275
  if (character === "/" && isRegexLiteralStart(scan.previousCode, line.slice(0, offset))) {
249
276
  scan.isInRegex = true;
@@ -254,10 +281,14 @@ function scanRegexStart(line: string, offset: number, character: string, scan: D
254
281
  return undefined;
255
282
  }
256
283
 
257
- // Updates the delimiter tallies and remembers this character as `previousCode` so the next `/`
258
- // can decide regex-vs-division. Whitespace is not recorded; it would corrupt the regex heuristic.
259
- // Also detects when a `}` returns to a saved template-interpolation depth and transitions the
260
- // scanner back into template-literal mode.
284
+ /**
285
+ * Counts `character` in `ctx.counts` and updates `ctx.scan` so later slashes classify as regex or division.
286
+ * Ignores whitespace when recording `previousCode`; a closing interpolation brace restores template-literal mode.
287
+ *
288
+ * @param character - Current ordinary character in executable code.
289
+ * @param ctx - Mutable delimiter counts and lexer state updated in place.
290
+ * @returns Continuing scan step after updating counts and interpolation/code state.
291
+ */
261
292
  function scanPlainCodeDelimiter(character: string, ctx: DelimiterScanContext): ScanStep {
262
293
  countDelimiter(character, ctx.counts);
263
294
  if (character === "}" && ctx.scan.templateInterpolationStack.length > 0 && ctx.counts.braces === (ctx.scan.templateInterpolationStack[ctx.scan.templateInterpolationStack.length - 1] ?? -1)) {
@@ -272,8 +303,14 @@ function scanPlainCodeDelimiter(character: string, ctx: DelimiterScanContext): S
272
303
  return continueScan();
273
304
  }
274
305
 
275
- // Increment on opener, decrement on closer. Other characters are no-ops so the function can be
276
- // called unconditionally per character without a guard in the caller.
306
+ /**
307
+ * Updates the supplied delimiter totals for `character` by incrementing on openers and decrementing on closers.
308
+ * Other characters are ignored so callers can pass every code character unconditionally.
309
+ *
310
+ * @param character - Character tested against `{`, `}`, `(`, `)`, `[`, and `]`.
311
+ * @param counts - Mutable delimiter totals updated in place.
312
+ * @returns Nothing. Mutates `counts` when `character` is a tracked delimiter.
313
+ */
277
314
  function countDelimiter(character: string, counts: DelimiterCounts): void {
278
315
  if (character === "{") {
279
316
  counts.braces += 1;
@@ -290,21 +327,33 @@ function countDelimiter(character: string, counts: DelimiterCounts): void {
290
327
  }
291
328
  }
292
329
 
293
- // Negative on any of the three means a closer ran ahead of its opener - caller reports immediately
294
- // at the current line because the original mismatch is local, not at EOF.
330
+ /**
331
+ * Checks whether `counts` has any negative brace, parenthesis, or bracket balance from a closer without an opener.
332
+ *
333
+ * @param counts - Running delimiter totals to inspect.
334
+ * @returns True if any delimiter balance is below zero; otherwise false.
335
+ */
295
336
  function hasNegativeDelimiterCount(counts: DelimiterCounts): boolean {
296
337
  return counts.braces < 0 || counts.parentheses < 0 || counts.brackets < 0;
297
338
  }
298
339
 
299
- // Non-zero after the whole file means an opener was never closed. Caller reports at EOF.
340
+ /**
341
+ * Checks whether `counts` has any nonzero brace, parenthesis, or bracket balance indicating unmatched delimiters.
342
+ *
343
+ * @param counts - Final delimiter totals at end of file.
344
+ * @returns True if any delimiter count is nonzero; otherwise false.
345
+ */
300
346
  function hasUnbalancedDelimiterCount(counts: DelimiterCounts): boolean {
301
347
  return counts.braces !== 0 || counts.parentheses !== 0 || counts.brackets !== 0;
302
348
  }
303
349
 
304
- /*
305
- * Emits a `parse-error` diagnostic. The CLI exit contract forces a non-zero exit (see `exitFor`)
306
- * whenever diagnostics fire - this builder reports failures so a broken file in the scan tree
307
- * cannot hide silently rather than throw the error or recover quietly.
350
+ /**
351
+ * Builds a parse-error diagnostic for a caller to include in scan results.
352
+ *
353
+ * @param file - source metadata whose displayPath identifies the failed file
354
+ * @param line - source line to attach to the error
355
+ * @param message - explanation copied into the diagnostic
356
+ * @returns a parse-error record containing the supplied message, display path, and line
308
357
  */
309
358
  function parseErrorDiagnostic(file: DiagnosticSourceFile, line: number, message: string): RunDiagnostic {
310
359
  return {
@@ -315,15 +364,25 @@ function parseErrorDiagnostic(file: DiagnosticSourceFile, line: number, message:
315
364
  };
316
365
  }
317
366
 
318
- // Heuristic for the regex-vs-division ambiguity: `/` is a regex opener after operators, control
319
- // punctuation, or `return`; otherwise it's division. False positives would expand a regex across
320
- // real code and break delimiter balance, so this list is intentionally conservative.
367
+ /**
368
+ * Determines whether a slash looks like a regex opener using a conservative heuristic to avoid masking real code.
369
+ * Empty `previousCode`, selected punctuation, or trailing `return` before the slash permits a regex.
370
+ *
371
+ * @param previousCode - Last non-whitespace code character, synthetic operand marker, or empty start marker.
372
+ * @param beforeSlash - Preceding line slice before the candidate `/` character.
373
+ * @returns True when the slash context permits a regex literal opener; otherwise false.
374
+ */
321
375
  function isRegexLiteralStart(previousCode: string, beforeSlash: string): boolean {
322
376
  return previousCode === "" || "([{=,:!&|?;".includes(previousCode) || /\breturn$/.test(beforeSlash.trimEnd());
323
377
  }
324
378
 
325
- // Masks non-code bytes without changing offsets. Regex-driven rules rely on the 1:1 byte mapping
326
- // to report raw-source line numbers while avoiding matches inside comments, strings, and regex bodies.
379
+ /**
380
+ * Masks recognized comment and literal bodies in `source` while preserving UTF-16 code-unit offsets and newlines.
381
+ * Regex-driven rules use the unchanged positions to report source locations without matching text inside those bodies.
382
+ *
383
+ * @param source - Raw source file text to mask.
384
+ * @returns Copy of `source` with comment, string, template, and regex bodies replaced by spaces.
385
+ */
327
386
  function maskNonCode(source: string): string {
328
387
  let result = "";
329
388
  const state = defaultMaskState();
@@ -335,10 +394,13 @@ function maskNonCode(source: string): string {
335
394
  return result;
336
395
  }
337
396
 
338
- // Replaces only `` ` `` template-literal body characters with spaces. Unlike `maskNonCode`, single
339
- // and double-quoted string bodies are preserved so syntax-pattern rules (e.g. import edges) still
340
- // see the specifier text on real `import ... from "..."` lines. Used by `import-edge` style rules
341
- // that must ignore fixture content embedded in template literals without losing real imports.
397
+ /**
398
+ * Masks template-literal bodies in `source` with spaces while preserving offsets and line-feed characters.
399
+ * Single- and double-quoted bodies remain visible so syntax-pattern rules can read real import specifiers.
400
+ *
401
+ * @param source - Raw source file text to mask.
402
+ * @returns Copy of `source` with backtick template contents replaced by spaces.
403
+ */
342
404
  function maskTemplateLiteralBodies(source: string): string {
343
405
  let result = "";
344
406
  const state = templateMaskState();
@@ -361,13 +423,24 @@ interface TemplateMaskState {
361
423
  isBlockComment: boolean;
362
424
  }
363
425
 
364
- // Fresh default state for a single-file template-mask pass.
426
+ /**
427
+ * Creates fresh default state for a single-file template-mask pass.
428
+ *
429
+ * @returns Initialized `TemplateMaskState` with no active quote or comment context.
430
+ */
365
431
  function templateMaskState(): TemplateMaskState {
366
432
  return { quote: undefined, isEscaped: false, isLineComment: false, isBlockComment: false };
367
433
  }
368
434
 
369
- // Per-character dispatch: newlines clear single-line state; backtick body chars are masked; quoted
370
- // and commented chars pass through. Skips the regex branch because regex bodies cannot start an import.
435
+ /**
436
+ * Transforms `character` with lookahead `next` for template-body masking, mutating `state` in place.
437
+ * Preserves delimiters, newlines, single/double-quoted strings, and comments while masking template body text.
438
+ *
439
+ * @param character - Current character from the source text.
440
+ * @param next - Lookahead character immediately following `character`.
441
+ * @param state - Mutable quote and comment context carried across characters.
442
+ * @returns Output text and extra-character skip count; regex literals receive no dedicated handling.
443
+ */
371
444
  function templateMaskCharacter(character: string, next: string, state: TemplateMaskState): MaskStep {
372
445
  if (character === "\n") return templateMaskNewline(state);
373
446
  if (state.isLineComment) return { text: character, skip: 0 };
@@ -376,7 +449,12 @@ function templateMaskCharacter(character: string, next: string, state: TemplateM
376
449
  return templateMaskCodeCharacter(character, next, state);
377
450
  }
378
451
 
379
- // Newlines clear line-comment state and any non-template quote; template literals survive across lines.
452
+ /**
453
+ * Clears line-comment state and any non-template quote at a newline while preserving template-literal mode.
454
+ *
455
+ * @param state - Mutable template-mask state updated in place at the line boundary.
456
+ * @returns Step emitting `"\n"` with no extra-character skip.
457
+ */
380
458
  function templateMaskNewline(state: TemplateMaskState): MaskStep {
381
459
  state.isLineComment = false;
382
460
  if (state.quote !== "`") {
@@ -385,7 +463,14 @@ function templateMaskNewline(state: TemplateMaskState): MaskStep {
385
463
  return { text: "\n", skip: 0 };
386
464
  }
387
465
 
388
- // Inside a block comment: pass body through and detect the closing `*/`.
466
+ /**
467
+ * Preserves block-comment text and clears `state.isBlockComment` when the closing delimiter is reached.
468
+ *
469
+ * @param character - Current character inside the block comment.
470
+ * @param next - Lookahead character immediately following `character`.
471
+ * @param state - Mutable template-mask state updated on a block-comment closer.
472
+ * @returns Preserved text with `skip: 1` on the closing pair, or `skip: 0` otherwise.
473
+ */
389
474
  function templateMaskBlockComment(character: string, next: string, state: TemplateMaskState): MaskStep {
390
475
  if (character === "*" && next === "/") {
391
476
  state.isBlockComment = false;
@@ -394,7 +479,14 @@ function templateMaskBlockComment(character: string, next: string, state: Templa
394
479
  return { text: character, skip: 0 };
395
480
  }
396
481
 
397
- // Inside any quoted string: bodies of `` ` `` get masked, single/double-quote bodies pass through.
482
+ /**
483
+ * Processes a character inside a quoted literal, masking backtick bodies while passing single/double quotes through.
484
+ * Preserves an unescaped closing quote and mutates escape and quote flags in `state`.
485
+ *
486
+ * @param character - Current character inside the active literal.
487
+ * @param state - Mutable template-mask state tracking escapes and the active quote delimiter.
488
+ * @returns Transformed character step with `skip: 0`.
489
+ */
398
490
  function templateMaskQuotedCharacter(character: string, state: TemplateMaskState): MaskStep {
399
491
  const masked = state.quote === "`";
400
492
  if (state.isEscaped) {
@@ -412,7 +504,15 @@ function templateMaskQuotedCharacter(character: string, state: TemplateMaskState
412
504
  return { text: masked ? " " : character, skip: 0 };
413
505
  }
414
506
 
415
- // In code: detect comment openers and the three quote types, otherwise pass through.
507
+ /**
508
+ * Detects comment openers and the three quote types in code, passing ordinary characters through unchanged.
509
+ * Mutates `state` when a comment or quote opener is matched.
510
+ *
511
+ * @param character - Current character in code context.
512
+ * @param next - Lookahead character immediately following `character`.
513
+ * @param state - Mutable template-mask state updated on comment or quote entry.
514
+ * @returns Preserved text and extra-character skip count (`1` for comment openers, `0` otherwise).
515
+ */
416
516
  function templateMaskCodeCharacter(character: string, next: string, state: TemplateMaskState): MaskStep {
417
517
  if (character === "/" && next === "/") {
418
518
  state.isLineComment = true;
@@ -440,7 +540,10 @@ interface MaskState {
440
540
  isRegexCharClass: boolean;
441
541
  isRegexEscaped: boolean;
442
542
  previousCode: string;
443
- templateInterpolationDepth: number;
543
+ // One entry per open `${`, innermost last, counting the braces still open inside that interpolation. A scalar
544
+ // depth cannot tell a nested template's own `}` from the enclosing interpolation's, so it resumed code where the
545
+ // inner template body continued and masked the rest of the file.
546
+ templateInterpolationDepths: number[];
444
547
  }
445
548
 
446
549
  // `text` is what gets written for this character (space for masked, original for code, " " for
@@ -450,7 +553,11 @@ interface MaskStep {
450
553
  skip: number;
451
554
  }
452
555
 
453
- // All flags start cleared so the first scanner step treats source as code.
556
+ /**
557
+ * Builds fresh `MaskState` with all flags cleared so the first scanner step treats source as code.
558
+ *
559
+ * @returns Initialized `MaskState` with empty prior code and no active literal or comment flags.
560
+ */
454
561
  function defaultMaskState(): MaskState {
455
562
  return {
456
563
  quote: undefined,
@@ -461,12 +568,19 @@ function defaultMaskState(): MaskState {
461
568
  isRegexCharClass: false,
462
569
  isRegexEscaped: false,
463
570
  previousCode: "",
464
- templateInterpolationDepth: 0,
571
+ templateInterpolationDepths: [],
465
572
  };
466
573
  }
467
574
 
468
- // Newlines short-circuit first - single-line `//` comments must clear at line end, and ordinary
469
- // quotes do too, but template literals (` ` `) survive across lines.
575
+ /**
576
+ * Masks or preserves `source[index]` according to `state`, mutating `state` as comments and literals open or close.
577
+ * Newlines end line comments and single-line quote or regex state while template literals and block comments remain active.
578
+ *
579
+ * @param source - Complete source text being masked.
580
+ * @param index - Zero-based UTF-16 offset of the current character in `source`.
581
+ * @param state - Mutable masking context carried across characters.
582
+ * @returns Output text and extra-character skip count for the current character or opener/closer pair.
583
+ */
470
584
  function maskNonCodeCharacter(source: string, index: number, state: MaskState): MaskStep {
471
585
  const character = source[index] ?? "";
472
586
  const next = source[index + 1] ?? "";
@@ -488,8 +602,13 @@ function maskNonCodeCharacter(source: string, index: number, state: MaskState):
488
602
  return maskCodeCharacter(source, index, character, next, state);
489
603
  }
490
604
 
491
- // At a newline: drop line-comment / single-quote / regex state, but preserve template-literal state
492
- // because backtick strings legitimately span multiple lines. Emits `\n` verbatim to keep offsets aligned.
605
+ /**
606
+ * Updates `state` at a newline by clearing line-comment, single-quote, double-quote, and regex modes.
607
+ * Keeps template-literal and block-comment modes because both can span lines, preserving source offsets.
608
+ *
609
+ * @param state - Mutable mask state updated in place at the newline.
610
+ * @returns Step emitting `"\n"` with `skip: 0`.
611
+ */
493
612
  function maskNewline(state: MaskState): MaskStep {
494
613
  state.isLineComment = false;
495
614
  if (state.quote !== "`") {
@@ -501,8 +620,15 @@ function maskNewline(state: MaskState): MaskStep {
501
620
  return { text: "\n", skip: 0 };
502
621
  }
503
622
 
504
- // Replaces block-comment text with spaces; the closing `*/` becomes " " so the two output
505
- // characters line up with the two consumed characters.
623
+ /**
624
+ * Replaces block-comment text with spaces, turning the closing delimiter into two spaces to preserve character alignment.
625
+ * Clears `state.isBlockComment` when the closing pair is consumed.
626
+ *
627
+ * @param character - Current character inside the block comment.
628
+ * @param next - Lookahead character immediately following `character`.
629
+ * @param state - Mutable mask state updated when the block comment closes.
630
+ * @returns Two spaces with `skip: 1` on a closer, or a single masked space step otherwise.
631
+ */
506
632
  function maskBlockComment(character: string, next: string, state: MaskState): MaskStep {
507
633
  if (character === "*" && next === "/") {
508
634
  state.isBlockComment = false;
@@ -511,8 +637,15 @@ function maskBlockComment(character: string, next: string, state: MaskState): Ma
511
637
  return maskSingleCharacter();
512
638
  }
513
639
 
514
- // Inside a string: mask body characters but emit the closing quote unchanged so downstream rules
515
- // can still see the quote boundary. `\` arms `isEscaped` to keep the next character literal.
640
+ /**
641
+ * Masks characters inside a quoted literal while keeping the closing quote and template `${` openers visible.
642
+ * Mutates `state` for escapes, closing quotes, and pushing brace depth when a template interpolation opens.
643
+ *
644
+ * @param character - Current character inside the quoted literal.
645
+ * @param next - Lookahead character immediately following `character`.
646
+ * @param state - Mutable mask state tracking escape, quote, and template interpolation stack state.
647
+ * @returns Masking step with spaces for literal body text, `"${"` on interpolation, or the closing quote.
648
+ */
516
649
  function maskQuotedCharacter(character: string, next: string, state: MaskState): MaskStep {
517
650
  if (state.isEscaped) {
518
651
  state.isEscaped = false;
@@ -524,7 +657,7 @@ function maskQuotedCharacter(character: string, next: string, state: MaskState):
524
657
  }
525
658
  if (state.quote === "`" && character === "$" && next === "{") {
526
659
  state.quote = undefined;
527
- state.templateInterpolationDepth += 1;
660
+ state.templateInterpolationDepths.push(1);
528
661
  state.previousCode = "{";
529
662
  return { text: "${", skip: 1 };
530
663
  }
@@ -536,8 +669,14 @@ function maskQuotedCharacter(character: string, next: string, state: MaskState):
536
669
  return maskSingleCharacter();
537
670
  }
538
671
 
539
- // Inside `/.../`: mask body characters and pass through the closing `/`. `[ ... ]` character classes
540
- // suspend the closing-slash check so `/[/]/` does not terminate at the inner slash.
672
+ /**
673
+ * Masks regex literal body characters and passes through the closing `/`, tracking escapes and `[...]` classes.
674
+ * Character classes suspend the closing-slash check so `/[/]/` does not terminate at the inner slash.
675
+ *
676
+ * @param character - Current character inside the regex literal.
677
+ * @param state - Mutable mask state updated for escapes, class boundaries, and regex exit.
678
+ * @returns Space-mask step for body characters, or the closing `/` with `skip: 0`.
679
+ */
541
680
  function maskRegexCharacter(character: string, state: MaskState): MaskStep {
542
681
  if (state.isRegexEscaped) {
543
682
  state.isRegexEscaped = false;
@@ -563,8 +702,17 @@ function maskRegexCharacter(character: string, state: MaskState): MaskStep {
563
702
  return maskSingleCharacter();
564
703
  }
565
704
 
566
- // Dispatch order in code mode matters: detect comment openers before regex, since `/*` would
567
- // otherwise be misread as a regex start; detect regex before quote because no quote begins with `/`.
705
+ /**
706
+ * Dispatches code-context masking for `source[index]`, mutating `state` on openers, braces, or code tokens.
707
+ * Checks comment openers before regex starts so a comment opener cannot enter regex mode, preserving offsets.
708
+ *
709
+ * @param source - Complete source text used to inspect context before a candidate regex slash.
710
+ * @param index - Zero-based offset of `character` in `source`.
711
+ * @param character - Current character in code context.
712
+ * @param next - Lookahead character immediately following `character`.
713
+ * @param state - Mutable mask state updated by the matching detector or plain-code fallback.
714
+ * @returns Output text and extra-character skip count from the first matching detector.
715
+ */
568
716
  function maskCodeCharacter(source: string, index: number, character: string, next: string, state: MaskState): MaskStep {
569
717
  return (
570
718
  maskTemplateInterpolationBrace(character, state) ??
@@ -576,21 +724,30 @@ function maskCodeCharacter(source: string, index: number, character: string, nex
576
724
  );
577
725
  }
578
726
 
579
- // While inside a template `${...}` expression, braces are executable code and must stay visible.
580
- // The depth counter returns to backtick masking only after the matching interpolation closer.
727
+ /**
728
+ * Tracks `{` and `}` inside the active template interpolation, mutating only its innermost brace depth.
729
+ * Closing the final brace pops the interpolation entry and resumes template-body masking.
730
+ *
731
+ * @param character - Current character in code context.
732
+ * @param state - Mutable mask state carrying `templateInterpolationDepths` and `previousCode`.
733
+ * @returns Step preserving the brace with `skip: 0`, or `undefined` outside interpolations or for other characters.
734
+ */
581
735
  function maskTemplateInterpolationBrace(character: string, state: MaskState): MaskStep | undefined {
582
- if (state.templateInterpolationDepth === 0) {
736
+ const openBraceDepths = state.templateInterpolationDepths;
737
+ const innermost = openBraceDepths.length - 1;
738
+ if (innermost < 0) {
583
739
  return undefined;
584
740
  }
585
741
  if (character === "{") {
586
- state.templateInterpolationDepth += 1;
742
+ openBraceDepths[innermost] = (openBraceDepths[innermost] ?? 0) + 1;
587
743
  state.previousCode = character;
588
744
  return { text: character, skip: 0 };
589
745
  }
590
746
  if (character === "}") {
591
- state.templateInterpolationDepth -= 1;
747
+ openBraceDepths[innermost] = (openBraceDepths[innermost] ?? 0) - 1;
592
748
  state.previousCode = character;
593
- if (state.templateInterpolationDepth === 0) {
749
+ if (openBraceDepths[innermost] === 0) {
750
+ openBraceDepths.pop();
594
751
  state.quote = "`";
595
752
  }
596
753
  return { text: character, skip: 0 };
@@ -598,8 +755,14 @@ function maskTemplateInterpolationBrace(character: string, state: MaskState): Ma
598
755
  return undefined;
599
756
  }
600
757
 
601
- // Detects `//` and arms line-comment mode; the actual masking happens on subsequent characters
602
- // via the `state.isLineComment` branch in `maskNonCodeCharacter`.
758
+ /**
759
+ * Detects a `//` line-comment opener and mutates `state.isLineComment` so the rest of the line is masked.
760
+ *
761
+ * @param character - Current character in code context.
762
+ * @param next - Lookahead character immediately following `character`.
763
+ * @param state - Mutable mask state updated when a line comment starts.
764
+ * @returns Two spaces with `skip: 1` on match, or `undefined` for the next detector.
765
+ */
603
766
  function maskLineCommentStart(character: string, next: string, state: MaskState): MaskStep | undefined {
604
767
  if (character === "/" && next === "/") {
605
768
  state.isLineComment = true;
@@ -608,7 +771,14 @@ function maskLineCommentStart(character: string, next: string, state: MaskState)
608
771
  return undefined;
609
772
  }
610
773
 
611
- // Detects `/*` and masks the two opener characters. State flips so subsequent chars route to `maskBlockComment`.
774
+ /**
775
+ * Detects a block-comment opener (`/*`) and mutates `state.isBlockComment` so comment text is masked.
776
+ *
777
+ * @param character - Current character in code context.
778
+ * @param next - Lookahead character immediately following `character`.
779
+ * @param state - Mutable mask state updated when a block comment starts.
780
+ * @returns Two spaces with `skip: 1` on match, or `undefined` for the next detector.
781
+ */
612
782
  function maskBlockCommentStart(character: string, next: string, state: MaskState): MaskStep | undefined {
613
783
  if (character === "/" && next === "*") {
614
784
  state.isBlockComment = true;
@@ -617,8 +787,15 @@ function maskBlockCommentStart(character: string, next: string, state: MaskState
617
787
  return undefined;
618
788
  }
619
789
 
620
- // Same regex-vs-division heuristic as `parseDiagnostics`, but with up to 80 prior characters of
621
- // context (rather than just one) to recognise the `return /pattern/` case across multi-token expressions.
790
+ /**
791
+ * Detects a regex literal opener using up to 80 characters before `index` and mutates `state.isRegex`.
792
+ *
793
+ * @param source - Complete source text supplying preceding context for the regex-start heuristic.
794
+ * @param index - Zero-based offset of `character` in `source`.
795
+ * @param character - Current character in code context.
796
+ * @param state - Mutable mask state supplying `previousCode` and updated on regex entry.
797
+ * @returns Step preserving `/` with `skip: 0` on match, or `undefined` for the next detector.
798
+ */
622
799
  function maskRegexStart(source: string, index: number, character: string, state: MaskState): MaskStep | undefined {
623
800
  if (character === "/" && isRegexLiteralStart(state.previousCode, source.slice(Math.max(0, index - 80), index))) {
624
801
  state.isRegex = true;
@@ -628,8 +805,14 @@ function maskRegexStart(source: string, index: number, character: string, state:
628
805
  return undefined;
629
806
  }
630
807
 
631
- // Opening quote is emitted unchanged so downstream rules can detect string boundaries; subsequent
632
- // body characters get masked by `maskQuotedCharacter`.
808
+ /**
809
+ * Detects a string or template quote opener and mutates `state.quote` and `state.previousCode`.
810
+ * Later calls mask literal text while keeping quote boundaries and template interpolation code visible.
811
+ *
812
+ * @param character - Current character in code context.
813
+ * @param state - Mutable mask state updated with the active quote delimiter.
814
+ * @returns Step preserving the quote with `skip: 0` on match, or `undefined` for the plain-code fallback.
815
+ */
633
816
  function maskQuoteStart(character: string, state: MaskState): MaskStep | undefined {
634
817
  if (isQuote(character)) {
635
818
  state.quote = character;
@@ -639,8 +822,14 @@ function maskQuoteStart(character: string, state: MaskState): MaskStep | undefin
639
822
  return undefined;
640
823
  }
641
824
 
642
- // Code characters survive into the masked output; only non-whitespace updates `previousCode` because
643
- // the regex-start heuristic must look at the last real token, not at the space before it.
825
+ /**
826
+ * Passes an ordinary code character through into masked output, updating `state.previousCode` only for non-whitespace.
827
+ * Only non-whitespace updates `previousCode` because the regex-start heuristic must see the last real token.
828
+ *
829
+ * @param character - Current ordinary character in code context.
830
+ * @param state - Mutable mask state whose `previousCode` is updated for non-whitespace characters.
831
+ * @returns Step preserving `character` with `skip: 0`.
832
+ */
644
833
  function maskPlainCodeCharacter(character: string, state: MaskState): MaskStep {
645
834
  if (isNonWhitespaceCharacter(character)) {
646
835
  state.previousCode = character;
@@ -648,14 +837,22 @@ function maskPlainCodeCharacter(character: string, state: MaskState): MaskStep {
648
837
  return { text: character, skip: 0 };
649
838
  }
650
839
 
651
- // One space per masked byte. Preserves overall length so byte offsets in masked text map 1:1 to source.
840
+ /**
841
+ * Builds a single-space mask step to obscure one UTF-16 code unit while preserving source offsets.
842
+ *
843
+ * @returns `MaskStep` emitting `" "` with `skip: 0`.
844
+ */
652
845
  function maskSingleCharacter(): MaskStep {
653
846
  return { text: " ", skip: 0 };
654
847
  }
655
848
 
656
- // Cheaper, line-local mask used when rules don't need full lexer state - strips line-comments and
657
- // string bodies but does not track block comments. Use `maskNonCode` instead when state must
658
- // survive across lines.
849
+ /**
850
+ * Strips string bodies and line comments from a single line while leaving quote delimiters for matching.
851
+ * This line-local scanner has no block-comment state; use `maskNonCode` to preserve state across lines.
852
+ *
853
+ * @param line - Single source line to strip for local pattern matching.
854
+ * @returns Line text with quoted contents and trailing line comments removed.
855
+ */
659
856
  function codeLineForMatching(line: string): string {
660
857
  let result = "";
661
858
  const state: CodeLineState = { quote: undefined, isEscaped: false };
@@ -682,8 +879,15 @@ interface CodeLineStep {
682
879
  shouldStopLine: boolean;
683
880
  }
684
881
 
685
- // Quotes are emitted (so callers can see the literal boundary) but their bodies are dropped, while
686
- // any `//` outside a string truncates the rest of the line.
882
+ /**
883
+ * Evaluates `line[index]` for line-local matching, mutating `state` to track string delimiters and escapes.
884
+ * A line-comment opener outside a string emits empty text and stops the line; other characters continue scanning.
885
+ *
886
+ * @param line - Raw source line being scanned.
887
+ * @param index - Zero-based offset of the current character in `line`.
888
+ * @param state - Mutable quote and escape state carried along the line.
889
+ * @returns Output text (keeping quotes and code, dropping string bodies) and `shouldStopLine` flag.
890
+ */
687
891
  function codeLineCharacter(line: string, index: number, state: CodeLineState): CodeLineStep {
688
892
  const character = line[index] ?? "";
689
893
  const next = line[index + 1] ?? "";
@@ -700,8 +904,14 @@ function codeLineCharacter(line: string, index: number, state: CodeLineState): C
700
904
  return { text: character, shouldStopLine: false };
701
905
  }
702
906
 
703
- // Body characters of a string are dropped so `"// not a comment"` doesn't truncate the line, but
704
- // the closing quote is emitted so the caller still sees a balanced literal.
907
+ /**
908
+ * Suppresses quoted literal contents while keeping the unescaped closing quote visible as the literal boundary.
909
+ * Mutates `state` to track escapes and clears `state.quote` when the literal closes.
910
+ *
911
+ * @param character - Current character inside the quoted literal.
912
+ * @param state - Mutable quote and escape state updated in place.
913
+ * @returns Closing quote or empty text, always with `shouldStopLine: false`.
914
+ */
705
915
  function quotedCodeLineCharacter(character: string, state: CodeLineState): CodeLineStep {
706
916
  if (state.isEscaped) {
707
917
  state.isEscaped = false;
@@ -718,28 +928,50 @@ function quotedCodeLineCharacter(character: string, state: CodeLineState): CodeL
718
928
  return { text: "", shouldStopLine: false };
719
929
  }
720
930
 
721
- // Default step: caller advances by one, line continues. Centralised so callers stay symmetrical.
931
+ /**
932
+ * Default scan step advancing by one character while keeping the line scan active.
933
+ *
934
+ * @returns `ScanStep` with `skip: 0` and `shouldStopLine: false`.
935
+ */
722
936
  function continueScan(): ScanStep {
723
937
  return { skip: 0, shouldStopLine: false };
724
938
  }
725
939
 
726
- // Skip one extra character - used to swallow the second half of a two-character token like `*/`.
940
+ /**
941
+ * Builds a scan step that skips the second character of a two-character token and keeps scanning.
942
+ *
943
+ * @returns `ScanStep` with `skip: 1` and `shouldStopLine: false`.
944
+ */
727
945
  function skipNextCharacter(): ScanStep {
728
946
  return { skip: 1, shouldStopLine: false };
729
947
  }
730
948
 
731
- // End-of-line short circuit returned when a `//` line comment starts.
949
+ /**
950
+ * Builds a scan step that ends the current line scan at a line comment so remaining text contributes no delimiters.
951
+ *
952
+ * @returns `ScanStep` with `skip: 0` and `shouldStopLine: true`.
953
+ */
732
954
  function stopLineScan(): ScanStep {
733
955
  return { skip: 0, shouldStopLine: true };
734
956
  }
735
957
 
736
- // String, template literal, and char-class quotes recognised by every lexer in this module.
958
+ /**
959
+ * Checks whether `character` can delimit a single-quoted string, double-quoted string, or template literal.
960
+ *
961
+ * @param character - Single character to check against `"`, `'`, and `` ` ``.
962
+ * @returns True when `character` is one of the three JS/TS quote delimiters; otherwise false.
963
+ */
737
964
  function isQuote(character: string): boolean {
738
965
  return character === "\"" || character === "'" || character === "`";
739
966
  }
740
967
 
741
- // Used by `maskPlainCodeCharacter` to decide whether a character should overwrite `previousCode`.
742
- // Whitespace must not, otherwise the regex-vs-division heuristic would be fed the wrong token.
968
+ /**
969
+ * Checks whether `character` is non-empty and not horizontal or vertical ASCII whitespace.
970
+ * Used by `maskPlainCodeCharacter` so whitespace must not overwrite `previousCode` for the regex heuristic.
971
+ *
972
+ * @param character - Character inspected before updating `previousCode`.
973
+ * @returns True if `character` is non-empty and not space, tab, CR, or LF; otherwise false.
974
+ */
743
975
  function isNonWhitespaceCharacter(character: string): boolean {
744
976
  return character !== "" && character !== " " && character !== "\t" && character !== "\r" && character !== "\n";
745
977
  }