package-json-scripts-portability 0.0.0 → 0.0.2

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 (66) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +235 -45
  3. package/dist/analyze-script.d.mts +34 -0
  4. package/dist/analyze-script.mjs +48 -0
  5. package/dist/command-checker.mjs +295 -0
  6. package/dist/command-usage.mjs +364 -0
  7. package/dist/commands.mjs +520 -0
  8. package/dist/context.mjs +18 -0
  9. package/dist/fixes.d.mts +9 -0
  10. package/dist/fixes.mjs +210 -0
  11. package/dist/index.d.mts +6 -0
  12. package/dist/index.mjs +5 -0
  13. package/dist/line-break-checker.mjs +71 -0
  14. package/dist/messages.mjs +30 -0
  15. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-difference.mjs +11 -0
  16. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-includes.mjs +8 -0
  17. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-intersection.mjs +13 -0
  18. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-is-subset.mjs +16 -0
  19. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/arrayify.mjs +7 -0
  20. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/iterable/sliding-window.mjs +30 -0
  21. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/map/map-get-or-insert-computed.mjs +42 -0
  22. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/map/map-get-or-insert.mjs +40 -0
  23. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/math/clamp.mjs +7 -0
  24. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/path/to-forward-slashes.mjs +8 -0
  25. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/predicate/is-array.mjs +39 -0
  26. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/set/set-has.mjs +8 -0
  27. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-after-last.mjs +24 -0
  28. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-before.mjs +24 -0
  29. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/truncate.mjs +46 -0
  30. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/ts/all-union-members.mjs +45 -0
  31. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/types/maybe-readonly-array.d.mts +17 -0
  32. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/value/is-equal.mjs +37 -0
  33. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/@antfu/utils/dist/index.mjs +5 -0
  34. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/globalThis.mjs +5 -0
  35. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/differenceBy.mjs +40 -0
  36. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/differenceWith.mjs +37 -0
  37. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/intersectionWith.mjs +43 -0
  38. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/isSubsetWith.mjs +36 -0
  39. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/bigint/clamp.mjs +15 -0
  40. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/getSymbols.mjs +5 -0
  41. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/getTag.mjs +13 -0
  42. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/regexMultiByte.mjs +10 -0
  43. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/tags.mjs +27 -0
  44. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isObject.mjs +28 -0
  45. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/string/truncate.mjs +78 -0
  46. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/eq.mjs +18 -0
  47. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/function/noop.mjs +12 -0
  48. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/math/clamp.mjs +23 -0
  49. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isBuffer.mjs +24 -0
  50. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isEqual.mjs +21 -0
  51. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isEqualWith.mjs +151 -0
  52. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isPlainObject.mjs +50 -0
  53. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/remeda/dist/isArray.mjs +18 -0
  54. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/ts-extras/distribution/array-includes.mjs +5 -0
  55. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/ts-extras/distribution/set-has.mjs +5 -0
  56. package/dist/platforms.d.mts +8 -0
  57. package/dist/platforms.mjs +26 -0
  58. package/dist/redirection-checker.mjs +117 -0
  59. package/dist/reporter.d.mts +32 -0
  60. package/dist/reporter.mjs +98 -0
  61. package/dist/runners.d.mts +24 -0
  62. package/dist/runners.mjs +118 -0
  63. package/dist/script-analyzer.mjs +551 -0
  64. package/dist/word-checker.mjs +444 -0
  65. package/dist/words.mjs +43 -0
  66. package/package.json +118 -6
@@ -0,0 +1,295 @@
1
+ import { checkCommandUsage } from "./command-usage.mjs";
2
+ import { CMD_BUILTINS, COMMANDS, EXEC_SUBCOMMANDS, EXEC_VALUE_OPTIONS, PACKAGE_MANAGER_VALUE_OPTIONS, PORTABLE_SHELL_BUILTINS, WRAPPER_VALUE_OPTIONS } from "./commands.mjs";
3
+ import { withCovered } from "./context.mjs";
4
+ import { DEPENDENCY_BINARY, commandFix, pathCommandFix, replacement } from "./fixes.mjs";
5
+ import { NODE_SCRIPT_SUGGESTION, SHELL_SCRIPT_SUGGESTION, truncate } from "./messages.mjs";
6
+ import { LINUX_PLATFORMS, PLATFORMS, POSIX_PLATFORMS, WINDOWS_PLATFORMS } from "./platforms.mjs";
7
+ import { arrayDifference } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-difference.mjs";
8
+ import { arrayIncludes } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-includes.mjs";
9
+ import { setHas } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/set/set-has.mjs";
10
+ import { slidingWindow } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/iterable/sliding-window.mjs";
11
+ import { ASSIGNMENT, WHITESPACE, isPlainAssignment, isShortOptionCluster, staticValue } from "./words.mjs";
12
+ // src/command-checker.ts
13
+ const MAX_DEPTH = 10;
14
+ /** Where Yarn v1 replaces `/` with `\` in a command's name: at the start and after an operator */
15
+ const YARN_COMMAND_START = /(?:^|&&|&|\|\||\|)\s*$/;
16
+ /**
17
+ * Checks whether a name is a package spec rather than a path, e.g. `@scope/name` or
18
+ * `github:user/repo` (for `npx`)
19
+ */
20
+ const isPackageSpec = (name) => name.startsWith("@") || name.includes(":");
21
+ const SHELL_SCRIPT = /\.(?:bash|command|sh|zsh)$/;
22
+ const WINDOWS_SCRIPT = /\.(?:bat|cmd|exe|ps1|vbs)$/i;
23
+ /** Exit statuses of commands that `exit` can replace at the end of a script */
24
+ const EXIT_STATUSES = /* @__PURE__ */ new Map([
25
+ [":", "0"],
26
+ ["false", "1"],
27
+ ["true", "0"]
28
+ ]);
29
+ /** Options of npx and `npm exec` that take a shell string */
30
+ const CALL_OPTIONS = /* @__PURE__ */ new Set(["--call", "-c"]);
31
+ /** Options of pnpm and aube that make the command and its arguments a shell line */
32
+ const SHELL_MODE_OPTIONS = /* @__PURE__ */ new Set(["--shell-mode", "-c"]);
33
+ /**
34
+ * Finds the command that a command runs, e.g. `rm` in `cross-env A=1 rm -rf dist`.
35
+ * @param values The static values of the outer command's arguments
36
+ * @param start Index of the first argument to consider
37
+ * @param valueOptions Options of the outer command that take a value
38
+ * @param shouldSkipAssignments Whether to skip `NAME=value` arguments
39
+ * @returns Index of the nested command's name, or -1 if there is none
40
+ */
41
+ const findCommandIndex = (values, start, valueOptions, shouldSkipAssignments = false) => {
42
+ for (let index = start; index < values.length; index++) {
43
+ const value = values[index];
44
+ if (value == null) return index;
45
+ if (value === "--") return index + 1;
46
+ if (value.startsWith("-") && value.length > 1) {
47
+ if (valueOptions.includes(value)) index++;
48
+ continue;
49
+ }
50
+ if (!(shouldSkipAssignments && ASSIGNMENT.test(value))) return index;
51
+ }
52
+ return -1;
53
+ };
54
+ /** Checks commands, e.g. whether they're available everywhere, and the commands they run */
55
+ var CommandChecker = class {
56
+ #analyzeNestedWords;
57
+ #dependencies;
58
+ #ignoredCommands;
59
+ /** Fixes that depend on where a command is, by the command's name, e.g. `exit 0` for `true` */
60
+ #positionalFixes = /* @__PURE__ */ new Map();
61
+ #reporter;
62
+ constructor(reporter, { dependencies = [], ignoreCommands = [] }, analyzeNestedWords) {
63
+ this.#reporter = reporter;
64
+ this.#dependencies = new Set(dependencies);
65
+ this.#ignoredCommands = new Set(ignoreCommands);
66
+ this.#analyzeNestedWords = analyzeNestedWords;
67
+ }
68
+ /**
69
+ * Adds fixes for commands that end the script, which can change what follows them.
70
+ * @param statements Top-level statements of a script
71
+ */
72
+ addPositionalFixes(statements) {
73
+ const last = statements.at(-1);
74
+ if (!last || last.background) return;
75
+ const list = last.command;
76
+ const commands = list.type === "AndOr" ? list.commands : [list];
77
+ const final = commands.at(-1);
78
+ if (final?.type === "Command" && final.name && final.prefix.length === 0 && final.suffix.length === 0) {
79
+ const status = EXIT_STATUSES.get(staticValue(final.name) || "");
80
+ if (status != null) this.#positionalFixes.set(final.name, replacement(final.name, final.name.text, `exit ${status}`));
81
+ }
82
+ const [exporting, command] = commands;
83
+ if (list.type === "AndOr" && list.operators.length === 1 && list.operators[0] === "&&" && exporting?.type === "Command" && exporting.name && staticValue(exporting.name) === "export" && exporting.prefix.length === 0 && exporting.suffix.length > 0 && exporting.suffix.every(isPlainAssignment) && command?.type === "Command" && command.name) this.#positionalFixes.set(exporting.name, {
84
+ description: "Replace `export ... &&` with `cross-env`.",
85
+ edits: [{
86
+ end: exporting.name.end,
87
+ pos: exporting.name.pos,
88
+ text: "cross-env"
89
+ }, {
90
+ end: command.pos,
91
+ pos: exporting.end,
92
+ text: " "
93
+ }]
94
+ });
95
+ }
96
+ #checkCommandAvailability(name, nameWord, argumentWords, context) {
97
+ if (name === "del" && this.#dependencies.has("del-cli")) return this.#reporter.report(context, nameWord, "inconsistentBehavior", {
98
+ reason: "cmd.exe's builtin `del` takes precedence over del-cli's `del` binary",
99
+ suggestion: "Use `del-cli` instead.",
100
+ syntax: "`del`"
101
+ }, WINDOWS_PLATFORMS, replacement(nameWord, nameWord.text, "del-cli"));
102
+ if (context.portable && PORTABLE_SHELL_BUILTINS.has(name)) return [];
103
+ const lowerCaseName = name.toLowerCase();
104
+ let info = COMMANDS.get(name);
105
+ if (!info) {
106
+ const windowsInfo = COMMANDS.get(lowerCaseName);
107
+ if (windowsInfo && !windowsInfo.platforms.includes("win32")) info = windowsInfo;
108
+ }
109
+ if (!info) return [];
110
+ let { platforms } = info;
111
+ if (info.bashBuiltin && context.shell === "bash") platforms = arrayDifference(platforms, LINUX_PLATFORMS);
112
+ if (context.portable && CMD_BUILTINS.has(lowerCaseName)) platforms = PLATFORMS;
113
+ return this.#reporter.report(context, nameWord, "unsupportedCommand", {
114
+ command: name,
115
+ suggestion: info.suggestion
116
+ }, platforms, this.#positionalFixes.get(nameWord) || commandFix(name, nameWord, argumentWords, context.source));
117
+ }
118
+ /**
119
+ * Checks a command and the commands that it runs.
120
+ * @param nameWord The command's name, e.g. `rm`
121
+ * @param argumentWords The words that follow it
122
+ * @param context Where the command is
123
+ * @param depth How many commands run this command, e.g. 1 for `rm` in `cross-env A=1 rm`
124
+ * @param isCrossSpawned Whether cross-spawn runs the command (in `cross-env`), which works with
125
+ * paths and shebangs on Windows
126
+ * @returns What the command is, and what it runs
127
+ */
128
+ checkInvocation(nameWord, argumentWords, context, depth, isCrossSpawned = false) {
129
+ const name = staticValue(nameWord);
130
+ const result = {
131
+ crossEnv: name === "cross-env" || name === "cross-env-shell",
132
+ name,
133
+ target: name
134
+ };
135
+ if (name == null || depth > MAX_DEPTH) return result;
136
+ if (this.#ignoredCommands.has(name)) {
137
+ result.target = this.#checkWrapped(name, argumentWords, context, depth)?.target ?? name;
138
+ return result;
139
+ }
140
+ const covered = [];
141
+ if (SHELL_SCRIPT.test(name)) covered.push(...this.#reporter.report(context, nameWord, "unsupportedCommand", {
142
+ command: truncate(nameWord.text),
143
+ suggestion: SHELL_SCRIPT_SUGGESTION
144
+ }, WINDOWS_PLATFORMS));
145
+ else if (WINDOWS_SCRIPT.test(name)) covered.push(...this.#reporter.report(context, nameWord, "unsupportedCommand", {
146
+ command: truncate(nameWord.text),
147
+ suggestion: NODE_SCRIPT_SUGGESTION
148
+ }, POSIX_PLATFORMS));
149
+ else if (name.includes("/") && !isPackageSpec(name)) {
150
+ const isConverted = context.convertsSlashes && depth === 0 && DEPENDENCY_BINARY.test(name) && YARN_COMMAND_START.test(context.source.slice(0, nameWord.pos));
151
+ if (!isCrossSpawned && !isConverted) covered.push(...this.#reporter.reportSyntax(context, nameWord, "posix", true, "unsupportedSyntax", {
152
+ suggestion: "cmd.exe treats `/` as an option prefix; run files with `node`, and binaries by their name instead.",
153
+ syntax: `Running a command by its path (\`${truncate(nameWord.text)}\`)`
154
+ }, pathCommandFix(name, nameWord)));
155
+ } else covered.push(...this.#checkCommandAvailability(name, nameWord, argumentWords, context));
156
+ covered.push(...this.#checkUsage(name, nameWord, argumentWords, context));
157
+ result.target = this.#checkWrapped(name, argumentWords, withCovered(context, covered), depth)?.target ?? name;
158
+ return result;
159
+ }
160
+ #checkUsage(name, nameWord, argumentWords, context) {
161
+ const values = argumentWords.map(staticValue);
162
+ const wrapperValueOptions = WRAPPER_VALUE_OPTIONS.get(name);
163
+ const commandIndex = wrapperValueOptions ? findCommandIndex(values, 0, wrapperValueOptions) : -1;
164
+ const optionsEnd = Math.min(values.includes("--") ? values.indexOf("--") : values.length, commandIndex === -1 ? values.length : commandIndex);
165
+ return checkCommandUsage(name, argumentWords.map((argument, index) => ({
166
+ text: argument.text,
167
+ value: values[index]
168
+ })), {
169
+ bash: context.shell === "bash",
170
+ optionsEnd,
171
+ portable: context.portable
172
+ }).flatMap(({ argumentIndex, data, fix, messageId, platforms }) => {
173
+ const fixedWord = fix && argumentWords[fix.argumentIndex];
174
+ return this.#reporter.report(context, argumentIndex == null ? nameWord : {
175
+ end: argumentWords[argumentIndex]?.end || nameWord.end,
176
+ pos: nameWord.pos
177
+ }, messageId, data, platforms, fix && fixedWord ? {
178
+ description: fix.description,
179
+ edits: [{
180
+ end: fixedWord.end,
181
+ pos: fixedWord.pos,
182
+ text: fix.text
183
+ }]
184
+ } : void 0);
185
+ });
186
+ }
187
+ #checkWrapped(name, argumentWords, context, depth) {
188
+ const values = argumentWords.map(staticValue);
189
+ const invoke = (index, nestedContext = context, isCrossSpawned = false) => {
190
+ const word = argumentWords[index];
191
+ return !word || values[index] === "." ? void 0 : this.checkInvocation(word, argumentWords.slice(index + 1), nestedContext, depth + 1, isCrossSpawned);
192
+ };
193
+ const nestedShellString = (index, shell = "native", bashOptions) => {
194
+ const word = argumentWords[index];
195
+ if (word && depth < MAX_DEPTH) this.#analyzeNestedWords([word], context, {
196
+ bashOptions,
197
+ crossEnv: false,
198
+ maskScriptGlobs: name === "concurrently",
199
+ shell
200
+ });
201
+ };
202
+ const nestedShellLine = (index, isCrossEnv = false) => {
203
+ if (index !== -1 && depth < MAX_DEPTH) this.#analyzeNestedWords(argumentWords.slice(index), context, {
204
+ crossEnv: isCrossEnv,
205
+ shell: "native"
206
+ });
207
+ };
208
+ const commandStringIndex = () => {
209
+ const index = values.findIndex((value) => isShortOptionCluster(value, "c"));
210
+ return index === -1 ? -1 : index + 1;
211
+ };
212
+ const callIndex = (start, valueOptions) => {
213
+ const commandIndex = findCommandIndex(values, start, [...valueOptions, ...CALL_OPTIONS]);
214
+ const end = commandIndex === -1 ? values.length : commandIndex;
215
+ const index = values.findIndex((value, i) => i >= start && i < end && setHas(CALL_OPTIONS, value));
216
+ return index === -1 ? -1 : index + 1;
217
+ };
218
+ const shellModeIndex = (start, valueOptions) => {
219
+ const commandIndex = findCommandIndex(values, start, valueOptions);
220
+ return values.slice(start, commandIndex === -1 ? values.length : commandIndex).some((value) => setHas(SHELL_MODE_OPTIONS, value)) ? commandIndex : -1;
221
+ };
222
+ const valueOptions = WRAPPER_VALUE_OPTIONS.get(name);
223
+ switch (name) {
224
+ case "bash":
225
+ case "ksh":
226
+ case "zsh":
227
+ nestedShellString(commandStringIndex(), "bash", new Set(slidingWindow(values, 2).flatMap(([option, value]) => option === "-O" && value ? [value] : [])));
228
+ return;
229
+ case "concurrently":
230
+ argumentWords.forEach((argument, index) => {
231
+ if (argument.parts?.some((part) => part.type === "DoubleQuoted" || part.type === "SingleQuoted") && WHITESPACE.test(argument.value)) nestedShellString(index);
232
+ });
233
+ return;
234
+ case "cross-env":
235
+ case "cross-env-shell": {
236
+ const index = values.findIndex((value) => value == null || !ASSIGNMENT.test(value));
237
+ if (name === "cross-env") return invoke(index, {
238
+ ...context,
239
+ crossEnv: true
240
+ }, true);
241
+ nestedShellLine(index, true);
242
+ return;
243
+ }
244
+ case "dash":
245
+ case "sh":
246
+ nestedShellString(commandStringIndex(), "sh");
247
+ return;
248
+ case "aube":
249
+ case "bun":
250
+ case "npm":
251
+ case "pnpm":
252
+ case "upm":
253
+ case "yarn": {
254
+ const subcommand = findCommandIndex(values, 0, PACKAGE_MANAGER_VALUE_OPTIONS);
255
+ if (!arrayIncludes(EXEC_SUBCOMMANDS[name], values[subcommand])) return;
256
+ if (name === "npm" || name === "upm") {
257
+ const call = callIndex(subcommand + 1, EXEC_VALUE_OPTIONS);
258
+ if (call !== -1) {
259
+ nestedShellString(call);
260
+ return;
261
+ }
262
+ } else if (name === "aube" || name === "pnpm") {
263
+ const shellLine = shellModeIndex(subcommand + 1, EXEC_VALUE_OPTIONS);
264
+ if (shellLine !== -1) {
265
+ nestedShellLine(shellLine);
266
+ return;
267
+ }
268
+ }
269
+ return invoke(findCommandIndex(values, subcommand + 1, EXEC_VALUE_OPTIONS));
270
+ }
271
+ case "npx":
272
+ case "upx": {
273
+ const call = callIndex(0, valueOptions || []);
274
+ if (call !== -1) {
275
+ nestedShellString(call);
276
+ return;
277
+ }
278
+ break;
279
+ }
280
+ case "aubx":
281
+ case "pnpx": {
282
+ const shellLine = shellModeIndex(0, valueOptions || []);
283
+ if (shellLine !== -1) {
284
+ nestedShellLine(shellLine);
285
+ return;
286
+ }
287
+ break;
288
+ }
289
+ }
290
+ if (!valueOptions) return;
291
+ const commandIndex = findCommandIndex(values, 0, valueOptions, name === "env");
292
+ return name === "command" && values.slice(0, commandIndex).some((value) => value === "-v" || value === "-V") ? void 0 : invoke(commandIndex);
293
+ }
294
+ };
295
+ export { CommandChecker };
@@ -0,0 +1,364 @@
1
+ import { NO_LONG_OPTIONS_ON_MACOS } from "./commands.mjs";
2
+ import { CROSS_ENV_SUGGESTION, NODE_SCRIPT_SUGGESTION, RIMRAF_SUGGESTION, describeReplacement, truncate } from "./messages.mjs";
3
+ import { LINUX_PLATFORMS, MACOS_PLATFORMS, NOT_MACOS_OR_WINDOWS, PLATFORMS, POSIX_PLATFORMS, WINDOWS_PLATFORMS } from "./platforms.mjs";
4
+ import { setHas } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/set/set-has.mjs";
5
+ import { substringBefore } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-before.mjs";
6
+ import { ASSIGNMENT, isShortOptionCluster } from "./words.mjs";
7
+ // src/command-usage.ts
8
+ /** Commands that also exist in cmd.exe, whose names are case-insensitive there */
9
+ const CMD_COMMANDS = /* @__PURE__ */ new Set([
10
+ "mkdir",
11
+ "rmdir",
12
+ "set",
13
+ "sort",
14
+ "timeout"
15
+ ]);
16
+ /** Bash's pseudo-signals for `trap`, which dash doesn't support */
17
+ const BASH_TRAP_CONDITIONS = /* @__PURE__ */ new Set([
18
+ "DEBUG",
19
+ "ERR",
20
+ "RETURN"
21
+ ]);
22
+ const DASH = "dash, the `sh` of Debian/Ubuntu,";
23
+ /** GNU `find` primaries that BSD `find` doesn't support */
24
+ const GNU_FIND_PRIMARIES = /* @__PURE__ */ new Set([
25
+ "-executable",
26
+ "-fprintf",
27
+ "-printf",
28
+ "-readable",
29
+ "-regextype",
30
+ "-writable",
31
+ "-xtype"
32
+ ]);
33
+ /** BSD `find` options, which come before the starting paths */
34
+ const BSD_FIND_OPTIONS = /^-[EHLPXdsx]+$/;
35
+ /** GNU regex escapes that BSD `sed` doesn't support, e.g. `\s` */
36
+ const GNU_SED_ESCAPE = /\\[<>bsw]/i;
37
+ /** The same, in basic regexes only */
38
+ const GNU_SED_BASIC_ESCAPE = /\\[+?]/;
39
+ /** GNU `xargs` options that BSD `xargs` doesn't support, e.g. `-d` */
40
+ const GNU_XARGS_OPTION = /^(?:-[0prtx]*[adil]|--(?:arg-file|delimiter|max-lines|replace)\b)/;
41
+ const LONG_OPTION = /^--[^-]/;
42
+ /** Any option, e.g. `-p` */
43
+ const POSIX_OPTION = /^-./;
44
+ /** A cmd.exe option, e.g. `/s` */
45
+ const CMD_OPTION = /^\/[a-z]/i;
46
+ /** Including combined switches, e.g. `/s/q` */
47
+ const RMDIR_CMD_OPTION = /^(?:\/[qs])+$/i;
48
+ const TIMEOUT_CMD_OPTION = /^\/t$/i;
49
+ const ECHO_OPTIONS = /^-[Een]+$/;
50
+ const HEAD_COUNT_OPTION = /^-[cn]$/;
51
+ /** e.g. `-n-1` */
52
+ const HEAD_NEGATIVE_COUNT_OPTION = /^-[cn]-\d/;
53
+ const NEGATIVE_NUMBER = /^-\d/;
54
+ const SED_EXTENDED_OPTION = /^-[a-z]*[er]/i;
55
+ const SED_IN_PLACE_OPTION = /^-[a-z]*i$/i;
56
+ /** `set -o`, possibly after other options, e.g. `set -euo` */
57
+ const SET_NAMED_OPTION = /^-[a-z]*o$/i;
58
+ const SET_SHELL_OPTIONS = /^[+-][a-z]+$/i;
59
+ /** Including attached values, e.g. `-f%z` */
60
+ const STAT_FORMAT_OPTION = /^-[cf]/;
61
+ /**
62
+ * Checks a command's options for ones that don't work (the same) on all platforms, e.g. `sed -i`.
63
+ * @param name Name that the command was invoked with, e.g. `sed`
64
+ * @param commandArguments The words that follow the command name
65
+ * @param options Where the command runs, and where its options end
66
+ * @returns The issues found
67
+ */
68
+ const checkCommandUsage = (name, commandArguments, options) => {
69
+ const { bash, optionsEnd, portable } = options;
70
+ const values = commandArguments.map(({ value }) => value);
71
+ const textOf = (index) => commandArguments[index]?.text || "";
72
+ const issues = [];
73
+ const optionIndex = (isMatch) => values.findIndex((value, index) => index < optionsEnd && value != null && isMatch(value, index));
74
+ const report = (index, platforms, data, fix) => {
75
+ if (data.syntax) issues.push({
76
+ argumentIndex: index,
77
+ data,
78
+ fix,
79
+ messageId: "inconsistentBehavior",
80
+ platforms
81
+ });
82
+ else {
83
+ const usage = data.usage || `${name} ${truncate(values[index] ?? textOf(index))}`;
84
+ issues.push({
85
+ argumentIndex: index,
86
+ data: {
87
+ ...data,
88
+ usage
89
+ },
90
+ fix,
91
+ messageId: "unsupportedUsage",
92
+ platforms
93
+ });
94
+ }
95
+ };
96
+ const reportOption = (isMatch, platforms, data) => {
97
+ const index = optionIndex(isMatch);
98
+ if (index !== -1) report(index, platforms, data);
99
+ };
100
+ /** Creates a fix that replaces an argument's source text */
101
+ const replaceArgument = (index, text) => ({
102
+ argumentIndex: index,
103
+ description: describeReplacement(textOf(index), text),
104
+ text
105
+ });
106
+ const reportCommand = (platforms, suggestion) => {
107
+ issues.push({
108
+ argumentIndex: void 0,
109
+ data: {
110
+ command: name,
111
+ suggestion
112
+ },
113
+ messageId: "unsupportedCommand",
114
+ platforms
115
+ });
116
+ };
117
+ if (NO_LONG_OPTIONS_ON_MACOS.has(name)) {
118
+ const index = optionIndex((value) => LONG_OPTION.test(value));
119
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
120
+ reason: `BSD \`${name}\` doesn't support GNU-style long options`,
121
+ suggestion: "Use short options instead.",
122
+ usage: `${name} ${substringBefore(values[index] || "", "=")}`
123
+ });
124
+ }
125
+ const lowerCaseName = name.toLowerCase();
126
+ const isDash = !bash && !portable;
127
+ switch (CMD_COMMANDS.has(lowerCaseName) ? lowerCaseName : name) {
128
+ case ".": {
129
+ const [file] = values;
130
+ if (isDash && file != null && !file.includes("/")) report(0, LINUX_PLATFORMS, {
131
+ reason: "dash only looks for the file in `PATH`, not in the current directory",
132
+ suggestion: `Use \`. ./${truncate(file)}\` instead.`
133
+ }, replaceArgument(0, `./${textOf(0)}`));
134
+ break;
135
+ }
136
+ case "[":
137
+ case "test": {
138
+ const index = values.indexOf("==");
139
+ if (isDash && index !== -1) report(index, LINUX_PLATFORMS, {
140
+ reason: `${DASH} only supports \`=\` for comparing strings`,
141
+ suggestion: "Use `=` instead.",
142
+ usage: name === "[" ? "[ ... == ... ]" : "test ... == ..."
143
+ }, replaceArgument(index, "="));
144
+ break;
145
+ }
146
+ case "base64":
147
+ reportOption((value) => isShortOptionCluster(value, "w"), MACOS_PLATFORMS, {
148
+ reason: "BSD `base64` uses `-b` to wrap lines",
149
+ suggestion: NODE_SCRIPT_SUGGESTION
150
+ });
151
+ break;
152
+ case "bash":
153
+ case "shopt": {
154
+ const option = name === "bash" ? "-O" : "-s";
155
+ const index = optionIndex((value, valueIndex) => value === "globstar" && values.slice(0, valueIndex).includes(option));
156
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
157
+ reason: "macOS ships Bash 3.2, which doesn't have the `globstar` option",
158
+ suggestion: "Quote globs with escaped double quotes (`\\\"`) and let the tool expand them instead.",
159
+ usage: `${name} ${option} globstar`
160
+ });
161
+ break;
162
+ }
163
+ case "cp":
164
+ reportOption((value) => isShortOptionCluster(value, "t"), MACOS_PLATFORMS, {
165
+ reason: "BSD `cp` doesn't support `-t`",
166
+ suggestion: "Put the target directory last instead."
167
+ });
168
+ break;
169
+ case "date":
170
+ reportOption((value) => value.startsWith("-d"), MACOS_PLATFORMS, {
171
+ reason: "BSD `date` uses `-j -f` to parse dates",
172
+ suggestion: NODE_SCRIPT_SUGGESTION
173
+ });
174
+ break;
175
+ case "dir": {
176
+ const index = optionIndex((value) => CMD_OPTION.test(value));
177
+ if (index !== -1) report(index, LINUX_PLATFORMS, {
178
+ reason: `\`${values[index] || ""}\` is a cmd.exe option`,
179
+ suggestion: NODE_SCRIPT_SUGGESTION
180
+ });
181
+ break;
182
+ }
183
+ case "du":
184
+ reportOption((value) => isShortOptionCluster(value, "b"), MACOS_PLATFORMS, {
185
+ reason: "BSD `du` doesn't support `-b`",
186
+ suggestion: NODE_SCRIPT_SUGGESTION
187
+ });
188
+ break;
189
+ case "echo": {
190
+ const [first] = values;
191
+ if (isDash && first != null && ECHO_OPTIONS.test(first)) {
192
+ const doesInterpretEscapes = first.toLowerCase().includes("e");
193
+ report(0, doesInterpretEscapes ? PLATFORMS : NOT_MACOS_OR_WINDOWS, {
194
+ reason: doesInterpretEscapes ? "`sh`'s `echo` on macOS and Debian/Ubuntu, and cmd.exe's `echo` print the option literally" : "`sh`'s `echo` on macOS and cmd.exe's `echo` print the option literally",
195
+ suggestion: NODE_SCRIPT_SUGGESTION,
196
+ syntax: `\`echo ${first}\``
197
+ });
198
+ }
199
+ break;
200
+ }
201
+ case "find": {
202
+ const start = values.findIndex((value) => value == null || !BSD_FIND_OPTIONS.test(value));
203
+ const primary = values.findIndex((value) => setHas(GNU_FIND_PRIMARIES, value));
204
+ if (values[start]?.startsWith("-")) report(start, MACOS_PLATFORMS, {
205
+ reason: "BSD `find` requires a starting path",
206
+ suggestion: "Add `.` before the expression.",
207
+ usage: `find ${values[start] || ""}`
208
+ }, {
209
+ argumentIndex: start,
210
+ description: "Add `.` before the expression.",
211
+ text: `. ${textOf(start)}`
212
+ });
213
+ else if (primary !== -1) report(primary, MACOS_PLATFORMS, {
214
+ reason: `BSD \`find\` doesn't support \`${values[primary] || ""}\``,
215
+ suggestion: NODE_SCRIPT_SUGGESTION
216
+ });
217
+ break;
218
+ }
219
+ case "fuser":
220
+ reportOption((value) => isShortOptionCluster(value, "k"), MACOS_PLATFORMS, {
221
+ reason: "macOS' `fuser` doesn't support `-k`",
222
+ suggestion: NODE_SCRIPT_SUGGESTION
223
+ });
224
+ break;
225
+ case "grep":
226
+ reportOption((value) => isShortOptionCluster(value, "P") || value === "--perl-regexp", MACOS_PLATFORMS, {
227
+ reason: "BSD `grep` doesn't support Perl-compatible regular expressions",
228
+ suggestion: "Use `grep -E` or a Node.js script instead."
229
+ });
230
+ break;
231
+ case "head": {
232
+ const index = optionIndex((value, valueIndex) => HEAD_NEGATIVE_COUNT_OPTION.test(value) || HEAD_COUNT_OPTION.test(value) && NEGATIVE_NUMBER.test(values[valueIndex + 1] || ""));
233
+ if (index !== -1) {
234
+ const countIndex = HEAD_COUNT_OPTION.test(values[index] || "") ? index + 1 : index;
235
+ report(countIndex, MACOS_PLATFORMS, {
236
+ reason: "BSD `head` doesn't support negative counts",
237
+ suggestion: NODE_SCRIPT_SUGGESTION,
238
+ usage: `head ${values.slice(index, countIndex + 1).join(" ")}`
239
+ });
240
+ }
241
+ break;
242
+ }
243
+ case "ln":
244
+ reportOption((value) => isShortOptionCluster(value, "r"), MACOS_PLATFORMS, {
245
+ reason: "BSD `ln` doesn't support `-r`",
246
+ suggestion: NODE_SCRIPT_SUGGESTION
247
+ });
248
+ break;
249
+ case "mkdir":
250
+ case "rmdir": {
251
+ const suggestion = lowerCaseName === "mkdir" ? NODE_SCRIPT_SUGGESTION : RIMRAF_SUGGESTION;
252
+ if (portable) {
253
+ reportCommand(WINDOWS_PLATFORMS, suggestion);
254
+ break;
255
+ }
256
+ const windowsOption = optionIndex((value) => RMDIR_CMD_OPTION.test(value));
257
+ if (lowerCaseName === "rmdir" && windowsOption !== -1) {
258
+ report(windowsOption, POSIX_PLATFORMS, {
259
+ reason: `\`${values[windowsOption] || ""}\` is a cmd.exe option`,
260
+ suggestion
261
+ });
262
+ break;
263
+ }
264
+ const posixOption = optionIndex((value) => POSIX_OPTION.test(value));
265
+ if (posixOption !== -1) {
266
+ report(posixOption, WINDOWS_PLATFORMS, {
267
+ reason: `cmd.exe's \`${name}\` doesn't support POSIX options`,
268
+ suggestion
269
+ });
270
+ break;
271
+ }
272
+ const pathWithSlash = values.findIndex((value, index) => value != null && !value.startsWith("-") && value.includes("/") && !textOf(index).startsWith("\""));
273
+ if (pathWithSlash !== -1) report(pathWithSlash, WINDOWS_PLATFORMS, {
274
+ reason: `cmd.exe's \`${name}\` treats \`/\` as an option prefix`,
275
+ suggestion
276
+ });
277
+ break;
278
+ }
279
+ case "sed": {
280
+ const isExtended = optionIndex((value) => SED_EXTENDED_OPTION.test(value) || value === "--regexp-extended") !== -1;
281
+ const findEscape = (value) => value == null || value.startsWith("-") ? void 0 : (GNU_SED_ESCAPE.exec(value) || (isExtended ? null : GNU_SED_BASIC_ESCAPE.exec(value)))?.[0];
282
+ const escapeIndex = values.findIndex((value) => findEscape(value) != null);
283
+ if (escapeIndex !== -1) report(escapeIndex, MACOS_PLATFORMS, {
284
+ reason: "BSD `sed` doesn't support it, so the pattern doesn't match",
285
+ suggestion: "Use POSIX regex syntax (e.g. `[[:space:]]`, or `+` with `sed -E`) instead.",
286
+ syntax: `The GNU regex escape \`${findEscape(values[escapeIndex]) || ""}\``
287
+ });
288
+ const index = optionIndex((value) => SED_IN_PLACE_OPTION.test(value));
289
+ if (index === -1) break;
290
+ if (values[index + 1]?.length === 0) report(index + 1, LINUX_PLATFORMS, {
291
+ reason: "GNU `sed` treats the empty backup suffix as the script",
292
+ suggestion: "Use an attached suffix (e.g. `-i.bak`) or a Node.js script instead.",
293
+ usage: `sed ${values[index] || ""} ''`
294
+ });
295
+ else report(index, MACOS_PLATFORMS, {
296
+ reason: "BSD `sed` requires a backup suffix argument after `-i`",
297
+ suggestion: "Use an attached suffix (e.g. `-i.bak`) or a Node.js script instead."
298
+ });
299
+ break;
300
+ }
301
+ case "set": {
302
+ const [first] = values;
303
+ const pipefail = optionIndex((value, index) => value === "pipefail" && SET_NAMED_OPTION.test(values[index - 1] || ""));
304
+ if (isDash && pipefail !== -1) report(pipefail, LINUX_PLATFORMS, {
305
+ reason: `${DASH} doesn't support \`pipefail\``,
306
+ suggestion: "Remove it or use a Node.js script instead.",
307
+ usage: "set -o pipefail"
308
+ });
309
+ if (first == null) break;
310
+ if (SET_SHELL_OPTIONS.test(first)) report(0, WINDOWS_PLATFORMS, {
311
+ reason: "cmd.exe's `set` manages environment variables instead of shell options",
312
+ suggestion: "Remove it or use a Node.js script instead."
313
+ });
314
+ else if (ASSIGNMENT.test(first)) report(0, portable ? PLATFORMS : POSIX_PLATFORMS, {
315
+ reason: "POSIX shells don't set environment variables with `set`",
316
+ suggestion: CROSS_ENV_SUGGESTION,
317
+ syntax: `\`set ${truncate(first)}\``
318
+ });
319
+ break;
320
+ }
321
+ case "sort":
322
+ reportOption((value) => POSIX_OPTION.test(value), WINDOWS_PLATFORMS, {
323
+ reason: "Windows' `sort` command uses `/` options",
324
+ suggestion: NODE_SCRIPT_SUGGESTION
325
+ });
326
+ break;
327
+ case "stat": {
328
+ const index = optionIndex((value) => STAT_FORMAT_OPTION.test(value));
329
+ if (index === -1) break;
330
+ if (values[index]?.startsWith("-c")) report(index, MACOS_PLATFORMS, {
331
+ reason: "BSD `stat` uses `-f` to specify the format",
332
+ suggestion: NODE_SCRIPT_SUGGESTION
333
+ });
334
+ else report(index, LINUX_PLATFORMS, {
335
+ reason: "GNU `stat -f` displays file system status instead of formatting the output",
336
+ suggestion: NODE_SCRIPT_SUGGESTION,
337
+ syntax: "`stat -f`"
338
+ });
339
+ break;
340
+ }
341
+ case "timeout":
342
+ if (TIMEOUT_CMD_OPTION.test(values[0] || "")) report(0, POSIX_PLATFORMS, {
343
+ reason: "`/t` is an option of Windows' `timeout` command",
344
+ suggestion: NODE_SCRIPT_SUGGESTION
345
+ });
346
+ else reportCommand(NOT_MACOS_OR_WINDOWS, NODE_SCRIPT_SUGGESTION);
347
+ break;
348
+ case "trap": {
349
+ const index = values.findIndex((value, valueIndex) => valueIndex > 0 && setHas(BASH_TRAP_CONDITIONS, value));
350
+ if (isDash && index !== -1) report(index, LINUX_PLATFORMS, {
351
+ reason: `${DASH} doesn't support the \`${values[index] || ""}\` condition, so it ignores the trap`,
352
+ suggestion: NODE_SCRIPT_SUGGESTION,
353
+ syntax: `\`trap ... ${values[index] || ""}\``
354
+ });
355
+ break;
356
+ }
357
+ case "xargs": reportOption((value) => GNU_XARGS_OPTION.test(value), MACOS_PLATFORMS, {
358
+ reason: "BSD `xargs` doesn't support this GNU option",
359
+ suggestion: NODE_SCRIPT_SUGGESTION
360
+ });
361
+ }
362
+ return issues;
363
+ };
364
+ export { checkCommandUsage };