@alexwkleung/reika 0.4.0 → 0.5.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.
@@ -9,8 +9,8 @@ import { execFileSync } from 'node:child_process';
9
9
  import { existsSync } from 'node:fs';
10
10
  import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
- import { WORD_RE, maskQuoted, splitSegments } from './_readonly.js';
13
- import { stripHeredocs } from './_heredoc.js';
12
+ import { maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
13
+ import { scanHeredocs, stripHeredocs } from './_heredoc.js';
14
14
  import { maskMarkdownData } from './_markdown.js';
15
15
  // Workflow-policy commands: not destructive (a commit is local and reversible, a push is
16
16
  // recoverable), but they record or publish work, and the user generally wants to stay in the
@@ -141,24 +141,57 @@ const PACKAGE_PATTERNS = [
141
141
  // detectDangerousPatterns. Matching is per shell segment, because the verb position is what
142
142
  // makes this precise: `grep -rn install src/` passes `install` as an *argument*, and the
143
143
  // read-only leads below never install anything, so they are skipped outright.
144
+ //
145
+ // Position is read TWO ways and a segment needs only one of them (#752). On whitespace,
146
+ // `GENERIC_PACKAGE_RE` counted `CFLAGS="-O2`, `-g` and `-Wall"` in `make CFLAGS="-O2 -g -Wall"
147
+ // install` as three leading tokens, so the verb landed past the budget and the install ran
148
+ // unprompted; `genericVerbWord` reads the same shape off the shell's own words, where that value is
149
+ // ONE token. The whitespace reading stays because `words()` drops a quote it cannot close and so
150
+ // SPLITS an unterminated run (`FOO="a b` reads as `FOO=`, `a`, `b`), and the extra words can push
151
+ // the verb past the budget — an under-report. Keeping both means quoting can add a label but never
152
+ // cost one. A quote-aware token PATTERN was the rejected option: an anchored reader that also
153
+ // tolerates an unterminated quote has two viable ends per token and re-explores every earlier one
154
+ // (`GENERIC_PACKAGE_RE` ends in `install`, so a `""` run backtracks catastrophically). `words()` is
155
+ // a lexer, so it costs one linear scan.
144
156
  const GENERIC_PACKAGE_RE = /^(?:\S+\s+){1,3}?(?:-{1,2}[\w-]+\s+)*(un)?install(?![\w./-])/;
157
+ // A flag token: the gap between the leading words and the verb.
158
+ const GENERIC_FLAG_RE = /^-{1,2}[\w-]+$/;
159
+ // A `VAR=value` operand (`make DESTDIR=/x install`) sits in the same gap: a make line carries
160
+ // several, and counted as leading words they pushed the verb past the budget.
161
+ const GENERIC_ASSIGN_RE = /^[A-Za-z_]\w*=/;
162
+ function genericVerbWord(list) {
163
+ // 1–3 leading words, then any run of flags and assignments, then the verb.
164
+ for (let i = 1; i <= 3 && i < list.length; i++) {
165
+ let j = i;
166
+ while (j < list.length && (GENERIC_FLAG_RE.test(list[j]) || GENERIC_ASSIGN_RE.test(list[j]))) {
167
+ j++;
168
+ }
169
+ if (j >= list.length)
170
+ break;
171
+ if (list[j] === 'uninstall')
172
+ return 'uninstall';
173
+ if (list[j] === 'install')
174
+ return 'install';
175
+ }
176
+ return undefined;
177
+ }
145
178
  const READ_ONLY_LEAD_RE = /^(?:e?grep|fgrep|rg|ag|ack|find|man|which|type|whereis|cat|bat|less|more|head|tail|awk|sed|echo|printf|ls|wc|git)\b/;
146
179
  // Tools whose own patterns already describe what they do. Without this, `helm uninstall app`
147
180
  // falls through to the generic label and reads as "removes third-party code" — it removes a
148
181
  // release from a cluster, and a misleading label is its own bug: the warning text is what the
149
182
  // user reads to decide.
150
183
  const SELF_COVERED_LEAD_RE = /^(?:helm|kubectl|oc|docker|podman|terraform|tofu|pulumi)\b/;
151
- function genericPackageLabel(command) {
152
- for (const segment of command.split(/[;&|]+/)) {
153
- const seg = segment.trim();
184
+ // Reads `verbSegments`' segments, so the two per-segment readers agree on what a segment is (#749).
185
+ function genericPackageLabel(segments) {
186
+ for (const seg of segments.map(s => s.trim())) {
154
187
  if (!seg || READ_ONLY_LEAD_RE.test(seg) || SELF_COVERED_LEAD_RE.test(seg))
155
188
  continue;
189
+ const word = genericVerbWord(words(seg));
156
190
  const m = GENERIC_PACKAGE_RE.exec(seg);
157
- if (m) {
158
- return m[1]
159
- ? 'Uninstall command (removes third-party code)'
160
- : 'Install command (fetches and runs third-party code)';
161
- }
191
+ if (word === 'uninstall' || m?.[1])
192
+ return 'Uninstall command (removes third-party code)';
193
+ if (word === 'install' || m)
194
+ return 'Install command (fetches and runs third-party code)';
162
195
  }
163
196
  return undefined;
164
197
  }
@@ -579,41 +612,267 @@ const VERB_PATTERNS = [
579
612
  ];
580
613
  // Leading tokens that don't change what a segment actually runs: env assignments, privilege and
581
614
  // timing wrappers, and the shell keywords a segment can open with (`if curl … ; then`).
582
- const VERB_PREFIX_RE = /^(?:(?:[A-Za-z_]\w*=\S*|sudo|command|nohup|exec|env|time|if|then|else|elif|do|while|until|!)\s+)+/;
615
+ //
616
+ // The quoted reading (`stripVerbPrefix`) walks the segment one shell word at a time, so an
617
+ // assignment's value is whatever the shell reads as one word: `"a b"`, `pre"a b"`, `"a b"c`, `$'a b'`,
618
+ // `a\ b`. `[A-Za-z_]\w*=\S*` stops at the space inside `"a b"` and leaves `b" curl …` standing, so
619
+ // the `^`-anchored verbs never see `curl` and the fetch runs unprompted (#752); a regex alternative
620
+ // that read only a value made of exactly one quoted run was the first cut, and missed the rest. A
621
+ // quote the walk cannot close takes the rest of its non-space run, the old reading, so an assignment
622
+ // is never left unmatchable. A lexer rather than a quote-aware pattern because a pattern that also
623
+ // tolerates an unclosed quote gives each token two viable ends, and anything anchored after it
624
+ // re-explores every earlier token's choice.
625
+ //
626
+ // `VERB_PREFIX_WS_RE` is the old strip, and it stays because the fragment IT leaves behind is
627
+ // sometimes the verb: `A="x pkill node" bash -c "$A"` reads as a `pkill` only through the blind
628
+ // reading, and the value is exactly what that `bash -c` runs. So `verbLabels` reads a segment both
629
+ // ways and reports the union — quoting can add a label, and cannot cost one. Both readings strip the
630
+ // same words, from one list, or the union would disagree about a wrapper only one of them knows.
631
+ const VERB_PREFIX_WORDS = [
632
+ 'sudo',
633
+ 'command',
634
+ 'nohup',
635
+ 'exec',
636
+ 'env',
637
+ 'time',
638
+ 'if',
639
+ 'then',
640
+ 'else',
641
+ 'elif',
642
+ 'do',
643
+ 'while',
644
+ 'until',
645
+ '!',
646
+ ];
647
+ const VERB_PREFIX_WORD_SET = new Set(VERB_PREFIX_WORDS);
648
+ const VERB_PREFIX_WS_RE = new RegExp(String.raw `^(?:(?:[A-Za-z_]\w*=\S*|${VERB_PREFIX_WORDS.join('|')})\s+)+`);
649
+ const SHELL_WORD_RE = /(?:"(?:[^"\\]|\\[\s\S])*"|\$'(?:[^'\\]|\\[\s\S])*'|'[^']*'|\\[\s\S]|[^\s"'\\])+/y;
650
+ const NON_SPACE_RUN_RE = /\S*/y;
651
+ const WORD_GAP_RE = /\s+/y;
652
+ const ENV_ASSIGN_WORD_RE = /^[A-Za-z_]\w*=/;
653
+ function stripVerbPrefix(segment) {
654
+ let at = 0;
655
+ for (;;) {
656
+ SHELL_WORD_RE.lastIndex = at;
657
+ let end = SHELL_WORD_RE.exec(segment) ? SHELL_WORD_RE.lastIndex : at;
658
+ if (end < segment.length && /["'\\]/.test(segment[end])) {
659
+ NON_SPACE_RUN_RE.lastIndex = end;
660
+ NON_SPACE_RUN_RE.exec(segment);
661
+ end = NON_SPACE_RUN_RE.lastIndex;
662
+ }
663
+ const word = segment.slice(at, end);
664
+ WORD_GAP_RE.lastIndex = end;
665
+ const gap = WORD_GAP_RE.exec(segment);
666
+ if (!gap || !(VERB_PREFIX_WORD_SET.has(word) || ENV_ASSIGN_WORD_RE.test(word))) {
667
+ return segment.slice(at);
668
+ }
669
+ at = WORD_GAP_RE.lastIndex;
670
+ }
671
+ }
583
672
  // Segments split on the operators AND on command substitution, so `$(curl …)` and `` `pkill …` ``
584
- // are seen as the commands they are rather than as arguments of whatever encloses them.
585
- // A separator inside quotes is data — `grep "a\|gh pr\|b"` is one grep, not a `gh pr` — except a
586
- // substitution, which runs inside double quotes too.
673
+ // are seen as the commands they are rather than as arguments of whatever encloses them. Matched
674
+ // against `maskShellData`, where a separator inside quotes is data — `grep "a\|gh pr\|b"` is one
675
+ // grep, not a `gh pr` — but a `$(…)` inside `"…"` is commands, and one inside `'…'` is neither.
587
676
  const VERB_SEPARATOR_RE = /[\n;&|(){}]+|\$\(|`/g;
588
- function verbSegments(command) {
677
+ // The shells that read a heredoc body as a program of their own. Everything else — `python3 -`,
678
+ // `node -`, `cat > run.py`, `gh --body-file -` — reads a body as a script in another language or as
679
+ // text, where a `; curl y` inside a string literal is a string and not a second command. Naming a
680
+ // shell here is the direction that KEEPS a body in the scan, so the set errs long: a wrong name
681
+ // costs an over-reported label, not a hidden command.
682
+ const SHELL_READERS = new Set([
683
+ 'sh',
684
+ 'bash',
685
+ 'rbash',
686
+ 'dash',
687
+ 'ash',
688
+ 'ksh',
689
+ 'mksh',
690
+ 'pdksh',
691
+ 'oksh',
692
+ 'zsh',
693
+ 'yash',
694
+ 'csh',
695
+ 'tcsh',
696
+ 'fish',
697
+ 'xonsh',
698
+ 'elvish',
699
+ 'busybox',
700
+ 'su',
701
+ ]);
702
+ // A version suffix still names the shell: `ksh93`, `bash5`, `zsh-5.9`.
703
+ function namesShell(word) {
704
+ const name = word.slice(word.lastIndexOf('/') + 1);
705
+ return SHELL_READERS.has(name) || SHELL_READERS.has(name.replace(/-?\d[\d.]*$/, ''));
706
+ }
707
+ // `.`/`source` read a file as shell, and stdin is a file: `. /dev/stdin <<'EOF'` runs the body.
708
+ const SOURCE_STDIN_RE = /(?:^|[\s;&|(])(?:\.|source)\s+\/(?:dev\/stdin|dev\/fd\/0|proc\/self\/fd\/0)(?=\s|$)/m;
709
+ // Whether a shell is named anywhere in the command outside its heredoc bodies. Any one then keeps
710
+ // every body in the scan, because the reader is not only the operator's own pipeline: a body
711
+ // written to a file is run by a shell on a later line (`cat > s.sh <<'EOF'` … `sh s.sh`), a shell
712
+ // on an earlier line reaches it through a `\` continuation or an open `bash -c "$(`, and a pipe
713
+ // carries on past a comment (`| # note`). Over-reports a command that merely names a shell.
714
+ function shellOutsideBodies(command, heredocs) {
715
+ let outside = command;
716
+ for (const h of heredocs) {
717
+ outside =
718
+ outside.slice(0, h.bodyStart) + ' '.repeat(h.end - h.bodyStart) + outside.slice(h.end);
719
+ }
720
+ return SOURCE_STDIN_RE.test(outside) || words(outside).some(namesShell);
721
+ }
722
+ // Whether a pipeline stage could be the shell that runs the body. ANY word naming a shell counts,
723
+ // not just the command word, because the shell can sit behind a wrapper's flags — `sudo -u me bash`,
724
+ // `env -i sh` — where the first word is the wrapper or one of its operands, and because a shell in
725
+ // the stage is the one reading the body either way. Coarse on purpose: `cat <<'EOF' | grep -n sh`
726
+ // then keeps the body in the scan and over-reports, which is the direction this can afford. A stage
727
+ // with no words at all is one the caller cannot read (`cat <<'EOF' |` with the pipeline continuing on
728
+ // the next line) and is answered the same way.
729
+ //
730
+ // The lookup is lexical, so it misses any name that only BECOMES a shell after quote removal or
731
+ // expansion — `s\h`, `$SHELL`, a backtick — and each miss HIDES a body a shell runs. One character
732
+ // of them is visible without guessing: they all carry a `\`, a `$` or a backtick, which no literal
733
+ // shell name does. A stage carrying one is answered as a shell too; over-report is the affordable
734
+ // error, a hidden `pkill node` is not.
735
+ function readsAsShell(stage) {
736
+ const ws = words(stage);
737
+ return ws.length === 0 || /[$`\\]/.test(stage) || ws.some(namesShell);
738
+ }
739
+ // The pipeline stages of one physical line, split on `|` as the quote mask sees it: a `|` inside a
740
+ // quoted string is a data character, not a stage boundary.
741
+ function lineStages(command, view, lineStart, lineEnd) {
742
+ const stages = [];
743
+ let start = lineStart;
744
+ for (let i = lineStart; i < lineEnd; i++) {
745
+ if (view[i] !== '|')
746
+ continue;
747
+ stages.push({ start, end: i });
748
+ start = i + 1;
749
+ }
750
+ stages.push({ start, end: lineEnd });
751
+ return stages;
752
+ }
753
+ // The verb question's two accounts of one command: `maskQuoted`'s, plus the heredoc bodies nothing
754
+ // runs (#699). A body is the verb scan's blind spot in both directions. The shell pastes it whole,
755
+ // so none of its separators are the shell's — but the walk that builds the quote mask deliberately
756
+ // records no quote spans inside one, because the shell doesn't quote-parse a body either. So before
757
+ // this, a `;` inside a string literal in a body split a segment and made the next word a verb:
758
+ // `python3 - <<'EOF'` / `print("x; curl y")` / `EOF` read as a `curl`, which for a script that runs
759
+ // no shell is exactly the reflexive-approval prompt the gate exists to avoid. Approving it also runs
760
+ // the script UNSANDBOXED (a flagged command a human cleared is `decideSandbox`'s unbounded case),
761
+ // where without the label it would have run sandboxed and unprompted.
762
+ //
763
+ // `pasted` comes back as its own list rather than as more blanking in `syntax`, and that is not
764
+ // cosmetic: `verbSegments` finds its separators in that mask, and a body's OPENING newline cannot be
765
+ // blanked without changing the command's line structure. A region is therefore reported as the
766
+ // half-open span `[bodyStart - 1, bodyEnd)` — the body plus the newline that opened
767
+ // it, terminator line excluded — and a caller asks whether a separator RUN ends in one. Not where
768
+ // it STARTS: `cat <<'EOF';` glues the body's opening newline onto the `;` before it, so a
769
+ // start-position test lets the body's first line through as a segment — while a run starting inside
770
+ // the body (a separator-char delimiter like `cat <<';'`) can cross `bodyEnd` and swallow the
771
+ // newline that restores `keep`, hiding the command after the body. The END of the run is what says
772
+ // "inside": it is the separator the run stands for.
773
+ //
774
+ // Three things keep a body out of `pasted`, and they are all the over-reporting side:
775
+ //
776
+ // - an UNQUOTED delimiter (`<<EOF`, `<<\EOF`): the shell expands `$(…)` and backticks in the body,
777
+ // so a substitution there runs — the same body `expandingHeredocBodies` reports. Only a body
778
+ // the shell pastes literally is data here.
779
+ // - a shell as the reader: `sh -s <<'EOF'`, one behind a wrapper's flags (`env -i sh <<'EOF'`) or
780
+ // further down the pipeline (`cat <<'EOF' | sh`, `cat <<'EOF' | sudo /bin/bash -s`), where the
781
+ // body arrives on the shell's stdin as commands. Such a body stays in the scan, because nothing
782
+ // here quote-parses it and so a bare `pkill node` line in one cannot be told from a string.
783
+ // - a reader that cannot be read: a stage with no words at all, and a line that ends in `\`, are
784
+ // both pipelines this does not see the end of.
785
+ //
786
+ // A command the lexer cannot read exactly pastes nothing, exactly as `maskQuoted` blanks nothing:
787
+ // the labels then over-report, never hide.
788
+ function verbData(command) {
789
+ const syntax = maskShellData(command);
589
790
  const masked = maskQuoted(command);
791
+ const scan = scanHeredocs(command);
792
+ if (scan.uncertain || shellOutsideBodies(command, scan.heredocs))
793
+ return { syntax, pasted: [] };
794
+ const pasted = [];
795
+ for (const h of scan.heredocs) {
796
+ if (!h.literal)
797
+ continue;
798
+ // An EMPTY body still reports its opening newline: the line that would close it is the
799
+ // terminator, and a terminator that reads as a verb (`cat <<'curl'` / `curl`) is not a command.
800
+ // The span degenerates to that one newline, which is all the caller needs.
801
+ // The verb question runs per line, and the reader and every stage the body could reach are both
802
+ // on the operator's own line: the body starts after the newline that ends it.
803
+ const lineStart = command.lastIndexOf('\n', h.opAt - 1) + 1;
804
+ const nl = command.indexOf('\n', h.opAt);
805
+ // A backslash before the newline continues the line, so the pipeline the operator sits in may
806
+ // reach further than this reads (and the shell puts the body after the NEXT newline, which is
807
+ // not where the lexer looked). Nothing is pasted then: the body stays in the scan.
808
+ let trailing = 0;
809
+ while (nl > lineStart && command[nl - 1 - trailing] === '\\')
810
+ trailing++;
811
+ if (trailing % 2 === 1)
812
+ continue;
813
+ const stages = lineStages(command, masked, lineStart, nl === -1 ? command.length : nl);
814
+ // The stage the operator sits in is the reader's; the ones after it are where a pipe could hand
815
+ // the body on to a shell. Earlier stages cannot read it, so `sh setup.sh | cat <<'EOF'` pastes.
816
+ const readers = stages
817
+ .slice(stages.findIndex(s => h.opAt < s.end))
818
+ .map(s => command.slice(s.start, s.end));
819
+ if (readers.some(readsAsShell))
820
+ continue;
821
+ pasted.push([h.bodyStart - 1, h.bodyEnd]);
822
+ }
823
+ return { syntax, pasted };
824
+ }
825
+ // A separator the mask blanked is not found at all, so the segment it sits in runs on to the next
826
+ // real one: cutting there and dropping the rest hid `FOO="a;b" make install` (#749).
827
+ function verbSegments(command, pasteBodies) {
828
+ const { syntax, pasted: found } = verbData(command);
829
+ const pasted = pasteBodies ? found : [];
830
+ // The shell deletes a line continuation, so the readers see it as the space it leaves; an escaped
831
+ // backslash before a newline is not one, and the mask is what tells them apart.
832
+ const text = command.replace(/\\\n/g, (m, at) => syntax[at] === ' ' && syntax[at + 1] === ' ' ? ' ' : m);
590
833
  const segments = [];
591
834
  let start = 0;
592
835
  let keep = true;
593
836
  VERB_SEPARATOR_RE.lastIndex = 0;
594
- for (let m = VERB_SEPARATOR_RE.exec(command); m; m = VERB_SEPARATOR_RE.exec(command)) {
837
+ for (let m = VERB_SEPARATOR_RE.exec(syntax); m; m = VERB_SEPARATOR_RE.exec(syntax)) {
595
838
  if (keep)
596
- segments.push(command.slice(start, m.index));
839
+ segments.push(text.slice(start, m.index));
597
840
  start = m.index + m[0].length;
598
- keep = m[0] === '$(' || m[0] === '`' || masked[m.index] === command[m.index];
841
+ // A separator inside a pasted body ends nothing the shell runs, so the text it closes is not a
842
+ // segment of its own — and `keep` goes false, which is what holds the body's own lines out of
843
+ // the next segment. It is read off `pasted` rather than off a blanked `masked`, because the
844
+ // opening separator of a body IS that body's newline and stays one in the mask. The test is
845
+ // where the run ENDS: `cat <<'EOF';` glues the body's opening newline onto the `;` before it
846
+ // (a start-position test would let the body's first line through), and a run starting inside
847
+ // the body can cross `bodyEnd` and swallow the newline that restores `keep` (hiding the command
848
+ // after the body) — an END past the region means the run ends in real syntax, and its text is
849
+ // the shell's again. A `$(…)` inside a pasted body is a string in that script.
850
+ keep = !pasted.some(([from, to]) => m.index + m[0].length > from && m.index + m[0].length <= to);
599
851
  }
600
852
  if (keep)
601
- segments.push(command.slice(start));
853
+ segments.push(text.slice(start));
602
854
  return segments;
603
855
  }
604
- function verbLabels(command) {
856
+ function verbLabels(segments) {
605
857
  const hits = [];
606
- for (const segment of verbSegments(command)) {
607
- const seg = segment.trim().replace(VERB_PREFIX_RE, '');
608
- if (!seg)
609
- continue;
610
- for (const { re, label } of VERB_PATTERNS) {
611
- if (re.test(seg) && !hits.includes(label))
612
- hits.push(label);
858
+ for (const segment of segments) {
859
+ const trimmed = segment.trim();
860
+ // Both prefix readings, unioned — see `VERB_PREFIX_WS_RE` above. They agree on any segment
861
+ // without a quoted value holding a space, which is nearly all of them, so the second pass only
862
+ // runs when they differ.
863
+ const quoted = stripVerbPrefix(trimmed);
864
+ const spaced = trimmed.replace(VERB_PREFIX_WS_RE, '');
865
+ for (const seg of spaced === quoted ? [quoted] : [quoted, spaced]) {
866
+ if (!seg)
867
+ continue;
868
+ for (const { re, label } of VERB_PATTERNS) {
869
+ if (re.test(seg) && !hits.includes(label))
870
+ hits.push(label);
871
+ }
872
+ const cluster = clusterLabel(seg) ?? ghLabel(seg) ?? hfLabel(seg);
873
+ if (cluster && !hits.includes(cluster))
874
+ hits.push(cluster);
613
875
  }
614
- const cluster = clusterLabel(seg) ?? ghLabel(seg) ?? hfLabel(seg);
615
- if (cluster && !hits.includes(cluster))
616
- hits.push(cluster);
617
876
  }
618
877
  return hits;
619
878
  }
@@ -832,6 +1091,11 @@ function readWord(rest) {
832
1091
  const SHELL_C_RE = /\b(?:sh|bash|zsh|dash|ksh)\s+(?:-[\w-]+\s+)*-c(?![\w-])/g;
833
1092
  const INTERPRETER_C_RE = /\b(python[\d.]*|ruby|perl|node|deno|php)\s+(?:-[\w-]+\s+)*(-[ce])(?![\w-])/g;
834
1093
  const CONTAINER_EXEC_RE = /\b(kubectl|oc|docker|podman)\s+(?:exec|run)\b[^\n]*?\s--(?=\s)/g;
1094
+ // The assignment arm keeps its bare `\S*` where the verb reader went to a lexer (#752), and the
1095
+ // trailing `ssh` is why: a quoted value has two viable ends (up to the space, or at the closing
1096
+ // `"`) and an `ssh` that fails to appear makes the engine re-explore every earlier token's choice.
1097
+ // What a miss costs here is the `via ssh:` detail only: `stripVerbPrefix` still puts `ssh` itself
1098
+ // in verb position, so the remote command prompts as remote host access.
835
1099
  const SSH_LEAD_RE = /(?:^|[\n;&|`(])\s*(?:(?:[A-Za-z_]\w*=\S*|sudo|command|nohup|env|time)\s+)*ssh(?![\w./-])/g;
836
1100
  const MAX_NESTED_BODIES = 8;
837
1101
  function nestedBodies(command) {
@@ -888,13 +1152,13 @@ function* segmentsWithDir(command, cwd) {
888
1152
  const stripped = stripHeredocs(command);
889
1153
  let dir = cwd;
890
1154
  for (const raw of splitSegments(stripped, maskQuoted(stripped))) {
891
- const words = (raw.trim().match(WORD_RE) ?? []).map(w => w.replace(/['"]/g, ''));
892
- if (words[0] === 'cd') {
893
- if (words[1])
894
- dir = resolve(dir, expandHome(words[1]));
1155
+ const ws = words(raw.trim());
1156
+ if (ws[0] === 'cd') {
1157
+ if (ws[1])
1158
+ dir = resolve(dir, expandHome(ws[1]));
895
1159
  continue;
896
1160
  }
897
- yield { dir, words };
1161
+ yield { dir, words: ws };
898
1162
  }
899
1163
  }
900
1164
  function expandHome(path) {
@@ -1013,8 +1277,11 @@ function detectAtDepth(rawCommand, depth, cwd) {
1013
1277
  if (re.test(command) && !hits.includes(label))
1014
1278
  hits.push(label);
1015
1279
  }
1280
+ // A shell's `-c` program pastes nothing: a heredoc there can be a `$(cat <<'EOF' …)` whose
1281
+ // output IS the program, and the shell that runs it was named one level up, out of sight here.
1282
+ const segments = verbSegments(command, depth === 0);
1016
1283
  for (const label of [
1017
- ...verbLabels(command),
1284
+ ...verbLabels(segments),
1018
1285
  remoteExecLabel(command, cwd),
1019
1286
  checkoutPathLabel(command, cwd),
1020
1287
  ]) {
@@ -1025,7 +1292,7 @@ function detectAtDepth(rawCommand, depth, cwd) {
1025
1292
  // reports one precise label instead of two overlapping ones. Every install/uninstall label
1026
1293
  // above contains the word, which is what makes this cheap test sufficient.
1027
1294
  if (!hits.some(h => /install/i.test(h))) {
1028
- const generic = genericPackageLabel(command);
1295
+ const generic = genericPackageLabel(segments);
1029
1296
  if (generic)
1030
1297
  hits.push(generic);
1031
1298
  }
@@ -39,6 +39,8 @@ const WORD_END_RE = /[\s;&|<>()]/;
39
39
  export function scanHeredocs(command) {
40
40
  const heredocs = [];
41
41
  const quotes = [];
42
+ const substitutions = [];
43
+ const escapes = [];
42
44
  let unclosedQuote = false;
43
45
  let ambiguousQuote = false;
44
46
  let uncertain = false;
@@ -46,6 +48,11 @@ export function scanHeredocs(command) {
46
48
  let pending = [];
47
49
  const n = command.length;
48
50
  let i = 0;
51
+ const closeSubstitution = (end) => {
52
+ const f = stack.pop();
53
+ if (f?.subAt !== undefined)
54
+ substitutions.push({ start: f.subAt, end });
55
+ };
49
56
  const innermostCloser = () => {
50
57
  for (let k = stack.length - 1; k >= 0; k--) {
51
58
  if (stack[k].kind === 'sub')
@@ -69,12 +76,12 @@ export function scanHeredocs(command) {
69
76
  i++;
70
77
  }
71
78
  else if (ch === '`') {
72
- stack.push({ kind: 'tick', parens: 0 });
79
+ stack.push({ kind: 'tick', parens: 0, subAt: i });
73
80
  i++;
74
81
  }
75
82
  else if (ch === '$' && command[i + 1] === '(') {
76
83
  const arith = command[i + 2] === '(';
77
- stack.push({ kind: arith ? 'arith' : 'sub', parens: 0 });
84
+ stack.push({ kind: arith ? 'arith' : 'sub', parens: 0, subAt: arith ? undefined : i });
78
85
  i += arith ? 3 : 2;
79
86
  }
80
87
  else
@@ -108,6 +115,7 @@ export function scanHeredocs(command) {
108
115
  }
109
116
  // A command context: the top level, a `$(…)`, a backtick or a process substitution.
110
117
  if (ch === '\\') {
118
+ escapes.push(i);
111
119
  i += 2;
112
120
  continue;
113
121
  }
@@ -150,15 +158,15 @@ export function scanHeredocs(command) {
150
158
  }
151
159
  if (ch === '`') {
152
160
  if (frame.kind === 'tick')
153
- stack.pop();
161
+ closeSubstitution(i + 1);
154
162
  else
155
- stack.push({ kind: 'tick', parens: 0 });
163
+ stack.push({ kind: 'tick', parens: 0, subAt: i });
156
164
  i++;
157
165
  continue;
158
166
  }
159
167
  if (ch === '$' && command[i + 1] === '(') {
160
168
  const arith = command[i + 2] === '(';
161
- stack.push({ kind: arith ? 'arith' : 'sub', parens: 0 });
169
+ stack.push({ kind: arith ? 'arith' : 'sub', parens: 0, subAt: arith ? undefined : i });
162
170
  i += arith ? 3 : 2;
163
171
  continue;
164
172
  }
@@ -182,13 +190,13 @@ export function scanHeredocs(command) {
182
190
  if (frame.parens > 0)
183
191
  frame.parens--;
184
192
  else if (frame.kind === 'sub')
185
- stack.pop();
193
+ closeSubstitution(i + 1);
186
194
  i++;
187
195
  continue;
188
196
  }
189
197
  if ((ch === '<' || ch === '>') && command[i + 1] === '(') {
190
198
  // Process substitution runs a command of its own, with its own heredocs.
191
- stack.push({ kind: 'sub', parens: 0 });
199
+ stack.push({ kind: 'sub', parens: 0, subAt: i });
192
200
  i += 2;
193
201
  continue;
194
202
  }
@@ -261,7 +269,11 @@ export function scanHeredocs(command) {
261
269
  // the `)` ever arrives, so the spans read there are good either way.
262
270
  if (stack.some(f => f.kind === 'dq'))
263
271
  unclosedQuote = true;
264
- return { heredocs, quotes, unclosedQuote, ambiguousQuote, uncertain };
272
+ for (const f of stack) {
273
+ if (f.subAt !== undefined)
274
+ substitutions.push({ start: f.subAt, end: n });
275
+ }
276
+ return { heredocs, quotes, substitutions, escapes, unclosedQuote, ambiguousQuote, uncertain };
265
277
  }
266
278
  function pendingFields(p) {
267
279
  return {
@@ -366,6 +378,8 @@ export function scanQuotes(command) {
366
378
  const scan = scanHeredocs(command);
367
379
  return {
368
380
  spans: scan.quotes,
381
+ substitutions: scan.substitutions,
382
+ escapes: scan.escapes,
369
383
  uncertain: scan.unclosedQuote || scan.ambiguousQuote,
370
384
  heredocOperator: heredocOperatorIn(scan),
371
385
  };