@j-o-r/sh 1.1.6 → 1.1.8

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/lib/SH.js CHANGED
@@ -31,12 +31,11 @@ import SHDispatch from './SHDispatch.js';
31
31
  import Test from './Test.js'
32
32
 
33
33
  /**
34
- * @typedef {Object.<string, string>} ArgsObject
35
- * @property {string} [key: string] - Any string key maps to an object
34
+ * @typedef {Object.<string, string | string[]>} ArgsObject
35
+ * @property {string} [key: string] - Any string key maps to a string value
36
36
  * @property {string[]} _ - Array of strings, unnamed parameters
37
37
  * @description Parsed parameters result.
38
38
  */
39
-
40
39
  /**
41
40
  * @typedef {Function} RejectCallback
42
41
  * @param {Error} error - The error object passed to the callback.
@@ -260,32 +259,46 @@ function* expBackoff(max = '60s', rand = '100ms') {
260
259
  /**
261
260
  * Parses command-line arguments into an object.
262
261
  *
263
- * The function recognizes arguments that start with two dashes (`--`) as keys,
262
+ * The function recognizes arguments that start with two dashes (`--`) or one dash (`-`) as keys,
264
263
  * and the subsequent value (if not another key) as the corresponding value.
265
264
  * If a key does not have a value, it defaults to `true`.
266
265
  * All unrecognized arguments are collected in an array under the `_` property.
267
266
  *
268
- * @param {string[]} args - An array of command-line arguments.
267
+ * @param {string[]} [args] - An array of command-line arguments (process.argv.slice(2)).
269
268
  * @returns {ArgsObject} An object where:
270
- * - Each key corresponds to an argument that starts with `--`,
269
+ * - If args is not passed, process.argv.slice(2) will be the default
270
+ * - Each key corresponds to an argument that starts with `--` or `-`,
271
271
  * - The value is either the next argument or `true` if no value is provided,
272
272
  * - The `_` property contains an array of unbound arguments.
273
273
  */
274
274
  const parseArgs = (args) => {
275
- const result = { _: [] }; // Initialize result with an empty array for unbound values
275
+ if (!args) args = process.argv.slice(2);
276
+ const result = { _: [] };
277
+ const seenKeys = new Set();
276
278
  for (let i = 0; i < args.length; i++) {
277
- if (args[i].startsWith('--')) {
278
- const key = args[i].substring(2);
279
- const value = args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true;
279
+ if (args[i].startsWith('--') || args[i].startsWith('-')) {
280
+ if (args[i].startsWith('-') && !args[i].startsWith('--') && args[i].length > 2) {
281
+ throw new Error(`Invalid argument: ${args[i]}. Use '--' for long options.`);
282
+ }
283
+ const key = args[i].startsWith('--') ? args[i].substring(2) : args[i].substring(1);
284
+ if (seenKeys.has(key)) {
285
+ throw new Error(`Duplicate argument: ${args[i]}`);
286
+ }
287
+ seenKeys.add(key);
288
+ let value;
289
+ if (args[i + 1] && !args[i + 1].startsWith('-')) {
290
+ value = args[i + 1];
291
+ i++; // Skip next element as it is a value
292
+ } else {
293
+ value = true;
294
+ }
280
295
  result[key] = value;
281
- if (value !== true) i++; // Skip the next element as it is a value
282
296
  } else {
283
- result._.push(args[i]); // Add unbound value to the array
297
+ result._.push(args[i]);
284
298
  }
285
299
  }
286
300
  return result;
287
- }
288
-
301
+ };
289
302
 
290
303
  export {
291
304
  SH,
package/lib/SHDispatch.js CHANGED
@@ -8,15 +8,18 @@ import SHExec from './SHExecute.js';
8
8
  * @property {Buffer|null} stdout - The standard output of the child process.
9
9
  * @property {Buffer|null} stderr - The standard error of the child process.
10
10
  */
11
- /**
12
- * Default options for the execution environment.
13
- *
11
+ /**
14
12
  * @typedef {Object} SHOptions
15
- * @property {string} [cwd] - The current working directory.
16
- * @property {NodeJS.ProcessEnv} [env] - The environment variables.
17
- * @property {string} [shell] - The shell to use for execution.
18
- * @property {StdioOptions|StdioOption} [stdio] - The stdio configuration.
19
- * @property {number} [timeout] - default 20000: a timeout error is triggerd when a process execution time is exceeded, 0 is no timeout
13
+ * @property {string} [cwd] - Current working directory of the child process.
14
+ * @property {Object} [env] - Environment key-value pairs.
15
+ * @property {Array|string} [argv0] - Explicitly set the value of `argv[0]` sent to the child process.
16
+ * @property {boolean} [detached=false] - If true, the child will be a process group leader.
17
+ * @property {number} [uid] - Sets the user identity of the process.
18
+ * @property {number} [gid] - Sets the group identity of the process.
19
+ * @property {StdioOptions|StdioOption} [stdio='pipe'] - Child's stdio configuration.
20
+ * @property {boolean|string} [shell="bash"] - If true, runs command inside a shell.
21
+ * @property {number} [timeout=0] - In milliseconds, specifies when to terminate the child process.
22
+ * @property {string|Buffer|URL} [input] - The input to write to stdin.
20
23
  */
21
24
  /**
22
25
  * @typedef {('pipe' | 'ignore' | 'inherit' | number)} StdioOption
@@ -49,22 +52,24 @@ import SHExec from './SHExecute.js';
49
52
  * @returns {SHOptions}
50
53
  */
51
54
  const mergeOptions = (predefined, options) => {
52
- const keys = Object.keys(predefined);
53
- const mergedObj = keys.reduce((acc, key) => {
54
- acc[key] = options[key] !== undefined ? options[key] : predefined[key];
55
- return acc;
56
- }, {});
55
+ const mergedObj = { ...predefined };
56
+
57
+ for (const key in options) {
58
+ if (options[key] !== undefined) {
59
+ mergedObj[key] = options[key];
60
+ }
61
+ }
62
+
57
63
  return mergedObj;
58
64
  }
59
65
 
60
-
61
66
  /** @type {SHOptions} */
62
67
  const defaultOptions = {
63
68
  cwd: process.cwd(),
64
69
  env: process.env,
65
70
  shell: 'bash',
66
71
  stdio: ['inherit', 'pipe', 'pipe'],
67
- timeout: 10000 // when 0 there is no timeout
72
+ timeout: 0 // when 0 there is no timeout
68
73
  };
69
74
 
70
75
 
@@ -107,6 +112,7 @@ class SHDispatch {
107
112
  this.#options = mergeOptions(defaultOptions, options)
108
113
  return this;
109
114
  }
115
+
110
116
  /**
111
117
  * @param {string} [payload]
112
118
  * @returns {Promise<string>}
@@ -117,7 +123,7 @@ class SHDispatch {
117
123
  }
118
124
 
119
125
  /**
120
- * Works for screen takeovers like editors
126
+ * Works for terminal screen takeovers like editors
121
127
  * @param {string} [payload]
122
128
  * @returns {import('child_process').SpawnSyncReturns}
123
129
  */
package/lib/SHExecute.js CHANGED
@@ -93,13 +93,9 @@ class SHExecute {
93
93
  * @retuns {Promise<string>}
94
94
  */
95
95
  run(payload) {
96
- let to = 0;
97
96
  if (payload && typeof payload !== 'string') {
98
97
  throw new Error('Argument is not a string');
99
98
  }
100
- if (this.#options.timeout) {
101
- to = this.#options.timeout;
102
- }
103
99
  /** @type {import('node:child_process').SpawnOptions} */
104
100
  const options = this.#options;
105
101
  // pipe need to be set on stdin when posting a payload
@@ -117,21 +113,14 @@ class SHExecute {
117
113
  this.#proc.stdin.end(payload);
118
114
  }
119
115
  return new Promise((resolve, reject) => {
120
- let timeout;
121
- if (to > 0) {
122
- timeout = setTimeout(async () => {
123
- this.#proc.kill();
124
- reject(new Error(`Process timed out: ${this.#command}`));
125
- }, to); // options.timeout
126
- }
127
116
  this.#proc.on('close', (code) => {
128
- if (timeout) clearTimeout(timeout);
129
117
  if (this.#forcedKill) {
130
118
  // Resolve without content
131
119
  resolve();
132
120
  return;
133
121
  }
134
- if (code === 0) {
122
+ // Detached does not closes with an exitcode
123
+ if (code === 0 || code === null || typeof (code) === 'undefined') {
135
124
  resolve(this.#stdout.trim());
136
125
  } else {
137
126
  reject(new Error(`${code}: ${this.#command} "${this.#stderr.trim()}"`));
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@j-o-r/sh",
3
3
  "author": "Jorrit Duin <j-o-r@duin.work>",
4
4
  "type": "module",
5
- "version": "1.1.6",
5
+ "version": "1.1.8",
6
6
  "description": "Execute shell commands on Linux-based systems from javascript",
7
7
  "main": "lib/SH.js",
8
8
  "types": "types/SH.d.ts",
package/types/SH.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export type ArgsObject = {
2
- [x: string]: string;
2
+ [x: string]: string | string[];
3
3
  };
4
4
  export type RejectCallback = Function;
5
5
  export type ResolveCallback = Function;
@@ -44,7 +44,7 @@ export function sleep(duration: string | number): Promise<any>;
44
44
  * // Retry a command 3 times with irregular intervals using exponential backoff
45
45
  * const p = await retry(3, expBackoff(), () => SH`curl -s https://flipwrsi`);
46
46
  */
47
- export function retry(count: number, a: string | typeof expBackoff | Function, b?: Function | undefined): Promise<any>;
47
+ export function retry(count: number, a: string | typeof expBackoff | Function, b?: Function): Promise<any>;
48
48
  /**
49
49
  * This function reads the standard input (stdin) from the current process.
50
50
  * @example
@@ -67,7 +67,7 @@ export function readIn(): Promise<string>;
67
67
  * return 'res';
68
68
  * });
69
69
  */
70
- export function within(callback: Function, resolve?: Function | undefined, reject?: Function | undefined): void;
70
+ export function within(callback: Function, resolve?: ResolveCallback, reject?: RejectCallback): void;
71
71
  /**
72
72
  * Generates an exponential backoff time with a random jitter.
73
73
  *
@@ -76,25 +76,26 @@ export function within(callback: Function, resolve?: Function | undefined, rejec
76
76
  * @param {string} [rand='100ms'] - The maximum random jitter time in a human-readable format (e.g., '100ms' for 100 milliseconds).
77
77
  * @yields {number} The backoff time in milliseconds.
78
78
  */
79
- export function expBackoff(max?: string | undefined, rand?: string | undefined): Generator<number, void, unknown>;
79
+ export function expBackoff(max?: string, rand?: string): Generator<number, void, unknown>;
80
80
  /**
81
81
  * Parses command-line arguments into an object.
82
82
  *
83
- * The function recognizes arguments that start with two dashes (`--`) as keys,
83
+ * The function recognizes arguments that start with two dashes (`--`) or one dash (`-`) as keys,
84
84
  * and the subsequent value (if not another key) as the corresponding value.
85
85
  * If a key does not have a value, it defaults to `true`.
86
86
  * All unrecognized arguments are collected in an array under the `_` property.
87
87
  *
88
- * @param {string[]} args - An array of command-line arguments.
88
+ * @param {string[]} [args] - An array of command-line arguments (process.argv.slice(2)).
89
89
  * @returns {ArgsObject} An object where:
90
- * - Each key corresponds to an argument that starts with `--`,
90
+ * - If args is not passed, process.argv.slice(2) will be the default
91
+ * - Each key corresponds to an argument that starts with `--` or `-`,
91
92
  * - The value is either the next argument or `true` if no value is provided,
92
93
  * - The `_` property contains an array of unbound arguments.
93
94
  */
94
- export function parseArgs(args: string[]): ArgsObject;
95
+ export function parseArgs(args?: string[]): ArgsObject;
95
96
  /**
96
- * @typedef {Object.<string, string>} ArgsObject
97
- * @property {string} [key: string] - Any string key maps to an object
97
+ * @typedef {Object.<string, string | string[]>} ArgsObject
98
+ * @property {string} [key: string] - Any string key maps to a string value
98
99
  * @property {string[]} _ - Array of strings, unnamed parameters
99
100
  * @description Parsed parameters result.
100
101
  */
@@ -25,30 +25,47 @@ export type SpawnSyncResponse = {
25
25
  */
26
26
  stderr: Buffer | null;
27
27
  };
28
- /**
29
- * Default options for the execution environment.
30
- */
31
28
  export type SHOptions = {
32
29
  /**
33
- * - The current working directory.
30
+ * - Current working directory of the child process.
34
31
  */
35
32
  cwd?: string | undefined;
36
33
  /**
37
- * - The environment variables.
34
+ * - Environment key-value pairs.
38
35
  */
39
- env?: NodeJS.ProcessEnv | undefined;
36
+ env?: Object | undefined;
40
37
  /**
41
- * - The shell to use for execution.
38
+ * - Explicitly set the value of `argv[0]` sent to the child process.
42
39
  */
43
- shell?: string | undefined;
40
+ argv0?: string | any[] | undefined;
44
41
  /**
45
- * - The stdio configuration.
42
+ * - If true, the child will be a process group leader.
43
+ */
44
+ detached?: boolean | undefined;
45
+ /**
46
+ * - Sets the user identity of the process.
47
+ */
48
+ uid?: number | undefined;
49
+ /**
50
+ * - Sets the group identity of the process.
51
+ */
52
+ gid?: number | undefined;
53
+ /**
54
+ * - Child's stdio configuration.
46
55
  */
47
56
  stdio?: number | "pipe" | "ignore" | "inherit" | StdioOption[] | undefined;
48
57
  /**
49
- * - default 20000: a timeout error is triggerd when a process execution time is exceeded, 0 is no timeout
58
+ * - If true, runs command inside a shell.
59
+ */
60
+ shell?: string | boolean | undefined;
61
+ /**
62
+ * - In milliseconds, specifies when to terminate the child process.
50
63
  */
51
64
  timeout?: number | undefined;
65
+ /**
66
+ * - The input to write to stdin.
67
+ */
68
+ input?: string | Buffer<ArrayBufferLike> | URL | undefined;
52
69
  };
53
70
  export type StdioOption = ("pipe" | "ignore" | "inherit" | number);
54
71
  export type StdioOptions = Array<StdioOption> | StdioOption;
@@ -62,18 +79,18 @@ declare class SHDispatch {
62
79
  * @param {string} [prefix] - command prefix e.g (default) '/usr/bin/env'
63
80
  * @returns {SHDispatch}
64
81
  */
65
- options(options: import("child_process").SpawnOptions | import("child_process").SpawnSyncOptions, prefix?: string | undefined): SHDispatch;
82
+ options(options: import("child_process").SpawnOptions | import("child_process").SpawnSyncOptions, prefix?: string): SHDispatch;
66
83
  /**
67
84
  * @param {string} [payload]
68
85
  * @returns {Promise<string>}
69
86
  */
70
- run(payload?: string | undefined): Promise<string>;
87
+ run(payload?: string): Promise<string>;
71
88
  /**
72
- * Works for screen takeovers like editors
89
+ * Works for terminal screen takeovers like editors
73
90
  * @param {string} [payload]
74
91
  * @returns {import('child_process').SpawnSyncReturns}
75
92
  */
76
- runSync(payload?: string | undefined): import("child_process").SpawnSyncReturns<any>;
93
+ runSync(payload?: string): import("child_process").SpawnSyncReturns<any>;
77
94
  kill(signal?: string): Promise<number[]>;
78
95
  #private;
79
96
  }
@@ -10,12 +10,12 @@ declare class SHExecute {
10
10
  * @param {string} [payload] - data to write
11
11
  * @retuns {Promise<object>}
12
12
  */
13
- runSync(payload?: string | undefined): import("child_process").SpawnSyncReturns<string | Buffer>;
13
+ runSync(payload?: string): import("child_process").SpawnSyncReturns<string | Buffer<ArrayBufferLike>>;
14
14
  /**
15
15
  * @param {string} [payload] - data to write
16
16
  * @retuns {Promise<string>}
17
17
  */
18
- run(payload?: string | undefined): Promise<any>;
18
+ run(payload?: string): Promise<any>;
19
19
  /**
20
20
  * Kill this process and possible child processes
21
21
  * @param {number | string} signal - kill signal
package/types/Test.d.ts CHANGED
@@ -37,7 +37,7 @@ declare class Test {
37
37
  /**
38
38
  * @param {boolean} [quiet] - does not output a report when true, default `false`
39
39
  */
40
- constructor(quiet?: boolean | undefined);
40
+ constructor(quiet?: boolean);
41
41
  /**
42
42
  * Set the timeout when a synced function is called.
43
43
  * This settles async code used in a sync function
@@ -58,7 +58,7 @@ declare class Test {
58
58
  * @param {number[]} [execute] - limit the execution tests
59
59
  * @returns {Promise<Report>}
60
60
  */
61
- run(execute?: number[] | undefined): Promise<Report>;
61
+ run(execute?: number[]): Promise<Report>;
62
62
  /**
63
63
  * Empty tests
64
64
  */