package-json-scripts-portability 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,3788 @@
1
+ import { parse } from "unbash";
2
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/function/noop.mjs
3
+ /**
4
+ * A no-operation function that does nothing.
5
+ * This can be used as a placeholder or default function.
6
+ *
7
+ * @example
8
+ * noop(); // Does nothing
9
+ *
10
+ * @returns This function does not return anything.
11
+ */
12
+ function noop() {}
13
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/_internal/globalThis.mjs
14
+ const globalThis_ = typeof globalThis === "object" && globalThis || typeof window === "object" && window || typeof self === "object" && self || typeof global === "object" && global || (function() {
15
+ return this;
16
+ })();
17
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/predicate/isPlainObject.mjs
18
+ /**
19
+ * Checks if a given value is a plain object.
20
+ *
21
+ * @param value - The value to check.
22
+ * @returns True if the value is a plain object, otherwise false.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * // ✅👇 True
27
+ *
28
+ * isPlainObject({ }); // ✅
29
+ * isPlainObject({ key: 'value' }); // ✅
30
+ * isPlainObject({ key: new Date() }); // ✅
31
+ * isPlainObject(new Object()); // ✅
32
+ * isPlainObject(Object.create(null)); // ✅
33
+ * isPlainObject({ nested: { key: true} }); // ✅
34
+ * isPlainObject(new Proxy({}, {})); // ✅
35
+ * isPlainObject({ [Symbol('tag')]: 'A' }); // ✅
36
+ *
37
+ * // ✅👇 (cross-realms, node context, workers, ...)
38
+ * const runInNewContext = await import('node:vm').then(
39
+ * (mod) => mod.runInNewContext
40
+ * );
41
+ * isPlainObject(runInNewContext('({})')); // ✅
42
+ *
43
+ * // ❌👇 False
44
+ *
45
+ * class Test { };
46
+ * isPlainObject(new Test()) // ❌
47
+ * isPlainObject(10); // ❌
48
+ * isPlainObject(null); // ❌
49
+ * isPlainObject('hello'); // ❌
50
+ * isPlainObject([]); // ❌
51
+ * isPlainObject(new Date()); // ❌
52
+ * isPlainObject(new Uint8Array([1])); // ❌
53
+ * isPlainObject(Buffer.from('ABC')); // ❌
54
+ * isPlainObject(Promise.resolve({})); // ❌
55
+ * isPlainObject(Object.create({})); // ❌
56
+ * isPlainObject(new (class Cls {})); // ❌
57
+ * isPlainObject(globalThis); // ❌,
58
+ * ```
59
+ */
60
+ function isPlainObject(value) {
61
+ if (!value || typeof value !== "object") return false;
62
+ const proto = Object.getPrototypeOf(value);
63
+ if (!(proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null)) return false;
64
+ return Object.prototype.toString.call(value) === "[object Object]";
65
+ }
66
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/array/differenceWith.mjs
67
+ /**
68
+ * Computes the difference between two arrays based on a custom equality function.
69
+ *
70
+ * This function takes two arrays and a custom comparison function. It returns a new array containing
71
+ * the elements that are present in the first array but not in the second array. The comparison to determine
72
+ * if elements are equal is made using the provided custom function.
73
+ *
74
+ * @template T, U
75
+ * @param firstArr - The array from which to get the difference.
76
+ * @param secondArr - The array containing elements to exclude from the first array.
77
+ * @param areItemsEqual - A function to determine if two items are equal.
78
+ * @returns A new array containing the elements from the first array that do not match any elements in the second array
79
+ * according to the custom equality function.
80
+ *
81
+ * @example
82
+ * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
83
+ * const array2 = [{ id: 2 }, { id: 4 }];
84
+ * const areItemsEqual = (a, b) => a.id === b.id;
85
+ * const result = differenceWith(array1, array2, areItemsEqual);
86
+ * // result will be [{ id: 1 }, { id: 3 }] since the elements with id 2 are considered equal and are excluded from the result.
87
+ *
88
+ * @example
89
+ * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
90
+ * const array2 = [2, 4];
91
+ * const areItemsEqual = (a, b) => a.id === b;
92
+ * const result = differenceWith(array1, array2, areItemsEqual);
93
+ * // result will be [{ id: 1 }, { id: 3 }] since the element with id 2 is considered equal to the second array's element and is excluded from the result.
94
+ */
95
+ function differenceWith(firstArr, secondArr, areItemsEqual) {
96
+ return firstArr.filter((firstItem) => {
97
+ return secondArr.every((secondItem) => {
98
+ return !areItemsEqual(firstItem, secondItem);
99
+ });
100
+ });
101
+ }
102
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/array/intersectionBy.mjs
103
+ /**
104
+ * Returns the intersection of two arrays based on a mapping function.
105
+ *
106
+ * This function takes two arrays and a mapping function. It returns a new array containing
107
+ * the elements from the first array that, when mapped using the provided function, have matching
108
+ * mapped elements in the second array. It effectively filters out any elements from the first array
109
+ * that do not have corresponding mapped values in the second array.
110
+ *
111
+ * @template T - The type of elements in the first array.
112
+ * @template U - The type of elements in the second array.
113
+ * @param firstArr - The first array to compare.
114
+ * @param secondArr - The second array to compare.
115
+ * @param mapper - A function to map the elements of both arrays for comparison.
116
+ * @returns A new array containing the elements from the first array that have corresponding mapped values in the second array.
117
+ *
118
+ * @example
119
+ * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
120
+ * const array2 = [{ id: 2 }, { id: 4 }];
121
+ * const mapper = item => item.id;
122
+ * const result = intersectionBy(array1, array2, mapper);
123
+ * // result will be [{ id: 2 }] since only this element has a matching id in both arrays.
124
+ *
125
+ * @example
126
+ * const array1 = [
127
+ * { id: 1, name: 'jane' },
128
+ * { id: 2, name: 'amy' },
129
+ * { id: 3, name: 'michael' },
130
+ * ];
131
+ * const array2 = [2, 4];
132
+ * const mapper = item => (typeof item === 'object' ? item.id : item);
133
+ * const result = intersectionBy(array1, array2, mapper);
134
+ * // result will be [{ id: 2, name: 'amy' }] since only this element has a matching id that is equal to seconds array's element.
135
+ */
136
+ function intersectionBy(firstArr, secondArr, mapper) {
137
+ const result = [];
138
+ const mappedSecondSet = new Set(secondArr.map(mapper));
139
+ for (let i = 0; i < firstArr.length; i++) {
140
+ const item = firstArr[i];
141
+ const mappedItem = mapper(item);
142
+ if (mappedSecondSet.has(mappedItem)) {
143
+ result.push(item);
144
+ mappedSecondSet.delete(mappedItem);
145
+ }
146
+ }
147
+ return result;
148
+ }
149
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/array/intersectionWith.mjs
150
+ /**
151
+ * Returns the intersection of two arrays based on a custom equality function.
152
+ *
153
+ * This function takes two arrays and a custom equality function. It returns a new array containing
154
+ * the elements from the first array that have matching elements in the second array, as determined
155
+ * by the custom equality function. It effectively filters out any elements from the first array that
156
+ * do not have corresponding matches in the second array according to the equality function.
157
+ *
158
+ * @template T - The type of elements in the first array.
159
+ * @template U - The type of elements in the second array.
160
+ * @param firstArr - The first array to compare.
161
+ * @param secondArr - The second array to compare.
162
+ * @param areItemsEqual - A custom function to determine if two elements are equal.
163
+ * This function takes two arguments, one from each array, and returns `true` if the elements are considered equal, and `false` otherwise.
164
+ * @returns A new array containing the elements from the first array that have corresponding matches in the second array according to the custom equality function.
165
+ *
166
+ * @example
167
+ * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
168
+ * const array2 = [{ id: 2 }, { id: 4 }];
169
+ * const areItemsEqual = (a, b) => a.id === b.id;
170
+ * const result = intersectionWith(array1, array2, areItemsEqual);
171
+ * // result will be [{ id: 2 }] since this element has a matching id in both arrays.
172
+ *
173
+ * @example
174
+ * const array1 = [
175
+ * { id: 1, name: 'jane' },
176
+ * { id: 2, name: 'amy' },
177
+ * { id: 3, name: 'michael' },
178
+ * ];
179
+ * const array2 = [2, 4];
180
+ * const areItemsEqual = (a, b) => a.id === b;
181
+ * const result = intersectionWith(array1, array2, areItemsEqual);
182
+ * // result will be [{ id: 2, name: 'amy' }] since this element has a matching id that is equal to seconds array's element.
183
+ */
184
+ function intersectionWith(firstArr, secondArr, areItemsEqual) {
185
+ return firstArr.filter((firstItem) => {
186
+ return secondArr.some((secondItem) => {
187
+ return areItemsEqual(firstItem, secondItem);
188
+ });
189
+ });
190
+ }
191
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/array/array-intersection.mjs
192
+ function arrayIntersection(firstArray, secondArray, fn) {
193
+ if (!fn) {
194
+ const secondSet = new Set(secondArray);
195
+ return firstArray.filter((item) => secondSet.has(item));
196
+ }
197
+ return fn.length === 2 ? intersectionWith(firstArray, secondArray, fn) : intersectionBy(firstArray, secondArray, fn);
198
+ }
199
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/array/isSubsetWith.mjs
200
+ /**
201
+ * Checks if the `subset` array is entirely contained within the `superset` array based on a custom equality function.
202
+ *
203
+ * This function takes two arrays and a custom comparison function. It returns a boolean indicating
204
+ * whether all elements in the subset array are present in the superset array, as determined by the provided
205
+ * custom equality function.
206
+ *
207
+ * @template T - The type of elements contained in the arrays.
208
+ * @param superset - The array that may contain all elements of the subset.
209
+ * @param subset - The array to check against the superset.
210
+ * @param areItemsEqual - A function to determine if two items are equal.
211
+ * @returns Returns `true` if all elements of the subset are present in the superset
212
+ * according to the custom equality function, otherwise returns `false`.
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * const superset = [{ id: 1 }, { id: 2 }, { id: 3 }];
217
+ * const subset = [{ id: 2 }, { id: 1 }];
218
+ * const areItemsEqual = (a, b) => a.id === b.id;
219
+ * isSubsetWith(superset, subset, areItemsEqual); // true
220
+ * ```
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * const superset = [{ id: 1 }, { id: 2 }, { id: 3 }];
225
+ * const subset = [{ id: 4 }];
226
+ * const areItemsEqual = (a, b) => a.id === b.id;
227
+ * isSubsetWith(superset, subset, areItemsEqual); // false
228
+ * ```
229
+ */
230
+ function isSubsetWith(superset, subset, areItemsEqual) {
231
+ return differenceWith(subset, superset, areItemsEqual).length === 0;
232
+ }
233
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/array/array-is-subset.mjs
234
+ function arrayIsSubset(superset, subset, fn) {
235
+ if (!fn) {
236
+ const supersetSet = new Set(superset);
237
+ return subset.every((item) => supersetSet.has(item));
238
+ }
239
+ if (fn.length === 2) {
240
+ const areItemsEqual = fn;
241
+ return isSubsetWith(superset, subset, (subsetItem, supersetItem) => areItemsEqual(supersetItem, subsetItem));
242
+ }
243
+ const mapper = fn;
244
+ const mappedSuperset = new Set(superset.map((item) => mapper(item)));
245
+ return subset.every((item) => mappedSuperset.has(mapper(item)));
246
+ }
247
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/@antfu_utils@9.3.0/node_modules/@antfu/utils/dist/index.mjs
248
+ function slash(str) {
249
+ return str.replace(/\\/g, "/");
250
+ }
251
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/_internal/getTag.mjs
252
+ /**
253
+ * Gets the `toStringTag` of `value`.
254
+ *
255
+ * @private
256
+ * @param {T} value The value to query.
257
+ * @returns {string} Returns the `Object.prototype.toString.call` result.
258
+ */
259
+ function getTag(value) {
260
+ if (value == null) return value === void 0 ? "[object Undefined]" : "[object Null]";
261
+ return Object.prototype.toString.call(value);
262
+ }
263
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/util/eq.mjs
264
+ /**
265
+ * Performs a `SameValueZero` comparison between two values to determine if they are equivalent.
266
+ *
267
+ * @param value The value to compare.
268
+ * @param other The other value to compare.
269
+ * @returns Returns `true` if the values are equivalent, else `false`.
270
+ *
271
+ * @example
272
+ * eq(1, 1); // true
273
+ * eq(0, -0); // true
274
+ * eq(NaN, NaN); // true
275
+ * eq('a', Object('a')); // false
276
+ */
277
+ function eq(value, other) {
278
+ return value === other || Number.isNaN(value) && Number.isNaN(other);
279
+ }
280
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/predicate/isObject.mjs
281
+ /**
282
+ * Checks if the given value is an object. An object is a value that is
283
+ * not a primitive type (string, number, boolean, symbol, null, or undefined).
284
+ *
285
+ * This function tests whether the provided value is an object or not.
286
+ * It returns `true` if the value is an object, and `false` otherwise.
287
+ *
288
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to an object value.
289
+ *
290
+ * @param value - The value to check if it is an object.
291
+ * @returns `true` if the value is an object, `false` otherwise.
292
+ *
293
+ * @example
294
+ * const value1 = {};
295
+ * const value2 = [1, 2, 3];
296
+ * const value3 = () => {};
297
+ * const value4 = null;
298
+ *
299
+ * console.log(isObject(value1)); // true
300
+ * console.log(isObject(value2)); // true
301
+ * console.log(isObject(value3)); // true
302
+ * console.log(isObject(value4)); // false
303
+ */
304
+ function isObject(value) {
305
+ return value !== null && (typeof value === "object" || typeof value === "function");
306
+ }
307
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/_internal/getSymbols.mjs
308
+ function getSymbols(object) {
309
+ return Object.getOwnPropertySymbols(object).filter((symbol) => Object.prototype.propertyIsEnumerable.call(object, symbol));
310
+ }
311
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/_internal/tags.mjs
312
+ const regexpTag = "[object RegExp]";
313
+ const stringTag = "[object String]";
314
+ const numberTag = "[object Number]";
315
+ const booleanTag = "[object Boolean]";
316
+ const symbolTag = "[object Symbol]";
317
+ const dateTag = "[object Date]";
318
+ const mapTag = "[object Map]";
319
+ const setTag = "[object Set]";
320
+ const arrayTag = "[object Array]";
321
+ const functionTag = "[object Function]";
322
+ const arrayBufferTag = "[object ArrayBuffer]";
323
+ const objectTag = "[object Object]";
324
+ const errorTag = "[object Error]";
325
+ const dataViewTag = "[object DataView]";
326
+ const uint8ArrayTag = "[object Uint8Array]";
327
+ const uint8ClampedArrayTag = "[object Uint8ClampedArray]";
328
+ const uint16ArrayTag = "[object Uint16Array]";
329
+ const uint32ArrayTag = "[object Uint32Array]";
330
+ const bigUint64ArrayTag = "[object BigUint64Array]";
331
+ const int8ArrayTag = "[object Int8Array]";
332
+ const int16ArrayTag = "[object Int16Array]";
333
+ const int32ArrayTag = "[object Int32Array]";
334
+ const bigInt64ArrayTag = "[object BigInt64Array]";
335
+ const float32ArrayTag = "[object Float32Array]";
336
+ const float64ArrayTag = "[object Float64Array]";
337
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/predicate/isBuffer.mjs
338
+ /**
339
+ * Checks if the given value is a Buffer instance.
340
+ *
341
+ * This function tests whether the provided value is an instance of Buffer.
342
+ * It returns `true` if the value is a Buffer, and `false` otherwise.
343
+ *
344
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`.
345
+ *
346
+ * @param x - The value to check if it is a Buffer.
347
+ * @returns Returns `true` if `x` is a Buffer, else `false`.
348
+ *
349
+ * @example
350
+ * const buffer = Buffer.from("test");
351
+ * console.log(isBuffer(buffer)); // true
352
+ *
353
+ * const notBuffer = "not a buffer";
354
+ * console.log(isBuffer(notBuffer)); // false
355
+ */
356
+ function isBuffer(x) {
357
+ return typeof globalThis_.Buffer !== "undefined" && globalThis_.Buffer.isBuffer(x);
358
+ }
359
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/remeda@2.54.1_patch_hash_9e52c151cff234b19010b1ed56a1d6f22b52ec860a1eb5634c6db1a592239273/node_modules/remeda/dist/isArray.mjs
360
+ /**
361
+ * A function that checks if the passed parameter is an Array and narrows its type accordingly.
362
+ *
363
+ * @param data - The variable to check.
364
+ * @returns True if the passed input is an Array, false otherwise.
365
+ * @signature
366
+ * isArray(data)
367
+ * @example
368
+ * isArray([5]) //=> true
369
+ * isArray([]) //=> true
370
+ * isArray('somethingElse') //=> false
371
+ * @category Guard
372
+ */
373
+ function isArray$1(data) {
374
+ return Array.isArray(data);
375
+ }
376
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/predicate/is-array.mjs
377
+ /**
378
+ * Checks whether a value is an array, like `Array.isArray`, but also narrows readonly arrays.
379
+ *
380
+ * `Array.isArray` narrows to `any[]`, and a readonly array is not assignable to it.
381
+ * So for a `T | readonly T[]` value, it gives `any[]` when `true` and keeps `readonly T[]` when
382
+ * `false`.
383
+ * This guard narrows to the array members of the value's type (or to `readonly unknown[]` if
384
+ * there are none) when `true`, and removes them when `false`.
385
+ * @param data - The value to check.
386
+ * @returns `true` if `data` is an array, `false` otherwise.
387
+ * @example
388
+ * declare const paths: string | readonly string[];
389
+ *
390
+ * if (isArray(paths)) {
391
+ * paths; // readonly string[]
392
+ * } else {
393
+ * paths; // string
394
+ * }
395
+ * @example
396
+ * // Mutable arrays and tuples keep their types
397
+ * declare const size: number | [width: number, height: number];
398
+ *
399
+ * const [width, height] = isArray(size) ? size : [size, size];
400
+ * @example
401
+ * // Narrows `unknown` to a readonly array, so its elements can't be modified by mistake
402
+ * declare const value: unknown;
403
+ *
404
+ * if (isArray(value)) {
405
+ * value; // readonly unknown[]
406
+ * }
407
+ * @example
408
+ * isArray([1, 2, 3]); // true
409
+ * isArray(new Set([1, 2, 3])); // false
410
+ * isArray({length: 0}); // false
411
+ */
412
+ const isArray = isArray$1;
413
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/array/arrayify.mjs
414
+ function arrayify(value, shouldWrapNullish = false) {
415
+ if (value == null) return shouldWrapNullish ? [value] : [];
416
+ return isArray(value) ? value : [value];
417
+ }
418
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/path/to-forward-slashes.mjs
419
+ /**
420
+ * Replaces every backslash in a path with a forward slash, turning a Windows path into the form
421
+ * that URLs, glob patterns and POSIX tools expect.
422
+ */
423
+ const toForwardSlashes = slash;
424
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/map/map-get-or-insert.mjs
425
+ /**
426
+ * Returns the value stored under `key`, first inserting `defaultValue` when the key is not present.
427
+ *
428
+ * The return type is not optional, unlike `Map#get`, so the result is directly usable, which
429
+ * collapses the usual "look up, create when missing, then use" dance into a single expression.
430
+ * An already present value is never overwritten, and a stored `undefined` counts as present.
431
+ *
432
+ * `defaultValue` is evaluated by the caller on every call, even when `key` is already present.
433
+ * Use `mapGetOrInsertComputed` when producing it is expensive or has side effects.
434
+ *
435
+ * Calls the native `Map#getOrInsert` when the map has it, which doesn't call the `has`, `get` and
436
+ * `set` methods of the map: a `Map` subclass that overrides them should override `getOrInsert` too.
437
+ * @param map - The map to read from.
438
+ * Mutated only when `key` is not present.
439
+ * @param key - The key to look up.
440
+ * @param defaultValue - The value to insert and return when `key` is not present.
441
+ * @returns The value already stored under `key`, or `defaultValue` when it has just been inserted.
442
+ * @example
443
+ * // Appending to an array-valued map without a separate existence check
444
+ * const tagsByPostId = new Map<string, string[]>();
445
+ * mapGetOrInsert(tagsByPostId, 'post-1', []).push('typescript');
446
+ * // Map { 'post-1' => ['typescript'] }
447
+ * @example
448
+ * // An existing value is returned as-is
449
+ * mapGetOrInsert(new Map([['alice', 10]]), 'alice', 0);
450
+ * // 10
451
+ * @example
452
+ * // A stored `undefined` is a value, not a miss
453
+ * mapGetOrInsert(new Map<string, number | undefined>([['a', undefined]]), 'a', 42);
454
+ * // undefined
455
+ */
456
+ const mapGetOrInsert = (map, key, defaultValue) => {
457
+ const nativeMap = map;
458
+ if (nativeMap.getOrInsert) return nativeMap.getOrInsert(key, defaultValue);
459
+ if (map.has(key)) return map.get(key);
460
+ map.set(key, defaultValue);
461
+ return defaultValue;
462
+ };
463
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/math/clamp.mjs
464
+ /**
465
+ * Clamps a number within the specified bounds.
466
+ *
467
+ * This function takes a number and one or two bounds, and returns the number clamped within the specified bounds.
468
+ * If only one bound is provided, it returns the minimum of the value and the bound.
469
+ *
470
+ * @param value - The number to clamp.
471
+ * @param bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided.
472
+ * @param [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit.
473
+ * @returns The clamped number within the specified bounds.
474
+ *
475
+ * @example
476
+ * const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5
477
+ * const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15
478
+ * const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5
479
+ * const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15
480
+ */
481
+ function clamp$2(value, bound1, bound2) {
482
+ if (bound2 == null) return Math.min(value, bound1);
483
+ return Math.min(Math.max(value, bound1), bound2);
484
+ }
485
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/bigint/clamp.mjs
486
+ /**
487
+ * Clamps a bigint within the inclusive lower and upper bounds.
488
+ *
489
+ * @param value - The bigint to clamp.
490
+ * @param bound1 - The upper bound when called with two arguments, otherwise the lower bound.
491
+ * @param bound2 - The upper bound when called with three arguments.
492
+ * @returns The clamped bigint.
493
+ */
494
+ function clamp$1(value, bound1, bound2) {
495
+ if (bound2 == null) return value < bound1 ? value : bound1;
496
+ const lowerClamped = value > bound1 ? value : bound1;
497
+ return lowerClamped < bound2 ? lowerClamped : bound2;
498
+ }
499
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/math/clamp.mjs
500
+ function clamp(value, bound1, bound2) {
501
+ return typeof value === "bigint" ? clamp$1(value, bound1, bound2) : clamp$2(value, bound1, bound2);
502
+ }
503
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/ts-extras@1.3.0/node_modules/ts-extras/distribution/set-has.mjs
504
+ /**
505
+ A strongly-typed version of `Set#has()` that properly acts as a type guard.
506
+
507
+ When `setHas` returns `true`, the type is narrowed to the set's element type.
508
+ When it returns `false`, the type remains unchanged (i.e., `unknown` stays `unknown`).
509
+
510
+ It was [rejected](https://github.com/microsoft/TypeScript/issues/42641#issuecomment-774168319) from being done in TypeScript itself.
511
+
512
+ @example
513
+ ```
514
+ import {setHas} from 'ts-extras';
515
+
516
+ const values = ['a', 'b', 'c'] as const;
517
+ const valueSet = new Set(values);
518
+ const valueToCheck: unknown = 'a';
519
+
520
+ if (setHas(valueSet, valueToCheck)) {
521
+ // We now know that the value is of type `typeof values[number]`.
522
+ } else {
523
+ // The value remains `unknown`.
524
+ }
525
+ ```
526
+
527
+ @category Improved builtin
528
+ @category Type guard
529
+ */
530
+ function setHas$1(set, item) {
531
+ return set.has(item);
532
+ }
533
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/set/set-has.mjs
534
+ /**
535
+ * Checks whether a set has a value, like `Set.prototype.has`, but as a type guard: when it returns
536
+ * `true`, the value is narrowed to the element type of the set.
537
+ */
538
+ const setHas = setHas$1;
539
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/string/substring-after-last.mjs
540
+ /**
541
+ * Gets the part of a string after the last occurrence of a delimiter.
542
+ * When the delimiter is missing, returns `fallback`, which defaults to the
543
+ * whole string.
544
+ * @param text - The string to search.
545
+ * @param delimiter - The substring to search for.
546
+ * @param fallback - What to return when the delimiter is missing (defaults to `text`).
547
+ * @returns The part after the last delimiter, or `fallback`.
548
+ * @example
549
+ * substringAfterLast('src/utils/index.ts', '/');
550
+ * // 'index.ts'
551
+ * @example
552
+ * // File extension, empty when there is none
553
+ * substringAfterLast('index.test.ts', '.', '');
554
+ * // 'ts'
555
+ * substringAfterLast('Makefile', '.', '');
556
+ * // ''
557
+ */
558
+ const substringAfterLast = (text, delimiter, fallback = text) => {
559
+ const index = text.lastIndexOf(delimiter);
560
+ return index === -1 ? fallback : text.slice(index + delimiter.length);
561
+ };
562
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/string/substring-before.mjs
563
+ /**
564
+ * Gets the part of a string before the first occurrence of a delimiter.
565
+ * When the delimiter is missing, returns `fallback`, which defaults to the
566
+ * whole string.
567
+ * @param text - The string to search.
568
+ * @param delimiter - The substring to search for.
569
+ * @param fallback - What to return when the delimiter is missing (defaults to `text`).
570
+ * @returns The part before the first delimiter, or `fallback`.
571
+ * @example
572
+ * substringBefore('index.test.ts', '.');
573
+ * // 'index'
574
+ * substringBefore('README', '.');
575
+ * // 'README'
576
+ * @example
577
+ * // A different result for a missing delimiter
578
+ * substringBefore('no-scheme', '://', '');
579
+ * // ''
580
+ */
581
+ const substringBefore = (text, delimiter, fallback = text) => {
582
+ const index = text.indexOf(delimiter);
583
+ return index === -1 ? fallback : text.slice(0, index);
584
+ };
585
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/string/escapeRegExp.mjs
586
+ /**
587
+ * Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `str`.
588
+ *
589
+ * @param str The string to escape.
590
+ * @returns Returns the escaped string.
591
+ *
592
+ * @example
593
+ * import { escapeRegExp } from 'es-toolkit/string';
594
+ *
595
+ * escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); // returns '\[es-toolkit\]\(https://es-toolkit\.dev/\)'
596
+ */
597
+ function escapeRegExp(str) {
598
+ return str.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
599
+ }
600
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/_internal/regexMultiByte.mjs
601
+ /**
602
+ * Used to compose unicode character classes.
603
+ * @link https://github.com/lodash/lodash/blob/4.17.21-es/_hasUnicode.js
604
+ *
605
+ * Used to detect strings with zero-width joiners or code points from the astral planes.
606
+ * @link http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/
607
+ */
608
+ const regexMultiByte = /* @__PURE__ */ new RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");
609
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/compat/string/truncate.mjs
610
+ /**
611
+ * This regex might more completely detect unicode, but it is slower and this project
612
+ * desires to mimic the behavior of lodash.
613
+ */
614
+ /**
615
+ * Truncates `string` if it's longer than the given maximum string length.
616
+ * The last characters of the truncated string are replaced with the omission
617
+ * string which defaults to "...".
618
+ *
619
+ * @param [string=''] The string to truncate.
620
+ * @param [options={}] The options object.
621
+ * @param [options.length=30] The maximum string length.
622
+ * @param [options.omission='...'] The string to indicate text is omitted.
623
+ * @param [options.separator] The separator pattern to truncate to.
624
+ *
625
+ * @example
626
+ * const test = 'hi-diddly-ho there, neighborino';
627
+ * const truncatedStr1 = truncate(test) // returns 'hi-diddly-ho there, neighbo...'
628
+ * const truncatedStr2 = truncate(test, { length: 24, separator: ' ' }) // returns 'hi-diddly-ho there,...'
629
+ * const truncatedStr3 = truncate(test, { length: 24, separator: /,? +/ }) // returns 'hi-diddly-ho there...'
630
+ * const truncatedStr4 = truncate(test, { omission: ' [...]' }) // returns 'hi-diddly-ho there, neig [...]'
631
+ * const truncatedStr5 = truncate('ABC', { length: 3 }) // returns 'ABC'
632
+ * const truncatedStr6 = truncate('ABC', { length: 2 }) // returns '...'
633
+ * const truncatedStr7 = truncate('¥§✈✉🤓', { length: 5 }) // returns '¥§✈✉🤓'
634
+ * const truncatedStr8 = truncate('¥§✈✉🤓', { length: 4, omission: '…' }) // returns '¥§✈…'
635
+ */
636
+ function truncate$1(string, options) {
637
+ string = string != null ? `${string}` : "";
638
+ let length = 30;
639
+ let omission = "...";
640
+ if (isObject(options)) {
641
+ length = parseLength(options.length);
642
+ omission = "omission" in options ? `${options.omission}` : "...";
643
+ }
644
+ let i = string.length;
645
+ const lengthOmission = Array.from(omission).length;
646
+ const lengthBase = Math.max(length - lengthOmission, 0);
647
+ let strArray = void 0;
648
+ if (regexMultiByte.test(string)) {
649
+ strArray = Array.from(string);
650
+ i = strArray.length;
651
+ }
652
+ if (length >= i) return string;
653
+ if (i <= lengthOmission) return omission;
654
+ let base = strArray === void 0 ? string.slice(0, lengthBase) : strArray === null || strArray === void 0 ? void 0 : strArray.slice(0, lengthBase).join("");
655
+ const separator = options === null || options === void 0 ? void 0 : options.separator;
656
+ if (!separator) {
657
+ base += omission;
658
+ return base;
659
+ }
660
+ const search = separator instanceof RegExp ? separator.source : escapeRegExp(separator);
661
+ const flags = "u" + (separator instanceof RegExp ? separator.flags.replace("u", "") : "");
662
+ const withoutSeparator = new RegExp(`(.*(?:(?!${search}).))(?:${search})`, flags).exec(base);
663
+ return (withoutSeparator == null ? base : withoutSeparator[1]) + omission;
664
+ }
665
+ function parseLength(length) {
666
+ if (length == null) return 30;
667
+ if (length <= 0) return 0;
668
+ return length;
669
+ }
670
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/string/truncate.mjs
671
+ /**
672
+ * Shortens a string to a maximum length, replacing the removed part with an
673
+ * omission (`'...'` by default).
674
+ * Strings that fit are returned as is.
675
+ * The length is counted in code points, so emoji are never split in half.
676
+ *
677
+ * The removed part is at the end by default; pass `position: 'start'` to keep
678
+ * the end (like the end of a long path), or `'middle'` to keep both ends (like
679
+ * a file name with its extension).
680
+ * With the default `'end'` position, a `separator` makes the cut happen before
681
+ * its last match within the limit, to avoid cutting a word in half.
682
+ * @param text - The string to truncate.
683
+ * @param options - `length` (`30` by default), `omission` (`'...'` by default), `position` (`'end'`
684
+ * by default) and `separator`.
685
+ * @returns The string, shortened if needed.
686
+ * @example
687
+ * truncate('hi-diddly-ho there, neighborino');
688
+ * // 'hi-diddly-ho there, neighbo...'
689
+ * truncate('hi-diddly-ho there, neighborino', {length: 24, separator: ' '});
690
+ * // 'hi-diddly-ho there,...'
691
+ * @example
692
+ * // Keep the end or both ends
693
+ * truncate('/home/user/projects/utilery/src/index.ts', {length: 20, position: 'start', omission: '…'});
694
+ * // '…nutils/src/index.ts'
695
+ * truncate('a-very-long-file-name.tar.gz', {length: 15, position: 'middle', omission: '…'});
696
+ * // 'a-very-….tar.gz'
697
+ */
698
+ const truncate$2 = (text, options = {}) => {
699
+ const { length = 30, omission = "...", position = "end", separator } = options;
700
+ if (position === "end") return truncate$1(text, {
701
+ length,
702
+ omission,
703
+ ...separator != null && { separator }
704
+ });
705
+ const characters = [...text];
706
+ if (characters.length <= length) return text;
707
+ const keptLength = Math.max(length - [...omission].length, 0);
708
+ const headLength = position === "middle" ? Math.ceil(keptLength / 2) : 0;
709
+ return characters.slice(0, headLength).join("") + omission + characters.slice(characters.length - (keptLength - headLength)).join("");
710
+ };
711
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/ts/all-union-members.mjs
712
+ /**
713
+ * Builds a compile-time guard that a tuple lists every member of `Union`
714
+ * exactly once: no missing members, no extras and no duplicates.
715
+ * It is meant to keep a runtime list in sync with a union type: whenever the
716
+ * union changes, the tuple stops type-checking until it is updated to match.
717
+ *
718
+ * Because TypeScript cannot infer one type argument while another is given
719
+ * explicitly, the union is passed to the outer call and the tuple is inferred
720
+ * by the returned function.
721
+ * At runtime the returned function is the identity function: all of the work
722
+ * happens in the type system.
723
+ * An invalid tuple fails to type-check with a message that names the missing,
724
+ * extra or duplicated members (see {@link AllUnionMembers}).
725
+ *
726
+ * By default the result is widened to a mutable tuple; pass `{readonly: true}`
727
+ * as the second type argument to preserve the `readonly` tuple type instead.
728
+ * @returns A function that accepts the tuple and returns it unchanged, typed as
729
+ * the tuple of `Union`'s members (mutable by default, `readonly` on request).
730
+ * @example
731
+ * type Fruit = 'apple' | 'banana' | 'cherry';
732
+ *
733
+ * // OK: lists every member exactly once
734
+ * const fruits = allUnionMembers<Fruit>()(['apple', 'banana', 'cherry']);
735
+ * // type: ['apple', 'banana', 'cherry']
736
+ * @example
737
+ * // Error: "...is missing these union members": "cherry"
738
+ * allUnionMembers<Fruit>()(['apple', 'banana']);
739
+ * @example
740
+ * // Error: 'apple' is duplicated
741
+ * allUnionMembers<Fruit>()(['apple', 'banana', 'cherry', 'apple']);
742
+ * @example
743
+ * // Error: 'date' is not a member of `Fruit`
744
+ * allUnionMembers<Fruit>()(['apple', 'banana', 'cherry', 'date']);
745
+ * @example
746
+ * // Keep the tuple `readonly`
747
+ * const readonlyFruits = allUnionMembers<Fruit, {readonly: true}>()([
748
+ * 'apple',
749
+ * 'banana',
750
+ * 'cherry',
751
+ * ]);
752
+ * // type: readonly ['apple', 'banana', 'cherry']
753
+ */
754
+ const allUnionMembers = () => (members) => members;
755
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/predicate/isEqualWith.mjs
756
+ /**
757
+ * Compares two values for equality using a custom comparison function.
758
+ *
759
+ * The custom function allows for fine-tuned control over the comparison process. If it returns a boolean, that result determines the equality. If it returns undefined, the function falls back to the default equality comparison.
760
+ *
761
+ * This function also uses the custom equality function to compare values inside objects,
762
+ * arrays, maps, sets, and other complex structures, ensuring a deep comparison.
763
+ *
764
+ * This approach provides flexibility in handling complex comparisons while maintaining efficient default behavior for simpler cases.
765
+ *
766
+ * The custom comparison function can take up to six parameters:
767
+ * - `x`: The value from the first object `a`.
768
+ * - `y`: The value from the second object `b`.
769
+ * - `property`: The property key used to get `x` and `y`.
770
+ * - `xParent`: The parent of the first value `x`.
771
+ * - `yParent`: The parent of the second value `y`.
772
+ * - `stack`: An internal stack (Map) to handle circular references.
773
+ *
774
+ * @param a - The first value to compare.
775
+ * @param b - The second value to compare.
776
+ * @param areValuesEqual - A function to customize the comparison.
777
+ * If it returns a boolean, that result will be used. If it returns undefined,
778
+ * the default equality comparison will be used.
779
+ * @returns `true` if the values are equal according to the customizer, otherwise `false`.
780
+ *
781
+ * @example
782
+ * const customizer = (a, b) => {
783
+ * if (typeof a === 'string' && typeof b === 'string') {
784
+ * return a.toLowerCase() === b.toLowerCase();
785
+ * }
786
+ * };
787
+ * isEqualWith('Hello', 'hello', customizer); // true
788
+ * isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true
789
+ * isEqualWith([1, 2, 3], [1, 2, 3], customizer); // true
790
+ */
791
+ function isEqualWith(a, b, areValuesEqual) {
792
+ return isEqualWithImpl(a, b, void 0, void 0, void 0, void 0, areValuesEqual);
793
+ }
794
+ function isEqualWithImpl(a, b, property, aParent, bParent, stack, areValuesEqual) {
795
+ const result = areValuesEqual(a, b, property, aParent, bParent, stack);
796
+ if (result !== void 0) return result;
797
+ if (typeof a === typeof b) switch (typeof a) {
798
+ case "bigint":
799
+ case "string":
800
+ case "boolean":
801
+ case "symbol":
802
+ case "undefined": return a === b;
803
+ case "number": return a === b || Object.is(a, b);
804
+ case "function": return a === b;
805
+ case "object": return areObjectsEqual(a, b, stack, areValuesEqual);
806
+ }
807
+ return areObjectsEqual(a, b, stack, areValuesEqual);
808
+ }
809
+ function areObjectsEqual(a, b, stack, areValuesEqual) {
810
+ if (Object.is(a, b)) return true;
811
+ let aTag = getTag(a);
812
+ let bTag = getTag(b);
813
+ if (aTag === "[object Arguments]") aTag = objectTag;
814
+ if (bTag === "[object Arguments]") bTag = objectTag;
815
+ if (aTag !== bTag) return false;
816
+ switch (aTag) {
817
+ case stringTag: return a.toString() === b.toString();
818
+ case numberTag: return eq(a.valueOf(), b.valueOf());
819
+ case booleanTag:
820
+ case dateTag:
821
+ case symbolTag: return Object.is(a.valueOf(), b.valueOf());
822
+ case regexpTag: return a.source === b.source && a.flags === b.flags;
823
+ case functionTag: return a === b;
824
+ }
825
+ stack = stack ?? /* @__PURE__ */ new Map();
826
+ const aStack = stack.get(a);
827
+ const bStack = stack.get(b);
828
+ if (aStack != null && bStack != null) return aStack === b;
829
+ stack.set(a, b);
830
+ stack.set(b, a);
831
+ try {
832
+ switch (aTag) {
833
+ case mapTag:
834
+ if (a.size !== b.size) return false;
835
+ for (const [key, value] of a.entries()) if (!b.has(key) || !isEqualWithImpl(value, b.get(key), key, a, b, stack, areValuesEqual)) return false;
836
+ return true;
837
+ case setTag: {
838
+ if (a.size !== b.size) return false;
839
+ const aValues = Array.from(a.values());
840
+ const bValues = Array.from(b.values());
841
+ for (let i = 0; i < aValues.length; i++) {
842
+ const aValue = aValues[i];
843
+ const index = bValues.findIndex((bValue) => {
844
+ return isEqualWithImpl(aValue, bValue, void 0, a, b, stack, areValuesEqual);
845
+ });
846
+ if (index === -1) return false;
847
+ bValues.splice(index, 1);
848
+ }
849
+ return true;
850
+ }
851
+ case arrayTag:
852
+ case uint8ArrayTag:
853
+ case uint8ClampedArrayTag:
854
+ case uint16ArrayTag:
855
+ case uint32ArrayTag:
856
+ case bigUint64ArrayTag:
857
+ case int8ArrayTag:
858
+ case int16ArrayTag:
859
+ case int32ArrayTag:
860
+ case bigInt64ArrayTag:
861
+ case float32ArrayTag:
862
+ case float64ArrayTag:
863
+ if (isBuffer(a) !== isBuffer(b)) return false;
864
+ if (a.length !== b.length) return false;
865
+ for (let i = 0; i < a.length; i++) if (!isEqualWithImpl(a[i], b[i], i, a, b, stack, areValuesEqual)) return false;
866
+ return true;
867
+ case arrayBufferTag:
868
+ if (a.byteLength !== b.byteLength) return false;
869
+ return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);
870
+ case dataViewTag:
871
+ if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) return false;
872
+ return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);
873
+ case errorTag: return a.name === b.name && a.message === b.message;
874
+ case objectTag: {
875
+ if (!(areObjectsEqual(a.constructor, b.constructor, stack, areValuesEqual) || isPlainObject(a) && isPlainObject(b))) return false;
876
+ const aKeys = [...Object.keys(a), ...getSymbols(a)];
877
+ const bKeys = [...Object.keys(b), ...getSymbols(b)];
878
+ if (aKeys.length !== bKeys.length) return false;
879
+ for (let i = 0; i < aKeys.length; i++) {
880
+ const propKey = aKeys[i];
881
+ const aProp = a[propKey];
882
+ if (!Object.hasOwn(b, propKey)) return false;
883
+ const bProp = b[propKey];
884
+ if (!isEqualWithImpl(aProp, bProp, propKey, a, b, stack, areValuesEqual)) return false;
885
+ }
886
+ return true;
887
+ }
888
+ default: return false;
889
+ }
890
+ } finally {
891
+ stack.delete(a);
892
+ stack.delete(b);
893
+ }
894
+ }
895
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/node_modules/.pnpm/es-toolkit@1.53.0_patch_hash_93b8686c006f68cd3d5723b3e8f5c057f2286cde300a8774f589c9f3fd32dd1b/node_modules/es-toolkit/dist/predicate/isEqual.mjs
896
+ /**
897
+ * Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison.
898
+ *
899
+ * @param a - The first value to compare.
900
+ * @param b - The second value to compare.
901
+ * @returns `true` if the values are equal, otherwise `false`.
902
+ *
903
+ * @example
904
+ * isEqual(1, 1); // true
905
+ * isEqual({ a: 1 }, { a: 1 }); // true
906
+ * isEqual(/abc/g, /abc/g); // true
907
+ * isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true
908
+ * isEqual([1, 2, 3], [1, 2, 3]); // true
909
+ */
910
+ function isEqual$1(a, b) {
911
+ return isEqualWith(a, b, noop);
912
+ }
913
+ // node_modules/.pnpm/utilery@0.3.0/node_modules/utilery/dist/value/is-equal.mjs
914
+ function isEqual(a, b, customizer) {
915
+ return customizer ? isEqualWith(a, b, customizer) : isEqual$1(a, b);
916
+ }
917
+ // src/messages.ts
918
+ const BASH_4_SUGGESTION = "It needs Bash 4 or later, which macOS doesn't ship; use a Node.js script instead.";
919
+ const BASH_SUGGESTION = "Scripts run with `sh` (which isn't Bash on e.g. Debian/Ubuntu) or cmd.exe (on Windows).";
920
+ const CROSS_ENV_SUGGESTION = "Use `cross-env` instead.";
921
+ const CROSS_ENV_VARIABLE_SUGGESTION = "`cross-env` only replaces `$VAR` and `${VAR}` in all versions; use a Node.js script instead.";
922
+ const DEFAULT_SUGGESTION = "Use a cross-platform package or a Node.js script instead.";
923
+ const NODE_SCRIPT_SUGGESTION = "Use a Node.js script instead.";
924
+ const QUOTE_GLOB_SUGGESTION = "Quote it with escaped double quotes (`\\\"`) and let the tool expand it instead.";
925
+ const RIMRAF_SUGGESTION = "Use `rimraf` instead.";
926
+ const SHELL_SCRIPT_SUGGESTION = "Shell scripts require a POSIX shell; use a Node.js script instead.";
927
+ const VARIABLE_SUGGESTION = "Use `cross-env` or a Node.js script instead.";
928
+ /** Joins names for people, e.g. "macOS, Linux, and Windows" */
929
+ const listFormat = new Intl.ListFormat("en");
930
+ /** Maximum length of script text in a report message */
931
+ const MAX_SNIPPET_CHARACTERS = 40;
932
+ const WHITESPACE$1 = /\s+/g;
933
+ /**
934
+ * Shortens script text for a report message.
935
+ * @param text Text from the script
936
+ * @returns The text on a single line, cut off at the maximum length
937
+ */
938
+ const truncate = (text) => truncate$2(text.replaceAll(WHITESPACE$1, " "), { length: MAX_SNIPPET_CHARACTERS });
939
+ /**
940
+ * Describes a fix that replaces script text, e.g. "Replace `rm -rf` with `rimraf`.".
941
+ * @param original The replaced text
942
+ * @param replacement The text that replaces it
943
+ * @returns The description
944
+ */
945
+ const describeReplacement = (original, replacement) => `Replace \`${truncate(original)}\` with \`${truncate(replacement)}\`.`;
946
+ // src/platforms.ts
947
+ const PLATFORMS = [
948
+ "darwin",
949
+ "linux",
950
+ "win32"
951
+ ];
952
+ const POSIX_PLATFORMS = ["darwin", "linux"];
953
+ const MACOS_PLATFORMS = ["darwin"];
954
+ const LINUX_PLATFORMS = ["linux"];
955
+ const WINDOWS_PLATFORMS = ["win32"];
956
+ const NOT_LINUX_OR_WINDOWS = ["linux", "win32"];
957
+ const NOT_MACOS_OR_WINDOWS = ["darwin", "win32"];
958
+ const PLATFORM_NAMES = {
959
+ darwin: "macOS",
960
+ linux: "Linux",
961
+ win32: "Windows"
962
+ };
963
+ /**
964
+ * Formats platforms as a list for people, e.g. "macOS, Linux, and Windows".
965
+ * @param platforms The platforms to format
966
+ * @returns The formatted list
967
+ */
968
+ const formatPlatforms = (platforms) => listFormat.format(arrayIntersection(PLATFORMS, platforms).map((platform) => PLATFORM_NAMES[platform]));
969
+ // src/context.ts
970
+ /**
971
+ * Gets where a node of a piece of the script is in the analyzed script.
972
+ * @param context The piece that the node is in
973
+ * @param node The node, with positions relative to the piece's source
974
+ * @returns The range in the analyzed script, or the piece's fixed range
975
+ */
976
+ const rangeInScript = (context, node) => context.fixedRange || {
977
+ end: context.offset + node.end,
978
+ pos: context.offset + node.pos
979
+ };
980
+ const withCovered = (context, platforms) => platforms.every((platform) => context.covered.has(platform)) ? context : {
981
+ ...context,
982
+ covered: /* @__PURE__ */ new Set([...context.covered, ...platforms])
983
+ };
984
+ /** Gets how reports name Bash syntax of a kind, e.g. "Bash 4" for Bash 4 syntax */
985
+ const bashLabel = (kind) => kind === "bash4" ? "Bash 4" : "Bash-specific";
986
+ // src/reporter.ts
987
+ /**
988
+ * Gets what identifies an issue, apart from the platforms and the runners that it's found for.
989
+ * @param issue The issue
990
+ * @returns A string that is the same for the same issues
991
+ */
992
+ const issueKey = (issue) => JSON.stringify([
993
+ issue.messageId,
994
+ issue.pos,
995
+ issue.end,
996
+ issue.data
997
+ ]);
998
+ /** Platforms on which each kind of syntax doesn't work, by the shell that runs it */
999
+ const SYNTAX_PLATFORMS = {
1000
+ bash: {
1001
+ bash: [],
1002
+ native: NOT_LINUX_OR_WINDOWS,
1003
+ sh: NOT_LINUX_OR_WINDOWS
1004
+ },
1005
+ bash4: {
1006
+ bash: MACOS_PLATFORMS,
1007
+ native: PLATFORMS,
1008
+ sh: PLATFORMS
1009
+ },
1010
+ bashNonPosix: {
1011
+ bash: [],
1012
+ native: PLATFORMS,
1013
+ sh: PLATFORMS
1014
+ },
1015
+ posix: {
1016
+ bash: [],
1017
+ native: WINDOWS_PLATFORMS,
1018
+ sh: []
1019
+ }
1020
+ };
1021
+ var Reporter = class {
1022
+ issues = [];
1023
+ /**
1024
+ * Length of the analyzed script, which unbash's positions can exceed, e.g. after a trailing `\\`
1025
+ */
1026
+ #length;
1027
+ #seen = /* @__PURE__ */ new Set();
1028
+ constructor(length) {
1029
+ this.#length = length;
1030
+ }
1031
+ /**
1032
+ * Maps a fix's positions to the analyzed script.
1033
+ * @param context Where the fix is
1034
+ * @param fix The fix, with positions relative to the context's source
1035
+ * @returns The mapped fix, or `undefined` if it can't be applied in the context
1036
+ */
1037
+ #mapFix(context, fix) {
1038
+ if (!fix || context.fixedRange) return;
1039
+ const edits = fix.edits.map(({ end, pos, text }) => ({
1040
+ end: context.offset + end,
1041
+ pos: context.offset + pos,
1042
+ text
1043
+ }));
1044
+ return edits.every(({ end, pos, text }) => pos >= 0 && pos <= end && end <= this.#length && context.fixExclusions.every((exclusion) => !exclusion.test(text))) ? {
1045
+ description: fix.description,
1046
+ edits
1047
+ } : void 0;
1048
+ }
1049
+ report(context, node, messageId, data, platforms, fix) {
1050
+ const remaining = platforms.filter((platform) => !context.covered.has(platform));
1051
+ if (remaining.length > 0) {
1052
+ const range = rangeInScript(context, node);
1053
+ const pos = clamp(range.pos, 0, this.#length);
1054
+ const end = clamp(range.end, pos, this.#length);
1055
+ const key = issueKey({
1056
+ data,
1057
+ end,
1058
+ messageId,
1059
+ pos
1060
+ });
1061
+ if (!this.#seen.has(key)) {
1062
+ this.#seen.add(key);
1063
+ this.issues.push({
1064
+ data,
1065
+ end,
1066
+ fix: this.#mapFix(context, fix),
1067
+ messageId,
1068
+ platforms: remaining,
1069
+ pos
1070
+ });
1071
+ }
1072
+ }
1073
+ return remaining;
1074
+ }
1075
+ reportSyntax(context, node, kind, isPortableSupported, messageId, data, fix) {
1076
+ let platforms = SYNTAX_PLATFORMS[kind][context.shell];
1077
+ if (context.portable) platforms = isPortableSupported ? [] : PLATFORMS;
1078
+ return this.report(context, node, messageId, data, platforms, fix);
1079
+ }
1080
+ };
1081
+ // src/runners.ts
1082
+ const RUNNERS = allUnionMembers()([
1083
+ "aube",
1084
+ "node",
1085
+ "npm",
1086
+ "pnpm",
1087
+ "pnpm-10",
1088
+ "upm",
1089
+ "yarn",
1090
+ "yarn-classic"
1091
+ ]);
1092
+ /** Runners that are package managers: all of them but `node`, which doesn't install packages */
1093
+ const PACKAGE_MANAGER_RUNNERS = RUNNERS.filter((runner) => runner !== "node");
1094
+ /**
1095
+ * Scripts that run with any package manager by default, as they run on the machine of whoever
1096
+ * installs the package: install scripts, and `prepare`, which runs when it's installed from git
1097
+ */
1098
+ const RUNNER_AGNOSTIC_SCRIPTS = /* @__PURE__ */ new Set([
1099
+ "install",
1100
+ "postinstall",
1101
+ "preinstall",
1102
+ "prepare"
1103
+ ]);
1104
+ /**
1105
+ * Checks whether any package manager may run a script.
1106
+ * @param scriptName The script's name in package.json
1107
+ * @param scripts `true` for all scripts, `false` for none, or whether each script is, on top of
1108
+ * the defaults
1109
+ * @returns Whether the script is runner-agnostic
1110
+ */
1111
+ const isRunnerAgnosticScript = (scriptName, scripts = {}) => {
1112
+ if (typeof scripts === "boolean") return scripts;
1113
+ if (scriptName == null) return false;
1114
+ return Object.hasOwn(scripts, scriptName) ? scripts[scriptName] === true : RUNNER_AGNOSTIC_SCRIPTS.has(scriptName);
1115
+ };
1116
+ const RUNNER_TRAITS = {
1117
+ aube: { label: "aube" },
1118
+ node: {
1119
+ label: "`node --run`",
1120
+ packageManagerVariables: /* @__PURE__ */ new Set()
1121
+ },
1122
+ npm: {
1123
+ label: "npm",
1124
+ setsHome: true
1125
+ },
1126
+ pnpm: { label: "pnpm" },
1127
+ "pnpm-10": {
1128
+ label: "pnpm v10",
1129
+ setsHome: true
1130
+ },
1131
+ upm: {
1132
+ label: "upm",
1133
+ packageManagerVariables: /* @__PURE__ */ new Set([
1134
+ "INIT_CWD",
1135
+ "npm_lifecycle_event",
1136
+ "npm_lifecycle_script",
1137
+ "npm_package_json",
1138
+ "npm_package_name",
1139
+ "npm_package_version"
1140
+ ])
1141
+ },
1142
+ yarn: {
1143
+ label: "Yarn",
1144
+ portableShell: true
1145
+ },
1146
+ "yarn-classic": {
1147
+ convertsSlashes: true,
1148
+ label: "Yarn v1"
1149
+ }
1150
+ };
1151
+ /** Runners that package managers of the same name are, i.e. all of them but pnpm and Yarn */
1152
+ const SAME_NAME_RUNNERS = /* @__PURE__ */ new Set([
1153
+ "aube",
1154
+ "npm",
1155
+ "upm"
1156
+ ]);
1157
+ /** The first number of a version or a version range, e.g. `1` in `^1.22.0` */
1158
+ const MAJOR_VERSION = /\d+/;
1159
+ /** A version range without an upper bound, e.g. `>=10`, which includes later major versions */
1160
+ const UNBOUNDED_RANGE = /^\s*>/;
1161
+ /**
1162
+ * Gets the runner for a package manager, e.g. the one in the `packageManager` or
1163
+ * `devEngines.packageManager` field of package.json.
1164
+ * @param name Name of the package manager, e.g. `yarn`
1165
+ * @param version Its version or version range, which tells Yarn v1 from Yarn v2+, and pnpm v10
1166
+ * from later versions, e.g. `1.22.22`
1167
+ * @returns The runner, or `undefined` if it's an unknown package manager or Yarn of an unknown
1168
+ * version
1169
+ */
1170
+ const getRunner = (name, version = "") => {
1171
+ const major = Number(MAJOR_VERSION.exec(version)?.[0]);
1172
+ if (name === "pnpm") return major <= 10 && !UNBOUNDED_RANGE.test(version) ? "pnpm-10" : "pnpm";
1173
+ if (name !== "yarn") return setHas(SAME_NAME_RUNNERS, name) ? name : void 0;
1174
+ if (major === 1) return "yarn-classic";
1175
+ return major >= 2 ? "yarn" : void 0;
1176
+ };
1177
+ /**
1178
+ * Gets how a runner runs the scripts.
1179
+ * @param runner What runs the scripts
1180
+ * @param isShellEmulated Whether pnpm's `shell-emulator` setting is on
1181
+ * @returns The runner's traits
1182
+ */
1183
+ const runnerTraits = (runner, isShellEmulated) => isShellEmulated && (runner === "pnpm" || runner === "pnpm-10") ? {
1184
+ ...RUNNER_TRAITS[runner],
1185
+ portableShell: true
1186
+ } : RUNNER_TRAITS[runner];
1187
+ /**
1188
+ * Formats runners as a list for people, e.g. "pnpm and Yarn v1".
1189
+ * @param runners The runners to format
1190
+ * @returns The formatted list
1191
+ */
1192
+ const formatRunners = (runners) => listFormat.format(arrayIntersection(RUNNERS, runners).map((runner) => RUNNER_TRAITS[runner].label));
1193
+ // src/commands.ts
1194
+ /** POSIX shells, which don't exist on Windows */
1195
+ const SHELLS = [
1196
+ "bash",
1197
+ "csh",
1198
+ "dash",
1199
+ "fish",
1200
+ "ksh",
1201
+ "sh",
1202
+ "tcsh",
1203
+ "zsh"
1204
+ ];
1205
+ const COMMAND_GROUPS = [
1206
+ [
1207
+ ["rm"],
1208
+ WINDOWS_PLATFORMS,
1209
+ RIMRAF_SUGGESTION
1210
+ ],
1211
+ [
1212
+ ["env", "export"],
1213
+ WINDOWS_PLATFORMS,
1214
+ CROSS_ENV_SUGGESTION
1215
+ ],
1216
+ [
1217
+ ["true", ":"],
1218
+ WINDOWS_PLATFORMS,
1219
+ "Use `exit 0` instead (e.g. `command || exit 0`)."
1220
+ ],
1221
+ [
1222
+ ["false"],
1223
+ WINDOWS_PLATFORMS,
1224
+ "Use `exit 1` instead."
1225
+ ],
1226
+ [
1227
+ ["find"],
1228
+ WINDOWS_PLATFORMS,
1229
+ "Windows ships an unrelated `find` command; use a Node.js script instead."
1230
+ ],
1231
+ [
1232
+ ["date"],
1233
+ WINDOWS_PLATFORMS,
1234
+ "cmd.exe's `date` sets the system date; use a Node.js script instead."
1235
+ ],
1236
+ [
1237
+ SHELLS,
1238
+ WINDOWS_PLATFORMS,
1239
+ SHELL_SCRIPT_SUGGESTION
1240
+ ],
1241
+ [[
1242
+ ".",
1243
+ "[",
1244
+ "alias",
1245
+ "awk",
1246
+ "base64",
1247
+ "basename",
1248
+ "bg",
1249
+ "bzip2",
1250
+ "cat",
1251
+ "chgrp",
1252
+ "chmod",
1253
+ "chown",
1254
+ "clear",
1255
+ "cmp",
1256
+ "column",
1257
+ "comm",
1258
+ "command",
1259
+ "cp",
1260
+ "crontab",
1261
+ "cut",
1262
+ "df",
1263
+ "diff",
1264
+ "dirname",
1265
+ "du",
1266
+ "egrep",
1267
+ "eval",
1268
+ "exec",
1269
+ "expr",
1270
+ "fg",
1271
+ "fgrep",
1272
+ "file",
1273
+ "fmt",
1274
+ "fold",
1275
+ "fuser",
1276
+ "getopts",
1277
+ "grep",
1278
+ "gunzip",
1279
+ "gzip",
1280
+ "hash",
1281
+ "head",
1282
+ "hexdump",
1283
+ "iconv",
1284
+ "id",
1285
+ "install",
1286
+ "jobs",
1287
+ "join",
1288
+ "kill",
1289
+ "killall",
1290
+ "less",
1291
+ "ln",
1292
+ "local",
1293
+ "ls",
1294
+ "lsof",
1295
+ "md5sum",
1296
+ "mktemp",
1297
+ "mv",
1298
+ "nice",
1299
+ "nl",
1300
+ "nohup",
1301
+ "od",
1302
+ "paste",
1303
+ "patch",
1304
+ "pgrep",
1305
+ "pkill",
1306
+ "printenv",
1307
+ "printf",
1308
+ "ps",
1309
+ "pwd",
1310
+ "read",
1311
+ "readlink",
1312
+ "readonly",
1313
+ "realpath",
1314
+ "return",
1315
+ "rev",
1316
+ "rsync",
1317
+ "sed",
1318
+ "seq",
1319
+ "sha1sum",
1320
+ "sha224sum",
1321
+ "sha256sum",
1322
+ "sha384sum",
1323
+ "sha512sum",
1324
+ "shasum",
1325
+ "shift",
1326
+ "sleep",
1327
+ "split",
1328
+ "stat",
1329
+ "stdbuf",
1330
+ "strings",
1331
+ "su",
1332
+ "sudo",
1333
+ "tail",
1334
+ "tee",
1335
+ "test",
1336
+ "time",
1337
+ "touch",
1338
+ "tput",
1339
+ "tr",
1340
+ "trap",
1341
+ "truncate",
1342
+ "ulimit",
1343
+ "umask",
1344
+ "uname",
1345
+ "uniq",
1346
+ "unset",
1347
+ "unzip",
1348
+ "wait",
1349
+ "wc",
1350
+ "which",
1351
+ "xargs",
1352
+ "xxd",
1353
+ "yes",
1354
+ "zcat",
1355
+ "zip"
1356
+ ], WINDOWS_PLATFORMS],
1357
+ [[
1358
+ "apk",
1359
+ "apt",
1360
+ "apt-get",
1361
+ "b2sum",
1362
+ "dnf",
1363
+ "dpkg",
1364
+ "free",
1365
+ "gawk",
1366
+ "inotifywait",
1367
+ "ip",
1368
+ "journalctl",
1369
+ "ldconfig",
1370
+ "ldd",
1371
+ "lsblk",
1372
+ "notify-send",
1373
+ "nproc",
1374
+ "pacman",
1375
+ "rpm",
1376
+ "sensible-browser",
1377
+ "service",
1378
+ "setsid",
1379
+ "shred",
1380
+ "snap",
1381
+ "ss",
1382
+ "strace",
1383
+ "systemctl",
1384
+ "tac",
1385
+ "taskset",
1386
+ "unxz",
1387
+ "wget",
1388
+ "wl-copy",
1389
+ "wl-paste",
1390
+ "xclip",
1391
+ "xdg-open",
1392
+ "xdotool",
1393
+ "xsel",
1394
+ "xz",
1395
+ "yum",
1396
+ "zypper"
1397
+ ], NOT_MACOS_OR_WINDOWS],
1398
+ [[
1399
+ "afplay",
1400
+ "agvtool",
1401
+ "caffeinate",
1402
+ "codesign",
1403
+ "defaults",
1404
+ "diskutil",
1405
+ "ditto",
1406
+ "hdiutil",
1407
+ "install_name_tool",
1408
+ "launchctl",
1409
+ "lipo",
1410
+ "md5",
1411
+ "mdfind",
1412
+ "networksetup",
1413
+ "open",
1414
+ "osacompile",
1415
+ "osascript",
1416
+ "pbcopy",
1417
+ "pbpaste",
1418
+ "pkgutil",
1419
+ "plutil",
1420
+ "pmset",
1421
+ "qlmanage",
1422
+ "say",
1423
+ "scutil",
1424
+ "security",
1425
+ "sw_vers",
1426
+ "tccutil",
1427
+ "xcodebuild",
1428
+ "xcrun",
1429
+ "xed"
1430
+ ], NOT_LINUX_OR_WINDOWS],
1431
+ [
1432
+ ["del"],
1433
+ POSIX_PLATFORMS,
1434
+ "Use `rimraf` instead (del-cli's `del` alias is shadowed by cmd.exe's builtin on Windows)."
1435
+ ],
1436
+ [
1437
+ ["erase", "rd"],
1438
+ POSIX_PLATFORMS,
1439
+ RIMRAF_SUGGESTION
1440
+ ],
1441
+ [
1442
+ ["setx"],
1443
+ POSIX_PLATFORMS,
1444
+ CROSS_ENV_SUGGESTION
1445
+ ],
1446
+ [
1447
+ ["rem"],
1448
+ POSIX_PLATFORMS,
1449
+ "Remove the comment instead."
1450
+ ],
1451
+ [["dir"], MACOS_PLATFORMS],
1452
+ [[
1453
+ "assoc",
1454
+ "attrib",
1455
+ "call",
1456
+ "certutil",
1457
+ "chcp",
1458
+ "chdir",
1459
+ "choice",
1460
+ "clip",
1461
+ "cls",
1462
+ "cmd",
1463
+ "copy",
1464
+ "cscript",
1465
+ "endlocal",
1466
+ "explorer",
1467
+ "findstr",
1468
+ "ftype",
1469
+ "goto",
1470
+ "icacls",
1471
+ "md",
1472
+ "mklink",
1473
+ "move",
1474
+ "msiexec",
1475
+ "netsh",
1476
+ "pause",
1477
+ "powershell",
1478
+ "reg",
1479
+ "ren",
1480
+ "rename",
1481
+ "robocopy",
1482
+ "rundll32",
1483
+ "schtasks",
1484
+ "setlocal",
1485
+ "start",
1486
+ "systeminfo",
1487
+ "taskkill",
1488
+ "tasklist",
1489
+ "title",
1490
+ "ver",
1491
+ "where",
1492
+ "wmic",
1493
+ "wscript",
1494
+ "wsl",
1495
+ "xcopy"
1496
+ ], POSIX_PLATFORMS]
1497
+ ];
1498
+ /** Bash builtins that POSIX `sh` (e.g. dash on Debian/Ubuntu) and cmd.exe don't have */
1499
+ const BASH_BUILTINS = [
1500
+ [[
1501
+ "bind",
1502
+ "builtin",
1503
+ "caller",
1504
+ "compgen",
1505
+ "complete",
1506
+ "declare",
1507
+ "dirs",
1508
+ "disown",
1509
+ "enable",
1510
+ "help",
1511
+ "history",
1512
+ "let",
1513
+ "logout",
1514
+ "shopt",
1515
+ "source",
1516
+ "suspend",
1517
+ "typeset"
1518
+ ], NOT_LINUX_OR_WINDOWS],
1519
+ [["popd", "pushd"], LINUX_PLATFORMS],
1520
+ [
1521
+ ["mapfile", "readarray"],
1522
+ PLATFORMS,
1523
+ BASH_4_SUGGESTION
1524
+ ]
1525
+ ];
1526
+ const COMMANDS = new Map([...COMMAND_GROUPS.flatMap(([names, platforms, suggestion = DEFAULT_SUGGESTION]) => names.map((name) => [name, {
1527
+ platforms,
1528
+ suggestion
1529
+ }])), ...BASH_BUILTINS.flatMap(([names, platforms, suggestion = BASH_SUGGESTION]) => names.map((name) => [name, {
1530
+ bashBuiltin: true,
1531
+ platforms,
1532
+ suggestion
1533
+ }]))]);
1534
+ /** cmd.exe builtins (rather than executables), which Yarn's portable shell can't run on Windows */
1535
+ const CMD_BUILTINS = /* @__PURE__ */ new Set([
1536
+ "assoc",
1537
+ "call",
1538
+ "chdir",
1539
+ "cls",
1540
+ "copy",
1541
+ "del",
1542
+ "dir",
1543
+ "endlocal",
1544
+ "erase",
1545
+ "ftype",
1546
+ "goto",
1547
+ "md",
1548
+ "mklink",
1549
+ "move",
1550
+ "pause",
1551
+ "rd",
1552
+ "rem",
1553
+ "ren",
1554
+ "rename",
1555
+ "setlocal",
1556
+ "start",
1557
+ "title",
1558
+ "ver"
1559
+ ]);
1560
+ /** Builtins of Yarn's portable shell, which work on all platforms */
1561
+ const PORTABLE_SHELL_BUILTINS = /* @__PURE__ */ new Set([
1562
+ ":",
1563
+ "cd",
1564
+ "echo",
1565
+ "exit",
1566
+ "false",
1567
+ "pwd",
1568
+ "sleep",
1569
+ "true",
1570
+ "unset"
1571
+ ]);
1572
+ /** BSD utilities on macOS that don't support GNU-style long options */
1573
+ const NO_LONG_OPTIONS_ON_MACOS = /* @__PURE__ */ new Set([
1574
+ "basename",
1575
+ "cat",
1576
+ "chmod",
1577
+ "chown",
1578
+ "cp",
1579
+ "cut",
1580
+ "date",
1581
+ "df",
1582
+ "dirname",
1583
+ "du",
1584
+ "install",
1585
+ "ln",
1586
+ "mkdir",
1587
+ "mv",
1588
+ "readlink",
1589
+ "realpath",
1590
+ "rm",
1591
+ "rmdir",
1592
+ "sed",
1593
+ "stat",
1594
+ "tee",
1595
+ "touch",
1596
+ "tr",
1597
+ "truncate",
1598
+ "uname",
1599
+ "wc"
1600
+ ]);
1601
+ /** OS commands rather than npm packages, including those that exist everywhere */
1602
+ const OS_COMMANDS = /* @__PURE__ */ new Set([
1603
+ ...COMMANDS.keys(),
1604
+ "cd",
1605
+ "echo",
1606
+ "mkdir",
1607
+ "rmdir",
1608
+ "sort",
1609
+ "timeout"
1610
+ ]);
1611
+ /** Package manager subcommands that run the command given as their arguments */
1612
+ const EXEC_SUBCOMMANDS = {
1613
+ aube: ["dlx", "exec"],
1614
+ bun: ["x"],
1615
+ npm: ["exec", "x"],
1616
+ pnpm: ["dlx", "exec"],
1617
+ upm: ["exec"],
1618
+ yarn: ["dlx", "exec"]
1619
+ };
1620
+ /** Options of package managers (before the subcommand) that take a value */
1621
+ const PACKAGE_MANAGER_VALUE_OPTIONS = [
1622
+ "--cd",
1623
+ "--cwd",
1624
+ "--dir",
1625
+ "--filter",
1626
+ "--filter-prod",
1627
+ "--prefix",
1628
+ "--workspace",
1629
+ "-C",
1630
+ "-F"
1631
+ ];
1632
+ /** Options of package managers' exec subcommands that take a value */
1633
+ const EXEC_VALUE_OPTIONS = ["--package", "-p"];
1634
+ /** Commands whose arguments are often patterns rather than paths */
1635
+ const PATTERN_COMMANDS = /* @__PURE__ */ new Set([
1636
+ "awk",
1637
+ "echo",
1638
+ "egrep",
1639
+ "findstr",
1640
+ "grep",
1641
+ "printf",
1642
+ "sed"
1643
+ ]);
1644
+ /** Commands that run the command given as their arguments, with their options that take a value */
1645
+ const WRAPPER_VALUE_OPTIONS = /* @__PURE__ */ new Map([
1646
+ ["aubx", ["--package", "-p"]],
1647
+ ["bunx", ["--package", "-p"]],
1648
+ ["command", []],
1649
+ ["env", [
1650
+ "--chdir",
1651
+ "--split-string",
1652
+ "--unset",
1653
+ "-C",
1654
+ "-S",
1655
+ "-u"
1656
+ ]],
1657
+ ["exec", ["-a"]],
1658
+ ["nice", ["--adjustment", "-n"]],
1659
+ ["nohup", []],
1660
+ ["npx", ["--package", "-p"]],
1661
+ ["pnpx", ["--package", "-p"]],
1662
+ ["sudo", [
1663
+ "-C",
1664
+ "-D",
1665
+ "-g",
1666
+ "-h",
1667
+ "-p",
1668
+ "-r",
1669
+ "-t",
1670
+ "-U",
1671
+ "-u"
1672
+ ]],
1673
+ ["time", ["-f", "-o"]],
1674
+ ["upx", ["--package", "-p"]],
1675
+ ["xargs", [
1676
+ "-a",
1677
+ "-d",
1678
+ "-E",
1679
+ "-I",
1680
+ "-L",
1681
+ "-n",
1682
+ "-P",
1683
+ "-s"
1684
+ ]]
1685
+ ]);
1686
+ /** Builtins that change the shell's state, which a subshell keeps from the commands that follow */
1687
+ const SHELL_STATE_COMMANDS = /* @__PURE__ */ new Set([
1688
+ ".",
1689
+ "alias",
1690
+ "cd",
1691
+ "exit",
1692
+ "export",
1693
+ "popd",
1694
+ "pushd",
1695
+ "read",
1696
+ "readonly",
1697
+ "return",
1698
+ "set",
1699
+ "shift",
1700
+ "source",
1701
+ "trap",
1702
+ "ulimit",
1703
+ "umask",
1704
+ "unalias",
1705
+ "unset"
1706
+ ]);
1707
+ // src/words.ts
1708
+ /** A `NAME=value` word, e.g. an argument of `cross-env` */
1709
+ const ASSIGNMENT = /^[a-z_]\w*=/i;
1710
+ const SHORT_OPTION_CLUSTER = /^-[a-z]+$/i;
1711
+ /**
1712
+ * Checks whether a word is a cluster of short options that includes a letter, e.g. `-rf` for `f`.
1713
+ * @param value Value of a word from the script
1714
+ * @param letter Letter of the short option to look for
1715
+ * @returns Whether the word includes the option
1716
+ */
1717
+ const isShortOptionCluster = (value, letter) => value != null && SHORT_OPTION_CLUSTER.test(value) && value.includes(letter);
1718
+ /** A tilde expansion at the start of a word, e.g. `~/.npmrc` */
1719
+ const TILDE_EXPANSION = /^~[\w\-.]*(?:\/|$)/;
1720
+ /** Characters that POSIX shells interpret in double quotes, e.g. `$` */
1721
+ const DOUBLE_QUOTED_SPECIAL_CHARACTERS = /["$\\`]/;
1722
+ const WHITESPACE = /\s/;
1723
+ const GLOB_PART_TYPES = [
1724
+ "BraceExpansion",
1725
+ "ExtendedGlob",
1726
+ "Glob"
1727
+ ];
1728
+ const isStatic = (parts) => parts.every((part) => part.type === "Literal" || part.type === "SingleQuoted" || part.type === "AnsiCQuoted" || part.type === "Glob" || part.type === "DoubleQuoted" && isStatic(part.parts));
1729
+ /**
1730
+ * Gets the value of a word, if it doesn't depend on expansions.
1731
+ * @param word A word from the parsed script
1732
+ * @returns The value, or `undefined` if it's dynamic
1733
+ */
1734
+ const staticValue = (word) => word.parts == null || isStatic(word.parts) ? word.value : void 0;
1735
+ /**
1736
+ * Checks whether a word is unquoted text without escapes or expansions, e.g. `dist/*.js`.
1737
+ * Double quotes don't change the value of such a word.
1738
+ * @param word A word from the parsed script
1739
+ * @param partTypes Types of parts that are allowed besides literal text, e.g. globs
1740
+ * @returns Whether the word is plain
1741
+ */
1742
+ const isPlainWord = (word, partTypes = []) => !DOUBLE_QUOTED_SPECIAL_CHARACTERS.test(word.text) && !TILDE_EXPANSION.test(word.text) && (word.parts || []).every((part) => part.type === "Literal" || partTypes.includes(part.type));
1743
+ const isPlainAssignment = (item) => item.type === "Assignment" && item.value.type === "Word" && item.index == null && !item.append;
1744
+ /** Device files, which (unlike e.g. `/usr/...`) are rarely paths in containers or remote hosts */
1745
+ const POSIX_PATH = /(?:^|=)\/dev\//;
1746
+ // src/command-usage.ts
1747
+ /** Commands that also exist in cmd.exe, whose names are case-insensitive there */
1748
+ const CMD_COMMANDS = /* @__PURE__ */ new Set([
1749
+ "mkdir",
1750
+ "rmdir",
1751
+ "set",
1752
+ "sort",
1753
+ "timeout"
1754
+ ]);
1755
+ /** Bash's pseudo-signals for `trap`, which dash doesn't support */
1756
+ const BASH_TRAP_CONDITIONS = /* @__PURE__ */ new Set([
1757
+ "DEBUG",
1758
+ "ERR",
1759
+ "RETURN"
1760
+ ]);
1761
+ const DASH = "dash, the `sh` of Debian/Ubuntu,";
1762
+ /** GNU `find` primaries that BSD `find` doesn't support */
1763
+ const GNU_FIND_PRIMARIES = /* @__PURE__ */ new Set([
1764
+ "-executable",
1765
+ "-fprintf",
1766
+ "-printf",
1767
+ "-readable",
1768
+ "-regextype",
1769
+ "-writable",
1770
+ "-xtype"
1771
+ ]);
1772
+ /** BSD `find` options, which come before the starting paths */
1773
+ const BSD_FIND_OPTIONS = /^-[EHLPXdsx]+$/;
1774
+ /** GNU regex escapes that BSD `sed` doesn't support, e.g. `\s` */
1775
+ const GNU_SED_ESCAPE = /\\[<>bsw]/i;
1776
+ /** The same, in basic regexes only */
1777
+ const GNU_SED_BASIC_ESCAPE = /\\[+?]/;
1778
+ /** GNU `xargs` options that BSD `xargs` doesn't support, e.g. `-d` */
1779
+ const GNU_XARGS_OPTION = /^(?:-[0prtx]*[adil]|--(?:arg-file|delimiter|max-lines|replace)\b)/;
1780
+ const LONG_OPTION = /^--[^-]/;
1781
+ /** Any option, e.g. `-p` */
1782
+ const POSIX_OPTION = /^-./;
1783
+ /** A cmd.exe option, e.g. `/s` */
1784
+ const CMD_OPTION = /^\/[a-z]/i;
1785
+ /** Including combined switches, e.g. `/s/q` */
1786
+ const RMDIR_CMD_OPTION = /^(?:\/[qs])+$/i;
1787
+ const TIMEOUT_CMD_OPTION = /^\/t$/i;
1788
+ const ECHO_OPTIONS = /^-[Een]+$/;
1789
+ const HEAD_COUNT_OPTION = /^-[cn]$/;
1790
+ /** e.g. `-n-1` */
1791
+ const HEAD_NEGATIVE_COUNT_OPTION = /^-[cn]-\d/;
1792
+ const NEGATIVE_NUMBER = /^-\d/;
1793
+ const SED_EXTENDED_OPTION = /^-[a-z]*[er]/i;
1794
+ const SED_IN_PLACE_OPTION = /^-[a-z]*i$/i;
1795
+ /** `set -o`, possibly after other options, e.g. `set -euo` */
1796
+ const SET_NAMED_OPTION = /^-[a-z]*o$/i;
1797
+ const SET_SHELL_OPTIONS = /^[+-][a-z]+$/i;
1798
+ /** Including attached values, e.g. `-f%z` */
1799
+ const STAT_FORMAT_OPTION = /^-[cf]/;
1800
+ /**
1801
+ * Checks a command's options for ones that don't work (the same) on all platforms, e.g. `sed -i`.
1802
+ * @param name Name that the command was invoked with, e.g. `sed`
1803
+ * @param commandArguments The words that follow the command name
1804
+ * @param options Where the command runs, and where its options end
1805
+ * @returns The issues found
1806
+ */
1807
+ const checkCommandUsage = (name, commandArguments, options) => {
1808
+ const { bash, optionsEnd, portable } = options;
1809
+ const values = commandArguments.map(({ value }) => value);
1810
+ const textOf = (index) => commandArguments[index]?.text || "";
1811
+ const issues = [];
1812
+ const optionIndex = (isMatch) => values.findIndex((value, index) => index < optionsEnd && value != null && isMatch(value, index));
1813
+ const report = (index, platforms, data, fix) => {
1814
+ if (data.syntax) issues.push({
1815
+ argumentIndex: index,
1816
+ data,
1817
+ fix,
1818
+ messageId: "inconsistentBehavior",
1819
+ platforms
1820
+ });
1821
+ else {
1822
+ const usage = data.usage || `${name} ${truncate(values[index] ?? textOf(index))}`;
1823
+ issues.push({
1824
+ argumentIndex: index,
1825
+ data: {
1826
+ ...data,
1827
+ usage
1828
+ },
1829
+ fix,
1830
+ messageId: "unsupportedUsage",
1831
+ platforms
1832
+ });
1833
+ }
1834
+ };
1835
+ /** Creates a fix that replaces an argument's source text */
1836
+ const replaceArgument = (index, text) => ({
1837
+ argumentIndex: index,
1838
+ description: describeReplacement(textOf(index), text),
1839
+ text
1840
+ });
1841
+ const reportCommand = (platforms, suggestion) => {
1842
+ issues.push({
1843
+ argumentIndex: void 0,
1844
+ data: {
1845
+ command: name,
1846
+ suggestion
1847
+ },
1848
+ messageId: "unsupportedCommand",
1849
+ platforms
1850
+ });
1851
+ };
1852
+ if (NO_LONG_OPTIONS_ON_MACOS.has(name)) {
1853
+ const index = optionIndex((value) => LONG_OPTION.test(value));
1854
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1855
+ reason: `BSD \`${name}\` doesn't support GNU-style long options`,
1856
+ suggestion: "Use short options instead.",
1857
+ usage: `${name} ${substringBefore(values[index] || "", "=")}`
1858
+ });
1859
+ }
1860
+ const lowerCaseName = name.toLowerCase();
1861
+ const isDash = !bash && !portable;
1862
+ switch (CMD_COMMANDS.has(lowerCaseName) ? lowerCaseName : name) {
1863
+ case ".": {
1864
+ const [file] = values;
1865
+ if (isDash && file != null && !file.includes("/")) report(0, LINUX_PLATFORMS, {
1866
+ reason: "dash only looks for the file in `PATH`, not in the current directory",
1867
+ suggestion: `Use \`. ./${truncate(file)}\` instead.`
1868
+ }, replaceArgument(0, `./${textOf(0)}`));
1869
+ break;
1870
+ }
1871
+ case "[":
1872
+ case "test": {
1873
+ const index = values.indexOf("==");
1874
+ if (isDash && index !== -1) report(index, LINUX_PLATFORMS, {
1875
+ reason: `${DASH} only supports \`=\` for comparing strings`,
1876
+ suggestion: "Use `=` instead.",
1877
+ usage: name === "[" ? "[ ... == ... ]" : "test ... == ..."
1878
+ }, replaceArgument(index, "="));
1879
+ break;
1880
+ }
1881
+ case "bash":
1882
+ case "shopt": {
1883
+ const option = name === "bash" ? "-O" : "-s";
1884
+ const index = optionIndex((value, valueIndex) => value === "globstar" && values.slice(0, valueIndex).includes(option));
1885
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1886
+ reason: "macOS ships Bash 3.2, which doesn't have the `globstar` option",
1887
+ suggestion: "Quote globs with escaped double quotes (`\\\"`) and let the tool expand them instead.",
1888
+ usage: `${name} ${option} globstar`
1889
+ });
1890
+ break;
1891
+ }
1892
+ case "base64": {
1893
+ const index = optionIndex((value) => isShortOptionCluster(value, "w"));
1894
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1895
+ reason: "BSD `base64` uses `-b` to wrap lines",
1896
+ suggestion: NODE_SCRIPT_SUGGESTION
1897
+ });
1898
+ break;
1899
+ }
1900
+ case "cp": {
1901
+ const index = optionIndex((value) => isShortOptionCluster(value, "t"));
1902
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1903
+ reason: "BSD `cp` doesn't support `-t`",
1904
+ suggestion: "Put the target directory last instead."
1905
+ });
1906
+ break;
1907
+ }
1908
+ case "date": {
1909
+ const index = optionIndex((value) => value.startsWith("-d"));
1910
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1911
+ reason: "BSD `date` uses `-j -f` to parse dates",
1912
+ suggestion: NODE_SCRIPT_SUGGESTION
1913
+ });
1914
+ break;
1915
+ }
1916
+ case "dir": {
1917
+ const index = optionIndex((value) => CMD_OPTION.test(value));
1918
+ if (index !== -1) report(index, LINUX_PLATFORMS, {
1919
+ reason: `\`${values[index] || ""}\` is a cmd.exe option`,
1920
+ suggestion: NODE_SCRIPT_SUGGESTION
1921
+ });
1922
+ break;
1923
+ }
1924
+ case "find": {
1925
+ const start = values.findIndex((value) => value == null || !BSD_FIND_OPTIONS.test(value));
1926
+ const primary = values.findIndex((value) => value != null && GNU_FIND_PRIMARIES.has(value));
1927
+ if (values[start]?.startsWith("-")) report(start, MACOS_PLATFORMS, {
1928
+ reason: "BSD `find` requires a starting path",
1929
+ suggestion: "Add `.` before the expression.",
1930
+ usage: `find ${values[start] || ""}`
1931
+ }, {
1932
+ argumentIndex: start,
1933
+ description: "Add `.` before the expression.",
1934
+ text: `. ${textOf(start)}`
1935
+ });
1936
+ else if (primary !== -1) report(primary, MACOS_PLATFORMS, {
1937
+ reason: `BSD \`find\` doesn't support \`${values[primary] || ""}\``,
1938
+ suggestion: NODE_SCRIPT_SUGGESTION
1939
+ });
1940
+ break;
1941
+ }
1942
+ case "fuser": {
1943
+ const index = optionIndex((value) => isShortOptionCluster(value, "k"));
1944
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1945
+ reason: "macOS' `fuser` doesn't support `-k`",
1946
+ suggestion: NODE_SCRIPT_SUGGESTION
1947
+ });
1948
+ break;
1949
+ }
1950
+ case "grep": {
1951
+ const index = optionIndex((value) => isShortOptionCluster(value, "P") || value === "--perl-regexp");
1952
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1953
+ reason: "BSD `grep` doesn't support Perl-compatible regular expressions",
1954
+ suggestion: "Use `grep -E` or a Node.js script instead."
1955
+ });
1956
+ break;
1957
+ }
1958
+ case "du": {
1959
+ const index = optionIndex((value) => isShortOptionCluster(value, "b"));
1960
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1961
+ reason: "BSD `du` doesn't support `-b`",
1962
+ suggestion: NODE_SCRIPT_SUGGESTION
1963
+ });
1964
+ break;
1965
+ }
1966
+ case "echo": {
1967
+ const [first] = values;
1968
+ if (isDash && first != null && ECHO_OPTIONS.test(first)) {
1969
+ const isInterpretsEscapes = first.toLowerCase().includes("e");
1970
+ report(0, isInterpretsEscapes ? PLATFORMS : NOT_MACOS_OR_WINDOWS, {
1971
+ reason: isInterpretsEscapes ? "`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",
1972
+ suggestion: NODE_SCRIPT_SUGGESTION,
1973
+ syntax: `\`echo ${first}\``
1974
+ });
1975
+ }
1976
+ break;
1977
+ }
1978
+ case "head": {
1979
+ const index = optionIndex((value, valueIndex) => HEAD_NEGATIVE_COUNT_OPTION.test(value) || HEAD_COUNT_OPTION.test(value) && NEGATIVE_NUMBER.test(values[valueIndex + 1] || ""));
1980
+ if (index !== -1) {
1981
+ const countIndex = HEAD_COUNT_OPTION.test(values[index] || "") ? index + 1 : index;
1982
+ report(countIndex, MACOS_PLATFORMS, {
1983
+ reason: "BSD `head` doesn't support negative counts",
1984
+ suggestion: NODE_SCRIPT_SUGGESTION,
1985
+ usage: `head ${values.slice(index, countIndex + 1).join(" ")}`
1986
+ });
1987
+ }
1988
+ break;
1989
+ }
1990
+ case "ln": {
1991
+ const index = optionIndex((value) => isShortOptionCluster(value, "r"));
1992
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
1993
+ reason: "BSD `ln` doesn't support `-r`",
1994
+ suggestion: NODE_SCRIPT_SUGGESTION
1995
+ });
1996
+ break;
1997
+ }
1998
+ case "mkdir":
1999
+ case "rmdir": {
2000
+ const suggestion = lowerCaseName === "mkdir" ? NODE_SCRIPT_SUGGESTION : RIMRAF_SUGGESTION;
2001
+ if (portable) {
2002
+ reportCommand(WINDOWS_PLATFORMS, suggestion);
2003
+ break;
2004
+ }
2005
+ const windowsOption = optionIndex((value) => RMDIR_CMD_OPTION.test(value));
2006
+ if (lowerCaseName === "rmdir" && windowsOption !== -1) {
2007
+ report(windowsOption, POSIX_PLATFORMS, {
2008
+ reason: `\`${values[windowsOption] || ""}\` is a cmd.exe option`,
2009
+ suggestion
2010
+ });
2011
+ break;
2012
+ }
2013
+ const posixOption = optionIndex((value) => POSIX_OPTION.test(value));
2014
+ if (posixOption !== -1) {
2015
+ report(posixOption, WINDOWS_PLATFORMS, {
2016
+ reason: `cmd.exe's \`${name}\` doesn't support POSIX options`,
2017
+ suggestion
2018
+ });
2019
+ break;
2020
+ }
2021
+ const pathWithSlash = values.findIndex((value, index) => value != null && !value.startsWith("-") && value.includes("/") && !textOf(index).startsWith("\""));
2022
+ if (pathWithSlash !== -1) report(pathWithSlash, WINDOWS_PLATFORMS, {
2023
+ reason: `cmd.exe's \`${name}\` treats \`/\` as an option prefix`,
2024
+ suggestion
2025
+ });
2026
+ break;
2027
+ }
2028
+ case "sed": {
2029
+ const isExtended = optionIndex((value) => SED_EXTENDED_OPTION.test(value) || value === "--regexp-extended") !== -1;
2030
+ const findEscape = (value) => value == null || value.startsWith("-") ? void 0 : (GNU_SED_ESCAPE.exec(value) || (isExtended ? null : GNU_SED_BASIC_ESCAPE.exec(value)))?.[0];
2031
+ const escapeIndex = values.findIndex((value) => findEscape(value) != null);
2032
+ if (escapeIndex !== -1) report(escapeIndex, MACOS_PLATFORMS, {
2033
+ reason: "BSD `sed` doesn't support it, so the pattern doesn't match",
2034
+ suggestion: "Use POSIX regex syntax (e.g. `[[:space:]]`, or `+` with `sed -E`) instead.",
2035
+ syntax: `The GNU regex escape \`${findEscape(values[escapeIndex]) || ""}\``
2036
+ });
2037
+ const index = optionIndex((value) => SED_IN_PLACE_OPTION.test(value));
2038
+ if (index === -1) break;
2039
+ if (values[index + 1]?.length === 0) report(index + 1, LINUX_PLATFORMS, {
2040
+ reason: "GNU `sed` treats the empty backup suffix as the script",
2041
+ suggestion: "Use an attached suffix (e.g. `-i.bak`) or a Node.js script instead.",
2042
+ usage: `sed ${values[index] || ""} ''`
2043
+ });
2044
+ else report(index, MACOS_PLATFORMS, {
2045
+ reason: "BSD `sed` requires a backup suffix argument after `-i`",
2046
+ suggestion: "Use an attached suffix (e.g. `-i.bak`) or a Node.js script instead."
2047
+ });
2048
+ break;
2049
+ }
2050
+ case "set": {
2051
+ const [first] = values;
2052
+ const pipefail = optionIndex((value, index) => value === "pipefail" && SET_NAMED_OPTION.test(values[index - 1] || ""));
2053
+ if (isDash && pipefail !== -1) report(pipefail, LINUX_PLATFORMS, {
2054
+ reason: `${DASH} doesn't support \`pipefail\``,
2055
+ suggestion: "Remove it or use a Node.js script instead.",
2056
+ usage: "set -o pipefail"
2057
+ });
2058
+ if (first == null) break;
2059
+ if (SET_SHELL_OPTIONS.test(first)) report(0, WINDOWS_PLATFORMS, {
2060
+ reason: "cmd.exe's `set` manages environment variables instead of shell options",
2061
+ suggestion: "Remove it or use a Node.js script instead."
2062
+ });
2063
+ else if (ASSIGNMENT.test(first)) report(0, portable ? PLATFORMS : POSIX_PLATFORMS, {
2064
+ reason: "POSIX shells don't set environment variables with `set`",
2065
+ suggestion: CROSS_ENV_SUGGESTION,
2066
+ syntax: `\`set ${truncate(first)}\``
2067
+ });
2068
+ break;
2069
+ }
2070
+ case "sort": {
2071
+ const index = optionIndex((value) => POSIX_OPTION.test(value));
2072
+ if (index !== -1) report(index, WINDOWS_PLATFORMS, {
2073
+ reason: "Windows' `sort` command uses `/` options",
2074
+ suggestion: NODE_SCRIPT_SUGGESTION
2075
+ });
2076
+ break;
2077
+ }
2078
+ case "stat": {
2079
+ const index = optionIndex((value) => STAT_FORMAT_OPTION.test(value));
2080
+ if (index === -1) break;
2081
+ if (values[index]?.startsWith("-c")) report(index, MACOS_PLATFORMS, {
2082
+ reason: "BSD `stat` uses `-f` to specify the format",
2083
+ suggestion: NODE_SCRIPT_SUGGESTION
2084
+ });
2085
+ else report(index, LINUX_PLATFORMS, {
2086
+ reason: "GNU `stat -f` displays file system status instead of formatting the output",
2087
+ suggestion: NODE_SCRIPT_SUGGESTION,
2088
+ syntax: "`stat -f`"
2089
+ });
2090
+ break;
2091
+ }
2092
+ case "trap": {
2093
+ const index = values.findIndex((value, valueIndex) => valueIndex > 0 && value != null && BASH_TRAP_CONDITIONS.has(value));
2094
+ if (isDash && index !== -1) report(index, LINUX_PLATFORMS, {
2095
+ reason: `${DASH} doesn't support the \`${values[index] || ""}\` condition, so it ignores the trap`,
2096
+ suggestion: NODE_SCRIPT_SUGGESTION,
2097
+ syntax: `\`trap ... ${values[index] || ""}\``
2098
+ });
2099
+ break;
2100
+ }
2101
+ case "xargs": {
2102
+ const index = optionIndex((value) => GNU_XARGS_OPTION.test(value));
2103
+ if (index !== -1) report(index, MACOS_PLATFORMS, {
2104
+ reason: "BSD `xargs` doesn't support this GNU option",
2105
+ suggestion: NODE_SCRIPT_SUGGESTION
2106
+ });
2107
+ break;
2108
+ }
2109
+ case "timeout": if (TIMEOUT_CMD_OPTION.test(values[0] || "")) report(0, POSIX_PLATFORMS, {
2110
+ reason: "`/t` is an option of Windows' `timeout` command",
2111
+ suggestion: NODE_SCRIPT_SUGGESTION
2112
+ });
2113
+ else reportCommand(NOT_MACOS_OR_WINDOWS, NODE_SCRIPT_SUGGESTION);
2114
+ }
2115
+ return issues;
2116
+ };
2117
+ // src/fixes.ts
2118
+ const LINE_WHITESPACE = /[\t ]/;
2119
+ const LINE_BREAK = /^\r?\n/;
2120
+ /** Options of `rm` that `rimraf` doesn't need, e.g. `-rf` */
2121
+ const RM_OPTION = /^(?:-[Rfr]+|--force|--recursive)$/;
2122
+ /** A binary of a dependency, which package managers add to `PATH` */
2123
+ const DEPENDENCY_BINARY = /^(?:\.\/)?node_modules\/\.bin\/([^/]+)$/;
2124
+ const JAVASCRIPT_FILE = /\.[cm]?js$/;
2125
+ /** A brace expansion of plain alternatives, e.g. `{a,b}` */
2126
+ const SIMPLE_BRACE_EXPANSION = /^\{([\w+\-./@]*(?:,[\w+\-./@]*)+)\}$/;
2127
+ const PLAIN_TEXT = /^[\w+\-./:=@]*$/;
2128
+ /** Creates a fix that replaces a piece of the script */
2129
+ const replacement = (node, original, text) => ({
2130
+ description: describeReplacement(original, text),
2131
+ edits: [{
2132
+ end: node.end,
2133
+ pos: node.pos,
2134
+ text
2135
+ }]
2136
+ });
2137
+ /** Creates a fix that wraps a word in double quotes */
2138
+ const quoting = (word, description) => ({
2139
+ description,
2140
+ edits: [{
2141
+ end: word.pos,
2142
+ pos: word.pos,
2143
+ text: "\""
2144
+ }, {
2145
+ end: word.end,
2146
+ pos: word.end,
2147
+ text: "\""
2148
+ }]
2149
+ });
2150
+ /**
2151
+ * Creates an edit that removes a piece of a script, along with the whitespace that separates it.
2152
+ * @param source The script
2153
+ * @param pos Start offset of the piece
2154
+ * @param end End offset (exclusive) of the piece
2155
+ * @returns The edit
2156
+ */
2157
+ const removal = (source, pos, end) => {
2158
+ let start = pos;
2159
+ let stop = end;
2160
+ while (start > 0 && LINE_WHITESPACE.test(source.charAt(start - 1))) start--;
2161
+ if (start === 0 || source[start - 1] === "\n") {
2162
+ while (stop < source.length && LINE_WHITESPACE.test(source.charAt(stop))) stop++;
2163
+ const lineBreak = LINE_BREAK.exec(source.slice(stop))?.[0];
2164
+ if (lineBreak) stop += lineBreak.length;
2165
+ else if (stop === source.length && start > 0) start -= source[start - 2] === "\r" ? 2 : 1;
2166
+ }
2167
+ return {
2168
+ end: stop,
2169
+ pos: start,
2170
+ text: ""
2171
+ };
2172
+ };
2173
+ /**
2174
+ * Gets a fix for a command that isn't available on all platforms, e.g. `rimraf` for `rm -rf`.
2175
+ * @param name Name that the command was invoked with, e.g. `rm`
2176
+ * @param nameWord Word that the name comes from
2177
+ * @param argumentWords The words that follow it
2178
+ * @param source The source that node positions refer to
2179
+ * @returns The fix, if there's a replacement that works the same
2180
+ */
2181
+ const commandFix = (name, nameWord, argumentWords, source) => {
2182
+ const first = argumentWords.at(0);
2183
+ switch (name) {
2184
+ case "env": return first && ASSIGNMENT.test(first.text) && argumentWords.some((word) => !ASSIGNMENT.test(word.text)) ? replacement(nameWord, nameWord.text, "cross-env") : void 0;
2185
+ case "rm": {
2186
+ const optionCount = argumentWords.findIndex((word) => !RM_OPTION.test(staticValue(word) || ""));
2187
+ const paths = optionCount === -1 ? [] : argumentWords.slice(optionCount);
2188
+ const globs = paths.filter((word) => word.parts?.some((part) => GLOB_PART_TYPES.includes(part.type)));
2189
+ if (paths.length === 0 || paths.some((word) => staticValue(word)?.startsWith("-") && word.text !== "--") || globs.some((word) => !isPlainWord(word, GLOB_PART_TYPES))) return;
2190
+ const end = argumentWords[optionCount - 1]?.end || nameWord.end;
2191
+ const original = source.slice(nameWord.pos, end);
2192
+ return globs.length === 0 ? replacement({
2193
+ end,
2194
+ pos: nameWord.pos
2195
+ }, original, "rimraf") : {
2196
+ description: `Replace \`${truncate(original)}\` with \`rimraf --glob\`, and quote the globs.`,
2197
+ edits: [{
2198
+ end,
2199
+ pos: nameWord.pos,
2200
+ text: "rimraf --glob"
2201
+ }, ...globs.flatMap((word) => quoting(word, "").edits)]
2202
+ };
2203
+ }
2204
+ case "source": {
2205
+ const file = first && staticValue(first);
2206
+ if (!first || file == null) return;
2207
+ const range = {
2208
+ end: first.end,
2209
+ pos: nameWord.pos
2210
+ };
2211
+ return replacement(range, source.slice(range.pos, range.end), `. ${file.includes("/") ? "" : "./"}${first.text}`);
2212
+ }
2213
+ default: return;
2214
+ }
2215
+ };
2216
+ /**
2217
+ * Gets a fix for running a command by its path, e.g. `node ./build.js` for `./build.js`.
2218
+ * @param name Path that the command was invoked with
2219
+ * @param nameWord Word that the path comes from
2220
+ * @returns The fix, if the path is a dependency's binary or a JavaScript file
2221
+ */
2222
+ const pathCommandFix = (name, nameWord) => {
2223
+ const binary = DEPENDENCY_BINARY.exec(name)?.[1];
2224
+ if (binary) return replacement(nameWord, nameWord.text, binary);
2225
+ return JAVASCRIPT_FILE.test(name) ? {
2226
+ description: "Run the file with `node`.",
2227
+ edits: [{
2228
+ end: nameWord.pos,
2229
+ pos: nameWord.pos,
2230
+ text: "node "
2231
+ }]
2232
+ } : void 0;
2233
+ };
2234
+ /**
2235
+ * Gets a fix that expands a brace expansion, e.g. `dist/a dist/b` for `dist/{a,b}`.
2236
+ * @param word The word that contains the brace expansion
2237
+ * @param part Brace expansion in the word, e.g. `{a,b}`
2238
+ * @returns The fix, if the word only consists of plain text and the brace expansion
2239
+ */
2240
+ const braceExpansionFix = (word, part) => {
2241
+ const alternatives = SIMPLE_BRACE_EXPANSION.exec(part.text)?.[1]?.split(",");
2242
+ const isPlain = (word.parts || []).every((other) => other === part || other.type === "Literal" && PLAIN_TEXT.test(other.text));
2243
+ if (!alternatives || !isPlain) return;
2244
+ const prefix = word.text.slice(0, part.pos - word.pos);
2245
+ const suffix = word.text.slice(part.end - word.pos);
2246
+ return replacement(word, word.text, alternatives.map((alternative) => `${prefix}${alternative}${suffix}`).join(" "));
2247
+ };
2248
+ /**
2249
+ * Checks whether making a statement part of an AND list with the previous one only stops it after
2250
+ * a failure.
2251
+ * @param next The statement that follows
2252
+ * @returns Whether the rest of the logic stays the same, e.g. not for `a; b || c`, which would run
2253
+ * `c` when `a` fails
2254
+ */
2255
+ const canChain = (next) => !next.background && !(next.command.type === "AndOr" && next.command.operators.includes("||"));
2256
+ /**
2257
+ * Gets a fix for a line break that separates commands.
2258
+ * @param gapStart Where the text between the commands starts
2259
+ * @param gap The text between the commands, including the line break
2260
+ * @param next The statement that follows it
2261
+ * @returns The fix, if the text is only whitespace and the rest of the logic stays the same
2262
+ */
2263
+ const lineBreakFix = (gapStart, gap, next) => gap.trim().length === 0 && canChain(next) ? {
2264
+ description: "Replace the line break with `&&`, which stops at the first failing command.",
2265
+ edits: [{
2266
+ end: next.pos,
2267
+ pos: gapStart,
2268
+ text: " && "
2269
+ }]
2270
+ } : void 0;
2271
+ /**
2272
+ * Gets a fix that joins the lines of a command, e.g. after `||` or a `\` line continuation.
2273
+ * @param source The source that the command is in
2274
+ * @param position Where the line break is
2275
+ * @param end Where the whitespace after the line break ends
2276
+ * @returns The fix, which keeps the command the same in POSIX shells
2277
+ */
2278
+ const joinLinesFix = (source, position, end) => {
2279
+ return {
2280
+ description: "Join the lines.",
2281
+ edits: [source[position - 1] === "\\" ? {
2282
+ end: position + 1,
2283
+ pos: position - 1,
2284
+ text: ""
2285
+ } : {
2286
+ end,
2287
+ pos: position,
2288
+ text: " "
2289
+ }]
2290
+ };
2291
+ };
2292
+ /**
2293
+ * Gets a fix for a `;` that separates commands.
2294
+ * @param range Where the `;` is
2295
+ * @param gap The text between the commands, including the `;`
2296
+ * @param next The statement that follows it, if any
2297
+ * @returns The fix, unless the statement that follows has alternatives (`||`) or runs in the
2298
+ * background
2299
+ */
2300
+ const semicolonFix = (range, gap, next) => {
2301
+ if (!next) return {
2302
+ description: "Remove the `;`.",
2303
+ edits: [{
2304
+ ...range,
2305
+ text: ""
2306
+ }]
2307
+ };
2308
+ return gap.trim() === ";" && canChain(next) ? {
2309
+ description: "Replace `;` with `&&`, which stops at the first failing command.",
2310
+ edits: [{
2311
+ end: next.pos,
2312
+ pos: range.pos - gap.indexOf(";"),
2313
+ text: " && "
2314
+ }]
2315
+ } : void 0;
2316
+ };
2317
+ /**
2318
+ * Applies a fix to the script that it was found in.
2319
+ * @param script Text of the script to change
2320
+ * @param fix A fix from `analyzeScript`
2321
+ * @returns The fixed script
2322
+ */
2323
+ const applyFix = (script, fix) => fix.edits.toSorted((left, right) => right.pos - left.pos).reduce((result, { end, pos, text }) => result.slice(0, pos) + text + result.slice(end), script);
2324
+ // src/command-checker.ts
2325
+ const MAX_DEPTH = 10;
2326
+ /** Where Yarn v1 replaces `/` with `\` in a command's name: at the start and after an operator */
2327
+ const YARN_COMMAND_START = /(?:^|&&|&|\|\||\|)\s*$/;
2328
+ /**
2329
+ * Checks whether a name is a package spec rather than a path, e.g. `@scope/name` or
2330
+ * `github:user/repo` (for `npx`)
2331
+ */
2332
+ const isPackageSpec = (name) => name.startsWith("@") || name.includes(":");
2333
+ const SHELL_SCRIPT = /\.(?:bash|command|sh|zsh)$/;
2334
+ const WINDOWS_SCRIPT = /\.(?:bat|cmd|exe|ps1|vbs)$/i;
2335
+ /** Exit statuses of commands that `exit` can replace at the end of a script */
2336
+ const EXIT_STATUSES = /* @__PURE__ */ new Map([
2337
+ [":", "0"],
2338
+ ["false", "1"],
2339
+ ["true", "0"]
2340
+ ]);
2341
+ /** Options of pnpm and aube that make the command and its arguments a shell line */
2342
+ const SHELL_MODE_OPTIONS = /* @__PURE__ */ new Set(["--shell-mode", "-c"]);
2343
+ /**
2344
+ * Finds the command that a command runs, e.g. `rm` in `cross-env A=1 rm -rf dist`.
2345
+ * @param values The static values of the outer command's arguments
2346
+ * @param start Index of the first argument to consider
2347
+ * @param valueOptions Options of the outer command that take a value
2348
+ * @param shouldSkipAssignments Whether to skip `NAME=value` arguments
2349
+ * @returns Index of the nested command's name, or -1 if there is none
2350
+ */
2351
+ const findCommandIndex = (values, start, valueOptions, shouldSkipAssignments = false) => {
2352
+ for (let index = start; index < values.length; index++) {
2353
+ const value = values[index];
2354
+ if (value == null) return index;
2355
+ if (value === "--") return index + 1;
2356
+ if (value.startsWith("-") && value.length > 1) {
2357
+ if (valueOptions.includes(value)) index++;
2358
+ continue;
2359
+ }
2360
+ if (!(shouldSkipAssignments && ASSIGNMENT.test(value))) return index;
2361
+ }
2362
+ return -1;
2363
+ };
2364
+ const isCommandOption = (value) => isShortOptionCluster(value, "c");
2365
+ /** Checks commands, e.g. whether they're available everywhere, and the commands they run */
2366
+ var CommandChecker = class {
2367
+ #analyzeNestedWords;
2368
+ #dependencies;
2369
+ #ignoredCommands;
2370
+ /** Fixes that depend on where a command is, by the command's name, e.g. `exit 0` for `true` */
2371
+ #positionalFixes = /* @__PURE__ */ new Map();
2372
+ #reporter;
2373
+ constructor(reporter, { dependencies = [], ignoreCommands = [] }, analyzeNestedWords) {
2374
+ this.#reporter = reporter;
2375
+ this.#dependencies = new Set(dependencies);
2376
+ this.#ignoredCommands = new Set(ignoreCommands);
2377
+ this.#analyzeNestedWords = analyzeNestedWords;
2378
+ }
2379
+ /**
2380
+ * Adds fixes for commands that end the script, which can change what follows them.
2381
+ * @param statements Top-level statements of a script
2382
+ */
2383
+ addPositionalFixes(statements) {
2384
+ const last = statements.at(-1);
2385
+ if (!last || last.background) return;
2386
+ const list = last.command;
2387
+ const commands = list.type === "AndOr" ? list.commands : [list];
2388
+ const final = commands.at(-1);
2389
+ if (final?.type === "Command" && final.name && final.prefix.length === 0 && final.suffix.length === 0) {
2390
+ const status = EXIT_STATUSES.get(staticValue(final.name) || "");
2391
+ if (status != null) this.#positionalFixes.set(final.name, replacement(final.name, final.name.text, `exit ${status}`));
2392
+ }
2393
+ const [exporting, command] = commands;
2394
+ 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, {
2395
+ description: "Replace `export ... &&` with `cross-env`.",
2396
+ edits: [{
2397
+ end: exporting.name.end,
2398
+ pos: exporting.name.pos,
2399
+ text: "cross-env"
2400
+ }, {
2401
+ end: command.pos,
2402
+ pos: exporting.end,
2403
+ text: " "
2404
+ }]
2405
+ });
2406
+ }
2407
+ #checkCommandAvailability(name, nameWord, argumentWords, context) {
2408
+ if (name === "del" && this.#dependencies.has("del-cli")) return this.#reporter.report(context, nameWord, "inconsistentBehavior", {
2409
+ reason: "cmd.exe's builtin `del` takes precedence over del-cli's `del` binary",
2410
+ suggestion: "Use `del-cli` instead.",
2411
+ syntax: "`del`"
2412
+ }, WINDOWS_PLATFORMS, replacement(nameWord, nameWord.text, "del-cli"));
2413
+ if (context.portable && PORTABLE_SHELL_BUILTINS.has(name)) return [];
2414
+ const lowerCaseName = name.toLowerCase();
2415
+ let info = COMMANDS.get(name);
2416
+ if (!info) {
2417
+ const windowsInfo = COMMANDS.get(lowerCaseName);
2418
+ if (windowsInfo && !windowsInfo.platforms.includes("win32")) info = windowsInfo;
2419
+ }
2420
+ if (!info) return [];
2421
+ let { platforms } = info;
2422
+ if (info.bashBuiltin && context.shell === "bash") platforms = platforms.filter((platform) => platform !== "linux");
2423
+ if (context.portable && CMD_BUILTINS.has(lowerCaseName)) platforms = PLATFORMS;
2424
+ return this.#reporter.report(context, nameWord, "unsupportedCommand", {
2425
+ command: name,
2426
+ suggestion: info.suggestion
2427
+ }, platforms, this.#positionalFixes.get(nameWord) || commandFix(name, nameWord, argumentWords, context.source));
2428
+ }
2429
+ /**
2430
+ * Checks a command and the commands that it runs.
2431
+ * @param nameWord The command's name, e.g. `rm`
2432
+ * @param argumentWords The words that follow it
2433
+ * @param context Where the command is
2434
+ * @param depth How many commands run this command, e.g. 1 for `rm` in `cross-env A=1 rm`
2435
+ * @param isCrossSpawned Whether cross-spawn runs the command (in `cross-env`), which works with
2436
+ * paths and shebangs on Windows
2437
+ * @returns What the command is, and what it runs
2438
+ */
2439
+ checkInvocation(nameWord, argumentWords, context, depth, isCrossSpawned = false) {
2440
+ const name = staticValue(nameWord);
2441
+ const result = {
2442
+ crossEnv: name === "cross-env" || name === "cross-env-shell",
2443
+ name,
2444
+ target: name
2445
+ };
2446
+ if (name == null || depth > MAX_DEPTH) return result;
2447
+ if (this.#ignoredCommands.has(name)) {
2448
+ result.target = this.#checkWrapped(name, argumentWords, context, depth)?.target ?? name;
2449
+ return result;
2450
+ }
2451
+ const covered = [];
2452
+ if (SHELL_SCRIPT.test(name)) covered.push(...this.#reporter.report(context, nameWord, "unsupportedCommand", {
2453
+ command: truncate(nameWord.text),
2454
+ suggestion: SHELL_SCRIPT_SUGGESTION
2455
+ }, WINDOWS_PLATFORMS));
2456
+ else if (WINDOWS_SCRIPT.test(name)) covered.push(...this.#reporter.report(context, nameWord, "unsupportedCommand", {
2457
+ command: truncate(nameWord.text),
2458
+ suggestion: NODE_SCRIPT_SUGGESTION
2459
+ }, POSIX_PLATFORMS));
2460
+ else if (name.includes("/") && !isPackageSpec(name)) {
2461
+ const isConverted = context.convertsSlashes && depth === 0 && DEPENDENCY_BINARY.test(name) && YARN_COMMAND_START.test(context.source.slice(0, nameWord.pos));
2462
+ if (!isCrossSpawned && !isConverted) covered.push(...this.#reporter.reportSyntax(context, nameWord, "posix", true, "unsupportedSyntax", {
2463
+ suggestion: "cmd.exe treats `/` as an option prefix; run files with `node`, and binaries by their name instead.",
2464
+ syntax: `Running a command by its path (\`${truncate(nameWord.text)}\`)`
2465
+ }, pathCommandFix(name, nameWord)));
2466
+ } else covered.push(...this.#checkCommandAvailability(name, nameWord, argumentWords, context));
2467
+ covered.push(...this.#checkUsage(name, nameWord, argumentWords, context));
2468
+ result.target = this.#checkWrapped(name, argumentWords, withCovered(context, covered), depth)?.target ?? name;
2469
+ return result;
2470
+ }
2471
+ #checkUsage(name, nameWord, argumentWords, context) {
2472
+ const values = argumentWords.map(staticValue);
2473
+ const wrapperValueOptions = WRAPPER_VALUE_OPTIONS.get(name);
2474
+ const commandIndex = wrapperValueOptions ? findCommandIndex(values, 0, wrapperValueOptions) : -1;
2475
+ const optionsEnd = Math.min(values.includes("--") ? values.indexOf("--") : values.length, commandIndex === -1 ? values.length : commandIndex);
2476
+ return checkCommandUsage(name, argumentWords.map((argument, index) => ({
2477
+ text: argument.text,
2478
+ value: values[index]
2479
+ })), {
2480
+ bash: context.shell === "bash",
2481
+ optionsEnd,
2482
+ portable: context.portable
2483
+ }).flatMap(({ argumentIndex, data, fix, messageId, platforms }) => {
2484
+ const fixedWord = fix && argumentWords[fix.argumentIndex];
2485
+ return this.#reporter.report(context, argumentIndex == null ? nameWord : {
2486
+ end: argumentWords[argumentIndex]?.end || nameWord.end,
2487
+ pos: nameWord.pos
2488
+ }, messageId, data, platforms, fix && fixedWord ? {
2489
+ description: fix.description,
2490
+ edits: [{
2491
+ end: fixedWord.end,
2492
+ pos: fixedWord.pos,
2493
+ text: fix.text
2494
+ }]
2495
+ } : void 0);
2496
+ });
2497
+ }
2498
+ #checkWrapped(name, argumentWords, context, depth) {
2499
+ const values = argumentWords.map(staticValue);
2500
+ const invoke = (index, nestedContext = context, isCrossSpawned = false) => {
2501
+ const word = argumentWords[index];
2502
+ return !word || values[index] === "." ? void 0 : this.checkInvocation(word, argumentWords.slice(index + 1), nestedContext, depth + 1, isCrossSpawned);
2503
+ };
2504
+ const nestedShellString = (index, shell = "native", bashOptions) => {
2505
+ const word = argumentWords[index];
2506
+ if (word && depth < MAX_DEPTH) this.#analyzeNestedWords([word], context, {
2507
+ bashOptions,
2508
+ crossEnv: false,
2509
+ maskScriptGlobs: name === "concurrently",
2510
+ shell
2511
+ });
2512
+ };
2513
+ const nestedShellLine = (index, isCrossEnv = false) => {
2514
+ if (index !== -1 && depth < MAX_DEPTH) this.#analyzeNestedWords(argumentWords.slice(index), context, {
2515
+ crossEnv: isCrossEnv,
2516
+ shell: "native"
2517
+ });
2518
+ };
2519
+ const commandStringIndex = () => {
2520
+ const index = values.findIndex((value) => value != null && isCommandOption(value));
2521
+ return index === -1 ? -1 : index + 1;
2522
+ };
2523
+ const callIndex = (start, valueOptions) => {
2524
+ const commandIndex = findCommandIndex(values, start, [
2525
+ ...valueOptions,
2526
+ "--call",
2527
+ "-c"
2528
+ ]);
2529
+ const end = commandIndex === -1 ? values.length : commandIndex;
2530
+ const index = values.findIndex((value, i) => i >= start && i < end && (value === "-c" || value === "--call"));
2531
+ return index === -1 ? -1 : index + 1;
2532
+ };
2533
+ const shellModeIndex = (start, valueOptions) => {
2534
+ const commandIndex = findCommandIndex(values, start, valueOptions);
2535
+ return values.slice(start, commandIndex === -1 ? values.length : commandIndex).some((value) => value != null && SHELL_MODE_OPTIONS.has(value)) ? commandIndex : -1;
2536
+ };
2537
+ switch (name) {
2538
+ case "bash":
2539
+ case "ksh":
2540
+ case "zsh":
2541
+ nestedShellString(commandStringIndex(), "bash", new Set(values.filter((value, index) => Boolean(value) && values[index - 1] === "-O")));
2542
+ return;
2543
+ case "concurrently":
2544
+ argumentWords.forEach((argument, index) => {
2545
+ if (argument.parts?.some((part) => part.type === "DoubleQuoted" || part.type === "SingleQuoted") && WHITESPACE.test(argument.value)) nestedShellString(index);
2546
+ });
2547
+ return;
2548
+ case "cross-env":
2549
+ case "cross-env-shell": {
2550
+ const index = values.findIndex((value) => value == null || !ASSIGNMENT.test(value));
2551
+ if (name === "cross-env") return invoke(index, {
2552
+ ...context,
2553
+ crossEnv: true
2554
+ }, true);
2555
+ nestedShellLine(index, true);
2556
+ return;
2557
+ }
2558
+ case "dash":
2559
+ case "sh":
2560
+ nestedShellString(commandStringIndex(), "sh");
2561
+ return;
2562
+ case "aube":
2563
+ case "bun":
2564
+ case "npm":
2565
+ case "pnpm":
2566
+ case "upm":
2567
+ case "yarn": {
2568
+ const subcommand = findCommandIndex(values, 0, PACKAGE_MANAGER_VALUE_OPTIONS);
2569
+ if (!EXEC_SUBCOMMANDS[name].includes(values[subcommand] || "")) return;
2570
+ if (name === "npm" || name === "upm") {
2571
+ const call = callIndex(subcommand + 1, EXEC_VALUE_OPTIONS);
2572
+ if (call !== -1) {
2573
+ nestedShellString(call);
2574
+ return;
2575
+ }
2576
+ } else if (name === "aube" || name === "pnpm") {
2577
+ const shellLine = shellModeIndex(subcommand + 1, EXEC_VALUE_OPTIONS);
2578
+ if (shellLine !== -1) {
2579
+ nestedShellLine(shellLine);
2580
+ return;
2581
+ }
2582
+ }
2583
+ return invoke(findCommandIndex(values, subcommand + 1, EXEC_VALUE_OPTIONS));
2584
+ }
2585
+ case "npx":
2586
+ case "upx": {
2587
+ const call = callIndex(0, WRAPPER_VALUE_OPTIONS.get(name) || []);
2588
+ if (call !== -1) {
2589
+ nestedShellString(call);
2590
+ return;
2591
+ }
2592
+ break;
2593
+ }
2594
+ case "aubx":
2595
+ case "pnpx": {
2596
+ const shellLine = shellModeIndex(0, WRAPPER_VALUE_OPTIONS.get(name) || []);
2597
+ if (shellLine !== -1) {
2598
+ nestedShellLine(shellLine);
2599
+ return;
2600
+ }
2601
+ break;
2602
+ }
2603
+ }
2604
+ const valueOptions = WRAPPER_VALUE_OPTIONS.get(name);
2605
+ return !valueOptions || name === "command" && values.some((value) => value === "-v" || value === "-V") ? void 0 : invoke(findCommandIndex(values, 0, valueOptions, name === "env"));
2606
+ }
2607
+ };
2608
+ // src/line-break-checker.ts
2609
+ const ONE_LINE_SUGGESTION = "Put the command on one line instead.";
2610
+ /** Checks line breaks, after which cmd.exe ignores the rest of the script */
2611
+ var LineBreakChecker = class {
2612
+ /** Ranges of reported line breaks in the analyzed script, e.g. to skip them in nested scripts */
2613
+ #lineBreaks = [];
2614
+ #multilineSources = /* @__PURE__ */ new Set();
2615
+ #reporter;
2616
+ constructor(reporter) {
2617
+ this.#reporter = reporter;
2618
+ }
2619
+ /**
2620
+ * Reports a line break in a command, e.g. after a `\\` line continuation or in a quoted string.
2621
+ * @param node The command
2622
+ * @param context Where the command is
2623
+ */
2624
+ checkCommandLineBreak(node, context) {
2625
+ const newline = context.source.slice(node.pos, node.end).indexOf("\n");
2626
+ if (newline === -1) return;
2627
+ const position = node.pos + newline;
2628
+ const isInWord = [
2629
+ node.name,
2630
+ ...node.prefix,
2631
+ ...node.suffix
2632
+ ].some((item) => item && item.pos <= position && position < item.end);
2633
+ const isQuoted = isInWord && context.source[position - 1] !== "\\";
2634
+ this.reportLineBreak(context, position, ONE_LINE_SUGGESTION, isInWord ? void 0 : joinLinesFix(context.source, position, position + 1), isQuoted);
2635
+ }
2636
+ /**
2637
+ * Reports a line break after an operator of a list or pipeline, e.g. after `||`.
2638
+ * @param commands The commands that the operators join
2639
+ * @param context Where the commands are
2640
+ */
2641
+ checkOperatorLineBreaks(commands, context) {
2642
+ for (const [index, next] of commands.entries()) {
2643
+ const command = commands[index - 1];
2644
+ if (!command) continue;
2645
+ const between = context.source.slice(command.end, next.pos);
2646
+ const newline = between.indexOf("\n");
2647
+ if (newline !== -1) {
2648
+ const position = command.end + newline;
2649
+ this.reportLineBreak(context, position, ONE_LINE_SUGGESTION, between.includes("#") ? void 0 : joinLinesFix(context.source, position, next.pos));
2650
+ return;
2651
+ }
2652
+ }
2653
+ }
2654
+ /**
2655
+ * Reports a line break, after which cmd.exe ignores the rest of the script, once per source.
2656
+ * @param context Where the line break is
2657
+ * @param position Where the line break is in the source
2658
+ * @param suggestion What to do instead
2659
+ * @param fix A fix for the report
2660
+ * @param isPortableSupported Whether Yarn's shell supports it, e.g. in quotes
2661
+ */
2662
+ reportLineBreak(context, position, suggestion, fix, isPortableSupported = false) {
2663
+ const range = rangeInScript(context, {
2664
+ end: position + 1,
2665
+ pos: position
2666
+ });
2667
+ if (this.#lineBreaks.some((reported) => reported.pos < range.end && range.pos < reported.end) || this.#multilineSources.has(context.source)) return;
2668
+ if (this.#reporter.reportSyntax(context, {
2669
+ end: position + 1,
2670
+ pos: position
2671
+ }, "posix", isPortableSupported, "unsupportedSyntax", {
2672
+ suggestion,
2673
+ syntax: "A multi-line script"
2674
+ }, fix).length === 0) return;
2675
+ this.#multilineSources.add(context.source);
2676
+ this.#lineBreaks.push(range);
2677
+ }
2678
+ };
2679
+ // src/redirection-checker.ts
2680
+ /** The target of a redirection that duplicates or closes a file descriptor, e.g. `1` or `-` */
2681
+ const DESCRIPTOR = /^(?:\d+|-)$/;
2682
+ /** Device names, which cmd.exe treats as the device in any directory */
2683
+ const WINDOWS_DEVICES = /* @__PURE__ */ new Set([
2684
+ "aux",
2685
+ "con",
2686
+ "nul",
2687
+ "prn"
2688
+ ]);
2689
+ /** Checks redirections, e.g. for Bash-specific operators and device files */
2690
+ var RedirectionChecker = class {
2691
+ /** End offsets of here-documents, by the source that they're in */
2692
+ hereDocumentEnds = /* @__PURE__ */ new Map();
2693
+ #reporter;
2694
+ #words;
2695
+ constructor(reporter, words) {
2696
+ this.#reporter = reporter;
2697
+ this.#words = words;
2698
+ }
2699
+ checkEchoToFile(node, context) {
2700
+ const isWritesFile = node.redirects.some((redirect) => redirect.type === "Redirect" && (redirect.operator === ">" || redirect.operator === ">>") && redirect.descriptor == null && !POSIX_PATH.test(redirect.target?.value || "") && !WINDOWS_DEVICES.has(redirect.target?.value.toLowerCase() || ""));
2701
+ const quoted = node.args.find((argument) => argument.type === "Word" && argument.parts?.some((part) => part.type === "DoubleQuoted"));
2702
+ if (isWritesFile && quoted) this.#reporter.reportSyntax(context, quoted, "posix", true, "inconsistentBehavior", {
2703
+ reason: "cmd.exe's `echo` writes the quotes into the file",
2704
+ suggestion: NODE_SCRIPT_SUGGESTION,
2705
+ syntax: "Writing a double-quoted string with `echo`"
2706
+ });
2707
+ }
2708
+ /**
2709
+ * Checks a redirection and its target.
2710
+ * @param redirection Redirection to check, e.g. `> out.log`
2711
+ * @param context Where the redirection is
2712
+ * @param isWholeCommand Whether it's all that its command consists of, e.g. in `tsc | >log`
2713
+ */
2714
+ checkRedirection(redirection, context, isWholeCommand = false) {
2715
+ const text = context.source.slice(redirection.pos, redirection.end);
2716
+ switch (redirection.type) {
2717
+ case "HereDoc":
2718
+ this.#reporter.reportSyntax(context, redirection, "posix", false, "unsupportedSyntax", {
2719
+ suggestion: NODE_SCRIPT_SUGGESTION,
2720
+ syntax: `The here-document \`${redirection.operator}\``
2721
+ });
2722
+ if (redirection.closing) mapGetOrInsert(this.hereDocumentEnds, context.source, []).push(redirection.closing.end);
2723
+ return;
2724
+ case "HereString":
2725
+ this.#reporter.reportSyntax(context, redirection, "bash", true, "unsupportedSyntax", {
2726
+ suggestion: "Pipe the value into the command instead.",
2727
+ syntax: "The Bash-specific here-string `<<<`"
2728
+ });
2729
+ break;
2730
+ case "Redirect": {
2731
+ const { descriptor, operator } = redirection;
2732
+ if (descriptor?.type === "FileDescriptorVariable") this.#reporter.reportSyntax(context, descriptor, "bash", false, "unsupportedSyntax", {
2733
+ suggestion: BASH_SUGGESTION,
2734
+ syntax: `The Bash-specific file descriptor variable \`{${descriptor.name}}\``
2735
+ });
2736
+ const separator = redirection.pos > 0 && !WHITESPACE.test(context.source.charAt(redirection.pos - 1)) ? " " : "";
2737
+ const redirectionFix = (fixed) => ({
2738
+ description: describeReplacement(text, fixed),
2739
+ edits: [{
2740
+ end: redirection.end,
2741
+ pos: redirection.pos,
2742
+ text: `${separator}${fixed}`
2743
+ }]
2744
+ });
2745
+ if (operator === "&>" || operator === "&>>") {
2746
+ const kind = operator === "&>" ? "bash" : "bash4";
2747
+ this.#reporter.reportSyntax(context, redirection, kind, false, "unsupportedSyntax", {
2748
+ suggestion: `Use \`${operator.slice(1)} file 2>&1\` instead.`,
2749
+ syntax: `The ${bashLabel(kind)} \`${operator}\` redirection`
2750
+ }, redirection.target && redirectionFix(`${operator.slice(1)} ${redirection.target.text} 2>&1`));
2751
+ } else if (operator === ">|" || operator === "<>") {
2752
+ const position = context.source.indexOf(operator, descriptor?.end || redirection.pos);
2753
+ this.#reporter.reportSyntax(context, redirection, "posix", false, "unsupportedSyntax", {
2754
+ suggestion: operator === ">|" ? "Use `>` instead." : NODE_SCRIPT_SUGGESTION,
2755
+ syntax: `The \`${operator}\` redirection`
2756
+ }, operator === ">|" ? replacement({
2757
+ end: position + operator.length,
2758
+ pos: position
2759
+ }, operator, ">") : void 0);
2760
+ }
2761
+ if (redirection.target && (operator === ">&" || operator === "<&")) {
2762
+ const target = staticValue(redirection.target);
2763
+ if (target != null && DESCRIPTOR.test(target)) return;
2764
+ if (operator === ">&" && target != null) this.#reporter.reportSyntax(context, redirection, "bash", false, "unsupportedSyntax", {
2765
+ suggestion: `Use \`> ${truncate(target)} 2>&1\` instead.`,
2766
+ syntax: "The Bash-specific `>&` redirection to a file"
2767
+ }, descriptor ? void 0 : redirectionFix(`> ${redirection.target.text} 2>&1`));
2768
+ }
2769
+ break;
2770
+ }
2771
+ }
2772
+ if (!redirection.target) return;
2773
+ const target = staticValue(redirection.target);
2774
+ if (target != null && WINDOWS_DEVICES.has(target.toLowerCase())) this.#reporter.report(context, redirection.target, "inconsistentBehavior", {
2775
+ reason: `POSIX shells create a file named \`${target}\` instead`,
2776
+ suggestion: "Remove the redirection or use a Node.js script instead.",
2777
+ syntax: `The redirection to \`${target}\``
2778
+ }, POSIX_PLATFORMS);
2779
+ this.#words.checkWord(redirection.target, context, { redirectTarget: true });
2780
+ if (target == null || target === "/dev/null" && context.portable) return;
2781
+ const isDiscardsOutput = !isWholeCommand && redirection.type === "Redirect" && (redirection.operator === ">" || redirection.operator === ">>") && target === "/dev/null";
2782
+ this.#words.checkPosixPath(redirection.target, target, context, isDiscardsOutput ? {
2783
+ description: `Remove \`${truncate(text)}\`.`,
2784
+ edits: [removal(context.source, redirection.pos, redirection.end)]
2785
+ } : void 0);
2786
+ }
2787
+ };
2788
+ // src/word-checker.ts
2789
+ /** Variables that Bash sets, but dash doesn't, by the kind of syntax they are */
2790
+ const BASH_VARIABLES = /* @__PURE__ */ new Map([
2791
+ ["BASH_SOURCE", "bash"],
2792
+ ["BASH_VERSION", "bash"],
2793
+ ["EPOCHREALTIME", "bash4"],
2794
+ ["EPOCHSECONDS", "bash4"],
2795
+ ["EUID", "bash"],
2796
+ ["HOSTNAME", "bash"],
2797
+ ["OSTYPE", "bash"],
2798
+ ["PIPESTATUS", "bash"],
2799
+ ["RANDOM", "bash"],
2800
+ ["SECONDS", "bash"],
2801
+ ["SRANDOM", "bash4"],
2802
+ ["UID", "bash"]
2803
+ ]);
2804
+ /**
2805
+ * Variables that POSIX shells and systems set, but Windows doesn't, e.g. `PWD`.
2806
+ * cmd.exe computes its own dynamic variables, like `%CD%`, so they aren't in the environment
2807
+ * either.
2808
+ * Some runners, like npm, set `HOME` on all platforms
2809
+ */
2810
+ const POSIX_ONLY_VARIABLES = /* @__PURE__ */ new Set([
2811
+ ...BASH_VARIABLES.keys(),
2812
+ "LOGNAME",
2813
+ "OLDPWD",
2814
+ "PPID",
2815
+ "PWD",
2816
+ "SHELL",
2817
+ "TMPDIR",
2818
+ "USER"
2819
+ ]);
2820
+ /** Variables that package managers set, e.g. `npm_package_version` */
2821
+ const PACKAGE_MANAGER_VARIABLE = /^(?:npm_\w+|INIT_CWD)$/;
2822
+ /** cmd.exe statements, which POSIX shells parse as commands, e.g. `IF` in `IF EXIST dist ...` */
2823
+ const CMD_STATEMENTS = /* @__PURE__ */ new Set(["for", "if"]);
2824
+ /** Characters that cmd.exe splits words at or interprets */
2825
+ const CMD_SPECIAL_CHARACTERS = /[\s"%&<>^|]/;
2826
+ /** Backslash escapes that POSIX shells remove, but cmd.exe passes on, e.g. `\$` or `\ ` */
2827
+ const UNQUOTED_ESCAPE = /\\[\t !#$&'()*;<>?[\]`{|}~]/;
2828
+ /** The same, in double quotes */
2829
+ const QUOTED_ESCAPE = /\\[$`]/;
2830
+ /** `cross-env` removes the backslashes of these escapes itself */
2831
+ const CROSS_ENV_ESCAPE = /^\\[$']$/;
2832
+ /** A named variable, e.g. `$HOME` rather than `$?` */
2833
+ const NAMED_VARIABLE = /^\$\w+$/;
2834
+ /** A `**` path segment, which `sh` doesn't expand recursively */
2835
+ const RECURSIVE_GLOB = /(?:^|[/=])\*\*\//;
2836
+ const WINDOWS_VARIABLE = /%[a-z_]\w+%/i;
2837
+ const WINDOWS_VARIABLES = new RegExp(WINDOWS_VARIABLE, "gi");
2838
+ /**
2839
+ * A Windows path: a drive, relative prefix or first segment, then `\`-separated segments.
2840
+ * The segments may be globs, e.g. `lib\**\*.js`
2841
+ */
2842
+ const BACKSLASH_PATH = /^(?:[a-z]:|[\w\-.]+|\*\*?(?:\.[\w-]+)*)(?:\\(?:[\w\-.]+|\*\*?(?:\.[\w-]+)*))+\\?$/i;
2843
+ /** A Windows path's drive or relative prefix, e.g. `C:\` or `.\` */
2844
+ const WINDOWS_PATH_PREFIX = /^(?:[a-z]:|\.{1,2})\\/i;
2845
+ const FILE_EXTENSION = /\.\w+$/;
2846
+ const MULTIPLE_BACKSLASHES = /\\.*\\/;
2847
+ /** Backslashes that only escape dots are rather a regex, e.g. `logging\.spec\.ts` */
2848
+ const NON_DOT_ESCAPE = /\\[^.]/;
2849
+ const hasBashArithmetic = (expression) => {
2850
+ switch (expression?.type) {
2851
+ case "ArithmeticBinary": return expression.operator.startsWith("**") || hasBashArithmetic(expression.left) || hasBashArithmetic(expression.right);
2852
+ case "ArithmeticGroup": return hasBashArithmetic(expression.expression);
2853
+ case "ArithmeticTernary": return [
2854
+ expression.test,
2855
+ expression.consequent,
2856
+ expression.alternate
2857
+ ].some(hasBashArithmetic);
2858
+ case "ArithmeticUnary": return expression.operator === "++" || expression.operator === "--" || hasBashArithmetic(expression.operand);
2859
+ default: return false;
2860
+ }
2861
+ };
2862
+ const parameterOperands = (operation) => {
2863
+ switch (operation.type) {
2864
+ case "CaseModification":
2865
+ case "Default":
2866
+ case "Remove":
2867
+ case "Transform": return [operation.operand];
2868
+ case "Replace": return [operation.pattern, operation.replacement];
2869
+ case "Slice": return [operation.offset, operation.length];
2870
+ default: return [];
2871
+ }
2872
+ };
2873
+ /**
2874
+ * Checks whether a command is rather a tool than an OS utility or a cmd.exe command, e.g. `eslint`.
2875
+ * Tools usually expand globs themselves and accept `/` as a path separator.
2876
+ * @param command Name of the command that receives the arguments
2877
+ * @returns Whether the command is likely a tool
2878
+ */
2879
+ const isTool = (command) => {
2880
+ const name = command?.toLowerCase();
2881
+ return name != null && !OS_COMMANDS.has(name) && !CMD_STATEMENTS.has(name);
2882
+ };
2883
+ /** Checks words, e.g. for quotes, expansions and paths */
2884
+ var WordChecker = class {
2885
+ #reporter;
2886
+ #runnerTraits;
2887
+ #walkNestedScript;
2888
+ constructor(reporter, walkNestedScript, runnerTraits) {
2889
+ this.#reporter = reporter;
2890
+ this.#walkNestedScript = walkNestedScript;
2891
+ this.#runnerTraits = runnerTraits;
2892
+ }
2893
+ /**
2894
+ * Checks a variable assignment.
2895
+ * @param assignment Assignment to check, e.g. `CI=1`
2896
+ * @param context Where the assignment is
2897
+ * @param command The command that the assignment prefixes, e.g. `jest` in `CI=1 jest`
2898
+ */
2899
+ checkAssignment(assignment, context, command) {
2900
+ const { append, index, value } = assignment;
2901
+ const isBashSpecific = value.type === "ArrayValue" || index != null || append;
2902
+ const isPrefixesCommand = command != null;
2903
+ if (isBashSpecific) this.#reporter.reportSyntax(context, assignment, "bash", false, "unsupportedSyntax", {
2904
+ suggestion: BASH_SUGGESTION,
2905
+ syntax: `The Bash-specific ${index || value.type === "ArrayValue" ? "array" : "appending"} assignment \`${truncate(assignment.text)}\``
2906
+ });
2907
+ else this.#reporter.reportSyntax(context, assignment, "posix", true, "unsupportedSyntax", {
2908
+ suggestion: CROSS_ENV_SUGGESTION,
2909
+ syntax: isPrefixesCommand ? `The inline environment variable assignment \`${truncate(assignment.text)}\`` : `The shell variable assignment \`${truncate(assignment.text)}\``
2910
+ }, command?.prefix.every(isPlainAssignment) ? {
2911
+ description: "Prefix the command with `cross-env`.",
2912
+ edits: [{
2913
+ end: command.pos,
2914
+ pos: command.pos,
2915
+ text: "cross-env "
2916
+ }]
2917
+ } : void 0);
2918
+ const valueContext = isPrefixesCommand && !isBashSpecific ? {
2919
+ ...context,
2920
+ crossEnv: true
2921
+ } : context;
2922
+ (value.type === "ArrayValue" ? value.elements : [value]).forEach((word) => {
2923
+ this.checkWord(word, valueContext);
2924
+ });
2925
+ }
2926
+ #checkBashVariable(name, node, context) {
2927
+ const kind = BASH_VARIABLES.get(name);
2928
+ if (kind) this.#reporter.reportSyntax(context, node, kind, true, "inconsistentBehavior", {
2929
+ reason: kind === "bash" ? "dash, the `sh` of Debian/Ubuntu, doesn't set it" : "only Bash 5 sets it, and macOS ships Bash 3.2",
2930
+ suggestion: NODE_SCRIPT_SUGGESTION,
2931
+ syntax: `The Bash variable \`$${name}\``
2932
+ });
2933
+ }
2934
+ /**
2935
+ * Reports a variable that package managers set, but the runner doesn't, e.g. `node --run`.
2936
+ * @param name Name of the variable, e.g. `npm_package_version`
2937
+ * @param node The node to report
2938
+ * @param context Where the variable is
2939
+ * @param text How the script refers to the variable, e.g. `%npm_package_version%`
2940
+ */
2941
+ #checkPackageManagerVariable(name, node, context, text = `$${name}`) {
2942
+ if (this.#isMissingPackageManagerVariable(name)) this.#reporter.report(context, node, "inconsistentBehavior", {
2943
+ reason: `${this.#runnerTraits.label} doesn't set it`,
2944
+ suggestion: NODE_SCRIPT_SUGGESTION,
2945
+ syntax: `The variable \`${text}\``
2946
+ }, PLATFORMS);
2947
+ }
2948
+ /**
2949
+ * Reports a variable that `cross-env` replaces with an empty string on Windows, e.g. `$PWD`.
2950
+ * @param name Name of the variable
2951
+ * @param node The variable expansion
2952
+ * @param context Where the expansion is
2953
+ * @returns The platforms that the report covers
2954
+ */
2955
+ #checkCrossEnvVariable(name, node, context) {
2956
+ if (context.portable || !this.#isUnsetOnWindows(name)) return [];
2957
+ return this.#reporter.report(context, node, "inconsistentBehavior", {
2958
+ reason: "Windows doesn't set it, so `cross-env` replaces it with an empty string",
2959
+ suggestion: this.#variableSuggestion(name),
2960
+ syntax: `The variable \`${node.text}\``
2961
+ }, WINDOWS_PLATFORMS);
2962
+ }
2963
+ /**
2964
+ * Reports an unquoted carriage return, e.g. of a CRLF line break, which POSIX shells keep.
2965
+ * @param word Word to check, e.g. `tsc` and a carriage return before a line break
2966
+ * @param context Where the word is
2967
+ */
2968
+ #checkCarriageReturn(word, context) {
2969
+ const literal = word.parts ? word.parts.find((part) => part.type === "Literal" && part.text.includes("\r")) : word;
2970
+ if (!literal?.text.includes("\r") || context.portable) return;
2971
+ const position = literal.pos + literal.text.indexOf("\r");
2972
+ this.#reporter.report(context, {
2973
+ end: position + 1,
2974
+ pos: position
2975
+ }, "inconsistentBehavior", {
2976
+ reason: "POSIX shells treat it as part of the word, e.g. of a command's name",
2977
+ suggestion: "Use line feeds (`\\n`) for line breaks instead.",
2978
+ syntax: "The carriage return (`\\r`)"
2979
+ }, POSIX_PLATFORMS, {
2980
+ description: "Remove the carriage return.",
2981
+ edits: [{
2982
+ end: position + 1,
2983
+ pos: position,
2984
+ text: ""
2985
+ }]
2986
+ });
2987
+ }
2988
+ #checkEscapes(word, context) {
2989
+ const literals = word.parts ? word.parts.flatMap((part) => {
2990
+ if (part.type === "Literal") return {
2991
+ escape: UNQUOTED_ESCAPE,
2992
+ text: part.text
2993
+ };
2994
+ return part.type === "DoubleQuoted" ? part.parts.flatMap((child) => child.type === "Literal" ? {
2995
+ escape: QUOTED_ESCAPE,
2996
+ text: child.text
2997
+ } : []) : [];
2998
+ }) : [{
2999
+ escape: UNQUOTED_ESCAPE,
3000
+ text: word.text
3001
+ }];
3002
+ const escape = literals.map(({ escape: pattern, text }) => pattern.exec(text)?.[0]).find((match) => match != null && !(context.crossEnv && CROSS_ENV_ESCAPE.test(match)));
3003
+ if (escape != null) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
3004
+ reason: "cmd.exe doesn't treat backslashes as escape characters, so it passes them on",
3005
+ suggestion: "Use escaped double quotes (`\\\"`) instead.",
3006
+ syntax: `The backslash escape \`${escape}\``
3007
+ });
3008
+ if (literals.some(({ escape: pattern, text }) => pattern === UNQUOTED_ESCAPE && text.includes("^"))) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
3009
+ reason: "cmd.exe treats `^` as an escape character and removes it",
3010
+ suggestion: "Quote it with double quotes instead.",
3011
+ syntax: `The caret in \`${truncate(word.text)}\``
3012
+ }, isPlainWord(word) ? quoting(word, "Quote it with escaped double quotes.") : void 0);
3013
+ }
3014
+ #checkParameterExpansion(part, context) {
3015
+ const { index, operation, prefix } = part;
3016
+ const isBashSpecific = index != null || prefix === "!" || operation != null && operation.type !== "Default" && operation.type !== "Remove";
3017
+ const bashKind = operation?.type === "CaseModification" || operation?.type === "Transform" ? "bash4" : "bash";
3018
+ let covered;
3019
+ if (isBashSpecific) covered = this.#reporter.reportSyntax(context, part, bashKind, false, "unsupportedSyntax", {
3020
+ suggestion: NODE_SCRIPT_SUGGESTION,
3021
+ syntax: `The ${bashLabel(bashKind)} parameter expansion \`${truncate(part.text)}\``
3022
+ });
3023
+ else if (operation == null && prefix == null && context.crossEnv) covered = this.#checkCrossEnvVariable(part.parameter, part, context);
3024
+ else {
3025
+ const isPortableSupported = prefix == null && (operation == null || operation.type === "Default" && (operation.operator === ":-" || operation.operator === ":+"));
3026
+ covered = this.#reporter.reportSyntax(context, part, "posix", isPortableSupported, "unsupportedSyntax", {
3027
+ suggestion: context.crossEnv ? CROSS_ENV_VARIABLE_SUGGESTION : this.#variableSuggestion(part.parameter),
3028
+ syntax: `The variable expansion \`${truncate(part.text)}\``
3029
+ });
3030
+ }
3031
+ const nestedContext = withCovered(context, covered);
3032
+ this.#checkBashVariable(part.parameter, part, nestedContext);
3033
+ this.#checkPackageManagerVariable(part.parameter, part, nestedContext);
3034
+ [index, ...operation ? parameterOperands(operation) : []].forEach((operand) => {
3035
+ if (operand) this.checkWord(operand, nestedContext, { skipGlobs: true });
3036
+ });
3037
+ }
3038
+ #checkParts(parts, context, state) {
3039
+ parts.forEach((part) => {
3040
+ this.#checkPart(part, context, state);
3041
+ });
3042
+ }
3043
+ /**
3044
+ * Checks a part of a word, e.g. a quoted string or an expansion.
3045
+ * @param part Part to check, e.g. `$HOME` in `$HOME/.npmrc`
3046
+ * @param context Where the word is
3047
+ * @param state What the word contains, collected while checking its parts
3048
+ */
3049
+ #checkPart(part, context, state) {
3050
+ switch (part.type) {
3051
+ case "AnsiCQuoted":
3052
+ this.#reporter.reportSyntax(context, part, "bash", true, "unsupportedSyntax", {
3053
+ suggestion: BASH_SUGGESTION,
3054
+ syntax: `The Bash-specific ANSI-C quoted string \`${truncate(part.text)}\``
3055
+ });
3056
+ break;
3057
+ case "ArithmeticExpansion": {
3058
+ const covered = this.#reporter.reportSyntax(context, part, "posix", true, "unsupportedSyntax", {
3059
+ suggestion: NODE_SCRIPT_SUGGESTION,
3060
+ syntax: `The arithmetic expansion \`${truncate(part.text)}\``
3061
+ });
3062
+ if (hasBashArithmetic(part.expression)) this.#reporter.reportSyntax(withCovered(context, covered), part, "bash", true, "unsupportedSyntax", {
3063
+ suggestion: NODE_SCRIPT_SUGGESTION,
3064
+ syntax: `The Bash-specific arithmetic in \`${truncate(part.text)}\``
3065
+ });
3066
+ break;
3067
+ }
3068
+ case "BraceExpansion":
3069
+ state.braceExpansions.push(part);
3070
+ break;
3071
+ case "CommandExpansion": {
3072
+ const covered = this.#reporter.reportSyntax(context, part, "posix", !part.text.startsWith("`"), "unsupportedSyntax", {
3073
+ suggestion: NODE_SCRIPT_SUGGESTION,
3074
+ syntax: `The command substitution \`${truncate(part.text)}\``
3075
+ });
3076
+ if (part.script && !part.script.errors?.length) this.#walkNestedScript(part.script, part, withCovered(context, covered));
3077
+ break;
3078
+ }
3079
+ case "DoubleQuoted":
3080
+ this.#checkParts(part.parts, context, state);
3081
+ break;
3082
+ case "ExtendedGlob":
3083
+ if (context.bashOptions?.has("extglob")) break;
3084
+ this.#reporter.report(context, part, "unsupportedSyntax", {
3085
+ suggestion: "It requires Bash's `extglob` option; quote the pattern and let the tool expand it instead.",
3086
+ syntax: `The extended glob \`${truncate(part.text)}\``
3087
+ }, PLATFORMS);
3088
+ break;
3089
+ case "Glob":
3090
+ if (part.kind === "star") state.globPosition ??= part.pos;
3091
+ break;
3092
+ case "LocaleString":
3093
+ this.#reporter.reportSyntax(context, part, "bash", false, "unsupportedSyntax", {
3094
+ suggestion: BASH_SUGGESTION,
3095
+ syntax: `The Bash-specific locale string \`${truncate(part.text)}\``
3096
+ });
3097
+ this.#checkParts(part.parts, context, state);
3098
+ break;
3099
+ case "ParameterExpansion":
3100
+ this.#checkParameterExpansion(part, context);
3101
+ break;
3102
+ case "ProcessSubstitution": {
3103
+ const covered = this.#reporter.reportSyntax(context, part, "bashNonPosix", false, "unsupportedSyntax", {
3104
+ suggestion: "Use a temporary file or a Node.js script instead.",
3105
+ syntax: `The Bash-specific process substitution \`${truncate(part.text)}\``
3106
+ });
3107
+ if (part.script && !part.script.errors?.length) this.#walkNestedScript(part.script, part, withCovered(context, covered));
3108
+ break;
3109
+ }
3110
+ case "SimpleExpansion": {
3111
+ const name = part.text.slice(1);
3112
+ const covered = context.crossEnv && NAMED_VARIABLE.test(part.text) ? this.#checkCrossEnvVariable(name, part, context) : this.#reporter.reportSyntax(context, part, "posix", true, "unsupportedSyntax", {
3113
+ suggestion: context.crossEnv ? CROSS_ENV_VARIABLE_SUGGESTION : this.#variableSuggestion(name),
3114
+ syntax: `The variable expansion \`${part.text}\``
3115
+ });
3116
+ const nestedContext = withCovered(context, covered);
3117
+ this.#checkBashVariable(name, part, nestedContext);
3118
+ this.#checkPackageManagerVariable(name, part, nestedContext);
3119
+ break;
3120
+ }
3121
+ case "SingleQuoted":
3122
+ state.hasSingleQuotes = true;
3123
+ if (state.printedToTerminal || context.crossEnv && !CMD_SPECIAL_CHARACTERS.test(part.value)) break;
3124
+ this.#reporter.reportSyntax(context, part, "posix", true, "inconsistentBehavior", {
3125
+ reason: context.crossEnv ? "cmd.exe doesn't treat single quotes as quotes, so it splits the string before `cross-env` removes them" : "cmd.exe doesn't treat single quotes as quotes, so they're passed on literally",
3126
+ suggestion: "Use escaped double quotes (`\\\"`) instead.",
3127
+ syntax: `The single-quoted string \`${truncate(part.text)}\``
3128
+ }, state.command === "echo" || DOUBLE_QUOTED_SPECIAL_CHARACTERS.test(part.value) ? void 0 : {
3129
+ description: "Use escaped double quotes instead.",
3130
+ edits: [{
3131
+ end: part.end,
3132
+ pos: part.pos,
3133
+ text: `"${part.value}"`
3134
+ }]
3135
+ });
3136
+ }
3137
+ }
3138
+ /**
3139
+ * Reports device paths like `/dev/null`, which don't exist on Windows.
3140
+ * @param word Word that contains the path
3141
+ * @param value Static value of the word
3142
+ * @param context Where the word is
3143
+ * @param fix A fix for the report, e.g. one that removes the redirection to the path
3144
+ */
3145
+ checkPosixPath(word, value, context, fix) {
3146
+ if (POSIX_PATH.test(value)) this.#reporter.report(context, word, "unsupportedSyntax", {
3147
+ suggestion: value.includes("/dev/") ? "Remove it or use a Node.js script instead." : "Use a path relative to the package or a Node.js script instead.",
3148
+ syntax: `The POSIX path \`${truncate(value)}\``
3149
+ }, WINDOWS_PLATFORMS, fix);
3150
+ }
3151
+ checkWord(word, context, options = {}) {
3152
+ const { text } = word;
3153
+ this.#checkCarriageReturn(word, context);
3154
+ if (TILDE_EXPANSION.test(text)) this.#reporter.reportSyntax(context, word, "posix", false, "unsupportedSyntax", {
3155
+ suggestion: "Use a path relative to the package or a Node.js script instead.",
3156
+ syntax: `The tilde expansion \`${truncate(text)}\``
3157
+ });
3158
+ const state = {
3159
+ braceExpansions: [],
3160
+ command: options.command,
3161
+ globPosition: void 0,
3162
+ hasSingleQuotes: false,
3163
+ printedToTerminal: options.printedToTerminal || false
3164
+ };
3165
+ this.#checkParts(word.parts || [], context, state);
3166
+ const hasGlob = state.globPosition != null;
3167
+ const globPrefix = hasGlob ? text.slice(0, (state.globPosition || 0) - word.pos) : "";
3168
+ const isLiteralPattern = globPrefix.startsWith("-") || globPrefix.includes("=");
3169
+ if (hasGlob && !isLiteralPattern && RECURSIVE_GLOB.test(text) && !context.portable && !context.bashOptions?.has("globstar") && !options.commandName && !options.redirectTarget && !options.skipGlobs) this.#reporter.report(context, word, "inconsistentBehavior", {
3170
+ reason: "`sh` doesn't support recursive `**` globs, and cmd.exe doesn't expand globs at all",
3171
+ suggestion: QUOTE_GLOB_SUGGESTION,
3172
+ syntax: `The unquoted glob \`${truncate(text)}\``
3173
+ }, PLATFORMS, isTool(options.command) && isPlainWord(word, GLOB_PART_TYPES) ? quoting(word, "Quote it with escaped double quotes.") : void 0);
3174
+ if (!hasGlob && (options.command == null || OS_COMMANDS.has(options.command))) state.braceExpansions.forEach((part) => {
3175
+ this.#reporter.reportSyntax(context, part, "bash", true, "unsupportedSyntax", {
3176
+ suggestion: "List the alternatives explicitly instead.",
3177
+ syntax: `The Bash-specific brace expansion \`${truncate(part.text)}\``
3178
+ }, braceExpansionFix(word, part));
3179
+ });
3180
+ const isPattern = options.command != null && PATTERN_COMMANDS.has(options.command);
3181
+ const unquoted = text.replaceAll("\"", "");
3182
+ const path = substringAfterLast(unquoted, "=");
3183
+ if (!isPattern && !state.hasSingleQuotes && BACKSLASH_PATH.test(path) && (WINDOWS_PATH_PREFIX.test(path) || FILE_EXTENSION.test(path) || MULTIPLE_BACKSLASHES.test(path)) && NON_DOT_ESCAPE.test(path)) this.#reporter.report(context, word, "inconsistentBehavior", {
3184
+ reason: "POSIX shells treat backslashes as escape characters",
3185
+ suggestion: "Use forward slashes instead.",
3186
+ syntax: `The backslash path separator in \`${truncate(path)}\``
3187
+ }, context.portable && !text.startsWith("\"") ? PLATFORMS : POSIX_PLATFORMS, options.commandName || options.redirectTarget || !isTool(options.command) ? void 0 : replacement(word, text, `${text.slice(0, text.lastIndexOf("=") + 1)}${toForwardSlashes(substringAfterLast(text, "="))}`));
3188
+ if (!BACKSLASH_PATH.test(path) && !WINDOWS_PATH_PREFIX.test(path)) this.#checkEscapes(word, context);
3189
+ if (!state.hasSingleQuotes && options.command !== "date" && options.command !== "printf") {
3190
+ const match = WINDOWS_VARIABLE.exec(text);
3191
+ if (match && !text.replaceAll(WINDOWS_VARIABLES, "").includes("%")) {
3192
+ const covered = this.#reporter.report(context, word, "unsupportedSyntax", {
3193
+ suggestion: VARIABLE_SUGGESTION,
3194
+ syntax: `The Windows variable reference \`${match[0]}\``
3195
+ }, context.portable ? PLATFORMS : POSIX_PLATFORMS);
3196
+ const nestedContext = withCovered(context, covered);
3197
+ text.matchAll(WINDOWS_VARIABLES).forEach(([reference]) => {
3198
+ this.#checkPackageManagerVariable(reference.slice(1, -1), word, nestedContext, reference);
3199
+ });
3200
+ }
3201
+ }
3202
+ const value = staticValue(word);
3203
+ if (value != null && !options.commandName && !options.redirectTarget) this.checkPosixPath(word, value, context);
3204
+ }
3205
+ /** Checks whether Windows doesn't set a variable, so `cross-env` replaces it with nothing */
3206
+ #isUnsetOnWindows(name) {
3207
+ return POSIX_ONLY_VARIABLES.has(name) || name === "HOME" && !this.#runnerTraits.setsHome;
3208
+ }
3209
+ /** Checks whether a variable is one that package managers set, but the runner doesn't */
3210
+ #isMissingPackageManagerVariable(name) {
3211
+ const variables = this.#runnerTraits.packageManagerVariables;
3212
+ return variables != null && PACKAGE_MANAGER_VARIABLE.test(name) && !variables.has(name);
3213
+ }
3214
+ /** Gets what to use instead of a variable on Windows, where `cross-env` can't help for some */
3215
+ #variableSuggestion(name) {
3216
+ if (name === "PWD") return "Use a relative path or a Node.js script instead.";
3217
+ return this.#isUnsetOnWindows(name) || this.#isMissingPackageManagerVariable(name) ? NODE_SCRIPT_SUGGESTION : VARIABLE_SUGGESTION;
3218
+ }
3219
+ };
3220
+ // src/script-analyzer.ts
3221
+ /** A `#` comment after a word boundary */
3222
+ const COMMENT = /(?:^|[\s&;|])(#.*)/;
3223
+ /** A glob of script names that `concurrently` expands, e.g. `npm run watch:*(!css)` */
3224
+ const SCRIPT_GLOB = /((?:bun|npm|pnpm|yarn) run|node --run|deno task) (\S*\*\S*)/;
3225
+ /** `shopt -s globstar`, which makes `**` recursive in the following commands */
3226
+ const SHOPT_GLOBSTAR = /\bshopt\s+-s\s+(?:\w+\s+)*globstar\b/;
3227
+ /** The rest of a script that only closes subshells */ const CLOSING_PARENTHESES = /^[\s)]*$/;
3228
+ const WINDOWS_BATCH_SYNTAX = /\bif\s+(?:\/i\s+)?(?:not\s+)?(?:defined|errorlevel|exist)\b|\bfor\s+(?:\/[a-z]\s+)*%%?[a-z]\b/gi;
3229
+ const SINGLE_QUOTE = /'/;
3230
+ const ANY_CHARACTER = /[\s\S]/;
3231
+ const doesChangeDirectory = (node) => {
3232
+ switch (node.type) {
3233
+ case "AndOr":
3234
+ case "Pipeline": return node.commands.some(doesChangeDirectory);
3235
+ case "Command": return node.name?.value === "cd" || node.name?.value === "pushd";
3236
+ default: return false;
3237
+ }
3238
+ };
3239
+ /**
3240
+ * Checks whether commands change the shell's state, e.g. with `exit` or a variable assignment.
3241
+ * @param node Commands of a command group
3242
+ * @returns Whether they do, or might, e.g. in an `if` statement
3243
+ */
3244
+ const doesChangeShellState = (node) => {
3245
+ switch (node.type) {
3246
+ case "AndOr":
3247
+ case "Pipeline": return node.commands.some(doesChangeShellState);
3248
+ case "BraceGroup": return node.body.commands.some((statement) => doesChangeShellState(statement.command));
3249
+ case "Command": return node.name ? SHELL_STATE_COMMANDS.has(node.name.value) : node.prefix.some((item) => item.type === "Assignment");
3250
+ case "Redirected": return doesChangeShellState(node.command);
3251
+ case "Subshell": return false;
3252
+ default: return true;
3253
+ }
3254
+ };
3255
+ /**
3256
+ * Gets the text that a command receives for a word, e.g. a script for `sh -c`.
3257
+ * The outer shell's expansions are replaced by placeholders of the same length.
3258
+ * Their results aren't known, and they're reported for the outer script already.
3259
+ * @param parts The word's parts
3260
+ * @returns The text, with placeholders
3261
+ */
3262
+ const nestedSource = (parts) => parts.map((part) => {
3263
+ switch (part.type) {
3264
+ case "AnsiCQuoted":
3265
+ case "Glob":
3266
+ case "Literal":
3267
+ case "SingleQuoted": return part.value;
3268
+ case "DoubleQuoted":
3269
+ case "LocaleString": return nestedSource(part.parts);
3270
+ default: return "_".repeat(part.text.length);
3271
+ }
3272
+ }).join("");
3273
+ /**
3274
+ * Finds the end of a run of `||` alternatives that each break on some platform, but together work
3275
+ * on all platforms, e.g. `open x || xdg-open x || start x`.
3276
+ * @param node The list that the alternatives are in
3277
+ * @param platformsOf Gets the platforms on which a command of the list doesn't work
3278
+ * @param first Index of the run's first command
3279
+ * @returns Index of the run's last command, if there's such a run
3280
+ */
3281
+ const findFallbackEnd = (node, platformsOf, first) => {
3282
+ let unsupported = platformsOf(first);
3283
+ for (let last = first + 1; unsupported.size > 0 && last < node.commands.length && node.operators[last - 1] === "||"; last++) {
3284
+ const platforms = platformsOf(last);
3285
+ if (platforms.size === 0) return;
3286
+ unsupported = unsupported.intersection(platforms);
3287
+ if (unsupported.size === 0) return last;
3288
+ }
3289
+ };
3290
+ var ScriptAnalyzer = class {
3291
+ #commands;
3292
+ #lineBreaks;
3293
+ /** Commands whose output goes into a pipe */
3294
+ #pipedCommands = /* @__PURE__ */ new Set();
3295
+ #redirections;
3296
+ #reporter;
3297
+ #words;
3298
+ constructor(length, options, traits) {
3299
+ this.#reporter = new Reporter(length);
3300
+ this.#words = new WordChecker(this.#reporter, (script, part, context) => {
3301
+ this.#walkNestedScript(script, part, context);
3302
+ }, traits);
3303
+ this.#lineBreaks = new LineBreakChecker(this.#reporter);
3304
+ this.#redirections = new RedirectionChecker(this.#reporter, this.#words);
3305
+ this.#commands = new CommandChecker(this.#reporter, options, (words, context, nested) => {
3306
+ this.#analyzeNestedWords(words, context, nested);
3307
+ });
3308
+ }
3309
+ get issues() {
3310
+ return this.#reporter.issues;
3311
+ }
3312
+ analyzeSource(context) {
3313
+ const script = parse(context.source);
3314
+ if (script.errors?.length) {
3315
+ this.#checkWindowsBatchSyntax(context);
3316
+ return;
3317
+ }
3318
+ this.#commands.addPositionalFixes(script.commands);
3319
+ const scriptContext = context.shell === "bash" && SHOPT_GLOBSTAR.test(context.source) ? {
3320
+ ...context,
3321
+ bashOptions: /* @__PURE__ */ new Set([...context.bashOptions || [], "globstar"])
3322
+ } : context;
3323
+ this.#walkStatements(script.commands, script.end, scriptContext);
3324
+ this.#checkComments(script.commands, scriptContext);
3325
+ }
3326
+ #analyzeNestedWords(words, context, { bashOptions, crossEnv, maskScriptGlobs = false, shell }) {
3327
+ const sources = words.map((word) => {
3328
+ const source = word.parts ? nestedSource(word.parts) : word.value;
3329
+ return maskScriptGlobs ? source.replace(SCRIPT_GLOB, (_, command, glob) => `${command} ${"_".repeat(glob.length)}`) : source;
3330
+ });
3331
+ const [word] = words;
3332
+ if (!word) return;
3333
+ const parts = word.parts || [];
3334
+ const [part] = parts;
3335
+ let { fixedRange } = context;
3336
+ let offset = context.offset + word.pos;
3337
+ let exclusion = ANY_CHARACTER;
3338
+ if (words.length === 1 && parts.length === 1 && (part?.type === "SingleQuoted" || part?.type === "DoubleQuoted" && part.parts.every((child) => child.type !== "Literal" || child.value === child.text))) {
3339
+ offset = context.offset + part.pos + 1;
3340
+ exclusion = part.type === "SingleQuoted" ? SINGLE_QUOTE : DOUBLE_QUOTED_SPECIAL_CHARACTERS;
3341
+ } else if (words.length > 1 || parts.length > 0 || word.text !== sources[0]) fixedRange ||= rangeInScript(context, {
3342
+ end: words.at(-1)?.end || word.end,
3343
+ pos: word.pos
3344
+ });
3345
+ this.analyzeSource({
3346
+ bashOptions,
3347
+ convertsSlashes: false,
3348
+ covered: context.covered,
3349
+ crossEnv,
3350
+ fixExclusions: [...context.fixExclusions, exclusion],
3351
+ fixedRange,
3352
+ offset,
3353
+ portable: false,
3354
+ shell,
3355
+ source: sources.join(" ")
3356
+ });
3357
+ }
3358
+ #checkComments(statements, context) {
3359
+ let position = 0;
3360
+ [...statements, void 0].forEach((statement, index) => {
3361
+ const end = statement?.pos ?? context.source.length;
3362
+ const match = COMMENT.exec(context.source.slice(position, end));
3363
+ const comment = match?.[1];
3364
+ if (match && comment != null) {
3365
+ const start = position + match.index + match[0].length - comment.length;
3366
+ const commentEnd = start + comment.length;
3367
+ this.#reporter.reportSyntax(context, {
3368
+ end: commentEnd,
3369
+ pos: start
3370
+ }, "posix", false, "unsupportedSyntax", {
3371
+ suggestion: "Remove it instead.",
3372
+ syntax: "The `#` comment"
3373
+ }, {
3374
+ description: "Remove the comment.",
3375
+ edits: [removal(context.source, start, commentEnd)]
3376
+ });
3377
+ }
3378
+ position = statement ? this.#statementEnd(statement, statements.at(index + 1)?.pos || context.source.length, context.source) : end;
3379
+ });
3380
+ }
3381
+ /**
3382
+ * Gets where the text after a statement starts, after the bodies of its here-documents.
3383
+ * @param statement A statement of the source
3384
+ * @param nextStart Where the next statement starts, or where the source ends
3385
+ * @param source The source that the statement is in
3386
+ * @returns The offset in the source
3387
+ */
3388
+ #statementEnd(statement, nextStart, source) {
3389
+ const hereDocumentEnds = (this.#redirections.hereDocumentEnds.get(source) || []).filter((end) => end <= nextStart);
3390
+ return Math.max(statement.end, ...hereDocumentEnds);
3391
+ }
3392
+ #checkWindowsBatchSyntax(context) {
3393
+ context.source.matchAll(WINDOWS_BATCH_SYNTAX).forEach((match) => {
3394
+ this.#reporter.report(context, {
3395
+ end: match.index + match[0].length,
3396
+ pos: match.index
3397
+ }, "unsupportedSyntax", {
3398
+ suggestion: NODE_SCRIPT_SUGGESTION,
3399
+ syntax: `The Windows batch syntax \`${truncate(match[0])}\``
3400
+ }, context.portable ? PLATFORMS : POSIX_PLATFORMS);
3401
+ });
3402
+ }
3403
+ /**
3404
+ * Drops the issues of alternatives for different platforms, e.g. `rm -rf a || rmdir /s /q a`.
3405
+ * @param node The list of commands joined by `||` (and other operators)
3406
+ * @param starts Index of the first issue of each command in the list, and of the end of its
3407
+ * issues
3408
+ */
3409
+ #dropPlatformFallbacks(node, starts) {
3410
+ const platformsOf = (index) => new Set(this.#reporter.issues.slice(starts[index], starts[index + 1]).flatMap((issue) => issue.platforms));
3411
+ const dropped = [];
3412
+ let first = 0;
3413
+ while (first < node.commands.length) {
3414
+ const last = findFallbackEnd(node, platformsOf, first);
3415
+ if (last == null) first++;
3416
+ else {
3417
+ dropped.push([first, last]);
3418
+ first = last + 1;
3419
+ }
3420
+ }
3421
+ dropped.toReversed().forEach(([runStart, runEnd]) => {
3422
+ const start = starts[runStart];
3423
+ const end = starts[runEnd + 1];
3424
+ if (start != null && end != null) this.#reporter.issues.splice(start, end - start);
3425
+ });
3426
+ }
3427
+ #walkCommand(node, context) {
3428
+ switch (node.type) {
3429
+ case "AndOr": {
3430
+ const starts = [];
3431
+ node.commands.forEach((command) => {
3432
+ starts.push(this.#reporter.issues.length);
3433
+ this.#walkCommand(command, context);
3434
+ });
3435
+ starts.push(this.#reporter.issues.length);
3436
+ this.#dropPlatformFallbacks(node, starts);
3437
+ this.#lineBreaks.checkOperatorLineBreaks(node.commands, context);
3438
+ break;
3439
+ }
3440
+ case "ArithmeticCommand":
3441
+ this.#reporter.reportSyntax(context, node, "bash", false, "unsupportedSyntax", {
3442
+ suggestion: BASH_SUGGESTION,
3443
+ syntax: "The Bash-specific `(( ... ))` arithmetic command"
3444
+ });
3445
+ break;
3446
+ case "ArithmeticFor":
3447
+ this.#walkList(node.body, this.#reportStatement(context, node, "for (( ... ))", "bash"));
3448
+ break;
3449
+ case "BraceGroup": {
3450
+ const isSubshellSafe = context.source[node.end - 1] === "}" && node.body.commands.every((statement) => !doesChangeShellState(statement.command));
3451
+ const covered = this.#reporter.reportSyntax(context, {
3452
+ end: node.pos + 1,
3453
+ pos: node.pos
3454
+ }, "posix", true, "unsupportedSyntax", {
3455
+ suggestion: "Use `( ... )` instead.",
3456
+ syntax: "The command group `{ ... }`"
3457
+ }, isSubshellSafe ? {
3458
+ description: "Replace `{ ... }` with `( ... )`.",
3459
+ edits: [{
3460
+ end: node.pos + 1,
3461
+ pos: node.pos,
3462
+ text: "("
3463
+ }, {
3464
+ end: node.end,
3465
+ pos: node.end - 1,
3466
+ text: ")"
3467
+ }]
3468
+ } : void 0);
3469
+ this.#walkList(node.body, withCovered(context, covered));
3470
+ break;
3471
+ }
3472
+ case "Case": {
3473
+ const nestedContext = this.#reportStatement(context, node, "case", "posix");
3474
+ this.#words.checkWord(node.word, nestedContext);
3475
+ node.items.forEach(({ body, end, terminator }) => {
3476
+ this.#walkList(body, nestedContext);
3477
+ if (terminator === ";&" || terminator === ";;&") this.#reporter.reportSyntax(nestedContext, {
3478
+ end,
3479
+ pos: end - terminator.length
3480
+ }, "bash4", false, "unsupportedSyntax", {
3481
+ suggestion: BASH_4_SUGGESTION,
3482
+ syntax: `The Bash 4 \`${terminator}\` case terminator`
3483
+ });
3484
+ });
3485
+ break;
3486
+ }
3487
+ case "Command":
3488
+ this.#walkSimpleCommand(node, context);
3489
+ break;
3490
+ case "Coproc": {
3491
+ const nestedContext = this.#reportStatement(context, node, "coproc", "bash4");
3492
+ if (node.body.type === "CompoundList") this.#walkList(node.body, nestedContext);
3493
+ else this.#walkCommand(node.body, nestedContext);
3494
+ break;
3495
+ }
3496
+ case "For": {
3497
+ const nestedContext = this.#reportStatement(context, node, "for", "posix");
3498
+ node.wordlist?.forEach((word) => {
3499
+ this.#words.checkWord(word, nestedContext);
3500
+ });
3501
+ this.#walkList(node.body, nestedContext);
3502
+ break;
3503
+ }
3504
+ case "Function": {
3505
+ const isUsesKeyword = context.source.startsWith("function", node.pos);
3506
+ const covered = this.#reporter.reportSyntax(context, {
3507
+ end: node.name.end,
3508
+ pos: node.pos
3509
+ }, isUsesKeyword ? "bash" : "posix", false, "unsupportedSyntax", isUsesKeyword ? {
3510
+ suggestion: "Use `name() { ... }` or a Node.js script instead.",
3511
+ syntax: "The Bash-specific `function` keyword"
3512
+ } : {
3513
+ suggestion: NODE_SCRIPT_SUGGESTION,
3514
+ syntax: `The shell function definition \`${node.name.text}()\``
3515
+ });
3516
+ const nestedContext = withCovered(context, covered);
3517
+ if (node.body.type === "CompoundList") this.#walkList(node.body, nestedContext);
3518
+ else this.#walkCommand(node.body, nestedContext);
3519
+ break;
3520
+ }
3521
+ case "If": {
3522
+ const nestedContext = this.#reportStatement(context, node, "if", "posix");
3523
+ this.#walkList(node.clause, nestedContext);
3524
+ this.#walkList(node.then, nestedContext);
3525
+ node.elif.forEach((elif) => {
3526
+ this.#walkList(elif.clause, nestedContext);
3527
+ this.#walkList(elif.then, nestedContext);
3528
+ });
3529
+ if (node.else) this.#walkList(node.else, nestedContext);
3530
+ break;
3531
+ }
3532
+ case "Pipeline":
3533
+ this.#walkPipeline(node, context);
3534
+ break;
3535
+ case "Redirected":
3536
+ this.#walkCommand(node.command, context);
3537
+ node.redirects.forEach((redirection) => {
3538
+ this.#redirections.checkRedirection(redirection, context);
3539
+ });
3540
+ break;
3541
+ case "Select": {
3542
+ const nestedContext = this.#reportStatement(context, node, "select", "bash");
3543
+ node.wordlist?.forEach((word) => {
3544
+ this.#words.checkWord(word, nestedContext);
3545
+ });
3546
+ this.#walkList(node.body, nestedContext);
3547
+ break;
3548
+ }
3549
+ case "Subshell":
3550
+ 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", {
3551
+ reason: "cmd.exe only groups the commands, so `cd` also changes the directory of the commands that follow",
3552
+ suggestion: "Use `npm --prefix <directory>` or workspaces instead.",
3553
+ syntax: "The subshell `( ... )`"
3554
+ });
3555
+ this.#walkList(node.body, context);
3556
+ break;
3557
+ case "TestCommand": {
3558
+ const covered = this.#reporter.reportSyntax(context, node, "bash", false, "unsupportedSyntax", {
3559
+ suggestion: "Use `test` or a Node.js script instead.",
3560
+ syntax: "The Bash-specific `[[ ... ]]` test"
3561
+ });
3562
+ this.#walkTestExpression(node.expression, withCovered(context, covered));
3563
+ break;
3564
+ }
3565
+ case "While": {
3566
+ const nestedContext = this.#reportStatement(context, node, node.kind, "posix");
3567
+ this.#walkList(node.clause, nestedContext);
3568
+ this.#walkList(node.body, nestedContext);
3569
+ break;
3570
+ }
3571
+ }
3572
+ }
3573
+ #walkList(list, context) {
3574
+ this.#walkStatements(list.commands, list.end, context);
3575
+ }
3576
+ #walkNestedScript(script, part, context) {
3577
+ const nestedContext = script.source == null ? context : {
3578
+ ...context,
3579
+ fixedRange: rangeInScript(context, part),
3580
+ source: script.source
3581
+ };
3582
+ this.#walkStatements(script.commands, script.end, nestedContext);
3583
+ }
3584
+ #walkPipeline(node, context) {
3585
+ node.prefixes.forEach((prefix) => {
3586
+ this.#reporter.reportSyntax(context, prefix, "posix", false, "unsupportedSyntax", prefix.type === "Negation" ? {
3587
+ suggestion: NODE_SCRIPT_SUGGESTION,
3588
+ syntax: "The pipeline negation `!`"
3589
+ } : {
3590
+ suggestion: "cmd.exe's `time` sets the system time; use a Node.js script instead.",
3591
+ syntax: "The `time` keyword"
3592
+ });
3593
+ });
3594
+ node.operators.forEach((operator, index) => {
3595
+ if (operator !== "|&") return;
3596
+ const position = context.source.indexOf("|&", node.commands[index]?.end);
3597
+ const range = {
3598
+ end: position + 2,
3599
+ pos: position
3600
+ };
3601
+ const separator = WHITESPACE.test(context.source[position - 1] || "") ? "" : " ";
3602
+ this.#reporter.reportSyntax(context, range, "bash4", true, "unsupportedSyntax", {
3603
+ suggestion: "Use `2>&1 |` instead.",
3604
+ syntax: "The Bash 4 `|&` operator"
3605
+ }, {
3606
+ description: describeReplacement("|&", "2>&1 |"),
3607
+ edits: [{
3608
+ ...range,
3609
+ text: `${separator}2>&1 |`
3610
+ }]
3611
+ });
3612
+ });
3613
+ node.commands.slice(0, -1).forEach((command) => {
3614
+ this.#pipedCommands.add(command);
3615
+ });
3616
+ node.commands.forEach((command) => {
3617
+ this.#walkCommand(command, context);
3618
+ });
3619
+ this.#lineBreaks.checkOperatorLineBreaks(node.commands, context);
3620
+ }
3621
+ #walkSimpleCommand(node, context) {
3622
+ const isRedirection = node.name == null && node.prefix.length + node.suffix.length === 1;
3623
+ node.prefix.forEach((item) => {
3624
+ if (item.type === "Assignment") this.#words.checkAssignment(item, context, node.name ? node : void 0);
3625
+ else this.#redirections.checkRedirection(item, context, isRedirection);
3626
+ });
3627
+ const invocation = node.name && this.#commands.checkInvocation(node.name, node.suffix.filter((item) => item.type === "Word"), context, 0);
3628
+ let argumentContext = invocation?.crossEnv ? {
3629
+ ...context,
3630
+ crossEnv: true
3631
+ } : context;
3632
+ if (invocation?.name != null && (SHELLS.includes(invocation.name) || invocation.name === "find")) argumentContext = withCovered(argumentContext, WINDOWS_PLATFORMS);
3633
+ if (node.name) {
3634
+ this.#words.checkWord(node.name, context, { commandName: true });
3635
+ if (invocation?.name === "echo" && !context.portable) this.#redirections.checkEchoToFile(node, context);
3636
+ }
3637
+ this.#lineBreaks.checkCommandLineBreak(node, argumentContext);
3638
+ const isPrintedToTerminal = invocation?.target === "echo" && node.redirects.length === 0 && !this.#pipedCommands.has(node);
3639
+ node.suffix.forEach((item) => {
3640
+ if (item.type === "Assignment") (item.value.type === "Word" ? [item.value] : item.value.elements).forEach((word) => {
3641
+ this.#words.checkWord(word, argumentContext);
3642
+ });
3643
+ else if (item.type === "Word") this.#words.checkWord(item, argumentContext, {
3644
+ command: invocation?.target,
3645
+ printedToTerminal: isPrintedToTerminal
3646
+ });
3647
+ else this.#redirections.checkRedirection(item, context);
3648
+ });
3649
+ }
3650
+ #reportStatement(context, node, keyword, kind) {
3651
+ const firstWord = substringBefore(keyword, " ");
3652
+ const covered = this.#reporter.reportSyntax(context, {
3653
+ end: node.pos + firstWord.length,
3654
+ pos: node.pos
3655
+ }, kind, false, "unsupportedSyntax", kind === "posix" ? {
3656
+ suggestion: NODE_SCRIPT_SUGGESTION,
3657
+ syntax: `The shell \`${keyword}\` statement`
3658
+ } : {
3659
+ suggestion: kind === "bash4" ? BASH_4_SUGGESTION : BASH_SUGGESTION,
3660
+ syntax: `The ${bashLabel(kind)} \`${keyword}\` statement`
3661
+ });
3662
+ return withCovered(context, covered);
3663
+ }
3664
+ #walkStatements(statements, end, context) {
3665
+ const firstIssue = this.#reporter.issues.length;
3666
+ const backgroundOperators = [];
3667
+ statements.forEach((statement, index) => {
3668
+ this.#walkCommand(statement.command, context);
3669
+ if (statement.background) {
3670
+ const position = context.source.lastIndexOf("&", statement.end - 1);
3671
+ backgroundOperators.push({
3672
+ end: position + 1,
3673
+ pos: position
3674
+ });
3675
+ return;
3676
+ }
3677
+ const next = statements.at(index + 1);
3678
+ const gapEnd = next?.pos || end;
3679
+ const gapStart = this.#statementEnd(statement, gapEnd, context.source);
3680
+ const gap = context.source.slice(gapStart, gapEnd);
3681
+ const comment = COMMENT.exec(gap);
3682
+ const commentText = comment?.[1];
3683
+ const commentStart = comment && commentText != null ? comment.index + comment[0].length - commentText.length : void 0;
3684
+ const semicolon = gap.slice(0, commentStart).indexOf(";");
3685
+ if (semicolon !== -1) {
3686
+ const range = {
3687
+ end: gapStart + semicolon + 1,
3688
+ pos: gapStart + semicolon
3689
+ };
3690
+ this.#reporter.reportSyntax(context, range, "posix", true, "unsupportedSyntax", {
3691
+ suggestion: "Use `&&` instead.",
3692
+ syntax: "The `;` command separator"
3693
+ }, semicolonFix(range, gap, next));
3694
+ } else if (next && gap.includes("\n")) this.#lineBreaks.reportLineBreak(context, gapStart + gap.indexOf("\n"), "Join the commands with `&&` instead.", lineBreakFix(gapStart, gap, next));
3695
+ });
3696
+ if (!this.#reporter.issues.slice(firstIssue).some(({ platforms }) => platforms.length === POSIX_PLATFORMS.length && arrayIsSubset(platforms, POSIX_PLATFORMS))) backgroundOperators.forEach((range) => {
3697
+ this.#reporter.reportSyntax(context, range, "posix", true, "inconsistentBehavior", {
3698
+ reason: "cmd.exe runs the commands sequentially instead of in the background",
3699
+ suggestion: "Use `concurrently` instead.",
3700
+ syntax: "The `&` operator"
3701
+ });
3702
+ });
3703
+ }
3704
+ #walkTestExpression(expression, context) {
3705
+ switch (expression.type) {
3706
+ case "TestBinary":
3707
+ this.#words.checkWord(expression.left, context, { skipGlobs: true });
3708
+ this.#words.checkWord(expression.right, context, { skipGlobs: true });
3709
+ break;
3710
+ case "TestGroup":
3711
+ this.#walkTestExpression(expression.expression, context);
3712
+ break;
3713
+ case "TestLogical":
3714
+ expression.operands.forEach((operand) => {
3715
+ this.#walkTestExpression(operand, context);
3716
+ });
3717
+ break;
3718
+ case "TestNot":
3719
+ this.#walkTestExpression(expression.operand, context);
3720
+ break;
3721
+ case "TestUnary": this.#words.checkWord(expression.operand, context, { skipGlobs: true });
3722
+ }
3723
+ }
3724
+ };
3725
+ /**
3726
+ * Analyzes a script as a runner runs it.
3727
+ * @param script The script's source
3728
+ * @param options Analysis options
3729
+ * @param runner What runs the script
3730
+ * @returns The issues found with the runner
3731
+ */
3732
+ const analyzeWithRunner = (script, options, runner) => {
3733
+ const traits = runnerTraits(runner, options.shellEmulator || false);
3734
+ const analyzer = new ScriptAnalyzer(script.length, options, traits);
3735
+ analyzer.analyzeSource({
3736
+ convertsSlashes: traits.convertsSlashes || false,
3737
+ covered: /* @__PURE__ */ new Set(),
3738
+ crossEnv: false,
3739
+ fixExclusions: [],
3740
+ fixedRange: void 0,
3741
+ offset: 0,
3742
+ portable: traits.portableShell || false,
3743
+ shell: "native",
3744
+ source: script
3745
+ });
3746
+ return analyzer.issues;
3747
+ };
3748
+ // src/analyze-script.ts
3749
+ const DEFAULT_RUNNERS = ["npm"];
3750
+ /** A script that only consists of a comment line, i.e. documentation rather than a script */
3751
+ const COMMENT_LINE = /^\s*#[^\n]*$/;
3752
+ /**
3753
+ * Merges the issues found with each runner, e.g. `rm` with both npm and pnpm.
3754
+ * A merged issue is on the platforms where any of the runners has it, and keeps its fix only if
3755
+ * all of them suggest the same one.
3756
+ * @param issuesByRunner The issues found with each runner
3757
+ * @returns The merged issues
3758
+ */
3759
+ const mergeIssues = (issuesByRunner) => {
3760
+ const merged = /* @__PURE__ */ new Map();
3761
+ issuesByRunner.forEach((issues, runner) => {
3762
+ issues.forEach((issue) => {
3763
+ const key = issueKey(issue);
3764
+ const existing = merged.get(key);
3765
+ if (existing) {
3766
+ existing.platforms = arrayIntersection(PLATFORMS, [...existing.platforms, ...issue.platforms]);
3767
+ existing.runners.push(runner);
3768
+ if (!isEqual(existing.fix, issue.fix)) existing.fix = void 0;
3769
+ } else merged.set(key, {
3770
+ ...issue,
3771
+ runners: [runner]
3772
+ });
3773
+ });
3774
+ });
3775
+ return [...merged.values()];
3776
+ };
3777
+ /**
3778
+ * Analyzes a package.json script for constructs that don't work (the same) on all platforms.
3779
+ * @param script The script's source
3780
+ * @param options Analysis options
3781
+ * @returns The issues found, with offsets relative to the script
3782
+ */
3783
+ const analyzeScript = (script, options = {}) => {
3784
+ if (COMMENT_LINE.test(script)) return [];
3785
+ const runners = isRunnerAgnosticScript(options.scriptName, options.runnerAgnosticScripts) ? PACKAGE_MANAGER_RUNNERS : arrayify(options.runner);
3786
+ return mergeIssues(new Map((runners.length > 0 ? runners : DEFAULT_RUNNERS).map((runner) => [runner, analyzeWithRunner(script, options, runner)])));
3787
+ };
3788
+ export { PLATFORMS, RUNNERS, RUNNER_AGNOSTIC_SCRIPTS, analyzeScript, applyFix, formatPlatforms, formatRunners, getRunner };