@eslint-sh/eslint-plugin 0.11.0 → 0.13.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 (84) hide show
  1. package/README.md +5 -2
  2. package/dist/api.d.ts +1 -1
  3. package/dist/command-harvest/harvest-commands.d.ts +10 -4
  4. package/dist/command-harvest/harvest-commands.js +39 -10
  5. package/dist/eslint-plugin-api.d.ts +36 -14
  6. package/dist/language/command-resolution.d.ts +16 -6
  7. package/dist/language/command-resolution.js +44 -17
  8. package/dist/language/line-breaks.d.ts +10 -4
  9. package/dist/language/line-breaks.js +14 -5
  10. package/dist/language/shell-language.d.ts +2 -0
  11. package/dist/language/shell-language.js +10 -1
  12. package/dist/language/shell-source-code.d.ts +29 -13
  13. package/dist/language/shell-source-code.js +126 -55
  14. package/dist/language/word-resolution.d.ts +18 -12
  15. package/dist/language/word-resolution.js +133 -3
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +2 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +4 -0
  18. package/dist/rules/compat/declaration-options.d.ts +2 -2
  19. package/dist/rules/compat/declaration-options.js +23 -17
  20. package/dist/rules/compat/no-case-attributes.js +2 -4
  21. package/dist/rules/compat/no-mapfile.js +16 -19
  22. package/dist/rules/compat/no-negative-array-index.d.ts +3 -8
  23. package/dist/rules/compat/no-negative-array-index.js +7 -30
  24. package/dist/rules/compat/no-nounset-empty-array.js +10 -7
  25. package/dist/rules/compat/no-parameter-transformation.js +2 -1
  26. package/dist/rules/compat/no-printf-time-format.js +38 -16
  27. package/dist/rules/compat/no-source.d.ts +3 -8
  28. package/dist/rules/compat/no-source.js +3 -40
  29. package/dist/rules/compat/no-test-v.js +243 -61
  30. package/dist/rules/compat/no-wait-n.js +43 -12
  31. package/dist/rules/compat/nounset-array-proof.d.ts +3 -1
  32. package/dist/rules/compat/nounset-array-proof.js +84 -63
  33. package/dist/rules/compat/posix-absent-command.js +3 -2
  34. package/dist/rules/compat/shopt-options.js +3 -2
  35. package/dist/rules/create-wrapper-rule.js +16 -9
  36. package/dist/rules/no-dynamic-invocation.js +8 -9
  37. package/dist/rules/no-eval.js +19 -8
  38. package/dist/rules/no-masked-exit-status.js +34 -46
  39. package/dist/rules/no-secret-flags.js +4 -3
  40. package/dist/rules/no-unchecked-cd.d.ts +8 -3
  41. package/dist/rules/no-unchecked-cd.js +54 -25
  42. package/dist/rules/no-unused-declarations.js +127 -30
  43. package/dist/rules/prefer-local.js +146 -52
  44. package/dist/rules/require-shebang.js +23 -21
  45. package/dist/rules/require-strict-mode.d.ts +2 -2
  46. package/dist/rules/require-strict-mode.js +28 -16
  47. package/dist/rules/require-tty-guard.d.ts +2 -0
  48. package/dist/rules/require-tty-guard.js +205 -50
  49. package/dist/rules/set-options.d.ts +5 -16
  50. package/dist/rules/set-options.js +17 -45
  51. package/dist/rules/shebang-interpreter.d.ts +33 -10
  52. package/dist/rules/shebang-interpreter.js +522 -53
  53. package/dist/rules/shebang-matches-dialect.js +4 -4
  54. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  55. package/dist/rules/strict-mode-prologue.js +45 -8
  56. package/dist/rules/variable-reads.d.ts +12 -0
  57. package/dist/rules/variable-reads.js +31 -0
  58. package/docs/custom-rule-tutorial.md +19 -10
  59. package/docs/error-codes.md +6 -1
  60. package/docs/examples/no-curl-in-functions-rule.mjs +7 -5
  61. package/docs/rules/README.md +5 -5
  62. package/docs/rules/compat/no-mapfile.md +11 -20
  63. package/docs/rules/compat/no-negative-array-index.md +9 -22
  64. package/docs/rules/compat/no-nounset-empty-array.md +5 -5
  65. package/docs/rules/compat/no-printf-time-format.md +2 -1
  66. package/docs/rules/compat/no-source.md +8 -17
  67. package/docs/rules/compat/no-test-v.md +7 -1
  68. package/docs/rules/compat/no-wait-n.md +3 -1
  69. package/docs/rules/no-dynamic-invocation.md +3 -0
  70. package/docs/rules/no-eval.md +22 -1
  71. package/docs/rules/no-masked-exit-status.md +4 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +2 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +18 -9
  76. package/docs/rules/prefer-local.md +15 -33
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-shebang.md +46 -3
  79. package/docs/rules/require-strict-mode.md +40 -15
  80. package/docs/rules/require-tty-guard.md +27 -4
  81. package/docs/rules/shebang-matches-dialect.md +3 -0
  82. package/docs/shellcheck.md +1 -1
  83. package/docs/wrapper-rules.md +1 -1
  84. package/package.json +4 -4
@@ -30,9 +30,11 @@
30
30
  * that here-document's terminator and would carry the other command into the
31
31
  * guard.
32
32
  */
33
+ import { analysisDialect, describeWordAtPosition, isSingleField, resolveWordTextAtPosition, } from '../language/word-resolution.js';
33
34
  import { DashHdoc, Hdoc } from 'sh-ast';
35
+ import { someShellNode } from '../language/syntax-view.js';
34
36
  import { createRule } from './create-rule.js';
35
- import { lineBreakOf } from '../language/line-breaks.js';
37
+ import { lineBreakOf, shellLineBreakOf } from '../language/line-breaks.js';
36
38
  /** Registry name of this rule. */
37
39
  const RULE_NAME = 'require-tty-guard';
38
40
  /** The interactive commands checked when `commands` is not configured. */
@@ -56,14 +58,43 @@ const REDIRECT_INPUT_OPS = new Set([
56
58
  const DUP_INPUT = 67;
57
59
  /** The `-t` unary test operator (`sh-ast`'s `TsFdTerm`). */
58
60
  const TS_FD_TERM = 123;
59
- /**
60
- * Read options that consume an argument, so the next word is not a variable
61
- * name or another option cluster.
62
- */
63
- const READ_ARG_FLAGS = new Set(['a', 'd', 'i', 'n', 'N', 'p', 't', 'u']);
61
+ /** Decimal timeout accepted by Bash read, including signs and zero spellings. */
62
+ const BASH_READ_TIMEOUT = /^(?:\+?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]*)|-(?:0+(?:\.0*)?|\.0*))$/u;
63
+ const MKSH_READ_TIMEOUT = /^[0-9]+(?:\.[0-9]+)?$/u;
64
+ /** Flags whose argument is required, and switches that leave stdin selected. */
65
+ const READ_FLAGS = {
66
+ bash: { operands: 'adinNptu', switches: 'Eers' },
67
+ posix: { operands: 'p', switches: 'r' },
68
+ mksh: { operands: 'adnNt', switches: 'Ars' },
69
+ zsh: { operands: 'du', switches: 'Aers' },
70
+ };
71
+ /** Decimal spellings of fd 0 and supported alternate descriptors. */
72
+ function descriptorInput(target, dialect, redirect) {
73
+ if (target === null)
74
+ return 'unknown';
75
+ if (redirect && target === '-')
76
+ return 'explicit';
77
+ if (target === 'p' && (dialect === 'mksh' || dialect === 'zsh'))
78
+ return 'explicit';
79
+ const numeric = dialect === 'posix' || dialect === 'mksh'
80
+ ? /^[0-9]$/u
81
+ : redirect
82
+ ? dialect === 'bash'
83
+ ? /^[0-9]+-?$/u
84
+ : /^[0-9]+$/u
85
+ : /^[ \t\n\r\f\v]*[+-]?[0-9]+$/u;
86
+ if (!numeric.test(target))
87
+ return 'unknown';
88
+ const fd = Number(redirect ? target.replace(/-$/u, '') : target);
89
+ if (!Number.isSafeInteger(fd) || fd < 0 || fd > 2_147_483_647)
90
+ return 'unknown';
91
+ if (fd > 0)
92
+ return 'explicit';
93
+ return redirect && target.endsWith('-') ? 'unknown' : 'stdin';
94
+ }
64
95
  /** The static text of `node` if it is a `Word` with a known value. */
65
96
  function textOf(sourceCode, node) {
66
- return node?.type === 'Word' ? sourceCode.resolveWordText(node) : null;
97
+ return node?.type === 'Word' ? resolveWordTextAtPosition(sourceCode, node) : null;
67
98
  }
68
99
  /**
69
100
  * Whether `call` is a `[ … -t 0 … ]` or `test … -t 0 …` command. `-t 0` must
@@ -78,7 +109,9 @@ function isCommandTtyTest(call, sourceCode) {
78
109
  }
79
110
  /** Whether `test` is a `[[ -t 0 ]]` unary test. */
80
111
  function isClauseTtyTest(test, sourceCode) {
81
- return test.op === TS_FD_TERM && textOf(sourceCode, test.x) === '0';
112
+ return (test.op === TS_FD_TERM &&
113
+ test.x?.type === 'Word' &&
114
+ resolveWordTextAtPosition(sourceCode, test.x) === '0');
82
115
  }
83
116
  /** Whether `inner` lies within `outer`, by source range. */
84
117
  function within(inner, outer) {
@@ -91,46 +124,138 @@ function listRange(stmts) {
91
124
  return [stmts[0].range[0], stmts[stmts.length - 1].range[1]];
92
125
  }
93
126
  /**
94
- * Whether a redirect on a statement feeds fd 0 from an explicit source:
95
- * `< file`, `0< file`, `<<`, `<<<`, `<> file`, or `<&N` for `N` other than 0.
127
+ * Whether a redirect feeds fd 0 from an explicit source:
128
+ * `< file`, `0< file`, `<<`, `<<<`, `<> file`, a known nonzero descriptor,
129
+ * a Zsh or mksh coprocess (`<&p`), or a closed descriptor (`<&-`).
96
130
  */
97
- function redirectsStdin(stmt, sourceCode) {
98
- return stmt.redirs.some((redir) => {
131
+ function redirectedInput(stmt, sourceCode) {
132
+ const dialect = analysisDialect(sourceCode.dialect);
133
+ let input = 'stdin';
134
+ for (const redir of stmt.redirs) {
99
135
  if (!REDIRECT_INPUT_OPS.has(redir.op))
100
- return false;
136
+ continue;
101
137
  const fd = redir.n === undefined ? '0' : redir.n.value;
102
- if (fd !== '0')
103
- return false;
104
- return redir.op !== DUP_INPUT || textOf(sourceCode, redir.word) !== '0';
105
- });
138
+ if (fd !== '0' && !((dialect === 'bash' || dialect === 'zsh') && /^0+$/u.test(fd)))
139
+ continue;
140
+ if (redir.op !== DUP_INPUT)
141
+ return 'explicit';
142
+ const duplicated = descriptorInput(textOf(sourceCode, redir.word), dialect, true);
143
+ if (duplicated === 'explicit')
144
+ return 'explicit';
145
+ if (duplicated === 'unknown')
146
+ input = 'unknown';
147
+ }
148
+ return input;
106
149
  }
107
150
  /**
108
- * Whether a `read` takes input from a descriptor other than 0 (`-u 3`,
109
- * `-u3`, `-ru 3`). A non-static descriptor counts as non-zero, because the
110
- * rule cannot show it is stdin. Option parsing stops at `--` or the first
111
- * non-option word.
151
+ * The final input descriptor selected by `read`. An unresolved option or
152
+ * operand can change subsequent option parsing. Even when the final descriptor
153
+ * is zero, an earlier nonzero descriptor can fail Bash's checks before the read.
112
154
  */
113
- function readsFromOtherFd(call, sourceCode) {
114
- const words = call.args.slice(1);
155
+ function readInput(call, sourceCode) {
156
+ const dialect = analysisDialect(sourceCode.dialect);
157
+ const { operands, switches } = READ_FLAGS[dialect];
158
+ const words = call.args
159
+ .slice(1)
160
+ .map((word) => describeWordAtPosition(sourceCode, word))
161
+ .filter((facts) => facts.fields.max !== 0);
162
+ let input = 'stdin';
163
+ let checkedAlternateDescriptor = false;
164
+ let usesCoprocess = false;
165
+ let readsKeys = false;
166
+ let selectedDescriptor = false;
167
+ let uncertainArguments = false;
115
168
  for (let i = 0; i < words.length; i += 1) {
116
- const text = textOf(sourceCode, words[i]);
117
- if (text === null || !text.startsWith('-') || text === '-' || text === '--')
118
- return false;
169
+ const word = words[i];
170
+ if (!isSingleField(word))
171
+ return 'unknown';
172
+ if (!word.resolution.static) {
173
+ if (word.knownPrefix === '' || word.knownPrefix.startsWith('-'))
174
+ return 'unknown';
175
+ // Option processing stops here. The variable operand can still be invalid.
176
+ uncertainArguments = true;
177
+ break;
178
+ }
179
+ const text = word.resolution.text;
180
+ if (!text.startsWith('-') || text === '-' || text === '--')
181
+ break;
119
182
  for (let j = 1; j < text.length; j += 1) {
120
183
  const flag = text.charAt(j);
121
- if (!READ_ARG_FLAGS.has(flag))
122
- continue;
123
184
  const rest = text.slice(j + 1);
185
+ if (switches.includes(flag))
186
+ continue;
187
+ if (dialect === 'zsh' && flag === 'k') {
188
+ readsKeys = true;
189
+ if (rest !== '') {
190
+ if (!/^[0-9]+$/u.test(rest))
191
+ return 'unknown';
192
+ }
193
+ else {
194
+ const next = words.at(i + 1)?.resolution;
195
+ if (next?.static && /^[0-9]+$/u.test(next.text))
196
+ i++;
197
+ }
198
+ break;
199
+ }
200
+ if (flag === 'p' && (dialect === 'mksh' || dialect === 'zsh')) {
201
+ if (dialect === 'zsh')
202
+ usesCoprocess = true;
203
+ input = 'explicit';
204
+ checkedAlternateDescriptor = true;
205
+ continue;
206
+ }
207
+ // mksh's -u takes an optional attached descriptor. -u with no digits
208
+ // selects stdin and leaves the next word to be read as a variable name.
209
+ if (flag === 'u' && dialect === 'mksh') {
210
+ input = descriptorInput(rest === '' ? '0' : rest, dialect, false);
211
+ if (input === 'unknown')
212
+ return input;
213
+ checkedAlternateDescriptor ||= input === 'explicit';
214
+ break;
215
+ }
216
+ if (!operands.includes(flag))
217
+ return 'unknown';
218
+ let operand = rest;
219
+ if (rest === '') {
220
+ const next = words.at(++i);
221
+ if (next === undefined || !isSingleField(next))
222
+ return 'unknown';
223
+ operand = next.resolution.static ? next.resolution.text : null;
224
+ // These arguments can be any one string. Keep uncertain expansions
225
+ // out of the proposed edit when read still uses stdin.
226
+ uncertainArguments ||= operand === null;
227
+ }
124
228
  if (flag === 'u') {
125
- const fd = rest === '' ? textOf(sourceCode, words[i + 1]) : rest;
126
- return fd !== '0';
229
+ selectedDescriptor = true;
230
+ if (dialect === 'zsh' && operand === 'p')
231
+ usesCoprocess = true;
232
+ input = descriptorInput(operand, dialect, false);
233
+ if (input === 'unknown')
234
+ return input;
235
+ checkedAlternateDescriptor ||= input === 'explicit';
236
+ }
237
+ else if (flag === 't') {
238
+ const timeout = dialect === 'bash' ? BASH_READ_TIMEOUT : MKSH_READ_TIMEOUT;
239
+ if (operand === null || !timeout.test(operand))
240
+ return 'unknown';
241
+ }
242
+ else if ((flag === 'n' || flag === 'N') &&
243
+ (operand === null || !/^[0-9]+$/u.test(operand) || Number(operand) > 2_147_483_647)) {
244
+ return 'unknown';
245
+ }
246
+ else if (flag === 'a' && (operand === null || !/^[A-Za-z_][A-Za-z_0-9]*$/u.test(operand))) {
247
+ return 'unknown';
127
248
  }
128
- if (rest === '')
129
- i += 1;
130
249
  break;
131
250
  }
132
251
  }
133
- return false;
252
+ if (usesCoprocess)
253
+ return 'explicit';
254
+ if (readsKeys && !selectedDescriptor)
255
+ return 'terminal';
256
+ return input === 'stdin' && (checkedAlternateDescriptor || uncertainArguments)
257
+ ? 'unknown'
258
+ : input;
134
259
  }
135
260
  /**
136
261
  * Whether the exit status of `stmt` steers control flow: it is a condition of
@@ -184,11 +309,14 @@ function sharesHeredocOpenerLine(stmt, text) {
184
309
  * must stay alone on its line.
185
310
  */
186
311
  function wrapInGuard(text, start, stmtText, endsInHeredoc) {
187
- const eol = lineBreakOf(text);
312
+ const end = start + stmtText.length;
313
+ const closing = text.startsWith('\r\n', end) ? 'fi #' : 'fi';
188
314
  const startsLine = /^[ \t]*$/u.test(text.slice(text.lastIndexOf('\n', start - 1) + 1, start));
189
- if (startsLine && stmtText.includes('\n'))
190
- return `if [ -t 0 ]; then${eol}${stmtText}${eol}fi`;
191
- return `if [ -t 0 ]; then ${stmtText}${endsInHeredoc ? eol : '; '}fi`;
315
+ if (startsLine && stmtText.includes('\n')) {
316
+ const bodyEnd = endsInHeredoc ? lineBreakOf(text, end) : shellLineBreakOf(text, end);
317
+ return `if [ -t 0 ]; then${shellLineBreakOf(text, start)}${stmtText}${bodyEnd}${closing}`;
318
+ }
319
+ return `if [ -t 0 ]; then ${stmtText}${endsInHeredoc ? lineBreakOf(text, end) : '; '}${closing}`;
192
320
  }
193
321
  /** Built-in rule `sh/require-tty-guard`. @internal */
194
322
  export const requireTtyGuard = createRule({
@@ -216,6 +344,21 @@ export const requireTtyGuard = createRule({
216
344
  },
217
345
  create(context) {
218
346
  const { sourceCode } = context;
347
+ const dialect = analysisDialect(sourceCode.dialect);
348
+ const statusNames = new Set(['?']);
349
+ if (dialect === 'bash')
350
+ statusNames.add('PIPESTATUS');
351
+ if (dialect === 'zsh') {
352
+ statusNames.add('pipestatus');
353
+ statusNames.add('status');
354
+ }
355
+ const readsStatus = (stmt) => someShellNode(stmt, (part) => {
356
+ if (part.type === 'ParamExp') {
357
+ return statusNames.has(part.param?.value ?? '') || (dialect === 'bash' && part.excl);
358
+ }
359
+ return ((part.type === 'ArithmExp' || part.type === 'ArithmCmd') &&
360
+ someShellNode(part, (term) => term.type === 'Lit' && statusNames.has(term.value)));
361
+ });
219
362
  const options = context.options[0];
220
363
  // Empty replacements intentionally remove defaults; a set makes overlapping
221
364
  // base/additional names one policy without mutating either configured list.
@@ -247,23 +390,29 @@ export const requireTtyGuard = createRule({
247
390
  return false;
248
391
  };
249
392
  /** Whether stdin is supplied to `node` by a redirect or a pipe. */
250
- const hasExplicitInput = (node) => {
393
+ const inheritedInput = (node) => {
251
394
  let child = node;
395
+ let input = 'stdin';
252
396
  for (let parent = sourceCode.getParent(child); parent; parent = sourceCode.getParent(child)) {
253
- if (parent.type === 'Stmt' && redirectsStdin(parent, sourceCode))
254
- return true;
397
+ if (parent.type === 'Stmt') {
398
+ const redirected = redirectedInput(parent, sourceCode);
399
+ if (redirected === 'explicit')
400
+ return 'explicit';
401
+ if (redirected === 'unknown')
402
+ input = 'unknown';
403
+ }
255
404
  // A coprocess body reads the coprocess's own input pipe, never the
256
405
  // terminal, so a terminal guard is meaningless there.
257
406
  if (parent.type === 'CoprocClause')
258
- return true;
407
+ return 'explicit';
259
408
  if (parent.type === 'BinaryCmd' &&
260
409
  (parent.op === PIPE || parent.op === PIPE_ALL) &&
261
410
  parent.y === child) {
262
- return true;
411
+ return 'explicit';
263
412
  }
264
413
  child = parent;
265
414
  }
266
- return false;
415
+ return input;
267
416
  };
268
417
  return {
269
418
  CallExpr(node) {
@@ -272,9 +421,10 @@ export const requireTtyGuard = createRule({
272
421
  const name = sourceCode.getCommandName(node);
273
422
  if (name === null || !commands.has(name))
274
423
  return;
275
- if (name === 'read' && readsFromOtherFd(node, sourceCode))
424
+ const input = name === 'read' ? readInput(node, sourceCode) : 'stdin';
425
+ if (input === 'explicit')
276
426
  return;
277
- candidates.push({ node, name });
427
+ candidates.push({ node, name, input });
278
428
  },
279
429
  UnaryTest(node) {
280
430
  if (isClauseTtyTest(node, sourceCode))
@@ -282,21 +432,26 @@ export const requireTtyGuard = createRule({
282
432
  },
283
433
  ForClause(node) {
284
434
  if (node.select && commands.has('select')) {
285
- candidates.push({ node, name: 'select' });
435
+ candidates.push({ node, name: 'select', input: 'stdin' });
286
436
  }
287
437
  },
288
438
  'File:exit'() {
289
- for (const { node, name } of candidates) {
290
- if (hasExplicitInput(node) || isGuarded(node))
439
+ for (const { node, name, input } of candidates) {
440
+ const inherited = inheritedInput(node);
441
+ if ((inherited === 'explicit' && input !== 'terminal') || isGuarded(node))
291
442
  continue;
292
443
  const stmt = sourceCode.getParent(node);
293
444
  // A statement that runs in the background cannot be wrapped without
294
445
  // changing what is backgrounded, so it gets no suggestion.
295
446
  // A statement sharing its here-document's opener line with another
296
- // command gets none either (see `sharesHeredocOpenerLine`).
297
- const wrappable = stmt?.type === 'Stmt' &&
447
+ // command gets none either (see `sharesHeredocOpenerLine`). The TTY
448
+ // test also changes the status visible to expansions in the statement.
449
+ const wrappable = input === 'stdin' &&
450
+ inherited === 'stdin' &&
451
+ stmt?.type === 'Stmt' &&
298
452
  !stmt.background &&
299
453
  !isControlFlowOperand(stmt, sourceCode) &&
454
+ !readsStatus(stmt) &&
300
455
  !sharesHeredocOpenerLine(stmt, sourceCode.text);
301
456
  context.report({
302
457
  node,
@@ -55,6 +55,8 @@ export interface ParsedSetArguments {
55
55
  */
56
56
  readonly stoppedBy: 'operand' | 'unknown' | 'malformed' | undefined;
57
57
  }
58
+ /** One field known to start positional arguments when an option does not consume it. @internal */
59
+ export declare const SET_POSITIONAL_OPERAND: unique symbol;
58
60
  /**
59
61
  * Reads a `set`-style argument list (the arguments after the command word, so
60
62
  * `["-euo", "pipefail"]` for `set -euo pipefail`) into the option changes it
@@ -69,7 +71,7 @@ export interface ParsedSetArguments {
69
71
  * @param args - Each argument's static text, or `null` when it is not static.
70
72
  * @internal
71
73
  */
72
- export declare function parseSetArguments(args: readonly (string | null)[]): ParsedSetArguments;
74
+ export declare function parseSetArguments(args: readonly (string | null | typeof SET_POSITIONAL_OPERAND)[]): ParsedSetArguments;
73
75
  /**
74
76
  * Applies `changes` to `enabled` in order, so a later `+e` undoes an earlier
75
77
  * `-e`. Mutates and returns `enabled`.
@@ -89,21 +91,8 @@ export declare function applySetOptionChanges(enabled: Set<string>, changes: rea
89
91
  */
90
92
  export declare function formatSetCommand(options: readonly string[]): string;
91
93
  /**
92
- * The option changes the shebang line passes to the shell (read by
93
- * the shared prologue definition and by
94
- * `compat/no-nounset-empty-array`). Only spellings the kernel hands to the shell as written
95
- * are read:
96
- *
97
- * - `#!/path/to/shell <word>`: the kernel passes everything after the
98
- * interpreter as one argument, so exactly one flag word is read
99
- * (`#!/bin/bash -eu`); more than one word (`#!/bin/bash -e -u`) arrives as a
100
- * single argument the shell rejects, and counts as nothing.
101
- * - `#!/usr/bin/env -S <shell> <words…>`: `env -S` splits the rest into words,
102
- * so every word after the shell name is read. GNU env's
103
- * `--split-string=<shell> <words…>` is read the same way; macOS env supports only `-S`.
104
- *
105
- * Plain `#!/usr/bin/env <shell> <flags>` counts as nothing: without `-S`,
106
- * Linux passes `<shell> <flags>` to `env` as one command name.
94
+ * Read the options from the kernel/GNU env argv using the shared set parser.
95
+ * An env directory or argv0 override can change the script that is read.
107
96
  *
108
97
  * @internal
109
98
  */
@@ -19,6 +19,7 @@
19
19
  * @see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
20
20
  * @see https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#set
21
21
  */
22
+ import { readShebangInvocation } from './shebang-interpreter.js';
22
23
  /**
23
24
  * Every long option name `set -o` accepts in bash or POSIX sh, mapped to the
24
25
  * single-letter flag that toggles the same option, or `undefined` when the
@@ -59,6 +60,8 @@ const SET_OPTION_FLAGS = Object.freeze({
59
60
  export const SET_OPTION_NAMES = Object.freeze(Object.keys(SET_OPTION_FLAGS));
60
61
  /** Single-letter flag → the long option name it toggles (the inverse of {@link SET_OPTION_FLAGS}). */
61
62
  const OPTION_NAME_BY_FLAG = new Map(Object.entries(SET_OPTION_FLAGS).flatMap(([name, flag]) => flag === undefined ? [] : [[flag, name]]));
63
+ /** One field known to start positional arguments when an option does not consume it. @internal */
64
+ export const SET_POSITIONAL_OPERAND = Symbol('set positional operand');
62
65
  /**
63
66
  * Reads a `set`-style argument list (the arguments after the command word, so
64
67
  * `["-euo", "pipefail"]` for `set -euo pipefail`) into the option changes it
@@ -79,6 +82,8 @@ export function parseSetArguments(args) {
79
82
  while (index < args.length) {
80
83
  const arg = args[index];
81
84
  index += 1;
85
+ if (arg === SET_POSITIONAL_OPERAND)
86
+ return { changes, stoppedBy: 'operand' };
82
87
  if (arg === null)
83
88
  return { changes, stoppedBy: 'unknown' };
84
89
  if (arg === '--')
@@ -97,7 +102,7 @@ export function parseSetArguments(args) {
97
102
  if (flag === 'o') {
98
103
  const name = index < args.length ? args[index] : undefined;
99
104
  index += 1;
100
- if (name === null)
105
+ if (name === null || name === SET_POSITIONAL_OPERAND)
101
106
  return { changes, stoppedBy: 'unknown' };
102
107
  if (name === undefined || !Object.hasOwn(SET_OPTION_FLAGS, name)) {
103
108
  return { changes, stoppedBy: 'malformed' };
@@ -158,56 +163,23 @@ export function formatSetCommand(options) {
158
163
  return words.join(' ');
159
164
  }
160
165
  /**
161
- * The option changes the shebang line passes to the shell (read by
162
- * the shared prologue definition and by
163
- * `compat/no-nounset-empty-array`). Only spellings the kernel hands to the shell as written
164
- * are read:
165
- *
166
- * - `#!/path/to/shell <word>`: the kernel passes everything after the
167
- * interpreter as one argument, so exactly one flag word is read
168
- * (`#!/bin/bash -eu`); more than one word (`#!/bin/bash -e -u`) arrives as a
169
- * single argument the shell rejects, and counts as nothing.
170
- * - `#!/usr/bin/env -S <shell> <words…>`: `env -S` splits the rest into words,
171
- * so every word after the shell name is read. GNU env's
172
- * `--split-string=<shell> <words…>` is read the same way; macOS env supports only `-S`.
173
- *
174
- * Plain `#!/usr/bin/env <shell> <flags>` counts as nothing: without `-S`,
175
- * Linux passes `<shell> <flags>` to `env` as one command name.
166
+ * Read the options from the kernel/GNU env argv using the shared set parser.
167
+ * An env directory or argv0 override can change the script that is read.
176
168
  *
177
169
  * @internal
178
170
  */
179
171
  export function shebangOptionChanges(text) {
180
172
  if (!text.startsWith('#!'))
181
173
  return [];
182
- const lineEnd = text.search(/\r?\n|\r/u);
183
- const words = text
184
- .slice(2, lineEnd === -1 ? undefined : lineEnd)
185
- .trim()
186
- .split(/\s+/u);
187
- const [interpreter = '', ...rest] = words;
188
- // Relative interpreters are resolved against the caller's directory, never through PATH.
189
- if (!interpreter.startsWith('/'))
174
+ const invocation = readShebangInvocation(text.slice(2));
175
+ if (invocation === undefined ||
176
+ invocation.chdirRequested === true ||
177
+ invocation.argv0Overridden === true) {
190
178
  return [];
191
- const isEnv = interpreter.endsWith('/env');
192
- let flagWords;
193
- if (isEnv) {
194
- const [split = '', , ...shellArgs] = rest;
195
- // The kernel's single argument makes `--split-string bash -eu` an unknown long option.
196
- if (split === '-S') {
197
- flagWords = shellArgs;
198
- }
199
- else if (split.startsWith('--split-string=')) {
200
- // The first word carries the command when attached; an empty value puts it next.
201
- flagWords = rest.slice(split === '--split-string=' ? 2 : 1);
202
- }
203
- else {
204
- return [];
205
- }
206
179
  }
207
- else {
208
- if (rest.length !== 1)
209
- return [];
210
- flagWords = rest;
211
- }
212
- return parseSetArguments(flagWords).changes;
180
+ // The original header tokenizer split at whitespace. A single resolved
181
+ // argument containing whitespace does not fit that token grammar.
182
+ if (invocation.args.some((arg) => arg !== null && /\s/u.test(arg)))
183
+ return [];
184
+ return parseSetArguments(invocation.args).changes;
213
185
  }
@@ -1,18 +1,41 @@
1
1
  /**
2
- * Shared reading of a shebang line's interpreter, so every rule that asks
3
- * "which shell does this file name?" gets one answer instead of re-deriving it.
2
+ * Read the kernel's interpreter path and optional argument, then apply the GNU
3
+ * env argument grammar when the path names env. A shebang is a shell comment.
4
4
  */
5
+ /** The interpreter names accepted by require-shebang. @internal */
6
+ export declare const RECOGNIZED_SHELLS: ReadonlySet<string>;
5
7
  /**
6
- * The shell basename a shebang's interpreter part (everything after `#!`)
7
- * runs, or `undefined` when it names no usable interpreter: either an absolute
8
- * path (`/usr/local/bin/bash` → `bash`), or an absolute path to `env` whose
9
- * command is the shell (`/usr/bin/env bash`, `/usr/bin/env -S bash -e` →
10
- * `bash`). A relative interpreter (`#!bash`) yields `undefined`: the kernel
11
- * would resolve it against the caller's working directory, not `PATH`.
8
+ * A work limit shared by all readings of one env argument. Each charge covers
9
+ * a bounded amount of work per argument node or code unit. Charge before
10
+ * scanning, copying, or looking up input-sized strings.
12
11
  *
13
- * Which names count as a shell, and whether one agrees with the configured
14
- * dialect, are the callers' questions; this only answers "what runs".
12
+ * @internal
13
+ */
14
+ export declare class EnvReadBudget {
15
+ private remaining;
16
+ constructor(length: number);
17
+ charge(units: number): void;
18
+ }
19
+ /** An interpreter selected from the kernel header. @internal */
20
+ export interface ShebangInvocation {
21
+ readonly shell: string;
22
+ /** GNU env requested a directory change in at least one reading. */
23
+ readonly chdirRequested?: true;
24
+ /** GNU env can change the executable's startup identity independently of its path. */
25
+ readonly argv0Overridden?: true;
26
+ /** Arguments before the kernel-supplied script path. Null marks uncertainty. */
27
+ readonly args: readonly (string | null)[];
28
+ }
29
+ /** Apply the kernel's LF, NUL, and blank handling to the physical header. @internal */
30
+ export declare function kernelShebangLine(text: string): string;
31
+ /**
32
+ * Read the interpreter basename and its initial arguments from the text
33
+ * after `#!`. An absolute path names the interpreter directly or, for `env`,
34
+ * through its command operand. A relative path depends on the caller's
35
+ * working directory.
15
36
  *
16
37
  * @internal
17
38
  */
39
+ export declare function readShebangInvocation(interpreterSpec: string): ShebangInvocation | undefined;
40
+ /** The interpreter basename, independent of its arguments. @internal */
18
41
  export declare function shebangShell(interpreterSpec: string): string | undefined;