package-json-scripts-portability 0.0.2 → 0.0.4

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 (71) hide show
  1. package/README.md +60 -19
  2. package/dist/analyze-script.d.mts +10 -3
  3. package/dist/analyze-script.mjs +24 -15
  4. package/dist/command-checker.mjs +331 -99
  5. package/dist/command-usage.mjs +85 -36
  6. package/dist/commands.mjs +124 -5
  7. package/dist/context.mjs +8 -1
  8. package/dist/fixes.d.mts +1 -1
  9. package/dist/fixes.mjs +193 -49
  10. package/dist/line-break-checker.mjs +40 -7
  11. package/dist/messages.mjs +9 -1
  12. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/sorted-array-insertion-index-with.mjs +33 -0
  13. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/sorted-array-insertion-index.mjs +10 -0
  14. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/semver/is-semver-in-range.mjs +5 -0
  15. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/semver/parse-semver.mjs +26 -0
  16. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-after.mjs +24 -0
  17. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/isUnsafeProperty.mjs +18 -0
  18. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/setOwnValue.mjs +23 -0
  19. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/toPropertyKey.mjs +16 -0
  20. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/baseToString.mjs +26 -0
  21. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/hasOwn.mjs +13 -0
  22. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/isDeepKey.mjs +39 -0
  23. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/isIndex.mjs +10 -0
  24. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/tags.mjs +2 -1
  25. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/toKey.mjs +15 -0
  26. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedIndex.mjs +36 -0
  27. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedIndexBy.mjs +54 -0
  28. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedLastIndex.mjs +34 -0
  29. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedLastIndexBy.mjs +21 -0
  30. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/function/identity.mjs +5 -0
  31. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/cloneDeep.mjs +52 -0
  32. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/cloneDeepWith.mjs +179 -0
  33. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/get.mjs +67 -0
  34. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/has.mjs +53 -0
  35. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/property.mjs +26 -0
  36. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isArguments.mjs +26 -0
  37. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isBuffer.mjs +24 -0
  38. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isMatch.mjs +34 -0
  39. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isMatchWith.mjs +163 -0
  40. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isNaN.mjs +18 -0
  41. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isNil.mjs +24 -0
  42. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isNumber.mjs +24 -0
  43. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isObjectLike.mjs +28 -0
  44. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isSymbol.mjs +19 -0
  45. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isTypedArray.mjs +21 -0
  46. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/matches.mjs +36 -0
  47. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/matchesProperty.mjs +47 -0
  48. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/iteratee.mjs +46 -0
  49. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/toPath.mjs +75 -0
  50. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/toString.mjs +23 -0
  51. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/function/identity.mjs +24 -0
  52. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isEqualWith.mjs +1 -2
  53. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isNil.mjs +24 -0
  54. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isNull.mjs +25 -0
  55. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isPrimitive.mjs +26 -0
  56. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isSymbol.mjs +28 -0
  57. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isTypedArray.mjs +20 -0
  58. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isUndefined.mjs +25 -0
  59. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/remeda/dist/binarySearchCutoffIndex-Bu-OMJ0Z.mjs +26 -0
  60. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/remeda/dist/sortedIndexWith.mjs +7 -0
  61. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/verkit/dist/comparison-CmVirWIW.mjs +108 -0
  62. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/verkit/dist/range-C5wjdo9a.mjs +164 -0
  63. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/verkit/dist/set-BGFWKKE8.mjs +38 -0
  64. package/dist/redirection-checker.mjs +76 -24
  65. package/dist/reporter.mjs +63 -18
  66. package/dist/runners.d.mts +2 -5
  67. package/dist/runners.mjs +103 -22
  68. package/dist/script-analyzer.mjs +457 -155
  69. package/dist/word-checker.mjs +232 -103
  70. package/dist/words.mjs +34 -7
  71. package/package.json +27 -23
@@ -1,30 +1,44 @@
1
+ import { forEachChild, parse } from "unbash";
1
2
  import { CommandChecker } from "./command-checker.mjs";
2
3
  import { SHELLS, SHELL_STATE_COMMANDS } from "./commands.mjs";
3
- import { bashLabel, rangeInScript, withCovered } from "./context.mjs";
4
- import { lineBreakFix, removal, semicolonFix } from "./fixes.mjs";
4
+ import { bashLabel, originalText, rangeInScript, withCovered } from "./context.mjs";
5
+ import { joinLinesFix, lineBreakFix, removal, semicolonFix } from "./fixes.mjs";
5
6
  import { LineBreakChecker } from "./line-break-checker.mjs";
6
7
  import { BASH_4_SUGGESTION, BASH_SUGGESTION, NODE_SCRIPT_SUGGESTION, describeReplacement, truncate } from "./messages.mjs";
7
8
  import { PLATFORMS, POSIX_PLATFORMS, WINDOWS_PLATFORMS } from "./platforms.mjs";
8
- import { RedirectionChecker } from "./redirection-checker.mjs";
9
+ import { RedirectionChecker, doesRedirectOutput } from "./redirection-checker.mjs";
9
10
  import { Reporter } from "./reporter.mjs";
10
- import { runnerTraits } from "./runners.mjs";
11
+ import { TraitsReader, runnerTraits } from "./runners.mjs";
11
12
  import { arrayIsSubset } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-is-subset.mjs";
13
+ import { mapGetOrInsert } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/map/map-get-or-insert.mjs";
12
14
  import { mapGetOrInsertComputed } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/map/map-get-or-insert-computed.mjs";
15
+ import { sortedArrayInsertionIndex } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/sorted-array-insertion-index.mjs";
13
16
  import { substringBefore } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-before.mjs";
14
- import { WordChecker } from "./word-checker.mjs";
15
- import { DOUBLE_QUOTED_SPECIAL_CHARACTERS, WHITESPACE } from "./words.mjs";
16
- import { parse } from "unbash";
17
+ import { CMD_STATEMENTS, WordChecker } from "./word-checker.mjs";
18
+ import { DOUBLE_QUOTED_SPECIAL_CHARACTERS, WHITESPACE, nestedSource, staticValue } from "./words.mjs";
17
19
  // src/script-analyzer.ts
18
- /** A `#` comment after a word boundary */
19
- const COMMENT = /(?:^|[\s&;|])(#.*)/;
20
- /** A glob of script names that `concurrently` expands, e.g. `npm run watch:*(!css)` */
21
- const SCRIPT_GLOB = /((?:bun|npm|pnpm|yarn) run|node --run|deno task) (\S*\*\S*)/;
20
+ /** `#` comments after a word boundary, which end at the line feed, not at a carriage return */
21
+ const COMMENTS = /(?:^|[\s&;|])(#[^\n]*)/g;
22
+ /** Globs of script names that `concurrently` expands, e.g. `npm run watch:*(!css)` */
23
+ const SCRIPT_GLOBS = /((?:bun|npm|pnpm|yarn) run|node --run|deno task) (\S*\*\S*)/g;
22
24
  /** `shopt -s globstar`, which makes `**` recursive in the following commands */
23
25
  const SHOPT_GLOBSTAR = /\bshopt\s+-s\s+(?:\w+\s+)*globstar\b/;
24
- /** The rest of a script that only closes subshells */ const CLOSING_PARENTHESES = /^[\s)]*$/;
25
- const WINDOWS_BATCH_SYNTAX = /\bif\s+(?:\/i\s+)?(?:not\s+)?(?:defined|errorlevel|exist)\b|\bfor\s+(?:\/[a-z]\s+)*%%?[a-z]\b/gi;
26
+ /**
27
+ * The rest of a script that doesn't depend on the directory: closing parentheses, `;`, `&` and
28
+ * comments, and `exit`, `true`, `false` or `:` after `&&` or `||`, e.g. in `(cd a && b) || exit 1`
29
+ */
30
+ const DIRECTORY_INDEPENDENT_REST = /^(?:[\s&);]|#[^\n]*(?:\n|$)|(?:&&|\|\|)\s*(?:exit(?:\s+\d+)?|true|false|:))*$/;
31
+ const ONE_LINE_SUGGESTION = "Put the commands on one line instead.";
32
+ /** cmd.exe's `if` and `for` statements, e.g. `if exist dist` or `if "%CI%"=="true"` */
33
+ const WINDOWS_BATCH_SYNTAX = [
34
+ /\bif\s+(?:\/i\s+)?(?:not\s+)?(?:defined|errorlevel|exist)\b/gi,
35
+ /\bif\s+(?:\/i\s+)?(?:not\s+)?(?:"[^\n"]*"|[^\s"]\S*?)(?:\s*==\s*|\s+(?:equ|geq|gtr|leq|lss|neq)\s+)(?:"[^\n"]*"|[^\s"]\S*)/gi,
36
+ /\bfor\s+(?:\/[a-z]\s+)*%%?[a-z]\b/gi
37
+ ];
26
38
  const SINGLE_QUOTE = /'/;
39
+ const DOUBLE_QUOTE = /"/;
27
40
  const ANY_CHARACTER = /[\s\S]/;
41
+ const NO_PLATFORMS = /* @__PURE__ */ new Set();
28
42
  const doesChangeDirectory = (node) => {
29
43
  switch (node.type) {
30
44
  case "AndOr":
@@ -33,101 +47,225 @@ const doesChangeDirectory = (node) => {
33
47
  default: return false;
34
48
  }
35
49
  };
50
+ /** Arithmetic operators that assign, e.g. `+=` */
51
+ const ARITHMETIC_ASSIGNMENT = /^(?:[%&*+\-/^|]|<<|>>)?=$/;
52
+ /**
53
+ * Checks whether a piece of a command has an expansion that assigns a variable, e.g. `${A:=1}` or
54
+ * `$((i++))`.
55
+ * @param node The piece, e.g. a command or a word
56
+ * @returns Whether it does, apart from in a command substitution, which runs in a subshell
57
+ */
58
+ const hasAssigningExpansion = (node) => {
59
+ switch (node.type) {
60
+ case "ArithmeticBinary":
61
+ if (ARITHMETIC_ASSIGNMENT.test(node.operator)) return true;
62
+ break;
63
+ case "ArithmeticCommandExpansion":
64
+ case "CommandExpansion":
65
+ case "ProcessSubstitution": return false;
66
+ case "ArithmeticUnary":
67
+ if (node.operator === "++" || node.operator === "--") return true;
68
+ break;
69
+ case "ParameterExpansion": if (node.operation?.type === "Default" && (node.operation.operator === "=" || node.operation.operator === ":=")) return true;
70
+ }
71
+ const children = [];
72
+ forEachChild(node, (child) => {
73
+ children.push(child);
74
+ });
75
+ return children.some(hasAssigningExpansion);
76
+ };
36
77
  /**
37
78
  * Checks whether commands change the shell's state, e.g. with `exit` or a variable assignment.
38
- * @param node Commands of a command group
79
+ * @param node A command group or its commands
39
80
  * @returns Whether they do, or might, e.g. in an `if` statement
40
81
  */
41
82
  const doesChangeShellState = (node) => {
42
83
  switch (node.type) {
43
84
  case "AndOr":
44
85
  case "Pipeline": return node.commands.some(doesChangeShellState);
45
- case "BraceGroup": return node.body.commands.some((statement) => doesChangeShellState(statement.command));
46
- case "Command": return node.name ? SHELL_STATE_COMMANDS.has(node.name.value) : node.prefix.some((item) => item.type === "Assignment");
47
- case "Redirected": return doesChangeShellState(node.command);
86
+ case "BraceGroup": return node.body.commands.some((statement) => statement.background || doesChangeShellState(statement.command));
87
+ case "Command": return (node.name ? SHELL_STATE_COMMANDS.has(node.name.value) : node.prefix.some((item) => item.type === "Assignment")) || hasAssigningExpansion(node);
88
+ case "Redirected": return doesChangeShellState(node.command) || node.redirects.some(hasAssigningExpansion);
48
89
  case "Subshell": return false;
49
90
  default: return true;
50
91
  }
51
92
  };
52
93
  /**
53
- * Gets the text that a command receives for a word, e.g. a script for `sh -c`.
54
- * The outer shell's expansions are replaced by placeholders of the same length.
55
- * Their results aren't known, and they're reported for the outer script already.
56
- * @param parts The word's parts
57
- * @returns The text, with placeholders
94
+ * Gets the original text of a script nested in a piece with placeholders, when it has a source of
95
+ * its own, e.g. in backticks, which is the piece's text without some backslashes.
96
+ * @param source The nested script's source
97
+ * @param text The piece's text, with placeholders
98
+ * @param original The piece's original text
99
+ * @returns The nested script's source with the original text instead of placeholders
100
+ */
101
+ const originalNestedSource = (source, text, original) => {
102
+ let result = "";
103
+ let index = 0;
104
+ for (let textIndex = 0; textIndex < text.length && index < source.length; textIndex++) {
105
+ if (text[textIndex] !== source[index]) continue;
106
+ result += original[textIndex];
107
+ index++;
108
+ }
109
+ return result + source.slice(index);
110
+ };
111
+ /**
112
+ * Gets the parts of a command whose failures make the command itself fail, e.g. the last
113
+ * statement of `( ... )`, but no command of an `if` statement, which succeeds when its condition
114
+ * fails.
115
+ * @param node The command
116
+ * @returns The ranges of the parts in the command's source
58
117
  */
59
- const nestedSource = (parts) => parts.map((part) => {
60
- switch (part.type) {
61
- case "AnsiCQuoted":
62
- case "Glob":
63
- case "Literal":
64
- case "SingleQuoted": return part.value;
65
- case "DoubleQuoted":
66
- case "LocaleString": return nestedSource(part.parts);
67
- default: return "_".repeat(part.text.length);
118
+ const failureRanges = (node) => {
119
+ switch (node.type) {
120
+ case "AndOr": return node.commands.slice(node.operators.lastIndexOf("||") + 1).flatMap(failureRanges);
121
+ case "ArithmeticFor":
122
+ case "Case":
123
+ case "Coproc":
124
+ case "For":
125
+ case "Function":
126
+ case "If":
127
+ case "Select":
128
+ case "While": return [];
129
+ case "BraceGroup":
130
+ case "Subshell": {
131
+ const last = node.body.commands.at(-1);
132
+ return last && !last.background ? failureRanges(last.command) : [];
133
+ }
134
+ case "Redirected": return [...failureRanges(node.command), ...node.redirects];
135
+ default: return [node];
68
136
  }
69
- }).join("");
137
+ };
138
+ /** Gets what identifies the message of an issue, e.g. to find the same issue elsewhere */
139
+ const issueDataKey = (issue) => JSON.stringify([issue.messageId, issue.data]);
70
140
  /**
71
- * Finds the end of a run of `||` alternatives that each break on some platform, but together work
72
- * on all platforms, e.g. `open x || xdg-open x || start x`.
141
+ * Looks for a run of `||` alternatives that each fail on some platform, e.g.
142
+ * `open x || xdg-open x || start x`.
73
143
  * @param node The list that the alternatives are in
74
- * @param platformsOf Gets the platforms on which a command of the list doesn't work
144
+ * @param platformsOf Gets the platforms on which a command of the list fails
75
145
  * @param first Index of the run's first command
76
- * @returns Index of the run's last command, if there's such a run
146
+ * @returns Index of the run's last command, which is `first` if there is no run, and the platforms
147
+ * on which all of its commands fail, which are none if they work together on all platforms
77
148
  */
78
- const findFallbackEnd = (node, platformsOf, first) => {
79
- let unsupported = platformsOf(first);
80
- for (let last = first + 1; unsupported.size > 0 && last < node.commands.length && node.operators[last - 1] === "||"; last++) {
81
- const platforms = platformsOf(last);
82
- if (platforms.size === 0) return;
83
- unsupported = unsupported.intersection(platforms);
84
- if (unsupported.size === 0) return last;
149
+ const findFallbackRun = (node, platformsOf, first) => {
150
+ let common = platformsOf(first);
151
+ let last = first;
152
+ while (common.size > 0 && last + 1 < node.commands.length && node.operators[last] === "||") {
153
+ const platforms = platformsOf(last + 1);
154
+ if (platforms.size === 0) break;
155
+ last++;
156
+ common = common.intersection(platforms);
85
157
  }
158
+ return {
159
+ common,
160
+ last
161
+ };
162
+ };
163
+ /**
164
+ * Checks whether an alternative is meant for a platform where another one fails: it works there,
165
+ * and fails where the other one works.
166
+ * @param own Where the other alternative fails
167
+ * @param platform One of these platforms
168
+ * @param other Where the alternative fails, if there is one
169
+ * @returns Whether it is
170
+ */
171
+ const isAlternativeOn = (own, platform, other) => other != null && !other.has(platform) && !other.isSubsetOf(own);
172
+ /**
173
+ * Gets where the alternatives of a run fail without it being reported, when they all still fail on
174
+ * some platforms, e.g. macOS for `sed -i s/a/b/ f` in `sed -i s/a/b/ f || sed -i '' s/a/b/ f`.
175
+ * That's where an alternative for that platform takes over: the one that runs next there, or an
176
+ * earlier one, unlike `cp f.bak f` in `sed -i s/a/b/ f || cp f.bak f`, which only handles errors.
177
+ * @param failing Where each alternative of the run fails
178
+ * @returns Where each of them fails without it being reported
179
+ */
180
+ const partialFallbackPlatforms = (failing) => {
181
+ const removed = failing.map(() => /* @__PURE__ */ new Set());
182
+ const next = /* @__PURE__ */ new Map();
183
+ failing.toReversed().forEach((own, reversedIndex) => {
184
+ const ownRemoved = removed[failing.length - 1 - reversedIndex];
185
+ own.forEach((platform) => {
186
+ if (isAlternativeOn(own, platform, next.get(platform))) ownRemoved?.add(platform);
187
+ });
188
+ PLATFORMS.forEach((platform) => {
189
+ if (!own.has(platform)) next.set(platform, own);
190
+ });
191
+ });
192
+ const earlier = /* @__PURE__ */ new Map();
193
+ failing.forEach((own, index) => {
194
+ own.forEach((platform) => {
195
+ if (earlier.values().some((other) => isAlternativeOn(own, platform, other))) removed[index]?.add(platform);
196
+ });
197
+ earlier.set([...own].sort().join(","), own);
198
+ });
199
+ return removed;
86
200
  };
87
201
  var ScriptAnalyzer = class {
88
202
  #commands;
203
+ /** How many scripts the analyzed source is nested in, e.g. 1 in `sh -c "..."` */
204
+ #depth = 0;
205
+ #ignoredCommands;
89
206
  #lineBreaks;
207
+ /**
208
+ * Words joined into a nested script, e.g. in `cross-env-shell rm $DIR`, which loses their quotes,
209
+ * so quoting them doesn't help
210
+ */
211
+ #joinedScriptWords;
212
+ /** Words analyzed as nested scripts, e.g. in `sh -c "..."`, whose text that analysis checks */
213
+ #nestedScriptWords;
214
+ /**
215
+ * Issues of the scripts joined from several words of the command being walked, e.g. in
216
+ * `cross-env-shell ls ~/x`, which are reported on all of the words
217
+ */
218
+ #joinedScriptIssues;
90
219
  /** Parsed sources of the script and of the scripts nested in it, e.g. in `sh -c "..."` */
91
220
  #parsedScripts;
92
- /** Commands whose output goes into a pipe */
93
- #pipedCommands = /* @__PURE__ */ new Set();
94
221
  #redirections;
95
222
  #reporter;
96
223
  #words;
97
- constructor(length, options, traits, parsedScripts) {
224
+ constructor(length, commandOptions, traits, parsedScripts) {
98
225
  this.#parsedScripts = parsedScripts;
226
+ this.#ignoredCommands = commandOptions.ignoredCommands;
99
227
  this.#reporter = new Reporter(length);
100
228
  this.#words = new WordChecker(this.#reporter, (script, part, context) => {
101
229
  this.#walkNestedScript(script, part, context);
102
230
  }, traits);
103
231
  this.#lineBreaks = new LineBreakChecker(this.#reporter);
104
232
  this.#redirections = new RedirectionChecker(this.#reporter, this.#words);
105
- this.#commands = new CommandChecker(this.#reporter, options, (words, context, nested) => {
233
+ this.#commands = new CommandChecker(this.#reporter, commandOptions, (words, context, nested) => {
106
234
  this.#analyzeNestedWords(words, context, nested);
107
- });
235
+ }, traits);
108
236
  }
109
237
  get issues() {
110
- return this.#reporter.issues;
238
+ return this.#reporter.uniqueIssues;
111
239
  }
240
+ /**
241
+ * Analyzes a script or a piece of it that is a script of its own, e.g. in `sh -c "..."`.
242
+ * @param context The piece
243
+ * @returns Whether it was parsed and analyzed, unlike one that isn't a valid POSIX script
244
+ */
112
245
  analyzeSource(context) {
113
246
  const script = mapGetOrInsertComputed(this.#parsedScripts, context.source, parse);
114
247
  if (script.errors?.length) {
115
248
  this.#checkWindowsBatchSyntax(context);
116
- return;
249
+ return false;
117
250
  }
118
- this.#commands.addPositionalFixes(script.commands);
251
+ this.#commands.addPositionalFixes(script.commands, context.source);
119
252
  const scriptContext = context.shell === "bash" && SHOPT_GLOBSTAR.test(context.source) ? {
120
253
  ...context,
121
254
  bashOptions: /* @__PURE__ */ new Set([...context.bashOptions || [], "globstar"])
122
255
  } : context;
123
- this.#walkStatements(script.commands, script.end, scriptContext);
124
- this.#checkComments(script.commands, scriptContext);
256
+ this.#walkStatements(script.commands, {
257
+ end: context.source.length,
258
+ pos: 0
259
+ }, scriptContext, "script");
260
+ return true;
125
261
  }
126
- #analyzeNestedWords(words, context, { bashOptions, crossEnv, maskScriptGlobs = false, shell }) {
262
+ #analyzeNestedWords(words, context, { bashOptions, crossEnv, maskScriptGlobs = false, outerWord, shell }) {
263
+ if (this.#depth >= 10) return;
127
264
  const sources = words.map((word) => {
128
265
  const source = word.parts ? nestedSource(word.parts) : word.value;
129
- return maskScriptGlobs ? source.replace(SCRIPT_GLOB, (_, command, glob) => `${command} ${"_".repeat(glob.length)}`) : source;
266
+ return maskScriptGlobs ? source.replaceAll(SCRIPT_GLOBS, (_, command, glob) => `${command} ${"￿".repeat(glob.length)}`) : source;
130
267
  });
268
+ const source = sources.join(" ");
131
269
  const [word] = words;
132
270
  if (!word) return;
133
271
  const parts = word.parts || [];
@@ -142,41 +280,91 @@ var ScriptAnalyzer = class {
142
280
  end: words.at(-1)?.end || word.end,
143
281
  pos: word.pos
144
282
  });
145
- this.analyzeSource({
283
+ const firstIssue = this.#reporter.issues.length;
284
+ this.#depth++;
285
+ const isAnalyzed = this.analyzeSource({
146
286
  bashOptions,
147
- convertsSlashes: false,
148
287
  covered: context.covered,
149
288
  crossEnv,
150
289
  fixExclusions: [...context.fixExclusions, exclusion],
151
290
  fixedRange,
152
291
  offset,
292
+ originalSource: source.includes("￿") ? words.map((nested) => nested.parts ? nestedSource(nested.parts, true) : nested.value).join(" ") : source,
153
293
  portable: false,
294
+ runnerScript: false,
154
295
  shell,
155
- source: sources.join(" ")
296
+ source
156
297
  });
298
+ this.#depth--;
299
+ if (isAnalyzed && words.length === 1) (this.#nestedScriptWords ||= /* @__PURE__ */ new WeakSet()).add(outerWord || word);
300
+ else if (words.length > 1) {
301
+ const joinedWords = this.#joinedScriptWords || /* @__PURE__ */ new WeakSet();
302
+ this.#joinedScriptWords = joinedWords;
303
+ words.forEach((joined) => {
304
+ joinedWords.add(joined);
305
+ });
306
+ if (this.#reporter.issues.length > firstIssue) (this.#joinedScriptIssues ||= []).push(...this.#reporter.issues.slice(firstIssue));
307
+ }
157
308
  }
158
- #checkComments(statements, context) {
159
- let position = 0;
160
- [...statements, void 0].forEach((statement, index) => {
161
- const end = statement?.pos ?? context.source.length;
162
- const match = COMMENT.exec(context.source.slice(position, end));
163
- const comment = match?.[1];
164
- if (match && comment != null) {
165
- const start = position + match.index + match[0].length - comment.length;
166
- const commentEnd = start + comment.length;
167
- this.#reporter.reportSyntax(context, {
168
- end: commentEnd,
169
- pos: start
170
- }, "posix", false, "unsupportedSyntax", {
171
- suggestion: "Remove it instead.",
172
- syntax: "The `#` comment"
173
- }, {
174
- description: "Remove the comment.",
175
- edits: [removal(context.source, start, commentEnd)]
176
- });
177
- }
178
- position = statement ? this.#statementEnd(statement, statements.at(index + 1)?.pos || context.source.length, context.source) : end;
309
+ /**
310
+ * Sets the issues collected for the command being walked.
311
+ * @param issues The issues to collect into from now on
312
+ * @returns The issues collected so far
313
+ */
314
+ #swapJoinedScriptIssues(issues) {
315
+ const collected = this.#joinedScriptIssues;
316
+ this.#joinedScriptIssues = issues;
317
+ return collected;
318
+ }
319
+ /**
320
+ * Removes the platforms of the issues of a script joined from several words on which a word
321
+ * itself has the same issue, which is reported at its exact position, e.g. `~/x` in
322
+ * `cross-env-shell ls ~/x`.
323
+ * @param joinedIssues Issues of the joined script
324
+ * @param wordIssues Issues of the words, among others
325
+ * @param start Index of the first issue that may be updated
326
+ */
327
+ #dropJoinedDuplicates(joinedIssues, wordIssues, start) {
328
+ const wordIssuesByKey = /* @__PURE__ */ new Map();
329
+ wordIssues.forEach((issue) => {
330
+ mapGetOrInsert(wordIssuesByKey, issueDataKey(issue), []).push(issue);
179
331
  });
332
+ const platformsByKey = /* @__PURE__ */ new Map();
333
+ const removedPlatforms = /* @__PURE__ */ new Map();
334
+ joinedIssues.forEach((joined) => {
335
+ const key = issueDataKey(joined);
336
+ const platforms = mapGetOrInsertComputed(platformsByKey, `${key} ${joined.pos} ${joined.end}`, () => new Set((wordIssuesByKey.get(key) || []).filter((issue) => joined.pos <= issue.pos && issue.end <= joined.end).flatMap((issue) => issue.platforms)));
337
+ if (platforms.size > 0) removedPlatforms.set(joined, platforms);
338
+ });
339
+ if (removedPlatforms.size > 0) this.#reporter.removePlatforms(start, (issue) => removedPlatforms.get(issue));
340
+ }
341
+ /**
342
+ * Reports the comments in text between statements, which `unbash` skips.
343
+ * @param gap The text
344
+ * @param position Where the text starts in the source
345
+ * @param context Where the text is
346
+ * @returns Where the first comment starts in the text, or -1 if there is none
347
+ */
348
+ #checkComments(gap, position, context) {
349
+ if (!gap.includes("#")) return -1;
350
+ let first = -1;
351
+ gap.matchAll(COMMENTS).forEach((match) => {
352
+ const [text, comment = ""] = match;
353
+ const start = match.index + text.length - comment.length;
354
+ const commentEnd = position + start + comment.length;
355
+ if (first === -1) first = start;
356
+ this.#reporter.reportSyntax(context, {
357
+ end: commentEnd,
358
+ pos: position + start
359
+ }, "posix", false, "unsupportedSyntax", {
360
+ suggestion: "Remove it instead.",
361
+ syntax: "The `#` comment"
362
+ }, {
363
+ description: "Remove the comment.",
364
+ edits: [removal(context.source, position + start, commentEnd)]
365
+ });
366
+ });
367
+ return first;
180
368
  }
181
369
  /**
182
370
  * Gets where the text after a statement starts, after the bodies of its here-documents.
@@ -186,45 +374,79 @@ var ScriptAnalyzer = class {
186
374
  * @returns The offset in the source
187
375
  */
188
376
  #statementEnd(statement, nextStart, source) {
189
- const hereDocumentEnds = (this.#redirections.hereDocumentEnds.get(source) || []).filter((end) => end <= nextStart);
190
- return Math.max(statement.end, ...hereDocumentEnds);
377
+ const hereDocumentEnds = this.#redirections.hereDocumentEnds.get(source);
378
+ if (!hereDocumentEnds) return statement.end;
379
+ const count = sortedArrayInsertionIndex(hereDocumentEnds, nextStart, { rightmost: true });
380
+ return Math.max(statement.end, hereDocumentEnds[count - 1] || 0);
191
381
  }
192
- #checkWindowsBatchSyntax(context) {
193
- context.source.matchAll(WINDOWS_BATCH_SYNTAX).forEach((match) => {
382
+ /**
383
+ * Reports cmd.exe syntax, e.g. `if exist`.
384
+ * @param context Where to look for it
385
+ * @param pos Where to start looking in the source
386
+ * @param end Where to stop looking in the source
387
+ * @returns Whether it was found
388
+ */
389
+ #checkWindowsBatchSyntax(context, pos = 0, end = context.source.length) {
390
+ const firstIssue = this.#reporter.issues.length;
391
+ const text = context.source.slice(pos, end);
392
+ const matches = WINDOWS_BATCH_SYNTAX.flatMap((syntax) => [...text.matchAll(syntax)]);
393
+ matches.forEach((match) => {
394
+ const start = pos + match.index;
194
395
  this.#reporter.report(context, {
195
- end: match.index + match[0].length,
196
- pos: match.index
396
+ end: start + match[0].length,
397
+ pos: start
197
398
  }, "unsupportedSyntax", {
198
399
  suggestion: NODE_SCRIPT_SUGGESTION,
199
400
  syntax: `The Windows batch syntax \`${truncate(match[0])}\``
200
401
  }, context.portable ? PLATFORMS : POSIX_PLATFORMS);
201
402
  });
403
+ this.#reporter.markFailures(firstIssue);
404
+ return matches.length > 0;
202
405
  }
203
406
  /**
204
407
  * Drops the issues of alternatives for different platforms, e.g. `rm -rf a || rmdir /s /q a`.
205
408
  * @param node The list of commands joined by `||` (and other operators)
206
409
  * @param starts Index of the first issue of each command in the list, and of the end of its
207
410
  * issues
411
+ * @param context Where the list is
208
412
  */
209
- #dropPlatformFallbacks(node, starts) {
210
- const platformsOf = (index) => new Set(this.#reporter.issues.slice(starts[index], starts[index + 1]).flatMap((issue) => issue.platforms));
211
- const dropped = [];
413
+ #dropPlatformFallbacks(node, starts, context) {
414
+ if (!node.operators.includes("||")) return;
415
+ const issuesOf = (index) => this.#reporter.issues.slice(starts[index], starts[index + 1]);
416
+ const failingPlatforms = node.commands.map((command, index) => {
417
+ const ranges = failureRanges(command).map((range) => rangeInScript(context, range));
418
+ return new Set(issuesOf(index).filter((issue) => ranges.some((range) => range.pos <= issue.pos && issue.end <= range.end)).flatMap((issue) => this.#reporter.failingPlatforms(issue)));
419
+ });
420
+ const platformsOf = (index) => failingPlatforms[index] || NO_PLATFORMS;
421
+ const removedPlatforms = /* @__PURE__ */ new Map();
212
422
  let first = 0;
213
423
  while (first < node.commands.length) {
214
- const last = findFallbackEnd(node, platformsOf, first);
215
- if (last == null) first++;
216
- else {
217
- dropped.push([first, last]);
218
- first = last + 1;
424
+ const { common, last } = findFallbackRun(node, platformsOf, first);
425
+ if (last > first) {
426
+ const runStart = first;
427
+ const failing = failingPlatforms.slice(runStart, last + 1);
428
+ (common.size === 0 ? failing : partialFallbackPlatforms(failing)).forEach((platforms, offset) => {
429
+ issuesOf(runStart + offset).forEach((issue) => {
430
+ const failures = this.#reporter.failingPlatforms(issue);
431
+ removedPlatforms.set(issue, failures.length > 0 && failures.every((platform) => platforms.has(platform)) ? new Set(issue.platforms) : platforms);
432
+ });
433
+ });
219
434
  }
435
+ first = last + 1;
220
436
  }
221
- dropped.toReversed().forEach(([runStart, runEnd]) => {
222
- const start = starts[runStart];
223
- const end = starts[runEnd + 1];
224
- if (start != null && end != null) this.#reporter.issues.splice(start, end - start);
225
- });
437
+ const [start] = starts;
438
+ if (start != null && removedPlatforms.size > 0) this.#reporter.removePlatforms(start, (issue) => removedPlatforms.get(issue));
226
439
  }
227
- #walkCommand(node, context) {
440
+ /**
441
+ * Walks a command and the commands in it.
442
+ * @param node The command
443
+ * @param context Where the command is
444
+ * @param commandEnd Where the command ends along with its redirections, e.g. `> log` after
445
+ * `( ... )`
446
+ * @param redirects The redirections of the command, if it's a compound command, e.g. `> log`
447
+ * after `( ... )`
448
+ */
449
+ #walkCommand(node, context, commandEnd = node.end, redirects = []) {
228
450
  switch (node.type) {
229
451
  case "AndOr": {
230
452
  const starts = [];
@@ -233,7 +455,7 @@ var ScriptAnalyzer = class {
233
455
  this.#walkCommand(command, context);
234
456
  });
235
457
  starts.push(this.#reporter.issues.length);
236
- this.#dropPlatformFallbacks(node, starts);
458
+ this.#dropPlatformFallbacks(node, starts, context);
237
459
  this.#lineBreaks.checkOperatorLineBreaks(node.commands, context);
238
460
  break;
239
461
  }
@@ -247,7 +469,7 @@ var ScriptAnalyzer = class {
247
469
  this.#walkList(node.body, this.#reportStatement(context, node, "for (( ... ))", "bash"));
248
470
  break;
249
471
  case "BraceGroup": {
250
- const isSubshellSafe = context.source[node.end - 1] === "}" && node.body.commands.every((statement) => !doesChangeShellState(statement.command));
472
+ const isSubshellSafe = context.source[node.end - 1] === "}" && !doesChangeShellState(node) && !redirects.some(hasAssigningExpansion);
251
473
  const covered = this.#reporter.reportSyntax(context, {
252
474
  end: node.pos + 1,
253
475
  pos: node.pos
@@ -259,20 +481,23 @@ var ScriptAnalyzer = class {
259
481
  edits: [{
260
482
  end: node.pos + 1,
261
483
  pos: node.pos,
262
- text: "("
484
+ text: context.source[node.pos - 1] === "(" ? " (" : "("
263
485
  }, {
264
486
  end: node.end,
265
487
  pos: node.end - 1,
266
- text: ")"
488
+ text: context.source[node.end] === ")" ? ") " : ")"
267
489
  }]
268
490
  } : void 0);
269
- this.#walkList(node.body, withCovered(context, covered));
491
+ this.#walkGroup(node, withCovered(context, covered));
270
492
  break;
271
493
  }
272
494
  case "Case": {
273
495
  const nestedContext = this.#reportStatement(context, node, "case", "posix");
274
- this.#words.checkWord(node.word, nestedContext);
275
- node.items.forEach(({ body, end, terminator }) => {
496
+ this.#words.checkWord(node.word, nestedContext, { skipGlobs: true });
497
+ node.items.forEach(({ body, end, pattern, terminator }) => {
498
+ pattern.forEach((word) => {
499
+ this.#words.checkWord(word, nestedContext, { skipGlobs: true });
500
+ });
276
501
  this.#walkList(body, nestedContext);
277
502
  if (terminator === ";&" || terminator === ";;&") this.#reporter.reportSyntax(nestedContext, {
278
503
  end,
@@ -302,7 +527,7 @@ var ScriptAnalyzer = class {
302
527
  break;
303
528
  }
304
529
  case "Function": {
305
- const hasFunctionKeyword = context.source.startsWith("function", node.pos);
530
+ const hasFunctionKeyword = node.name.pos > node.pos;
306
531
  const covered = this.#reporter.reportSyntax(context, {
307
532
  end: node.name.end,
308
533
  pos: node.pos
@@ -311,7 +536,7 @@ var ScriptAnalyzer = class {
311
536
  syntax: "The Bash-specific `function` keyword"
312
537
  } : {
313
538
  suggestion: NODE_SCRIPT_SUGGESTION,
314
- syntax: `The shell function definition \`${node.name.text}()\``
539
+ syntax: `The shell function definition \`${originalText(context, node.name)}()\``
315
540
  });
316
541
  const nestedContext = withCovered(context, covered);
317
542
  if (node.body.type === "CompoundList") this.#walkList(node.body, nestedContext);
@@ -332,12 +557,17 @@ var ScriptAnalyzer = class {
332
557
  case "Pipeline":
333
558
  this.#walkPipeline(node, context);
334
559
  break;
335
- case "Redirected":
336
- this.#walkCommand(node.command, context);
560
+ case "Redirected": {
561
+ const redirectedContext = node.redirects.some(doesRedirectOutput) ? {
562
+ ...context,
563
+ outputRedirected: true
564
+ } : context;
565
+ this.#walkCommand(node.command, redirectedContext, commandEnd, node.redirects);
337
566
  node.redirects.forEach((redirection) => {
338
- this.#redirections.checkRedirection(redirection, context);
567
+ this.#redirections.checkRedirection(redirection, redirectedContext);
339
568
  });
340
569
  break;
570
+ }
341
571
  case "Select": {
342
572
  const nestedContext = this.#reportStatement(context, node, "select", "bash");
343
573
  node.wordlist?.forEach((word) => {
@@ -347,12 +577,12 @@ var ScriptAnalyzer = class {
347
577
  break;
348
578
  }
349
579
  case "Subshell":
350
- if (!context.portable && node.body.commands.some((statement) => doesChangeDirectory(statement.command)) && !CLOSING_PARENTHESES.test(context.source.slice(node.end))) this.#reporter.reportSyntax(context, node, "posix", true, "inconsistentBehavior", {
580
+ if (!context.portable && node.body.commands.some((statement) => doesChangeDirectory(statement.command)) && !DIRECTORY_INDEPENDENT_REST.test(context.source.slice(commandEnd))) this.#reporter.reportSyntax(context, node, "posix", true, "inconsistentBehavior", {
351
581
  reason: "cmd.exe only groups the commands, so `cd` also changes the directory of the commands that follow",
352
582
  suggestion: "Use `npm --prefix <directory>` or workspaces instead.",
353
583
  syntax: "The subshell `( ... )`"
354
584
  });
355
- this.#walkList(node.body, context);
585
+ this.#walkGroup(node, context);
356
586
  break;
357
587
  case "TestCommand": {
358
588
  const covered = this.#reporter.reportSyntax(context, node, "bash", false, "unsupportedSyntax", {
@@ -371,15 +601,27 @@ var ScriptAnalyzer = class {
371
601
  }
372
602
  }
373
603
  #walkList(list, context) {
374
- this.#walkStatements(list.commands, list.end, context);
604
+ this.#walkStatements(list.commands, list, context);
605
+ }
606
+ /**
607
+ * Walks the commands of a group, i.e. `( ... )` or `{ ... }`.
608
+ * @param node The group
609
+ * @param context Where the group is
610
+ */
611
+ #walkGroup(node, context) {
612
+ this.#walkStatements(node.body.commands, {
613
+ end: Math.max(node.body.end, node.end - 1),
614
+ pos: node.pos + 1
615
+ }, context, "group");
375
616
  }
376
617
  #walkNestedScript(script, part, context) {
377
618
  const nestedContext = script.source == null ? context : {
378
619
  ...context,
379
620
  fixedRange: rangeInScript(context, part),
621
+ originalSource: context.originalSource === context.source ? script.source : originalNestedSource(script.source, context.source.slice(part.pos, part.end), originalText(context, part)),
380
622
  source: script.source
381
623
  };
382
- this.#walkStatements(script.commands, script.end, nestedContext);
624
+ this.#walkStatements(script.commands, script, nestedContext);
383
625
  }
384
626
  #walkPipeline(node, context) {
385
627
  node.prefixes.forEach((prefix) => {
@@ -410,42 +652,71 @@ var ScriptAnalyzer = class {
410
652
  }]
411
653
  });
412
654
  });
413
- node.commands.slice(0, -1).forEach((command) => {
414
- this.#pipedCommands.add(command);
415
- });
416
- node.commands.forEach((command) => {
417
- this.#walkCommand(command, context);
655
+ const pipedContext = {
656
+ ...context,
657
+ outputRedirected: true
658
+ };
659
+ node.commands.forEach((command, index) => {
660
+ this.#walkCommand(command, index < node.commands.length - 1 ? pipedContext : context);
418
661
  });
419
662
  this.#lineBreaks.checkOperatorLineBreaks(node.commands, context);
420
663
  }
421
664
  #walkSimpleCommand(node, context) {
665
+ const name = node.name && staticValue(node.name);
666
+ if (name != null && CMD_STATEMENTS.has(name.toLowerCase()) && this.#checkWindowsBatchSyntax(context, node.pos, node.end)) return;
422
667
  const isRedirection = node.name == null && node.prefix.length + node.suffix.length === 1;
668
+ const isOutputUsed = context.outputRedirected || node.redirects.some(doesRedirectOutput);
669
+ const redirectionContext = isOutputUsed && !context.outputRedirected ? {
670
+ ...context,
671
+ outputRedirected: true
672
+ } : context;
423
673
  node.prefix.forEach((item) => {
424
674
  if (item.type === "Assignment") this.#words.checkAssignment(item, context, node.name ? node : void 0);
425
- else this.#redirections.checkRedirection(item, context, isRedirection);
675
+ else this.#redirections.checkRedirection(item, redirectionContext, isRedirection);
426
676
  });
677
+ const enclosingJoinedIssues = this.#swapJoinedScriptIssues(void 0);
678
+ const invocationStart = this.#reporter.issues.length;
427
679
  const invocation = node.name && this.#commands.checkInvocation(node.name, node.suffix.filter((item) => item.type === "Word"), context, 0);
428
- let argumentContext = invocation?.crossEnv ? {
429
- ...context,
430
- crossEnv: true
431
- } : context;
432
- if (invocation?.name != null && (SHELLS.includes(invocation.name) || invocation.name === "find")) argumentContext = withCovered(argumentContext, WINDOWS_PLATFORMS);
680
+ const joinedIssues = this.#swapJoinedScriptIssues(enclosingJoinedIssues);
681
+ const argumentContext = invocation?.name != null && (SHELLS.includes(invocation.name) || invocation.name === "find") && !this.#ignoredCommands.has(invocation.name) ? withCovered(context, WINDOWS_PLATFORMS) : context;
682
+ const crossEnv = invocation?.crossEnv && {
683
+ ...invocation.crossEnv,
684
+ commandContext: {
685
+ ...argumentContext,
686
+ crossEnv: invocation.crossEnv.shell ? "arguments" : "command",
687
+ crossEnvVariables: invocation.crossEnv.variables
688
+ },
689
+ context: {
690
+ ...argumentContext,
691
+ crossEnv: "arguments"
692
+ }
693
+ };
694
+ const contextOf = (item) => {
695
+ if (!crossEnv || item.pos < crossEnv.start) return argumentContext;
696
+ return item.pos < crossEnv.commandStart ? crossEnv.context : crossEnv.commandContext;
697
+ };
433
698
  if (node.name) {
434
699
  this.#words.checkWord(node.name, context, { commandName: true });
435
- if (invocation?.name === "echo" && !context.portable) this.#redirections.checkEchoToFile(node, context);
700
+ if (isOutputUsed && !context.portable && invocation?.name === "echo") this.#redirections.checkQuotedEcho(node, context);
436
701
  }
437
702
  this.#lineBreaks.checkCommandLineBreak(node, argumentContext);
438
- const isPrintedToTerminal = invocation?.target === "echo" && node.redirects.length === 0 && !this.#pipedCommands.has(node);
703
+ const isPrintedToTerminal = invocation?.target === "echo" && !isOutputUsed;
704
+ const wordsStart = this.#reporter.issues.length;
439
705
  node.suffix.forEach((item) => {
440
- if (item.type === "Assignment") (item.value.type === "Word" ? [item.value] : item.value.elements).forEach((word) => {
441
- this.#words.checkWord(word, argumentContext);
442
- });
443
- else if (item.type === "Word") this.#words.checkWord(item, argumentContext, {
444
- command: invocation?.target,
445
- printedToTerminal: isPrintedToTerminal
446
- });
447
- else this.#redirections.checkRedirection(item, context);
706
+ if (item.type === "Assignment") this.#words.checkDeclaredAssignment(item, contextOf(item));
707
+ else if (item.type === "Word") {
708
+ const wordContext = contextOf(item);
709
+ this.#words.checkWord(item, this.#joinedScriptWords?.has(item) ? {
710
+ ...wordContext,
711
+ fixExclusions: [...wordContext.fixExclusions, DOUBLE_QUOTE]
712
+ } : wordContext, {
713
+ command: invocation?.target,
714
+ nestedScript: this.#nestedScriptWords?.has(item),
715
+ printedToTerminal: isPrintedToTerminal
716
+ });
717
+ } else this.#redirections.checkRedirection(item, redirectionContext);
448
718
  });
719
+ if (joinedIssues) this.#dropJoinedDuplicates(joinedIssues, this.#reporter.issues.slice(wordsStart), invocationStart);
449
720
  }
450
721
  #reportStatement(context, node, keyword, kind) {
451
722
  const firstWord = substringBefore(keyword, " ");
@@ -461,39 +732,56 @@ var ScriptAnalyzer = class {
461
732
  });
462
733
  return withCovered(context, covered);
463
734
  }
464
- #walkStatements(statements, end, context) {
735
+ /**
736
+ * Walks a list of statements and checks the text around them, e.g. `;` and comments.
737
+ * @param statements The statements
738
+ * @param listRange Where the list is, including the text before the first statement and after
739
+ * the last one, e.g. up to the closing parenthesis of `( ... )`
740
+ * @param context Where the list is
741
+ * @param kind What the list is: a whole script, the body of `( ... )` or `{ ... }` (a group), or
742
+ * another list, e.g. the body of `if`
743
+ */
744
+ #walkStatements(statements, listRange, context, kind = "list") {
465
745
  const firstIssue = this.#reporter.issues.length;
466
746
  const backgroundOperators = [];
747
+ const { source } = context;
748
+ const [first] = statements;
749
+ const leadingGap = source.slice(listRange.pos, first?.pos ?? listRange.end);
750
+ const leadingComment = this.#checkComments(leadingGap, listRange.pos, context);
751
+ const leadingLineBreak = leadingGap.indexOf("\n");
752
+ if (first && kind !== "list" && leadingLineBreak !== -1 && (leadingComment === -1 || leadingComment > leadingLineBreak)) {
753
+ const position = listRange.pos + leadingLineBreak;
754
+ this.#lineBreaks.reportLineBreak(context, position, ONE_LINE_SUGGESTION, joinLinesFix(source, position, first.pos));
755
+ }
467
756
  statements.forEach((statement, index) => {
468
757
  this.#walkCommand(statement.command, context);
469
758
  if (statement.background) {
470
- const position = context.source.lastIndexOf("&", statement.end - 1);
759
+ const position = source.lastIndexOf("&", statement.end - 1);
471
760
  backgroundOperators.push({
472
761
  end: position + 1,
473
762
  pos: position
474
763
  });
475
- return;
476
764
  }
477
765
  const next = statements.at(index + 1);
478
- const gapEnd = next?.pos || end;
479
- const gapStart = this.#statementEnd(statement, gapEnd, context.source);
480
- const gap = context.source.slice(gapStart, gapEnd);
481
- const comment = COMMENT.exec(gap);
482
- const commentText = comment?.[1];
483
- const commentStart = comment && commentText != null ? comment.index + comment[0].length - commentText.length : void 0;
484
- const semicolon = gap.slice(0, commentStart).indexOf(";");
766
+ const gapEnd = next?.pos || listRange.end;
767
+ const gapStart = this.#statementEnd(statement, gapEnd, source);
768
+ const gap = source.slice(gapStart, gapEnd);
769
+ const comment = this.#checkComments(gap, gapStart, context);
770
+ const semicolon = gap.slice(0, comment === -1 ? void 0 : comment).indexOf(";");
485
771
  if (semicolon !== -1) {
486
772
  const range = {
487
773
  end: gapStart + semicolon + 1,
488
774
  pos: gapStart + semicolon
489
775
  };
490
- this.#reporter.reportSyntax(context, range, "posix", true, "unsupportedSyntax", {
776
+ if (this.#reporter.reportSyntax(context, range, "posix", true, "unsupportedSyntax", {
491
777
  suggestion: "Use `&&` instead.",
492
778
  syntax: "The `;` command separator"
493
- }, semicolonFix(range, gap, next));
494
- } else if (next && gap.includes("\n")) this.#lineBreaks.reportLineBreak(context, gapStart + gap.indexOf("\n"), "Join the commands with `&&` instead.", lineBreakFix(gapStart, gap, next));
779
+ }, semicolonFix(range, gap, statement, next)).length > 0) return;
780
+ }
781
+ if ((next || kind === "group") && gap.includes("\n")) this.#lineBreaks.reportLineBreak(context, gapStart + gap.indexOf("\n"), next && !statement.background ? "Join the commands with `&&` instead." : ONE_LINE_SUGGESTION, semicolon === -1 && next ? lineBreakFix(source, gapStart, statement, next) : void 0);
495
782
  });
496
- if (!this.#reporter.issues.slice(firstIssue).some(({ platforms }) => platforms.length === POSIX_PLATFORMS.length && arrayIsSubset(platforms, POSIX_PLATFORMS))) backgroundOperators.forEach((range) => {
783
+ if (backgroundOperators.length === 0) return;
784
+ if (!this.#reporter.issues.slice(firstIssue).some((issue) => this.#reporter.isFailure(issue) && issue.platforms.length === POSIX_PLATFORMS.length && arrayIsSubset(issue.platforms, POSIX_PLATFORMS))) backgroundOperators.forEach((range) => {
497
785
  this.#reporter.reportSyntax(context, range, "posix", true, "inconsistentBehavior", {
498
786
  reason: "cmd.exe runs the commands sequentially instead of in the background",
499
787
  suggestion: "Use `concurrently` instead.",
@@ -527,25 +815,39 @@ var ScriptAnalyzer = class {
527
815
  * @param script The script's source
528
816
  * @param options Analysis options
529
817
  * @param runners What runs the script
530
- * @returns The issues found with each runner
818
+ * @returns The issues found with each runner, by their keys
531
819
  */
532
820
  const analyzeWithRunners = (script, options, runners) => {
533
821
  const parsedScripts = /* @__PURE__ */ new Map();
822
+ const commandOptions = {
823
+ dependencies: options.dependencies || [],
824
+ ignoredCommands: new Set(options.ignoreCommands)
825
+ };
826
+ const analyses = [];
534
827
  return new Map(runners.map((runner) => {
535
828
  const traits = runnerTraits(runner, options.shellEmulator || false);
536
- const analyzer = new ScriptAnalyzer(script.length, options, traits, parsedScripts);
829
+ const reused = analyses.find((analysis) => analysis.traits.matches(traits));
830
+ if (reused) return [runner, reused.issues];
831
+ const reader = new TraitsReader(traits);
832
+ const analyzer = new ScriptAnalyzer(script.length, commandOptions, reader, parsedScripts);
537
833
  analyzer.analyzeSource({
538
- convertsSlashes: traits.convertsSlashes || false,
539
834
  covered: /* @__PURE__ */ new Set(),
540
835
  crossEnv: false,
541
836
  fixExclusions: [],
542
837
  fixedRange: void 0,
543
838
  offset: 0,
544
- portable: traits.portableShell || false,
839
+ originalSource: script,
840
+ portable: reader.get("portableShell") || false,
841
+ runnerScript: true,
545
842
  shell: "native",
546
843
  source: script
547
844
  });
548
- return [runner, analyzer.issues];
845
+ const { issues } = analyzer;
846
+ analyses.push({
847
+ issues,
848
+ traits: reader
849
+ });
850
+ return [runner, issues];
549
851
  }));
550
852
  };
551
853
  export { analyzeWithRunners };