@j-o-r/sh 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,19 +1,24 @@
1
1
  {
2
2
  "name": "@j-o-r/sh",
3
- "author": "Jorrit Duin <jorrit.duin@gmail.com>",
3
+ "author": "Jorrit Duin <j-o-r@duin.work>",
4
4
  "type": "module",
5
- "version": "0.0.2",
5
+ "version": "0.0.4",
6
6
  "description": "Execute shell commands on Linux-based systems from javascript",
7
- "main": "src/sh.js",
7
+ "main": "lib/sh.js",
8
8
  "engines": {
9
- "node": ">=18.0.0"
9
+ "node": ">=20.0.0"
10
10
  },
11
11
  "scripts": {
12
- "test": "test/sh.js"
12
+ "test": "test/sh.js",
13
+ "compile": "npx rollup src/sh.js --generatedCode es2015 --file lib/sh.js --format es --name SH",
14
+ "publish": "npm run release && npm publish --access public",
15
+ "release": "npm pack --pack-destination=release",
16
+ "types": "tsc lib/*.js --module nodenext --moduleResolution nodenext --declaration --allowJs --emitDeclarationOnly --outDir lib/",
17
+ "clear:types": "rm lib/*.d.ts"
13
18
  },
14
19
  "repository": {
15
20
  "type": "git",
16
- "url": "https://github.com/j-o-r/sh.git"
21
+ "url": "https://codeberg.org/duin/sh"
17
22
  },
18
23
  "license": "Apache License, Version 2.0",
19
24
  "dependencies": {},
@@ -22,9 +27,9 @@
22
27
  "uvu": "^0.5.6"
23
28
  },
24
29
  "bugs": {
25
- "url": "https://github.com/j-o-r/sh/issues"
30
+ "url": "https://codeberg.org/duin/sh/issues"
26
31
  },
27
- "homepage": "https://github.com/j-o-r/sh",
32
+ "homepage": "https://codeberg.org/duin",
28
33
  "keywords": [
29
34
  "shell",
30
35
  "posix",
@@ -1,113 +0,0 @@
1
- // Copyright 2021 Google LLC
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // https://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- //
15
- //
16
- // Original Source: zx
17
- // Link to Original Source: https://github.com/google/zx
18
- // Reason for Using This Code:
19
- // The core functionality of this code is highly beneficial. However, certain parts of the original code
20
- // were overwriting the global namespace with core libraries and variables. This was causing conflicts with
21
- // other packages (for instance, fetch) and introducing unexpected elements into my code base.
22
- // Changes Made:
23
- // - The code has been or is being reformatted to comply with ES2020 standards.
24
- // - Some methods were added and existing ones were modified to enhance usability.
25
- // - The namespace has been changed from '$' to 'SH'.
26
- // Modified by: jorrit.duin+sh[AT]gmail.com
27
-
28
- import { inspect } from 'node:util';
29
- import { exitCodeInfo} from './utils.js';
30
-
31
- /**
32
- * The ProcessPromise returns a ProcessOutput even when it fails, by rejecting it.
33
- * The extension of the Error class is implemented to ensure compatibility when an Error is expected upon rejection.
34
- */
35
- class ProcessOutput extends Error {
36
- #code = 0;
37
- #signal;
38
- #stdout = '';
39
- #stderr = '';
40
- #combined = '';
41
- /**
42
- * @param {number} code - exit code
43
- * @param {string} signal - SIGTERM ...
44
- * @param {string} stdout - std reponse string
45
- * @param {string} stderr - error reponse string
46
- * @param {string} combined - stderr + stdout
47
- * @param {string} message - Error message
48
- */
49
- constructor(code, signal, stdout = '', stderr = '', combined = '', message = '') {
50
- super(message);
51
- this.#code = code;
52
- this.#signal = signal;
53
- this.#stdout = stdout;
54
- this.#stderr = stderr;
55
- this.#combined = combined;
56
- this.name = 'ProcessOutput';
57
- }
58
- /**
59
- * This string represents the standard output (stdout) from the child process.
60
- * @returns {string}
61
- */
62
- get stdout() {
63
- return this.#stdout;
64
- }
65
- /**
66
- * This string represents the error output (stderr) from the child process.
67
- * @returns {string}
68
- */
69
- get stderr() {
70
- return this.#stderr;
71
- }
72
-
73
- /**
74
- * This is an internal method that is often invoked automatically
75
- * by various JavaScript methods.
76
- * It consolidates the entire output for completeness and facilitates further processing.
77
- *
78
- * @returns {string} The consolidated output as a
79
- */
80
- toString() {
81
- return this.#combined.trim();
82
- }
83
- /**
84
- * This represents the exit code returned by the external process.
85
- * @returns {number} The exit
86
- */
87
- get exitCode() {
88
- return this.#code;
89
- }
90
- /**
91
- * This represents the exit signal, for example, "SIGTERM", received from the child process.
92
- * @returns {string} The exit signal from the child
93
- */
94
- get signal() {
95
- return this.#signal;
96
- }
97
- /**
98
- * This method is used for debugging purposes. It displays the current state of the object
99
- * when passed to the console.log function.
100
- */
101
- [inspect.custom]() {
102
- let stringify = (s) => s.length === 0 ? "''" : inspect(s);
103
- return `ProcessOutput {
104
- stdout: ${stringify(this.stdout)},
105
- stderr: ${stringify(this.stderr)},
106
- signal: ${inspect(this.signal)},
107
- exitCode: ${(this.exitCode)}${exitCodeInfo(this.exitCode)
108
- ? ' (' + exitCodeInfo(this.exitCode) + ')'
109
- : ''}
110
- }`;
111
- }
112
- }
113
- export default ProcessOutput;
@@ -1,341 +0,0 @@
1
- // Copyright 2021 Google LLC
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // https://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- //
15
- //
16
- // Original Source: zx
17
- // Link to Original Source: https://github.com/google/zx
18
- // Reason for Using This Code:
19
- // The core functionality of this code is highly beneficial. However, certain parts of the original code
20
- // were overwriting the global namespace with core libraries and variables. This was causing conflicts with
21
- // other packages (for instance, fetch) and introducing unexpected elements into my code base.
22
- // Changes Made:
23
- // - The code has been or is being reformatted to comply with ES2020 standards.
24
- // - Some methods were added and existing ones were modified to enhance usability.
25
- // - The namespace has been changed from '$' to 'SH'.
26
- // Modified by: jorrit.duin+sh[AT]gmail.com
27
-
28
- // import { spawn, exec } from 'node:child_process';
29
- import assert from 'node:assert';
30
- import { killProcesses, spawn, log, errnoMessage, exitCodeInfo, noop, parseDuration } from './utils.js';
31
- import ProcessOutput from './ProcessOutput.js';
32
-
33
- /**
34
- * @typedef {Function} resolver
35
- * @param {ProcessOutput} value
36
- */
37
- /**
38
- * @typedef {Function} rejecter
39
- * @param {ProcessOutput} value
40
- */
41
- /**
42
- * @typedef {Function} PromiseConstruct
43
- * @param {resolver} resolve
44
- * @param {rejecter} reject
45
- */
46
- /**
47
- * @typedef {('pipe' | 'ignore' | 'inherit' | Stream | number)} StdioOption
48
- * @description Defines the stdio configuration for each of the standard streams.
49
- *
50
- * - 'pipe' creates a pipe between the child process and the parent process.
51
- * The parent end of the pipe is exposed as a property on the `ChildProcess` object.
52
- * - 'ignore' indicates that the child process's corresponding stdio file descriptor will be ignored.
53
- * - 'inherit' passes the corresponding stdio stream to/from the child process.
54
- * - Stream object to be used for the stdio stream.
55
- * - Positive integer representing a file descriptor to be used for the stdio stream.
56
- */
57
-
58
- /**
59
- * @typedef {Array<StdioOption>|StdioOption} StdioOptions
60
- * @description
61
- * Configures the stdio streams for the child process. This can be an array or a single StdioOption.
62
- *
63
- * Array Form: Specify the configuration for [stdin, stdout, stderr].
64
- * - If array length is more than 3, additional positions correspond to extra streams.
65
- * Single Value: This value will be applied to stdin, stdout, and stderr.
66
- *
67
- * Examples:
68
- * - ['pipe', 'pipe', 'ignore']: Pipe stdin and stdout, ignore stderr.
69
- * - 'inherit': Inherit all stdio streams from the parent.
70
- */
71
- class ProcessPromise extends Promise {
72
- #command = '';
73
- #from = '';
74
- /** @type {resolver} */
75
- #resolve = () => { };
76
- /** @type {rejecter} */
77
- #reject = () => { };
78
- #snapshot = {};
79
- /** @type {StdioOptions} */
80
- #stdio = ['inherit', 'pipe', 'pipe'];
81
- #nothrow = false;
82
- #quiet = false;
83
- #resolved = false;
84
- #halted = false;
85
- #piped = false;
86
- #prerun = noop;
87
- #postrun = noop;
88
- /**
89
- * @param {PromiseConstruct} p - A function that takes two arguments, resolve and reject.
90
- */
91
- constructor(p) {
92
- super(p)
93
- }
94
- /**
95
- * Set the environment
96
- * and the
97
- * @param {string} cmd - Command to execute
98
- * @param {string} from - Position in the codfe where this is triggred from
99
- * @param {function} resolve - Promise resolve method
100
- * @param {function} reject - Reject method
101
- * @param {object} options - Settings (options default)
102
- */
103
- _bind(cmd, from, resolve, reject, options) {
104
- this.#command = cmd;
105
- this.#from = from;
106
- this.#resolve = resolve;
107
- this.#reject = reject;
108
- this.#snapshot = { ...options };
109
- }
110
- /**
111
- * Run the promise
112
- */
113
- run() {
114
- const ENV = this.#snapshot;
115
- if (this.child) return this; // The _run() can be called from a few places.
116
- this.#prerun(); // In case $1.pipe($2), the $2 returned, and on $2._run() invoke $1._run().
117
- log({
118
- kind: 'cmd',
119
- cmd: this.#command,
120
- verbose: ENV.verbose && !this.#quiet,
121
- });
122
- const cwd = ENV['processCwd'];
123
- const shell = ENV['shell'];
124
- this.child = spawn(ENV.prefix, [this.#command], {
125
- cwd,
126
- shell,
127
- stdio: this.#stdio,
128
- windowsHide: true,
129
- env: ENV.env,
130
- });
131
- this.child.on('close', (code, signal) => {
132
- let message = `exit code: ${code}`;
133
- if (code != 0 || signal != null) {
134
- message = `${stderr || '\n'} at ${this.#from}`;
135
- message += `\n exit code: ${code}${exitCodeInfo(code) ? ' (' + exitCodeInfo(code) + ')' : ''}`;
136
- if (signal != null) {
137
- message += `\n signal: ${signal}`;
138
- }
139
- }
140
- let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);
141
- if (code === 0 || this.#nothrow) {
142
- this.#resolve(output);
143
- }
144
- else {
145
- this.#reject(output);
146
- }
147
- this.#resolved = true;
148
- });
149
- this.child.on('error', (err) => {
150
- const message = `${err.message}\n` +
151
- ` errno: ${err.errno} (${errnoMessage(err.errno)})\n` +
152
- ` code: ${err.code}\n` +
153
- ` at ${this.#from}`;
154
- this.#reject(new ProcessOutput(null, null, stdout, stderr, combined, message));
155
- this.#resolved = true;
156
- });
157
- let stdout = '', stderr = '', combined = '';
158
- /** @param {Blob} data */
159
- const onStdout = (data) => {
160
- log({ kind: 'stdout', data, verbose: ENV.verbose && !this.#quiet });
161
- stdout += data;
162
- combined += data;
163
- };
164
- /** @param {Blob} data */
165
- const onStderr = (data) => {
166
- log({ kind: 'stderr', data, verbose: ENV.verbose && !this.#quiet });
167
- stderr += data;
168
- combined += data;
169
- };
170
- if (!this.#piped)
171
- this.child.stdout?.on('data', onStdout); // If process is piped, don't collect or print output.
172
- this.child.stderr?.on('data', onStderr); // Stderr should be printed regardless of piping.
173
- this.#postrun(); // In case $1.pipe($2), after both subprocesses are running, we can pipe $1.stdout to $2.stdin.
174
- if (this._timeout && this._timeoutSignal) {
175
- const t = setTimeout(() => this.kill(this._timeoutSignal), this._timeout);
176
- this.finally(() => clearTimeout(t)).catch(noop);
177
- }
178
- return this;
179
- }
180
- /**
181
- * stdin child stream
182
- * @retruns {Writeable}
183
- */
184
- get stdin() {
185
- this.stdio('pipe');
186
- this.run();
187
- assert(this.child);
188
- if (this.child.stdin == null)
189
- throw new Error('The stdin of subprocess is null.');
190
- return this.child.stdin;
191
- }
192
- /**
193
- * stdout child stream
194
- * @retruns {Readable}
195
- */
196
- get stdout() {
197
- this.run();
198
- assert(this.child);
199
- if (this.child.stdout == null)
200
- throw new Error('The stdout of subprocess is null.');
201
- return this.child.stdout;
202
- }
203
- /**
204
- * stderr child stream
205
- * @retruns {Readable}
206
- */
207
- get stderr() {
208
- this.run();
209
- assert(this.child);
210
- if (this.child.stderr == null)
211
- throw new Error('The stderr of subprocess is null.');
212
- return this.child.stderr;
213
- }
214
- /**
215
- * process exit code
216
- * @returns {Promise<number>}
217
- */
218
- get exitCode() {
219
- return this.then((p) => p.exitCode, (p) => p.exitCode);
220
- }
221
- then(onfulfilled, onrejected) {
222
- if (this.isHalted && !this.child) {
223
- throw new Error('The process is halted!');
224
- }
225
- return super.then(onfulfilled, onrejected);
226
- }
227
- catch(onrejected) {
228
- return super.catch(onrejected);
229
- }
230
- /**
231
- * Pipe the output to the input to the next Promise
232
- * @example
233
- * const res = await SH`ls -FLa`.pipe(SH`grep package.json`);
234
- */
235
- pipe(dest) {
236
- if (typeof dest == 'string')
237
- throw new Error('The pipe() method does not take strings. Forgot SH?');
238
- if (this.#resolved) {
239
- if (dest instanceof ProcessPromise)
240
- dest.stdin.end(); // In case of piped stdin, we may want to close stdin of dest as well.
241
- throw new Error("The pipe() method shouldn't be called after promise is already resolved!");
242
- }
243
- this.#piped = true;
244
- if (dest instanceof ProcessPromise) {
245
- dest.stdio('pipe');
246
- dest._prerun = this.run.bind(this);
247
- dest._postrun = () => {
248
- if (!dest.child)
249
- throw new Error('Access to stdin of pipe destination without creation a subprocess.');
250
- this.stdout.pipe(dest.stdin);
251
- };
252
- return dest;
253
- }
254
- else {
255
- this._postrun = () => this.stdout.pipe(dest);
256
- return this;
257
- }
258
- }
259
- /**
260
- * Send a KILL signal to the child process
261
- * @returns {Promise<number[]>} the pid numbers that has been killed
262
- */
263
- async kill(signal = 'SIGTERM') {
264
- if (!this.child)
265
- throw new Error('Trying to kill a process without creating one.');
266
- if (!this.child.pid)
267
- throw new Error('The process pid is undefined.');
268
-
269
- return await killProcesses(this.child.pid, signal)
270
- }
271
- stdio(stdin, stdout = 'pipe', stderr = 'pipe') {
272
- this.#stdio = [stdin, stdout, stderr];
273
- return this;
274
- }
275
- /**
276
- * Do not throw
277
- */
278
- nothrow() {
279
- this.#nothrow = true;
280
- return this;
281
- }
282
- /**
283
- * supress log output
284
- * SH.verbose = false; does the same
285
- */
286
- quiet() {
287
- this.#quiet = true;
288
- return this;
289
- }
290
- /**
291
- * Show log output in the console
292
- */
293
- verbose() {
294
- this._quiet = false;
295
- return this;
296
- }
297
- /**
298
- * Set a timeout to kill a process
299
- *
300
- * @param {string} d - 10s, 1000ms
301
- * @param {string} [signal] - default "SIGTERM" Signal to send to kill the proces
302
- */
303
- timeout(d, signal = 'SIGTERM') {
304
- this._timeout = parseDuration(d);
305
- this._timeoutSignal = signal;
306
- return this;
307
- }
308
- /**
309
- * stop execution for the next step
310
- */
311
- halt() {
312
- this.#halted = true;
313
- return this;
314
- }
315
- /**
316
- * @private
317
- * Set a prerun action, internal use only
318
- * @param {function} f
319
- */
320
- set _prerun(f) {
321
- // @ts-ignore
322
- this.#prerun = f;
323
- }
324
- /**
325
- * @private
326
- * Set a postrun action, internal use only
327
- * @param {function} f
328
- */
329
- set _postrun(f) {
330
- // @ts-ignore
331
- this.#postrun = f;
332
- }
333
- /**
334
- * Is this promise halted?
335
- * @returns {boolean}
336
- */
337
- get isHalted() {
338
- return this.#halted;
339
- }
340
- }
341
- export default ProcessPromise;