@kongyo2/ts-comment-scanner 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/directives.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { docblockPragmas } from "./docblock.js";
1
2
  import { lastLine, splitLines } from "./lines.js";
2
3
  import type { CommentKind } from "./types.js";
3
4
 
@@ -5,13 +6,19 @@ interface DirectiveRule {
5
6
  pattern: RegExp;
6
7
  /**
7
8
  * Fixed name, or derive it from the match — returning undefined rejects the
8
- * match, for checks a single regex cannot express. Defaults to the full
9
- * matched text.
9
+ * match, for checks a single regex cannot express, and a list reports every
10
+ * directive the match carries (a docblock can hold several pragmas).
11
+ * Defaults to the full matched text.
10
12
  */
11
- name?: string | ((match: RegExpExecArray) => string | undefined);
13
+ name?: string | ((match: RegExpExecArray) => string | readonly string[] | undefined);
12
14
  blockOnly?: boolean;
13
15
  /** Only match line comments (e.g. JetBrains suppressions in JS/TS). */
14
16
  lineOnly?: boolean;
17
+ /**
18
+ * Only match comments whose text holds no line feed — `//` comments and
19
+ * single-line block comments, the comments CodeQL reads suppressions from.
20
+ */
21
+ singleLine?: boolean;
15
22
  /** Match any content line, not just the first (for docblock pragmas). */
16
23
  anyLine?: boolean;
17
24
  /**
@@ -28,9 +35,8 @@ interface DirectiveRule {
28
35
  */
29
36
  rawText?: boolean;
30
37
  /**
31
- * Skip `/**`-opened block comments: webpack evaluates the comment body as
32
- * an object literal (JSDoc stars break it), and dprint/datadog skip only
33
- * whitespace before their marker, so a leading `*` defeats them.
38
+ * Skip `/**`-opened block comments: the datadog analyzer skips only
39
+ * whitespace before its marker, so a leading `*` defeats it.
34
40
  */
35
41
  notDocblock?: boolean;
36
42
  /**
@@ -60,94 +66,183 @@ function stylelintDirective(token: string): string | undefined {
60
66
  return STYLELINT_COMMANDS.has(command) ? `${STYLELINT_MARKER}${command}` : undefined;
61
67
  }
62
68
 
69
+ // Prettier's FORMAT_PRAGMAS and FORMAT_IGNORE_PRAGMAS (its
70
+ // `src/utilities/pragma/pragma.evaluate.js`): the docblock keys that
71
+ // --require-pragma looks for and --check-ignore-pragma stops on.
72
+ const FORMAT_PRAGMA_KEYS: ReadonlySet<string> = new Set(["format", "prettier", "noformat", "noprettier"]);
73
+
74
+ // The canonical spelling of each JSX pragma, keyed by its lowercased name.
75
+ const JSX_PRAGMAS: ReadonlyMap<string, string> = new Map(
76
+ ["jsx", "jsxFrag", "jsxRuntime", "jsxImportSource", "jsxImportSourceTypes"].map((name) => [
77
+ name.toLowerCase(),
78
+ `@${name}`,
79
+ ]),
80
+ );
81
+
82
+ // typescript-strict-plugin's two pragmas; the capture is the `-ignore` suffix.
83
+ const tsStrictName = (match: RegExpExecArray): string => (match[1] === undefined ? "@ts-strict" : "@ts-strict-ignore");
84
+
63
85
  const RULES: DirectiveRule[] = [
64
- // ESLint
65
- { pattern: /^eslint-(?:disable|enable)(?:-next-line|-line)?\b/ },
66
- { pattern: /^eslint-env\b/ },
67
- { pattern: /^eslint\s+\S/, name: "eslint", blockOnly: true, joinLines: true },
86
+ // ESLint and oxlint. ESLint 10 takes the label from the trimmed comment value
87
+ // (`[a-z]+(?:-[a-z]+)*` followed by whitespace or the end) and honours only
88
+ // `eslint-disable-line`/`-next-line` in `//` comments; oxlint reads all four
89
+ // commands, and its own prefix, from comments of either kind, under the
90
+ // same boundary. A JSDoc star in front of the label defeats both, and so
91
+ // does a glued suffix (`eslint-disable-foo`, `eslint-disable:foo`).
92
+ { pattern: /^(?:eslint|oxlint)-(?:disable(?:-next-line|-line)?|enable)(?=\s|$)/, keepStars: true },
93
+ // React Compiler (babel-plugin-react-compiler, and Bun's port of it) skips a
94
+ // component whose comments suppress its react-hooks rules: it searches each
95
+ // comment for `eslint-disable`/`-next-line`/`eslint-enable` followed by one
96
+ // of the rules, anywhere in the text — JSDoc blocks and mid-text mentions
97
+ // included.
98
+ {
99
+ pattern: /eslint-(disable(?:-next-line)?|enable)\s[^]*react-hooks\/(?:exhaustive-deps|rules-of-hooks)/,
100
+ rawText: true,
101
+ name: (match) => `eslint-${match[1] as string}`,
102
+ },
103
+ // ESLint 10 reports `/* eslint-env */` comments as no longer supported, and
104
+ // ESLint 9's eslintrc mode still applies them; both read block comments
105
+ // only, like the configuration comments below.
106
+ { pattern: /^eslint-env(?=\s|$)/, blockOnly: true, keepStars: true },
107
+ { pattern: /^eslint\s+\S/, name: "eslint", blockOnly: true, joinLines: true, keepStars: true },
68
108
  {
69
109
  pattern: /^(globals?|exported)\s+\S/,
70
110
  name: (match) => match[1] as string,
71
111
  blockOnly: true,
72
112
  joinLines: true,
113
+ keepStars: true,
73
114
  },
74
- // TSLint (legacy)
75
- { pattern: /^tslint:[a-z-]+/ },
115
+ // TSLint (legacy): tslint:(enable|disable)(-line|-next-line)? ending at a
116
+ // colon, whitespace or the end of the comment value.
117
+ { pattern: /^tslint:(?:enable|disable)(?:-line|-next-line)?(?=:|\s|$)/, keepStars: true },
76
118
  // JSHint (legacy): `key: value` options and ignore markers (`jshint
77
119
  // esversion: 6`, `jshint ignore:line`) plus `-W###`/`+W###` warning toggles.
78
120
  // Requiring those shapes keeps prose like `jshint is unused` ordinary.
79
121
  { pattern: /^jshint\s+(?:[A-Za-z$_][\w$]*\s*:|[-+]W\d+\b)/, name: "jshint", joinLines: true },
80
- // JSCS (legacy). Spacing after the colon is lenient (`jscs: enable` works),
81
- // so the name is normalised to the compact form.
82
- { pattern: /^jscs:\s*(disable|enable|ignore)\b/, name: (match) => `jscs:${match[1]}`, joinLines: true },
83
- // JSLint (legacy): the directive word must sit immediately after the
84
- // comment marker with no space (`/*jslint devel*/` works, `/* jslint */`
85
- // does not) and needs a body, so these match the raw text. The whole-line
86
- // pragmas (`/*jslint-disable*/`, `//jslint-ignore-line`) are exact strings.
87
- { pattern: /^\/[/*](jslint|property)\s+\S/, rawText: true, name: (match) => match[1] as string },
122
+ // JSCS (legacy) allows whitespace on both sides of the colon (`jscs :
123
+ // enable`), so the name is normalised to the compact form.
124
+ {
125
+ pattern: /^jscs\s*:\s*(disable|enable|ignore)/,
126
+ name: (match) => `jscs:${match[1]}`,
127
+ joinLines: true,
128
+ keepStars: true,
129
+ },
130
+ // JSLint: the directive word must sit immediately after the comment marker
131
+ // with no space (`/*jslint devel*/` works, `/* jslint */` does not) and
132
+ // needs a body, so these match the raw text; `//global` counts too. The
133
+ // whole-line pragmas (`/*jslint-disable*/`, `//jslint-ignore-line`) are
134
+ // exact strings.
135
+ { pattern: /^\/[/*](jslint|property|global)\s+\S/, rawText: true, name: (match) => match[1] as string },
88
136
  { pattern: /^\/\*jslint-(disable|enable)\*\/$/, rawText: true, name: (match) => `jslint-${match[1]}` },
89
137
  { pattern: /^\/\/jslint-(ignore-line|quiet)$/, rawText: true, name: (match) => `jslint-${match[1]}` },
90
- // oxlint
91
- { pattern: /^oxlint-(?:disable|enable)(?:-next-line|-line)?\b/ },
92
- // Biome
93
- { pattern: /^biome-ignore(?:-all|-start|-end)?\b/ },
94
- // Rome (Biome's predecessor). Case-insensitive keyword with `-` or `_`,
95
- // then known categories and a mandatory colon — without the colon Rome
96
- // reported a parse diagnostic and the suppression stayed inert.
138
+ // Biome parses every line of a comment (leading `*`s stripped) that opens
139
+ // with `biome-ignore`; `-all` applies only before the file's first token
140
+ // (anything later is rejected as a misplaced top-level suppression).
141
+ {
142
+ pattern: /^biome-ignore(-all|-start|-end)?/,
143
+ name: (match) => `biome-ignore${match[1] ?? ""}`,
144
+ anyLine: true,
145
+ },
146
+ // Rome (Biome's predecessor) used the same line-by-line parser: a
147
+ // case-insensitive keyword with `-` or `_`, then categories (`lint`,
148
+ // `lint/<group>/<rule>`, `format`, `parse`, ...) and a mandatory colon —
149
+ // without the colon Rome reported a parse diagnostic and the suppression
150
+ // stayed inert.
97
151
  {
98
- pattern: /^rome[-_]ignore\s*(?:(?:parse|format|lint)(?:\([^)]*\))?\s*)+:/i,
152
+ pattern:
153
+ /^rome[-_]ignore\s*(?:(?:lint(?:\/[A-Za-z0-9]+){0,2}|parse(?:\/[A-Za-z0-9]+)?|format|organizeImports)(?:\([^)]*\))?\s*)+:/i,
99
154
  name: "rome-ignore",
100
155
  anyLine: true,
101
156
  },
102
- // Deno
103
- { pattern: /^deno-(?:lint-ignore(?:-file)?|fmt-ignore(?:-file)?|coverage-ignore(?:-file|-start|-stop)?)\b/ },
157
+ // Deno. deno_lint compares the first whitespace-delimited token of the
158
+ // trimmed comment text with the directive, so a JSDoc star in front defeats
159
+ // it; `deno-lint-ignore` may be a block comment (the only form inside JSX
160
+ // children), the file form only a line comment in the header. The coverage
161
+ // directives are line comments compared the same way, and
162
+ // `deno-coverage-ignore-file` only counts as the file's first comment.
163
+ { pattern: /^deno-lint-ignore(?=\s|$)/, keepStars: true },
164
+ { pattern: /^deno-(?:lint-ignore-file|coverage-ignore(?:-file|-start|-stop)?)(?=\s|$)/, lineOnly: true },
104
165
  // Deno type directives. deno_graph matches them case-insensitively at the
105
- // comment start; `@deno-types` accepts a bare specifier, the newer names
106
- // require quotes.
107
- { pattern: /^@deno-types\s*=\s*(?:"[^"\n]+"|'[^'\n]+'|\S+)/i, name: "@deno-types" },
108
- { pattern: /^@ts-types\s*=\s*(?:"[^"\n]+"|'[^'\n]+')/i, name: "@ts-types" },
109
- { pattern: /^@ts-self-types\s*=\s*(?:"[^"\n]+"|'[^'\n]+')/i, name: "@ts-self-types" },
166
+ // start of the comment text; `@deno-types` accepts a bare specifier, the
167
+ // newer names require quotes. A JSDoc star in front defeats them.
168
+ { pattern: /^@deno-types\s*=\s*(?:["'][^"']+["']|\S+)/i, keepStars: true, name: "@deno-types" },
169
+ { pattern: /^@ts-types\s*=\s*["'][^"']+["']/i, keepStars: true, name: "@ts-types" },
170
+ { pattern: /^@ts-self-types\s*=\s*["'][^"']+["']/i, keepStars: true, name: "@ts-self-types" },
110
171
  // stylelint. A configuration comment is recognised from the first
111
172
  // whitespace-delimited token of the trimmed comment body alone (see
112
173
  // stylelintDirective), so a glued rule list, a suffix, prose before the
113
174
  // marker or a different case leave the comment inert — as does a JSDoc star
114
175
  // after `/**`, which postcss keeps as comment text (hence keepStars). `//`
115
176
  // comments count too: postcss-scss and postcss-less hand stylelint the same
116
- // trimmed text. Verified against stylelint 17.15. A project-specific
177
+ // trimmed text. Verified against stylelint 17.16. A project-specific
117
178
  // `configurationComment` prefix cannot be known here, so only the default
118
179
  // marker is matched.
119
180
  { pattern: /^\S+/, keepStars: true, name: (match) => stylelintDirective(match[0]) },
120
- // Formatter suppressions (prettier, and oxfmt which mirrors it). Both
121
- // parsers compare the exact trimmed comment body, so the marker must be the
181
+ // Formatter suppressions (prettier, and oxfmt which mirrors it). Prettier's
182
+ // isPrettierIgnoreComment compares `comment.value.trim()` with the exact
183
+ // string, for line and block comments alike, so the marker must be the
122
184
  // whole comment (joinLines makes `$` span every line): hyphenated
123
- // lookalikes (`oxfmt-ignore-more`) and prose stay ordinary. keepStars,
124
- // because the literal comparison also means a JSDoc `*` before the marker
125
- // (`/** prettier-ignore *​/`) leaves the comment ordinary — verified against
126
- // prettier 3.8.
127
- { pattern: /^prettier-ignore(?:-start|-end)?$/, joinLines: true, keepStars: true },
185
+ // lookalikes (`oxfmt-ignore-more`) and prose stay ordinary, and so do
186
+ // `prettier-ignore-start`/`-end`, which prettier only reads in Markdown.
187
+ // keepStars, because the literal comparison also means a JSDoc `*` before
188
+ // the marker (`/** prettier-ignore *​/`) leaves the comment ordinary.
189
+ { pattern: /^prettier-ignore$/, joinLines: true, keepStars: true },
128
190
  { pattern: /^oxfmt-ignore$/, joinLines: true, keepStars: true },
129
- // dprint. The file pragma is a starts-with check (trailing text allowed) on
130
- // the file's leading comments, skipping only whitespace — a `/**` docblock
131
- // star defeats it. The node pragma is a substring bounded by
132
- // non-alphanumerics anywhere in the comment, so a reason may follow.
133
- { pattern: /^dprint-ignore-file/, notDocblock: true, name: "dprint-ignore-file" },
191
+ // dprint, and `deno fmt`, which runs dprint's TypeScript plugin with
192
+ // `deno-fmt-ignore`/`deno-fmt-ignore-file` as its comment texts. The file
193
+ // pragma is a starts-with check on the file's leading comments, after only
194
+ // spaces in a `//` comment and any whitespace in a block one, so a tab or a
195
+ // `/**` docblock star defeats it. The node pragma is a substring bounded by
196
+ // non-alphanumerics anywhere in the comment, so a reason may follow — and
197
+ // below the header a stray file pragma still counts as one.
134
198
  {
135
- pattern: /(?:^|[^\p{L}\p{N}])dprint-ignore(?![\p{L}\p{N}])/u,
136
- name: "dprint-ignore",
199
+ pattern: /^\/(?:\/ *|\*\s*)(dprint|deno-fmt)-ignore-file/,
200
+ rawText: true,
201
+ name: (match) => `${match[1] as string}-ignore-file`,
202
+ },
203
+ {
204
+ pattern: /(?:^|[^\p{L}\p{N}])(dprint|deno-fmt)-ignore(?![\p{L}\p{N}])/u,
205
+ name: (match) => `${match[1] as string}-ignore`,
137
206
  anyLine: true,
138
207
  },
139
208
  // Prettier pragma mode (--require-pragma / --check-ignore-pragma). Prettier
140
- // reads them via jest-docblock: only the file's first block comment counts
141
- // and the pragma has to open a line. The lookahead keeps distinct keys like
142
- // `@prettier-plugin` ordinary, matching jest-docblock's `@(\S+)` parsing.
143
- { pattern: /^@(?:no)?(?:format|prettier)(?=\s|$)/, blockOnly: true, anyLine: true },
144
- // prettier-plugin-organize-imports: a literal whole-file substring check,
145
- // `//` and single space included, so it matches the raw comment text.
146
- { pattern: /\/\/ organize-imports-ignore/, rawText: true, name: "organize-imports-ignore" },
209
+ // reads the pragmas through jest-docblock (its `src/language-js/pragma.js`):
210
+ // only the file's first block comment counts, and a pragma is a key that
211
+ // opens a line of the docblock, so `@prettier-plugin` is a different key and
212
+ // stays ordinary. The port in docblock.ts carries jest-docblock's exact
213
+ // line-shape rules (spaces only before the gutter star and the `@`).
214
+ {
215
+ pattern: /^\/\*/,
216
+ rawText: true,
217
+ blockOnly: true,
218
+ name: (match) =>
219
+ docblockPragmas(match.input)
220
+ .filter((key) => FORMAT_PRAGMA_KEYS.has(key))
221
+ .map((key) => `@${key}`),
222
+ },
223
+ // JSDoc type casts. Prettier's isTypeCastComment takes any `/**` docblock
224
+ // whose value matches /@(?:type|satisfies)\b/ and keeps the parentheses of
225
+ // the expression that follows it (`/** @type {Foo} *​/ (bar)`), the cast
226
+ // tsc itself honours in JavaScript. A `/*` comment or `@typedef` is not one.
227
+ { pattern: /^\/\*\*[^]*?@(type|satisfies)\b/, rawText: true, blockOnly: true, name: (match) => `@${match[1]}` },
228
+ // Import sorting. prettier-plugin-organize-imports skips a file whose text
229
+ // contains `// organize-imports-ignore` or `// tslint:disable:ordered-imports`
230
+ // (single space included, so it matches the raw comment text);
231
+ // @trivago/prettier-plugin-sort-imports, and Bun's port of it, skip one
232
+ // whose leading or import comments start with `sort-imports-ignore` once
233
+ // leading whitespace is trimmed.
234
+ {
235
+ pattern: /\/\/ (?:organize-imports-ignore|tslint:disable:ordered-imports)/,
236
+ rawText: true,
237
+ name: "organize-imports-ignore",
238
+ },
239
+ { pattern: /^sort-imports-ignore/, keepStars: true, name: "sort-imports-ignore" },
147
240
  // js-beautify (legacy): exact-shape block comments with single spaces; only
148
- // the ignore/preserve pairs have an effect.
241
+ // the ignore/preserve pairs have an effect. The comment ending an ignored
242
+ // range is searched with `\s` instead, so any one whitespace character
243
+ // separates its words.
149
244
  {
150
- pattern: /^\/\* beautify(?: (?:ignore|preserve):(?:start|end))+ \*\/$/,
245
+ pattern: /^\/\*(?: beautify(?: (?:ignore|preserve):(?:start|end))+ |\sbeautify\signore:end\s)\*\/$/,
151
246
  rawText: true,
152
247
  blockOnly: true,
153
248
  name: "beautify",
@@ -163,9 +258,23 @@ const RULES: DirectiveRule[] = [
163
258
  { pattern: /^c8\s+ignore\b/, name: "c8-ignore" },
164
259
  { pattern: /^v8\s+ignore\s+([a-z]+)/, name: (match) => `v8-ignore-${match[1]}` },
165
260
  { pattern: /^v8\s+ignore\b/, name: "v8-ignore" },
261
+ // Node core reads `node:coverage` with `ignore next [N]`, `disable` and
262
+ // `enable`; Vitest's v8 provider also takes its `ignore` with `start`/`stop`
263
+ // as a range, which gets a range name like the other tools'
264
+ // (`node:coverage-ignore` stays the counted next-line pragma). Source text
265
+ // must never spell a range pragma out: the v8 provider finds one on any line
266
+ // of this file too, and would drop the rest of it from coverage.
166
267
  {
167
- pattern: /^node:coverage\s+(disable|enable|ignore)\b/,
168
- name: (match) => `node:coverage-${match[1]}`,
268
+ pattern: /^node:coverage\s+(?:ignore\s+(start|stop)(?=\W|$)|(disable|enable|ignore)\b)/,
269
+ name: (match) =>
270
+ match[1] === undefined ? `node:coverage-${match[2] as string}` : `node:coverage-ignore-${match[1]}`,
271
+ },
272
+ // ast-v8-to-istanbul finds `ignore start`/`stop` ranges with a plain text
273
+ // search over every line, so those count after any other text as well.
274
+ {
275
+ pattern: /(istanbul|[cv]8|node:coverage)\s+ignore\s+(start|stop)(?=\W|$)/,
276
+ name: (match) => `${match[1] as string}-ignore-${match[2] as string}`,
277
+ anyLine: true,
169
278
  },
170
279
  // type-coverage: substring match in any comment. There is no ignore-file
171
280
  // comment — file-level ignores are a CLI option only.
@@ -175,30 +284,36 @@ const RULES: DirectiveRule[] = [
175
284
  anyLine: true,
176
285
  },
177
286
  // StrykerJS mutation testing. The instrumenter runs
178
- // /^\s?Stryker (disable|restore)( next-line)? <mutators>/ against the raw
179
- // comment value: at most one space before `Stryker`, single literal spaces,
180
- // and a mandatory mutator list (`all` or names) — hence the rawText match.
287
+ // /^\s?Stryker (disable|restore)(?: (next-line))? ([a-zA-Z, ]+)/ against the
288
+ // raw comment value: at most one space before `Stryker`, single literal
289
+ // spaces, and a mandatory mutator list (`all` or names, which may itself
290
+ // open with blanks or a comma) — hence the rawText match.
181
291
  {
182
- pattern: /^\/[/*]\s?Stryker (disable|restore)( next-line)? [a-zA-Z]/,
292
+ pattern: /^\/[/*]\s?Stryker (disable|restore)( next-line)? [a-zA-Z, ]/,
183
293
  rawText: true,
184
294
  name: (match) => `stryker-${match[1]}${match[2] === undefined ? "" : "-next-line"}`,
185
295
  },
186
296
  // ts-prune: substring of the closest leading comment above an export.
187
297
  { pattern: /ts-prune-ignore-next/, name: "ts-prune-ignore-next", anyLine: true },
188
- // typescript-strict-plugin: token-equality scan over the whole file (the
189
- // CLI splits comment lines on spaces, the IDE plugin uses a TODO scan).
190
- {
191
- pattern: /(?:^|\s)@ts-strict(-ignore)?(?=\s|$)/,
192
- name: (match) => (match[1] === undefined ? "@ts-strict" : "@ts-strict-ignore"),
193
- anyLine: true,
194
- },
195
- // Flow. The pragmas live in the file's leading docblock and are matched as
196
- // whole words (text may surround them). Suppressions must open the comment
197
- // and take an optional [error-code]; all four historical suppressors are
198
- // recognised ($FlowIssue/$FlowIgnore stopped working in Flow 0.281 but
199
- // still gate older setups). flowlint takes rule:severity pairs.
298
+ // typescript-strict-plugin. Its CLI splits `//` lines on spaces and compares
299
+ // the tokens, so the pragma may sit anywhere on such a line; its IDE plugin
300
+ // finds it with tsc's TODO-comment scan instead — case-insensitively, right
301
+ // after the comment opener or a line's leading stars, and followed by
302
+ // anything but an ASCII letter or digit (`@ts-strict-ignore: legacy`).
303
+ { pattern: /(?:^|\s)@ts-strict(-ignore)?(?=\s|$)/, name: tsStrictName, anyLine: true },
304
+ { pattern: /(?:^[\s*]*|\/\/+\s*|\/\*+\s*)@ts-strict(-ignore)?(?![A-Za-z0-9])/im, rawText: true, name: tsStrictName },
305
+ // Flow. The pragmas live in the file's leading comments. Prettier's babel
306
+ // parser switches to Flow syntax when /@(?:no)?flow\b/ matches anywhere in
307
+ // the text before the first token (isFlowFile in its parse/babel.js), so
308
+ // `foo@flow.com` or `@flow-strict` in a header comment is live to it; Flow's
309
+ // own tokenised pragma (`@flow` as a whole word) is a subset of that.
310
+ // Suppressions must open the comment and take an optional [error-code]
311
+ // (Flow now requires one; older releases did not); all four historical
312
+ // suppressors are recognised ($FlowIssue/$FlowIgnore stopped working in
313
+ // Flow 0.281 but still gate older setups). flowlint takes rule:severity
314
+ // pairs.
200
315
  {
201
- pattern: /(?:^|[\s*/])@(no)?flow(?=$|[\s*/])/,
316
+ pattern: /@(no)?flow\b/,
202
317
  name: (match) => (match[1] === undefined ? "@flow" : "@noflow"),
203
318
  anyLine: true,
204
319
  },
@@ -206,6 +321,13 @@ const RULES: DirectiveRule[] = [
206
321
  pattern: /^\$Flow(FixMe|ExpectedError|Issue|Ignore)(?:\[[a-z-]+\])?(?![\w-])/,
207
322
  name: (match) => `$Flow${match[1]}`,
208
323
  },
324
+ // React Compiler also skips a component under a Flow suppression of its
325
+ // `react-rule-*` errors, found anywhere in a comment.
326
+ {
327
+ pattern: /\$(?:(FlowFixMe)\w*|(FlowExpectedError|FlowIssue))\[react-rule/,
328
+ rawText: true,
329
+ name: (match) => `$${match[1] ?? match[2]}`,
330
+ },
209
331
  {
210
332
  pattern: /^flowlint(-line|-next-line)?\s+[a-z][a-z-]*\s*:\s*(?:off|warn|error)/,
211
333
  name: (match) => `flowlint${match[1] ?? ""}`,
@@ -213,9 +335,15 @@ const RULES: DirectiveRule[] = [
213
335
  },
214
336
  // Bundlers. webpack's gate regex requires the colon to follow the key
215
337
  // immediately and evaluates the body as an object literal, which JSDoc
216
- // stars break — turbopack magic comments mirror the same `key: value` form.
217
- { pattern: /^webpack[A-Z][A-Za-z]+:/, name: "webpack-magic-comment", notDocblock: true },
218
- { pattern: /^turbopack[A-Z][A-Za-z]+:/, name: "turbopack-magic-comment", notDocblock: true },
338
+ // stars break. Turbopack reads the whole trimmed comment as one `key:
339
+ // value` pair instead — blanks before the colon allowed — and honours
340
+ // webpackIgnore and webpackExports as well as its own keys.
341
+ { pattern: /^webpack[A-Z][A-Za-z]+:/, name: "webpack-magic-comment", keepStars: true },
342
+ {
343
+ pattern: /^(?:turbopack[A-Z][A-Za-z]+|webpack(?:Ignore|Exports))\s*:/,
344
+ name: "turbopack-magic-comment",
345
+ keepStars: true,
346
+ },
219
347
  // Vite matches the literal block comment (`/\/\*\s*@vite-ignore\s*\*\//` in
220
348
  // importAnalysis), so line comments, suffixes and trailing words stay
221
349
  // ordinary.
@@ -223,40 +351,73 @@ const RULES: DirectiveRule[] = [
223
351
  // Terser/Rollup annotations: a bare substring search over any comment kind,
224
352
  // so leading or trailing words keep the annotation active.
225
353
  { pattern: /[#@]__(?:PURE|NO_SIDE_EFFECTS|INLINE|NOINLINE|KEY|MANGLE_PROP)__/, anyLine: true },
226
- // Million.js: substring of the leading comments of a component.
354
+ // Million.js: substring of the leading comments of a component; the skip
355
+ // annotations are compared with the whole trimmed comment value.
227
356
  { pattern: /million-ignore/, name: "million-ignore", anyLine: true },
228
357
  {
229
358
  pattern: /^@million (jsx-)?skip$/,
230
359
  joinLines: true,
360
+ keepStars: true,
231
361
  name: (match) => (match[1] === undefined ? "@million-skip" : "@million-jsx-skip"),
232
362
  },
233
363
  // Nx project graph: substring; the comment has to end on the line right
234
364
  // above the import it hides.
235
365
  { pattern: /nx-ignore-next-line/, name: "nx-ignore-next-line", anyLine: true },
236
- // UnoCSS: include/ignore are raw whole-file substring checks; the skip
237
- // markers must be their own comment.
238
- { pattern: /@unocss-(include|ignore)/, name: (match) => `@unocss-${match[1]}`, anyLine: true },
366
+ // UnoCSS: include/ignore (and the language server's ide-include) are raw
367
+ // whole-file substring checks; the skip markers must be their own comment.
368
+ {
369
+ pattern: /@unocss-(include|ignore|ide-include)/,
370
+ name: (match) => `@unocss-${match[1]}`,
371
+ anyLine: true,
372
+ },
239
373
  { pattern: /^@unocss-skip-(start|end)\b/, name: (match) => `@unocss-skip-${match[1]}` },
240
374
  // Next.js codemod markers: `next build` fails while an unresolved
241
375
  // @next-codemod-error comment is attached to the call.
242
376
  { pattern: /@next-codemod-(error|ignore)/, name: (match) => `@next-codemod-${match[1]}`, anyLine: true },
243
- // Bun: the runtime treats a file starting with the literal bytes `// @bun`
244
- // (optionally followed by flags like `@bytecode`) as already transpiled.
377
+ // Bun: the runtime treats a file whose first line, or whose line right after
378
+ // a `#!` line, starts with the literal bytes `// @bun` (optionally followed
379
+ // by flags like `@bytecode`) as already transpiled.
245
380
  { pattern: /^\/\/ @bun/, rawText: true, lineOnly: true, name: "@bun" },
246
381
  // React Fast Refresh / solid-refresh. react-refresh looks for the
247
382
  // substring `@refresh reset` in any comment; solid-refresh requires its
248
- // pragma to be the entire comment body.
249
- { pattern: /^@refresh (skip|reload)$/, joinLines: true, name: (match) => `@refresh-${match[1]}` },
383
+ // pragma to be the entire trimmed comment value.
384
+ {
385
+ pattern: /^@refresh (skip|reload|jsx-skip)$/,
386
+ joinLines: true,
387
+ keepStars: true,
388
+ name: (match) => `@refresh-${match[1]}`,
389
+ },
250
390
  { pattern: /@refresh reset/, name: "@refresh-reset", anyLine: true },
251
391
  // Embedded-language tag comments: prettier formats the following template
252
- // literal when the whole comment is `GraphQL` (graphql-tag-pluck matches it
253
- // case-insensitively) or `HTML` (prettier's exact ` HTML ` value).
254
- { pattern: /^graphql$/i, joinLines: true, name: "GraphQL" },
392
+ // literal when the whole comment is `GraphQL` (graphql-tag-pluck compares
393
+ // the trimmed value case-insensitively) or `HTML` (prettier's exact ` HTML `
394
+ // value).
395
+ { pattern: /^graphql$/i, joinLines: true, keepStars: true, name: "GraphQL" },
255
396
  { pattern: /^\/\* HTML \*\/$/, rawText: true, blockOnly: true, name: "HTML" },
256
- // Source maps (`//# sourceMappingURL=`, legacy `//@`, and the block form)
257
- { pattern: /^[#@]\s*(source(?:Mapping)?URL)=/, name: (match) => match[1] as string },
258
- // JSX pragmas (docblock pragmas: block comments only, honoured on any line)
259
- { pattern: /^@jsx(?:Runtime|ImportSource|Frag)?\b/, blockOnly: true, anyLine: true },
397
+ // Source maps (`//# sourceMappingURL=`, legacy `//@`, and the block form).
398
+ // deno_graph matches the name in any case and allows blanks around the `=`.
399
+ {
400
+ pattern: /^[#@]\s*(source(?:Mapping)?URL)\s*=/i,
401
+ name: (match) => ((match[1] as string).toLowerCase() === "sourceurl" ? "sourceURL" : "sourceMappingURL"),
402
+ },
403
+ // JSX pragmas. esbuild and Bun look at every `@` of every comment, Babel at
404
+ // every comment line (its TypeScript plugin anywhere in the text), and the
405
+ // oxc transformer at the leading comments — line comments included, all
406
+ // case-sensitive, all needing whitespace and an argument after the name.
407
+ // tsc lowercases the name of a block-comment pragma, and deno_graph matches
408
+ // `@jsxImportSource(Types)` block comments in any case, so block comments
409
+ // also match case-insensitively.
410
+ {
411
+ pattern: /@(jsx(?:Frag|Runtime|ImportSource)?)\s+\S/,
412
+ joinLines: true,
413
+ name: (match) => `@${match[1] as string}`,
414
+ },
415
+ {
416
+ pattern: /@(jsx(?:frag|runtime|importsource(?:types)?)?)\s+\S/i,
417
+ blockOnly: true,
418
+ joinLines: true,
419
+ name: (match) => JSX_PRAGMAS.get((match[1] as string).toLowerCase()),
420
+ },
260
421
  // Test runners. Jest reads these from the file's leading docblock, but
261
422
  // Vitest (which also honours the @jest- spellings) matches the pragma with
262
423
  // a bare regex over the whole file, so any comment kind and position can be
@@ -271,24 +432,27 @@ const RULES: DirectiveRule[] = [
271
432
  name: (match) => `@${match[1]}`,
272
433
  anyLine: true,
273
434
  },
274
- // Vitest module tags. Vitest requires the tag to sit right after a `//` or
275
- // `*` marker, which is what a content-line start means here.
276
- { pattern: /^@module-tag\s+[\w/-]/, name: "@module-tag", anyLine: true },
277
- // SonarQube/SonarCloud: the trimmed comment (JSDoc star stripped) has to
278
- // START with NOSONAR, case-insensitively; any suffix keeps it active.
279
- { pattern: /^NOSONAR/i, name: "NOSONAR" },
435
+ // Vitest module tags: /(\/\/|\*)\s*@module-tag\s+([\w\-/]+)\b/ over the
436
+ // whole file, so the tag has to follow a `//` or a `*` — any of the
437
+ // comment's — with only whitespace between.
438
+ { pattern: /(?:\/\/|\*)\s*@module-tag\s+[\w/-]*\w/, rawText: true, name: "@module-tag" },
439
+ // SonarQube/SonarCloud (SonarJS): the comment value, minus ONE leading `*`,
440
+ // trimmed, has to START with NOSONAR, case-insensitively; any suffix keeps
441
+ // it active. A star-prefixed line inside a block comment does not count.
442
+ { pattern: /^\/[/*]\*?\s*NOSONAR/i, rawText: true, name: "NOSONAR" },
280
443
  // Semgrep: ` nosemgrep`/` nosem` (case-insensitive) on the finding line or
281
444
  // standalone above it, with optional `:`/`=` rule ids. Semgrep itself needs
282
445
  // no trailing boundary; the lookahead just keeps words like `nosemantic`
283
446
  // ordinary.
284
447
  { pattern: /(?:^|\s)nosem(?:grep)?(?![\w-])/i, name: "nosemgrep", anyLine: true },
285
- // CodeQL / LGTM alert suppressions: the AlertSuppression queries only read
286
- // `//` comments, so block comments — even single-line ones — stay ordinary.
287
- // `lgtm[...]` matches anywhere in the comment; bare `lgtm` only at the
288
- // start or after a `;`; `codeql[...]` requires the bracketed query id.
289
- { pattern: /\blgtm\s*\[[^\]]*\]/i, lineOnly: true, name: "lgtm" },
290
- { pattern: /(?:^|;)\s*lgtm(?!\w)(?!\s*\[)/i, lineOnly: true, name: "lgtm" },
291
- { pattern: /\bcodeql\s*\[[^\]]*\]/i, lineOnly: true, name: "codeql" },
448
+ // CodeQL / LGTM alert suppressions: the JavaScript AlertSuppression query
449
+ // reads every comment whose text holds no line feed — `//` comments and
450
+ // single-line block comments alike. `lgtm[...]` matches anywhere in the
451
+ // text; bare `lgtm` only at its start or after a `;`; `codeql[...]` requires
452
+ // the bracketed query id.
453
+ { pattern: /\blgtm\s*\[[^\]]*\]/i, rawText: true, singleLine: true, name: "lgtm" },
454
+ { pattern: /(?:^\/[/*]|;)\s*lgtm(?!\w)(?!\s*\[)/i, rawText: true, singleLine: true, name: "lgtm" },
455
+ { pattern: /\bcodeql\s*\[[^\]]*\]/i, rawText: true, singleLine: true, name: "codeql" },
292
456
  // DeepSource: bare `skipcq` or `skipcq: CODE1, CODE2`, on the flagged line
293
457
  // or standalone above it (it may trail other comment text).
294
458
  { pattern: /\bskipcq(?![\w-])/, name: "skipcq", anyLine: true },
@@ -318,17 +482,18 @@ const RULES: DirectiveRule[] = [
318
482
  // cspell's legacy emacs-style word list (case-sensitive, colon optional).
319
483
  { pattern: /\bLocalWords(?::|\s+\S)/, name: "LocalWords", anyLine: true },
320
484
  // codespell: the tag must follow a punctuation character (the comment
321
- // marker itself at line starts) with at most one space between.
485
+ // marker itself at line starts), with any whitespace between.
322
486
  {
323
- pattern: /(?:^|[^\w\s]\s?)codespell:ignore(-next-line)?(?![\w-])/,
487
+ pattern: /(?:^|[^\w\s]\s*)codespell:ignore(?:(-next-line)\b|(?![\w-]))/,
324
488
  name: (match) => `codespell:ignore${match[1] ?? ""}`,
325
489
  anyLine: true,
326
490
  },
327
491
  // JetBrains IDEs. `noinspection` suppressions are line comments in JS/TS
492
+ // (`//\s*noinspection\s+ids`, or `//file:noinspection` for the whole file)
328
493
  // and take comma-separated inspection ids; editor-fold markers are
329
494
  // substring checks; a `language=` comment injects a language into the
330
495
  // literal that follows.
331
- { pattern: /^noinspection\s+[A-Za-z0-9_.-]+/, lineOnly: true, name: "noinspection" },
496
+ { pattern: /^\/\/(?:file:)?\s*noinspection\s+[\w.-]+/, rawText: true, lineOnly: true, name: "noinspection" },
332
497
  {
333
498
  pattern: /<(\/?)editor-fold/,
334
499
  name: (match) => (match[1] === "/" ? "editor-fold-end" : "editor-fold"),
@@ -337,29 +502,45 @@ const RULES: DirectiveRule[] = [
337
502
  { pattern: /^language=\S/, name: "language-injection" },
338
503
  // ReSharper/Rider suppressions (`ReSharper disable once RuleName`, ...).
339
504
  { pattern: /^ReSharper (disable|restore)\b/, lineOnly: true, name: (match) => `resharper-${match[1]}` },
340
- // Editor folding
341
- { pattern: /^#(?:region|endregion)\b/ },
505
+ // Editor folding regions: VS Code folds `// #region` and `// region`
506
+ // comments (`^\s*//\s*#?region\b`), IntelliJ any comment that opens with
507
+ // marker characters, blanks and `region` (`[/*#-]*\s*region.*`).
508
+ { pattern: /^[/*#-]*\s*#?(region|endregion)\b/, rawText: true, name: (match) => `#${match[1] as string}` },
509
+ // ESLint's no-fallthrough (in eslint:recommended) accepts a case that falls
510
+ // through when the last comment before the next case matches
511
+ // /falls?\s?through/iu anywhere in its value; oxlint's port and JSHint's
512
+ // `/* falls through */` accept narrower forms of the same words. ESLint's and
513
+ // oxlint's default-case accept a final comment that is exactly `no default`,
514
+ // in any case. Both only count in front of the code those rules read them
515
+ // before (see SWITCH_CLAUSE_TARGETS), so the same words elsewhere are prose.
516
+ { pattern: /falls?\s?through/iu, rawText: true, name: "fallthrough" },
517
+ { pattern: /^\/(?:\/\s*no default\s*|\*\s*no default\s*\*\/)$/iu, rawText: true, name: "no-default" },
342
518
  ];
343
519
 
344
- // Mirrors tsc's tripleSlashXMLCommentStartRegEx: the directive name (matched
520
+ // tsc 6 (the JavaScript compiler) reads triple-slash directives with
521
+ // tripleSlashXMLCommentStartRegEx: the directive name (matched
345
522
  // case-insensitively) must be followed by whitespace and the tag has to close
346
- // with `/>` — `/// <reference>` and `/// <reference types="node">` are plain
347
- // comments to the compiler. The AMD directives additionally need their
348
- // mandatory quoted argument, or tsc drops the pragma altogether.
523
+ // with `/>`, and the AMD directives additionally need their mandatory quoted
524
+ // argument, or the pragma is dropped altogether. tsc 7 (the Go port) has no
525
+ // AMD directives left and reads `reference` as a name of letters and hyphens
526
+ // that needs neither: `/// <reference types="node">` is a live type reference
527
+ // to it, and a bare `/// <reference>` a directive it rejects (TS1084).
349
528
  const TRIPLE_SLASH = /^\/\/\/\s*<(reference|amd-dependency|amd-module)\s.*?\/>/i;
350
529
  const TRIPLE_SLASH_REQUIRED_ARGUMENT: Readonly<Record<string, RegExp>> = {
351
530
  "amd-dependency": /\spath\s*=\s*(?:'[^']*'|"[^"]*")/i,
352
531
  "amd-module": /\sname\s*=\s*(?:'[^']*'|"[^"]*")/i,
353
532
  };
533
+ const TS7_TRIPLE_SLASH_REFERENCE = /^\/\/\/[ \t]*<reference(?![A-Za-z-])/i;
354
534
 
355
- /** The canonical triple-slash directive name the line comment carries, if tsc would honour it. */
535
+ /** The canonical triple-slash directive name the line comment carries, if either tsc would honour it. */
356
536
  function tripleSlashDirective(text: string): string | undefined {
357
537
  const match = TRIPLE_SLASH.exec(text);
358
- if (!match) return undefined;
359
- const name = (match[1] as string).toLowerCase();
360
- const requiredArgument = TRIPLE_SLASH_REQUIRED_ARGUMENT[name];
361
- if (requiredArgument !== undefined && !requiredArgument.test(text)) return undefined;
362
- return `triple-slash-${name}`;
538
+ if (match) {
539
+ const name = (match[1] as string).toLowerCase();
540
+ const requiredArgument = TRIPLE_SLASH_REQUIRED_ARGUMENT[name];
541
+ if (requiredArgument === undefined || requiredArgument.test(text)) return `triple-slash-${name}`;
542
+ }
543
+ return TS7_TRIPLE_SLASH_REFERENCE.test(text) ? "triple-slash-reference" : undefined;
363
544
  }
364
545
 
365
546
  /**
@@ -372,21 +553,43 @@ export interface DirectivePlacement {
372
553
  header: boolean;
373
554
  /** The comment is the file's first comment, preceded only by whitespace (or a shebang). */
374
555
  firstComment: boolean;
375
- /** The comment starts at the very first character of the file. */
556
+ /**
557
+ * The comment starts where Bun looks for its `// @bun` marker: the very
558
+ * first character of the file, or the first character after the line break
559
+ * that ends a leading `#!` line (see bunMarkerOffset).
560
+ */
376
561
  fileStart: boolean;
562
+ /**
563
+ * The token that follows the comment past any further comments (`case`,
564
+ * `}`, an identifier, ...), or `""` when only comments follow. ESLint's
565
+ * switch-clause comments (`// falls through`, `// no default`) count only in
566
+ * front of certain tokens. Left out, any token is assumed.
567
+ */
568
+ nextToken?: string;
377
569
  }
378
570
 
379
571
  const ANY_PLACEMENT: DirectivePlacement = { header: true, firstComment: true, fileStart: true };
380
572
 
573
+ /**
574
+ * The offset at which Bun reads its `// @bun` marker (`has_bun_pragma` in its
575
+ * parser): the start of the text, or, when the text opens with a `#!` line,
576
+ * the character after that line's first `\n` — -1 when the shebang line is
577
+ * the whole text, leaving no place for the marker.
578
+ */
579
+ export function bunMarkerOffset(text: string): number {
580
+ if (!text.startsWith("#!")) return 0;
581
+ const lineFeed = text.indexOf("\n");
582
+ return lineFeed === -1 ? -1 : lineFeed + 1;
583
+ }
584
+
381
585
  // File-wide pragmas (check pragmas, triple-slash directives, Flow/JSLint
382
- // header pragmas, Deno's *-ignore-file and @ts-self-types forms) only count
383
- // before the first token; anywhere later the tools treat them as ordinary
384
- // text. dprint-ignore-file is deliberately absent: a stray one below the
385
- // header no longer skips the file, but dprint's node pragma still matches
386
- // inside it, so the comment stays an active `dprint-ignore` and must keep its
387
- // tag. Coverage file pragmas (`istanbul ignore file`, `c8/v8 ignore file`)
388
- // are NOT gated: istanbul-lib-instrument and Vitest's v8 provider
389
- // (ast-v8-to-istanbul) honour them on any comment in the file. Test
586
+ // header pragmas, Biome's top-level suppression, Deno's lint file pragma,
587
+ // dprint/deno fmt file pragmas and @ts-self-types) only count before the first
588
+ // token; anywhere later the tools treat them as ordinary text — or, for a
589
+ // stray dprint/deno fmt file pragma, as the node pragma it contains, which the
590
+ // next rule then reports. Coverage file pragmas (`istanbul ignore file`,
591
+ // `c8/v8 ignore file`) are NOT gated: istanbul-lib-instrument and Vitest's v8
592
+ // provider (ast-v8-to-istanbul) honour them on any comment in the file. Test
390
593
  // environment pragmas are not gated either: Vitest matches them (including
391
594
  // the @jest- spellings) with a regex over the whole file, and neither are
392
595
  // @ts-strict pragmas (typescript-strict-plugin scans every line). @jsx
@@ -400,43 +603,75 @@ const HEADER_ONLY_DIRECTIVES = new Set([
400
603
  "@ts-self-types",
401
604
  "jslint",
402
605
  "property",
606
+ "biome-ignore-all",
607
+ "deno-lint-ignore-file",
608
+ "dprint-ignore-file",
609
+ "deno-fmt-ignore-file",
403
610
  ]);
404
611
 
405
612
  // Prettier's pragma mode reads the pragma through jest-docblock, which only
406
613
  // ever extracts the file's FIRST comment (a shebang may precede it) — a
407
- // docblock behind any other comment is ignored. Verified against prettier 3.8.
408
- const FIRST_COMMENT_ONLY_DIRECTIVES = new Set(["@format", "@noformat", "@prettier", "@noprettier"]);
614
+ // docblock behind any other comment is ignored. Cross-checked against the
615
+ // real prettier in directives.prettier.test.ts. Deno's coverage reads its
616
+ // file pragma from the first comment alone, too.
617
+ const FIRST_COMMENT_ONLY_DIRECTIVES = new Set([
618
+ "@format",
619
+ "@noformat",
620
+ "@prettier",
621
+ "@noprettier",
622
+ "deno-coverage-ignore-file",
623
+ ]);
409
624
 
410
- // Bun treats a file as pre-transpiled only when it literally STARTS with
411
- // `// @bun`; after a shebang or any other leading content the marker is inert.
625
+ // Bun treats a file as pre-transpiled only when `// @bun` opens it or the
626
+ // line after its shebang; anywhere else the marker is inert.
412
627
  const FILE_START_ONLY_DIRECTIVES = new Set(["@bun"]);
413
628
 
629
+ // ESLint's no-fallthrough reads the last comment before the next `case` or
630
+ // `default` (or before a case block's closing brace), and default-case the
631
+ // last one before the switch's closing brace; in front of anything else the
632
+ // same words are prose.
633
+ const SWITCH_CLAUSE_TARGETS: ReadonlyMap<string, ReadonlySet<string>> = new Map([
634
+ ["fallthrough", new Set(["case", "default", "}"])],
635
+ ["no-default", new Set(["}"])],
636
+ ]);
637
+
414
638
  function isActiveAt(name: string, placement: DirectivePlacement): boolean {
415
639
  if (FILE_START_ONLY_DIRECTIVES.has(name)) return placement.fileStart;
416
640
  if (FIRST_COMMENT_ONLY_DIRECTIVES.has(name)) return placement.firstComment;
417
- if (
418
- HEADER_ONLY_DIRECTIVES.has(name) ||
419
- (name.startsWith("deno-") && name.endsWith("-ignore-file")) ||
420
- name.startsWith("triple-slash-")
421
- ) {
641
+ if (HEADER_ONLY_DIRECTIVES.has(name) || name.startsWith("triple-slash-")) {
422
642
  return placement.header;
423
643
  }
644
+ const targets = SWITCH_CLAUSE_TARGETS.get(name);
645
+ if (targets !== undefined) return placement.nextToken === undefined || targets.has(placement.nextToken);
424
646
  return true;
425
647
  }
426
648
 
427
- // Mirrors the TypeScript compiler's own comment-directive matching, verified
428
- // against tsc: the suppression directives are case-sensitive PREFIX matches
429
- // (`@ts-ignoreTODO` is active), while the file-wide check pragmas go through
430
- // the case-insensitive pragma parser, whose name runs up to the next
431
- // whitespace or colon (`@ts-nocheck:reason` is active, `@ts-nocheckfoo` and
432
- // `@ts-nocheck-foo` are not).
433
- const TS_LINE_SUPPRESSION = /^\/\/\/?\s*@ts-(ignore|expect-error)/;
434
- const TS_LINE_CHECK_PRAGMA = /^\/\/\/?\s*@ts-(nocheck|check)(?=[^\S\r\n]|:|$)/i;
649
+ // Mirrors the TypeScript compilers' own comment-directive matching, verified
650
+ // against tsc 6.0 and 7.0 (a comment counts when either honours it). The
651
+ // suppression directives are case-sensitive PREFIX matches (`@ts-ignoreTODO`
652
+ // is active). In `//` comments tsc 6 allows one extra slash and any
653
+ // whitespace before the `@`, tsc 7 any number of extra slashes but only
654
+ // spaces and tabs — so `//// @ts-ignore` is live to tsc 7 alone.
655
+ const TS_LINE_SUPPRESSION = /^\/\/(?:\/?\s*|\/*[ \t]*)@ts-(ignore|expect-error)/;
656
+ // The file-wide check pragmas go through each compiler's case-insensitive
657
+ // pragma parser. tsc 6 reads the name up to the next whitespace or colon
658
+ // (`@ts-nocheck:reason` is active, `@ts-nocheckfoo` and `@ts-nocheck-foo` are
659
+ // not); tsc 7 reads it as a run of ASCII letters and hyphens after spaces and
660
+ // tabs only, so `@ts-nocheck.` and `@ts-nocheck1` are active to it.
661
+ const TS6_LINE_CHECK_PRAGMA = /^\/\/\/?\s*@ts-(nocheck|check)(?=[^\S\r\n]|:|$)/i;
662
+ const TS7_LINE_CHECK_PRAGMA = /^\/\/\/?[ \t]*@ts-(nocheck|check)(?![A-Za-z-])/i;
435
663
  // Block comments: only the suppression directives, and only on the comment's
436
664
  // literal last line (`*/` included), even when that line is otherwise blank.
437
665
  // tsc trims the line and then allows one run of `/`/`*` characters before the
438
666
  // directive, so `* @ts-ignore */` counts but `/ * @ts-ignore */` does not.
439
667
  const TS_BLOCK_SUPPRESSION = /^\s*[/*]*\s*@ts-(ignore|expect-error)/;
668
+ // Flow, which also checks TypeScript files, honours the same suppressions
669
+ // there with its own matching: the directive must OPEN the comment value,
670
+ // after any spaces, tabs, line breaks and stars — in a block comment
671
+ // whatever its last line holds — and end where an identifier would
672
+ // (`@ts-ignore: reason` counts, `@ts-ignoree` does not).
673
+ const FLOW_LINE_SUPPRESSION = /^\/\/[ \t*]*@ts-(ignore|expect-error)(?![\w-])/;
674
+ const FLOW_BLOCK_SUPPRESSION = /^\/\*[ \t\r\n*]*@ts-(ignore|expect-error)(?![\w-])/;
440
675
 
441
676
  /**
442
677
  * Returns the canonical name of the compiler/linter/tooling directive the
@@ -453,35 +688,52 @@ export function detectDirective(kind: CommentKind, text: string, placement?: Dir
453
688
  if (kind === "line") {
454
689
  const tripleSlash = tripleSlashDirective(text);
455
690
  if (tripleSlash !== undefined && isActiveAt(tripleSlash, at)) return tripleSlash;
456
- const suppression = TS_LINE_SUPPRESSION.exec(text);
691
+ const suppression = TS_LINE_SUPPRESSION.exec(text) ?? FLOW_LINE_SUPPRESSION.exec(text);
457
692
  if (suppression) {
458
693
  return `@ts-${suppression[1]}`;
459
694
  }
460
- const checkPragma = TS_LINE_CHECK_PRAGMA.exec(text);
695
+ const checkPragma = TS6_LINE_CHECK_PRAGMA.exec(text) ?? TS7_LINE_CHECK_PRAGMA.exec(text);
461
696
  if (checkPragma) {
462
697
  const name = `@ts-${checkPragma[1]?.toLowerCase()}`;
463
698
  if (isActiveAt(name, at)) return name;
464
699
  }
465
700
  } else {
466
- const suppression = TS_BLOCK_SUPPRESSION.exec(lastLine(text));
701
+ const suppression = TS_BLOCK_SUPPRESSION.exec(lastLine(text)) ?? FLOW_BLOCK_SUPPRESSION.exec(text);
467
702
  if (suppression) {
468
703
  return `@ts-${suppression[1]}`;
469
704
  }
470
705
  }
471
706
 
472
- for (const name of ruleMatches(kind, text)) {
473
- if (isActiveAt(name, at)) return name;
707
+ // A directive that opens the comment names it, however the comment goes on
708
+ // to mention other tools' markers (`// nosemgrep: ... @jsx h` stays a
709
+ // Semgrep suppression, with the next-line shield that goes with it); only
710
+ // without one does a marker found after other text name the comment.
711
+ let mention: string | undefined;
712
+ for (const { name, opening } of ruleMatches(kind, text)) {
713
+ if (!isActiveAt(name, at)) continue;
714
+ if (opening) return name;
715
+ mention ??= name;
474
716
  }
475
- return undefined;
717
+ return mention;
476
718
  }
477
719
 
478
720
  /** Directive names of every rule the comment matches, in rule order. */
479
- function* ruleMatches(kind: CommentKind, text: string): Generator<string> {
721
+ /** A rule's directive name, and whether its match opens the comment rather than following other text. */
722
+ interface RuleMatch {
723
+ name: string;
724
+ opening: boolean;
725
+ }
726
+
727
+ function* ruleMatches(kind: CommentKind, text: string): Generator<RuleMatch> {
480
728
  const lines = contentLines(kind, text, false);
481
729
  const literalLines = kind === "block" ? contentLines(kind, text, true) : lines;
730
+ // Where the raw text's content begins, past the comment opener, stars and
731
+ // blanks.
732
+ const contentStart = (/^[/*\s]*/.exec(text) as RegExpExecArray)[0].length;
482
733
  for (const rule of RULES) {
483
734
  if (rule.blockOnly === true && kind !== "block") continue;
484
735
  if (rule.lineOnly === true && kind !== "line") continue;
736
+ if (rule.singleLine === true && text.includes("\n")) continue;
485
737
  if (rule.notDocblock === true && kind === "block" && text.startsWith("/**")) continue;
486
738
  const ruleLines = rule.keepStars === true ? literalLines : lines;
487
739
  const candidates =
@@ -492,29 +744,31 @@ function* ruleMatches(kind: CommentKind, text: string): Generator<string> {
492
744
  : rule.joinLines === true
493
745
  ? [ruleLines.join(" ")]
494
746
  : ruleLines.slice(0, 1);
495
- for (const line of candidates) {
747
+ for (const [index, line] of candidates.entries()) {
496
748
  const match = rule.pattern.exec(line);
497
749
  if (!match) continue;
750
+ const opening = rule.rawText === true ? match.index <= contentStart : index === 0 && match.index === 0;
498
751
  const name =
499
752
  typeof rule.name === "string" ? rule.name : typeof rule.name === "function" ? rule.name(match) : match[0];
500
- if (name !== undefined) yield name;
753
+ if (name === undefined) continue;
754
+ for (const each of typeof name === "string" ? [name] : name) yield { name: each, opening };
501
755
  }
502
756
  }
503
757
  }
504
758
 
505
759
  /**
506
- * The position-dependent directives (prettier's first-comment pragmas, Bun's
507
- * file-start marker) the comment carries that are active at the given
508
- * placement, sorted. Unlike detectDirective — which reports one canonical
509
- * name — this sees through masking: an eslint config block can also hold a
510
- * `@format` pragma, and whether that pragma is live must not hide behind the
511
- * name an earlier rule already claimed. Only first-comment and file-start
512
- * gates are consulted; header-gated directives cannot change activation when
513
- * the comments around them change.
760
+ * The position-dependent directives (prettier's first-comment pragmas, Deno's
761
+ * coverage file pragma, Bun's file-start marker) the comment carries that are
762
+ * active at the given placement, sorted. Unlike detectDirective — which
763
+ * reports one canonical name — this sees through masking: an eslint config
764
+ * block can also hold a `@format` pragma, and whether that pragma is live
765
+ * must not hide behind the name an earlier rule already claimed. Only
766
+ * first-comment and file-start gates are consulted; header-gated directives
767
+ * cannot change activation when the comments around them change.
514
768
  */
515
769
  export function activePositionalDirectives(kind: CommentKind, text: string, placement: DirectivePlacement): string[] {
516
770
  const names = new Set<string>();
517
- for (const name of ruleMatches(kind, text)) {
771
+ for (const { name } of ruleMatches(kind, text)) {
518
772
  if (!FIRST_COMMENT_ONLY_DIRECTIVES.has(name) && !FILE_START_ONLY_DIRECTIVES.has(name)) continue;
519
773
  if (isActiveAt(name, placement)) names.add(name);
520
774
  }
@@ -536,8 +790,8 @@ export function isLegalComment(text: string): boolean {
536
790
  /**
537
791
  * Non-empty content lines of the comment, with comment markers stripped.
538
792
  * For line comments only the `//` marker itself is removed: extra slashes or
539
- * stars are content, so `//// @ts-ignore` and `// * prettier-ignore` stay
540
- * ordinary. JSDoc-style `*` prefixes are stripped for block comments unless
793
+ * stars are content, so `/// eslint-disable-line` and `// * prettier-ignore`
794
+ * stay ordinary. JSDoc-style `*` prefixes are stripped for block comments unless
541
795
  * `keepStars` asks for the literal lines (for tools that compare the raw
542
796
  * comment value, where a leading `*` defeats the directive).
543
797
  */