Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ee94feddfa | |||
| 04517232e8 | |||
| 0ff3596bd8 | |||
| a0010e7f0f | |||
| d65e1ed4f6 | |||
| e61b352576 | |||
| b7882ef60f | |||
| cd5194c365 | |||
| 71cc64b6d9 | |||
| f254a9e078 | |||
| 3d6a33f8d2 | |||
| d37071dae0 | |||
| 181d352e21 | |||
| 8a0a18f4da | |||
| bdc09afedd | |||
| 68060e8565 | |||
| f2552cda79 | |||
| b898382305 | |||
| 5f8f38c2e6 | |||
| 61f76af7d1 | |||
| 529b33fda1 | |||
| f8e431f41e | |||
| 5a32817349 | |||
| 35d22175db | |||
| cd3675280a | |||
| 7c14102324 | |||
| cb41dbaf1c | |||
| 149eb800e7 | |||
| 91e84c8422 | |||
| ff26cd0678 | |||
| acdd729e06 | |||
| 522fbfc42c | |||
| b854715940 | |||
| 35f59054f8 |
@@ -1,10 +1,5 @@
|
||||
{
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public",
|
||||
"npmRegistryUrl": "registry.npmjs.org"
|
||||
},
|
||||
"gitzone": {
|
||||
"@git.zone/cli": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "code.foss.global",
|
||||
@@ -24,9 +19,24 @@
|
||||
"process management",
|
||||
"typescript"
|
||||
]
|
||||
},
|
||||
"release": {
|
||||
"targets": {
|
||||
"npm": {
|
||||
"registries": [
|
||||
"https://registry.npmjs.org",
|
||||
"https://verdaccio.lossless.digital"
|
||||
],
|
||||
"accessLevel": "public"
|
||||
}
|
||||
}
|
||||
},
|
||||
"tsdoc": {
|
||||
"schemaVersion": 2
|
||||
},
|
||||
"@git.zone/tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
|
||||
},
|
||||
"@ship.zone/szci": {
|
||||
"npmGlobalTools": []
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["/npmextra.json"],
|
||||
"fileMatch": ["/.smartconfig.json"],
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+105
@@ -1,5 +1,110 @@
|
||||
# Changelog
|
||||
|
||||
## Pending
|
||||
|
||||
|
||||
## 2026-05-10 - 3.5.0
|
||||
|
||||
### Features
|
||||
|
||||
- Add inherited terminal stdio support to `execSpawn` for trusted interactive CLIs.
|
||||
|
||||
## 2026-05-09 - 3.4.0 - feat(smartshell)
|
||||
add cwd-aware execution options, structured strict-mode errors, and safer process tree termination
|
||||
|
||||
- adds cwd and env runtime options across exec, spawn, interactive, wait-for-line, and PTY execution APIs
|
||||
- introduces SmartshellError with exit code, signal, stdout, stderr, and combined result details for strict-mode failures
|
||||
- terminates timed-out commands via process tree killing to prevent detached child processes from continuing after timeout
|
||||
|
||||
## 2026-03-15 - 3.3.8 - fix(repo)
|
||||
remove obsolete Serena project configuration files
|
||||
|
||||
- Deletes the .serena project configuration from the repository
|
||||
- Cleans up editor or tooling metadata that is not part of the package runtime or source code
|
||||
|
||||
## 2026-03-05 - 3.3.7 - fix(smartshell)
|
||||
avoid triple shell nesting, improve WSL path filtering, and use chunked log buffer to reduce memory usage
|
||||
|
||||
- Spawn uses the executor shell binary directly (e.g. /bin/bash) and removes extra bash -c wrapping to avoid triple shell nesting
|
||||
- Only filter out /mnt/c/ and other WSL-specific PATH entries when running under WSL (adds _isWSL detection)
|
||||
- Replace single concatenated Buffer with chunked buffering in ShellLog (lazy concatenation, logLength property) and update checks to use logLength
|
||||
- Remove unused dependency "tree-kill" from package.json
|
||||
|
||||
## 2026-03-04 - 3.3.6 - fix(smartshell)
|
||||
use 'close' event on child processes to ensure exit handling and update dependency versions
|
||||
|
||||
- Replace child_process 'exit' listeners with 'close' in ts/classes.smartshell.ts (two occurrences) to ensure handlers run after stdio streams are closed.
|
||||
- Bump devDependencies: @git.zone/tsbuild ^2.7.3 -> ^4.1.2, @git.zone/tsrun ^1.6.2 -> ^2.0.1, @git.zone/tstest ^2.8.3 -> ^3.2.0, @types/node ^22.19.13 -> ^25.3.3.
|
||||
- Bump dependencies: @push.rocks/smartexit ^2.0.1 -> ^2.0.3, which ^5.0.0 -> ^6.0.1.
|
||||
|
||||
## 2026-03-03 - 3.3.2 - fix(release)
|
||||
add @git.zone/cli release configuration with registries and public access
|
||||
|
||||
- Updated file: npmextra.json
|
||||
- Added @git.zone/cli.release.registries: https://verdaccio.lossleess.digital, https://registry.npmjs.org
|
||||
- Set @git.zone/cli.release.accessLevel to "public"
|
||||
|
||||
## 2026-03-03 - 3.3.1 - fix(deps)
|
||||
bump @push.rocks/smartexit dependency to ^1.1.1
|
||||
|
||||
- Updated @push.rocks/smartexit from ^1.0.23 to ^1.1.1
|
||||
- Only package.json was modified
|
||||
- Project current version is 3.3.0; recommend a patch release to 3.3.1
|
||||
|
||||
## 2025-08-17 - 3.3.0 - feat(smartshell)
|
||||
Add secure spawn APIs, PTY support, interactive/streaming control, timeouts and buffer limits; update README and tests
|
||||
|
||||
- Introduce execSpawn family (execSpawn, execSpawnStreaming, execSpawnInteractiveControl) for shell-free, secure execution of untrusted input (shell:false).
|
||||
- Add PTY support (optional node-pty) with execInteractiveControlPty and execStreamingInteractiveControlPty; PTY is lazy-loaded and documented as an optional dependency.
|
||||
- Expose interactive control primitives (sendInput, sendLine, endInput, finalPromise) for both spawn and shell-based executions, and streaming interfaces with process control (terminate, kill, keyboardInterrupt, customSignal).
|
||||
- Implement timeouts, maxBuffer limits and onData callbacks to prevent OOM, stream output incrementally, and support early termination and debugging logs.
|
||||
- Improve process lifecycle handling: safe unpipe/unpipe-on-error, smartexit integration, and safer signal-based tree-kill behavior.
|
||||
- Enhance execAndWaitForLine with timeout and terminateOnMatch options to allow pattern-based waits with configurable behavior.
|
||||
- Update README with a Security Guide recommending execSpawn for untrusted input, PTY usage guidance, and new feature documentation (timeouts, buffer limits, debug mode, environment control).
|
||||
- Add extensive tests covering error handling, interactive control, passthrough, PTY behavior, spawn behavior, silent/streaming modes and environment propagation.
|
||||
|
||||
## 2025-08-16 - 3.2.4 - fix(tests)
|
||||
Update tests & CI config, bump deps, add docs and project configs
|
||||
|
||||
- Add comprehensive README overhaul with detailed usage, examples, API reference and best practices.
|
||||
- Add extensive silent-mode tests (test/test.silent.ts) to validate execSilent, execStrictSilent, execStreamingSilent and execAndWaitForLineSilent behaviors.
|
||||
- Update test runner and script: test script now runs tstest with --verbose, --logfile and --timeout; tests now import tapbundle from @git.zone/tstest.
|
||||
- Fix import in test/test.ts to use @git.zone/tstest/tapbundle.
|
||||
- Bump devDependencies: @git.zone/tsbuild -> ^2.6.4, @git.zone/tstest -> ^2.3.2; bump @push.rocks/smartpromise -> ^4.2.3.
|
||||
- Add typings entry and packageManager field to package.json.
|
||||
- Add project configuration files (.serena/project.yml) and local settings (.claude/settings.local.json).
|
||||
|
||||
## 2025-02-20 - 3.2.3 - fix(core)
|
||||
Refactor Smartshell class for improved code clarity and performance
|
||||
|
||||
- Refactored `_exec` method to improve code clarity.
|
||||
- Introduced `IExecOptions` interface for better type handling.
|
||||
- Replaced promise defer with native promises in command execution methods.
|
||||
- Improved logging and error handling in child process execution.
|
||||
- Ensured robust process management with signals handling.
|
||||
|
||||
## 2024-12-13 - 3.2.2 - fix(core)
|
||||
Fix minor code style and formatting issues
|
||||
|
||||
|
||||
## 2024-12-13 - 3.2.1 - fix(dependencies)
|
||||
Update @types/node dependency version
|
||||
|
||||
- Updated @types/node dependency from version ^22.10.1 to ^22.10.2.
|
||||
|
||||
## 2024-12-09 - 3.2.0 - feat(SmartExecution)
|
||||
Add support for scheduling restarts to SmartExecution
|
||||
|
||||
- Introduced the ability to handle consecutive restarts efficiently in SmartExecution.
|
||||
- Ensures that multiple restart requests merge into a single additional restart request if one is already in progress.
|
||||
|
||||
## 2024-12-09 - 3.1.0 - feat(core)
|
||||
Refactor codebase and update dependencies.
|
||||
|
||||
- Refactored core classes with improved structure and modularization.
|
||||
- Updated tsbuild, tsrun, tapbundle, and @types/node dependencies to newer versions.
|
||||
- Improved build script in package.json to use tsbuild with tsfolders.
|
||||
|
||||
## 2024-09-17 - 3.0.6 - fix(core)
|
||||
Fix interactive shell execution and update dependencies
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Task Venture Capital GmbH
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+14
-15
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"name": "@push.rocks/smartshell",
|
||||
"private": false,
|
||||
"version": "3.0.6",
|
||||
"version": "3.5.0",
|
||||
"description": "A library for executing shell commands using promises.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "(tstest test/)",
|
||||
"build": "(tsbuild --web)",
|
||||
"test": "(tstest test/ --verbose --logfile --timeout 20)",
|
||||
"build": "(tsbuild tsfolders --web)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"repository": {
|
||||
@@ -33,19 +33,17 @@
|
||||
},
|
||||
"homepage": "https://code.foss.global/push.rocks/smartshell",
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.1.84",
|
||||
"@git.zone/tsrun": "^1.2.49",
|
||||
"@git.zone/tstest": "^1.0.90",
|
||||
"@push.rocks/tapbundle": "^5.0.24",
|
||||
"@types/node": "^22.5.5"
|
||||
"@git.zone/tsbuild": "^4.4.1",
|
||||
"@git.zone/tsrun": "^2.0.4",
|
||||
"@git.zone/tstest": "^3.6.6",
|
||||
"@types/node": "^25.6.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartdelay": "^3.0.1",
|
||||
"@push.rocks/smartexit": "^1.0.23",
|
||||
"@push.rocks/smartpromise": "^4.0.4",
|
||||
"@push.rocks/smartdelay": "^3.1.0",
|
||||
"@push.rocks/smartexit": "^2.0.3",
|
||||
"@push.rocks/smartpromise": "^4.2.4",
|
||||
"@types/which": "^3.0.4",
|
||||
"tree-kill": "^1.2.2",
|
||||
"which": "^4.0.0"
|
||||
"which": "^7.0.0"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@@ -56,10 +54,11 @@
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
".smartconfig.json",
|
||||
"readme.md"
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
]
|
||||
],
|
||||
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
|
||||
}
|
||||
|
||||
Generated
+5664
-4279
File diff suppressed because it is too large
Load Diff
@@ -1,152 +1,639 @@
|
||||
# @push.rocks/smartshell
|
||||
shell actions designed as promises
|
||||
|
||||
`@push.rocks/smartshell` is a TypeScript-first Node.js library for running shell commands with modern async APIs. It wraps `child_process` in promises, adds strict and silent execution modes, supports streaming and programmatic stdin control, exposes safer shell-free spawn methods for untrusted arguments, and gives you practical process controls like timeouts, process-tree termination, custom environments, working directories, and optional PTY-backed terminal emulation.
|
||||
|
||||
## Issue Reporting and Security
|
||||
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Install
|
||||
|
||||
To install `@push.rocks/smartshell`, use npm:
|
||||
|
||||
```sh
|
||||
npm install @push.rocks/smartshell --save
|
||||
```bash
|
||||
pnpm add @push.rocks/smartshell
|
||||
```
|
||||
|
||||
Or if you prefer using Yarn:
|
||||
PTY support is optional and only needed when a command requires a real terminal:
|
||||
|
||||
```sh
|
||||
yarn add @push.rocks/smartshell
|
||||
```bash
|
||||
pnpm add --save-optional node-pty
|
||||
```
|
||||
|
||||
Ensure that you have TypeScript and the related dependencies installed as well since `@push.rocks/smartshell` is designed to work with TypeScript.
|
||||
|
||||
## Usage
|
||||
|
||||
The `@push.rocks/smartshell` package simplifies running shell commands within Node.js applications by wrapping these commands within promises. This approach enhances the readability and maintainability of code that relies on shell execution, making it particularly useful in automation scripts, build processes, and any scenario where interaction with the system shell is required.
|
||||
|
||||
### Getting Started with `@push.rocks/smartshell`
|
||||
|
||||
First, ensure that you import `Smartshell` from `@push.rocks/smartshell` using ESM syntax in your TypeScript file:
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { Smartshell } from '@push.rocks/smartshell';
|
||||
|
||||
const shell = new Smartshell({
|
||||
executor: 'bash',
|
||||
});
|
||||
|
||||
const result = await shell.exec('echo "hello from smartshell"');
|
||||
|
||||
console.log(result.exitCode); // 0
|
||||
console.log(result.stdout); // hello from smartshell
|
||||
```
|
||||
|
||||
### Creating a Smartshell Instance
|
||||
|
||||
Before executing any shell command, you need to create an instance of `Smartshell`. The constructor accepts configuration options such as the shell executor (`bash` or `sh`), and optionally, paths to source files and directories to include in the shell’s environment.
|
||||
Use `execSpawn()` whenever command arguments include user input or any other untrusted value:
|
||||
|
||||
```typescript
|
||||
const smartShellInstance = new Smartshell({
|
||||
executor: 'bash', // or 'sh'
|
||||
const filenameFromUser = 'report.txt; rm -rf /';
|
||||
|
||||
// Safe: no shell is used, so metacharacters are treated as argument text.
|
||||
const result = await shell.execSpawn('cat', [filenameFromUser], {
|
||||
silent: true,
|
||||
});
|
||||
```
|
||||
|
||||
### Executing Commands
|
||||
## What It Does
|
||||
|
||||
#### Basic Execution
|
||||
- Promise-based command execution for `async`/`await` code.
|
||||
- Shell-based methods for trusted command strings.
|
||||
- Shell-free spawn methods for safer argument handling.
|
||||
- Silent, strict, streaming, passthrough, and interactive-control modes.
|
||||
- Process-tree cleanup through `@push.rocks/smartexit`.
|
||||
- Timeout support for terminating long-running process trees.
|
||||
- `cwd`, `env`, and `AbortSignal` support.
|
||||
- Bounded output buffering with `maxBuffer`.
|
||||
- Separate `stderr` capture plus the historical combined output buffer.
|
||||
- Optional PTY support through `node-pty` for terminal-native programs.
|
||||
- A small `SmartExecution` helper for restarting long-running commands.
|
||||
- The `which` utility re-exported for command discovery.
|
||||
|
||||
To execute a shell command, use the `exec` method. This method returns a promise that resolves with an execution result object containing `exitCode` and `stdout`.
|
||||
## Execution Modes
|
||||
|
||||
### Standard Execution
|
||||
|
||||
`exec()` runs a trusted command string through the configured shell and resolves with an `IExecResult`.
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
const result = await smartShellInstance.exec('echo "Hello, SmartShell"');
|
||||
console.log(result.stdout); // Outputs: Hello, SmartShell
|
||||
})();
|
||||
const result = await shell.exec('git --version');
|
||||
|
||||
console.log(result.exitCode);
|
||||
console.log(result.stdout);
|
||||
```
|
||||
|
||||
#### Silent Execution
|
||||
|
||||
If you prefer not to display the output in the console, use `execSilent`:
|
||||
Shell execution is convenient for hardcoded command strings, pipes, redirects, globbing, and shell syntax:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
const result = await smartShellInstance.execSilent('ls');
|
||||
console.log(result.stdout); // Outputs the list of files and directories
|
||||
})();
|
||||
await shell.exec('mkdir -p dist && cp assets/*.json dist/');
|
||||
```
|
||||
|
||||
#### Strict Execution
|
||||
### Silent Execution
|
||||
|
||||
For scenarios where an execution error should immediately throw an exception, use `execStrict`:
|
||||
`execSilent()` captures output without writing it to the current process stdout.
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
try {
|
||||
const result = await smartShellInstance.execStrict('exit 1');
|
||||
} catch (error) {
|
||||
console.error('Command execution failed');
|
||||
const result = await shell.execSilent('node --version');
|
||||
console.log(result.stdout.trim());
|
||||
```
|
||||
|
||||
### Strict Execution
|
||||
|
||||
`execStrict()` rejects with `SmartshellError` when the command exits with a non-zero code or is terminated by a signal.
|
||||
|
||||
```typescript
|
||||
import { SmartshellError } from '@push.rocks/smartshell';
|
||||
|
||||
try {
|
||||
await shell.execStrict('pnpm test');
|
||||
} catch (error) {
|
||||
if (error instanceof SmartshellError) {
|
||||
console.error(error.message);
|
||||
console.error(error.exitCode);
|
||||
console.error(error.stderr);
|
||||
}
|
||||
})();
|
||||
}
|
||||
```
|
||||
|
||||
#### Streaming Output
|
||||
|
||||
Some commands benefit from streaming output as they execute, especially long-running tasks. For these cases, use `execStreaming`:
|
||||
Use `execStrictSilent()` for strict behavior without console output:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
const execStreamingResult = await smartShellInstance.execStreaming('tail -f /var/log/system.log');
|
||||
|
||||
execStreamingResult.childProcess.stdout.on('data', (data) => {
|
||||
console.log(data.toString());
|
||||
});
|
||||
|
||||
// Remember to handle the process termination as necessary.
|
||||
})();
|
||||
await shell.execStrictSilent('pnpm build');
|
||||
```
|
||||
|
||||
### Advanced Usage
|
||||
### Streaming Execution
|
||||
|
||||
#### Executing With Custom Environment Variables
|
||||
|
||||
`smartshell` allows for the execution of commands within a modified environment, facilitating the use of custom variables or altered PATH values:
|
||||
`execStreaming()` starts a command and returns immediately with the child process, a final result promise, and process-control helpers.
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
smartShellInstance.shellEnv.addSourceFiles(['/path/to/envFile']);
|
||||
smartShellInstance.shellEnv.pathDirArray.push('/custom/bin');
|
||||
const streaming = await shell.execStreaming('pnpm install');
|
||||
|
||||
const result = await smartShellInstance.exec('echo $CUSTOM_VAR');
|
||||
console.log(result.stdout); // Outputs the value of CUSTOM_VAR
|
||||
})();
|
||||
streaming.childProcess.stdout?.on('data', (chunk) => {
|
||||
process.stdout.write(`[install] ${chunk}`);
|
||||
});
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
console.log(result.exitCode);
|
||||
```
|
||||
|
||||
### Interactive Mode
|
||||
|
||||
For commands that require interactive terminal input (not typically recommended for automated scripts), you can use `execInteractive`:
|
||||
Streaming executions can be controlled explicitly:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
await smartShellInstance.execInteractive('npm init');
|
||||
})();
|
||||
const server = await shell.execStreaming('pnpm dev', false, {
|
||||
cwd: '/path/to/app',
|
||||
});
|
||||
|
||||
await server.keyboardInterrupt(); // SIGINT
|
||||
await server.terminate(); // SIGTERM
|
||||
await server.kill(); // SIGKILL
|
||||
await server.customSignal('SIGHUP');
|
||||
```
|
||||
|
||||
### Waiting for Specific Output
|
||||
`execStreamingSilent()` starts a streaming command without printing output automatically.
|
||||
|
||||
To wait for a specific line before proceeding, you might use `execAndWaitForLine`. This is useful for waiting on a process to log a certain message:
|
||||
### Passthrough Execution
|
||||
|
||||
`execPassthrough()` pipes the current process stdin into the command. This is useful for commands that should receive real user input while still returning a result.
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
await smartShellInstance.execAndWaitForLine('npm run watch', /Compilation complete./);
|
||||
console.log('The watch process has finished compiling.');
|
||||
})();
|
||||
await shell.execPassthrough('read name && echo "hello $name"');
|
||||
```
|
||||
|
||||
Given the vast array of features offered by `@push.rocks/smartshell`, integrating shell operations into your TypeScript applications becomes both straightforward and powerful. By harnessing promises and async/await syntax, `smartshell` effectively streamlines shell interactions, making your code cleaner and more intuitive.
|
||||
`execStreamingPassthrough()` combines passthrough stdin with the streaming interface.
|
||||
|
||||
### Programmatic Input Control
|
||||
|
||||
`execInteractiveControl()` returns methods for sending stdin manually.
|
||||
|
||||
```typescript
|
||||
const interactive = await shell.execInteractiveControl('cat');
|
||||
|
||||
await interactive.sendLine('first line');
|
||||
await interactive.sendInput('second line without newline');
|
||||
await interactive.sendInput('\n');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
console.log(result.stdout);
|
||||
```
|
||||
|
||||
`execStreamingInteractiveControl()` gives you both programmatic input and streaming process controls:
|
||||
|
||||
```typescript
|
||||
const repl = await shell.execStreamingInteractiveControl('node');
|
||||
|
||||
await repl.sendLine('console.log(21 * 2)');
|
||||
await repl.sendLine('.exit');
|
||||
|
||||
await repl.finalPromise;
|
||||
```
|
||||
|
||||
### Interactive Shell Execution
|
||||
|
||||
`execInteractive()` runs a trusted shell command with inherited stdio. It is meant for fully interactive terminal use and returns `void`; in CI environments it intentionally does nothing.
|
||||
|
||||
```typescript
|
||||
await shell.execInteractive('vim readme.md');
|
||||
```
|
||||
|
||||
## Secure Spawn APIs
|
||||
|
||||
The `execSpawn()` family uses `child_process.spawn()` with `shell: false`. That means shell metacharacters are not interpreted.
|
||||
|
||||
```typescript
|
||||
const result = await shell.execSpawn('git', ['status', '--short'], {
|
||||
cwd: '/path/to/repo',
|
||||
silent: true,
|
||||
});
|
||||
```
|
||||
|
||||
For trusted interactive CLIs that need the real terminal while still avoiding shell parsing, pass `stdio: 'inherit'`:
|
||||
|
||||
```typescript
|
||||
await shell.execSpawn('opencode', ['run', '--dir', process.cwd(), prompt], {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
```
|
||||
|
||||
Inherited stdio returns an `IExecResult` with the exit code, but stdout and stderr are not captured because the child process writes directly to the terminal.
|
||||
|
||||
### Why Spawn Matters
|
||||
|
||||
```typescript
|
||||
const userInput = 'file.txt; rm -rf /';
|
||||
|
||||
// Dangerous: shell syntax in userInput can be interpreted.
|
||||
await shell.exec(`cat ${userInput}`);
|
||||
|
||||
// Safe: userInput is passed as one literal argument.
|
||||
await shell.execSpawn('cat', [userInput]);
|
||||
```
|
||||
|
||||
### Spawn Streaming
|
||||
|
||||
```typescript
|
||||
const streaming = await shell.execSpawnStreaming('pnpm', ['test'], {
|
||||
cwd: '/path/to/package',
|
||||
});
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
```
|
||||
|
||||
### Spawn Interactive Control
|
||||
|
||||
```typescript
|
||||
const interactive = await shell.execSpawnInteractiveControl('cat', []);
|
||||
|
||||
await interactive.sendLine('hello');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
```
|
||||
|
||||
PTY mode is currently available for shell-based interactive-control methods, not for `execSpawn()`.
|
||||
|
||||
## PTY Support
|
||||
|
||||
Some tools behave differently when they are connected to pipes instead of a real terminal. Editors, REPLs, password prompts, full-screen terminal UIs, readline prompts, and programs that depend on ANSI terminal behavior often need a PTY.
|
||||
|
||||
Install the optional dependency first:
|
||||
|
||||
```bash
|
||||
pnpm add --save-optional node-pty
|
||||
```
|
||||
|
||||
Then use the PTY-specific methods:
|
||||
|
||||
```typescript
|
||||
const prompt = await shell.execInteractiveControlPty(
|
||||
'bash -c \'read -p "Name: " name && echo "Hello $name"\''
|
||||
);
|
||||
|
||||
await prompt.sendLine('Ada');
|
||||
|
||||
const result = await prompt.finalPromise;
|
||||
console.log(result.stdout);
|
||||
```
|
||||
|
||||
Streaming PTY control works the same way, with PTY-backed process controls:
|
||||
|
||||
```typescript
|
||||
const nodeRepl = await shell.execStreamingInteractiveControlPty('node');
|
||||
|
||||
await nodeRepl.sendLine('console.log("PTY ready")');
|
||||
await nodeRepl.sendLine('.exit');
|
||||
|
||||
await nodeRepl.finalPromise;
|
||||
```
|
||||
|
||||
PTY output combines stdout and stderr because terminal sessions expose a single terminal data stream.
|
||||
|
||||
## Runtime Options
|
||||
|
||||
Most execution methods accept these options:
|
||||
|
||||
```typescript
|
||||
interface TExecCommandOptions {
|
||||
ptyCols?: number;
|
||||
ptyRows?: number;
|
||||
ptyTerm?: string;
|
||||
ptyShell?: string;
|
||||
maxBuffer?: number;
|
||||
onData?: (chunk: Buffer | string) => void;
|
||||
timeout?: number;
|
||||
debug?: boolean;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
cwd?: string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
```
|
||||
|
||||
### Working Directory
|
||||
|
||||
Prefer the `cwd` option over embedding `cd ... && ...` into command strings:
|
||||
|
||||
```typescript
|
||||
await shell.execStrict('pnpm build', {
|
||||
cwd: '/path/to/package',
|
||||
});
|
||||
|
||||
await shell.execSpawn('git', ['status', '--short'], {
|
||||
cwd: '/path/to/repo',
|
||||
});
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```typescript
|
||||
await shell.execSpawn('node', ['server.js'], {
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: 'production',
|
||||
PORT: '3000',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Timeouts
|
||||
|
||||
Timeouts terminate the process tree with `SIGTERM`.
|
||||
|
||||
```typescript
|
||||
const result = await shell.execSpawn('sleep', ['10'], {
|
||||
timeout: 500,
|
||||
});
|
||||
|
||||
console.log(result.signal); // SIGTERM on typical POSIX platforms
|
||||
```
|
||||
|
||||
### Bounded Output Buffers
|
||||
|
||||
Regular shell and spawn executions keep a combined output buffer. `maxBuffer` limits that buffer and replaces it with a truncation marker if the limit is exceeded.
|
||||
|
||||
```typescript
|
||||
const result = await shell.exec('long-running-output-command', {
|
||||
maxBuffer: 10 * 1024 * 1024,
|
||||
onData: (chunk) => {
|
||||
// Stream chunks elsewhere while smartshell protects its own buffer.
|
||||
process.stdout.write(chunk);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Debug Logging
|
||||
|
||||
```typescript
|
||||
const streaming = await shell.execSpawnStreaming('sleep', ['30'], {
|
||||
debug: true,
|
||||
});
|
||||
|
||||
await streaming.terminate();
|
||||
await streaming.finalPromise;
|
||||
```
|
||||
|
||||
## Results and Errors
|
||||
|
||||
### `IExecResult`
|
||||
|
||||
```typescript
|
||||
interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
combinedOutput?: string;
|
||||
signal?: NodeJS.Signals;
|
||||
stderr?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Important: `stdout` intentionally preserves smartshell's legacy behavior and contains the combined stdout/stderr buffer. Use `stderr` when you need stderr separately, and use `combinedOutput` when you want to make that combined-buffer behavior explicit in your own code.
|
||||
|
||||
### `SmartshellError`
|
||||
|
||||
Strict methods reject with `SmartshellError` and expose the command result details directly:
|
||||
|
||||
```typescript
|
||||
class SmartshellError extends Error {
|
||||
command: string;
|
||||
result: IExecResult;
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
combinedOutput?: string;
|
||||
stderr?: string;
|
||||
signal?: NodeJS.Signals;
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming and Interactive Results
|
||||
|
||||
```typescript
|
||||
interface IExecResultStreaming {
|
||||
childProcess: import('child_process').ChildProcess;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signal: string) => Promise<void>;
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
}
|
||||
|
||||
interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
```
|
||||
|
||||
## Waiting for Output
|
||||
|
||||
`execAndWaitForLine()` starts a streaming command and resolves when stdout matches a regular expression.
|
||||
|
||||
```typescript
|
||||
await shell.execAndWaitForLine(
|
||||
'pnpm dev',
|
||||
/Server listening on port 3000/,
|
||||
false,
|
||||
{
|
||||
timeout: 30_000,
|
||||
terminateOnMatch: true,
|
||||
cwd: '/path/to/app',
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Use `execAndWaitForLineSilent()` to suppress automatic output:
|
||||
|
||||
```typescript
|
||||
await shell.execAndWaitForLineSilent('node server.js', /ready/, {
|
||||
timeout: 10_000,
|
||||
});
|
||||
```
|
||||
|
||||
If the process ends before a match or the timeout expires, the promise rejects.
|
||||
|
||||
## Environment Customization
|
||||
|
||||
`ShellEnv` is available through each `Smartshell` instance as `shell.shellEnv`. It lets you source files and add PATH directories before shell-based command strings execute.
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: ['/opt/project/env.sh'],
|
||||
pathDirectories: ['/opt/project/bin'],
|
||||
});
|
||||
|
||||
shell.shellEnv.addSourceFiles(['./local.env.sh']);
|
||||
shell.shellEnv.pathDirArray.push('/custom/bin');
|
||||
|
||||
await shell.exec('my-tool --version');
|
||||
```
|
||||
|
||||
`ShellEnv` also imports the current `PATH` and appends `SMARTSHELL_PATH` when that environment variable is set. On WSL it filters Windows path entries that commonly break POSIX shell execution.
|
||||
|
||||
## SmartExecution
|
||||
|
||||
`SmartExecution` is a tiny restart helper for long-running commands such as development servers. It lazily creates its own bash-backed `Smartshell` and keeps one streaming execution active.
|
||||
|
||||
```typescript
|
||||
import { SmartExecution } from '@push.rocks/smartshell';
|
||||
|
||||
const devServer = new SmartExecution('pnpm dev');
|
||||
|
||||
await devServer.restart(); // starts the command
|
||||
await devServer.restart(); // kills the current process tree and starts it again
|
||||
```
|
||||
|
||||
If multiple restarts are requested while a restart is already in progress, they are collapsed into one additional restart.
|
||||
|
||||
## Command Discovery
|
||||
|
||||
The package re-exports `which` for checking whether an executable is available.
|
||||
|
||||
```typescript
|
||||
import { which } from '@push.rocks/smartshell';
|
||||
|
||||
const gitPath = await which('git');
|
||||
console.log(gitPath);
|
||||
```
|
||||
|
||||
## API Overview
|
||||
|
||||
| API | Purpose | Shell interpretation |
|
||||
| --- | --- | --- |
|
||||
| `new Smartshell({ executor })` | Create an execution context using `bash` or `sh` | Depends on method |
|
||||
| `exec(command, options?)` | Run a trusted shell command | Yes |
|
||||
| `execSilent(command, options?)` | Run a trusted shell command without automatic output | Yes |
|
||||
| `execStrict(command, options?)` | Reject on non-zero exit or signal | Yes |
|
||||
| `execStrictSilent(command, options?)` | Strict and silent shell execution | Yes |
|
||||
| `execStreaming(command, silent?, options?)` | Return streaming process controls | Yes |
|
||||
| `execStreamingSilent(command, options?)` | Streaming shell execution without automatic output | Yes |
|
||||
| `execInteractive(command, options?)` | Inherit stdio for fully interactive terminal use | Yes |
|
||||
| `execPassthrough(command, options?)` | Pipe current stdin into the command | Yes |
|
||||
| `execStreamingPassthrough(command, options?)` | Streaming plus stdin passthrough | Yes |
|
||||
| `execInteractiveControl(command, options?)` | Send stdin programmatically | Yes |
|
||||
| `execStreamingInteractiveControl(command, options?)` | Streaming plus programmatic stdin | Yes |
|
||||
| `execInteractiveControlPty(command, options?)` | Programmatic stdin through a PTY | Yes |
|
||||
| `execStreamingInteractiveControlPty(command, options?)` | Streaming PTY control | Yes |
|
||||
| `execSpawn(command, args?, options?)` | Run an executable with literal args | No |
|
||||
| `execSpawnStreaming(command, args?, options?)` | Streaming shell-free spawn | No |
|
||||
| `execSpawnInteractiveControl(command, args?, options?)` | Programmatic stdin with shell-free spawn | No |
|
||||
| `execAndWaitForLine(command, regex, silent?, options?)` | Resolve when stdout matches | Yes |
|
||||
| `execAndWaitForLineSilent(command, regex, options?)` | Silent output wait | Yes |
|
||||
| `new SmartExecution(command)` | Restartable streaming command helper | Yes |
|
||||
| `which(command)` | Resolve executable path | No command execution |
|
||||
|
||||
## Security Guide
|
||||
|
||||
Command execution is powerful and dangerous when untrusted input is involved. The rule is simple: use shell-based APIs for trusted command strings, and use spawn APIs for untrusted arguments.
|
||||
|
||||
### Prefer Spawn for Untrusted Data
|
||||
|
||||
```typescript
|
||||
// Do not do this with untrusted values.
|
||||
await shell.exec(`git checkout ${branchFromRequest}`);
|
||||
|
||||
// Do this instead.
|
||||
await shell.execSpawn('git', ['checkout', branchFromRequest]);
|
||||
```
|
||||
|
||||
### Avoid Shell-Built Paths
|
||||
|
||||
```typescript
|
||||
// Risky if pathFromUser contains shell syntax.
|
||||
await shell.exec(`cat ${pathFromUser}`);
|
||||
|
||||
// Safer: validate the path and pass it as a literal argument.
|
||||
await shell.execSpawn('cat', [pathFromUser]);
|
||||
```
|
||||
|
||||
### Set Resource Limits
|
||||
|
||||
For user-triggered commands, set a timeout and a sensible buffer limit:
|
||||
|
||||
```typescript
|
||||
await shell.execSpawn('convert', [inputPath, outputPath], {
|
||||
timeout: 60_000,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
silent: true,
|
||||
});
|
||||
```
|
||||
|
||||
### Control the Environment
|
||||
|
||||
Pass an explicit `env` when secrets or inherited environment variables matter:
|
||||
|
||||
```typescript
|
||||
await shell.execSpawn('node', ['worker.js'], {
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
NODE_ENV: 'production',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Real-World Recipes
|
||||
|
||||
### Build Pipeline
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
await shell.execStrict('rm -rf dist');
|
||||
await shell.execStrict('pnpm build');
|
||||
await shell.execStrict('pnpm test');
|
||||
```
|
||||
|
||||
### Safe Git Automation
|
||||
|
||||
```typescript
|
||||
async function checkoutAndTag(branch: string, tag: string) {
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
await shell.execSpawn('git', ['checkout', branch], { strict: true });
|
||||
await shell.execSpawn('git', ['tag', tag], { strict: true });
|
||||
}
|
||||
```
|
||||
|
||||
### Wait for a Development Server
|
||||
|
||||
```typescript
|
||||
const server = shell.execAndWaitForLine(
|
||||
'pnpm dev',
|
||||
/ready|listening/i,
|
||||
false,
|
||||
{
|
||||
cwd: '/path/to/app',
|
||||
timeout: 30_000,
|
||||
}
|
||||
);
|
||||
|
||||
await server;
|
||||
```
|
||||
|
||||
### Restart on File Changes
|
||||
|
||||
```typescript
|
||||
import { watch } from 'node:fs';
|
||||
import { SmartExecution } from '@push.rocks/smartshell';
|
||||
|
||||
const execution = new SmartExecution('pnpm dev');
|
||||
|
||||
await execution.restart();
|
||||
|
||||
watch('./src', { recursive: true }, async () => {
|
||||
await execution.restart();
|
||||
});
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||
|
||||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
const getErrorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error);
|
||||
|
||||
tap.test('should handle EPIPE errors gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('head -n 1');
|
||||
|
||||
// Send more data after head exits (will cause EPIPE)
|
||||
await streaming.sendLine('Line 1');
|
||||
|
||||
// This should not throw even though head has exited
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await streaming.sendLine('Line 2');
|
||||
await streaming.sendLine('Line 3');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
// EPIPE or destroyed stdin is expected
|
||||
}
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Line 1');
|
||||
});
|
||||
|
||||
tap.test('should handle strict mode with non-zero exit codes', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execStrict('exit 42');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('exited with code 42');
|
||||
});
|
||||
|
||||
tap.test('should handle strict mode with signal termination', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
// Use execSpawn with strict mode and kill it
|
||||
const result = testSmartshell.execSpawn('sleep', ['10'], {
|
||||
strict: true,
|
||||
timeout: 100 // Will cause SIGTERM
|
||||
});
|
||||
await result;
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('terminated by signal');
|
||||
});
|
||||
|
||||
tap.test('strict mode errors should expose command result details', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let caughtError: smartshell.SmartshellError | null = null;
|
||||
|
||||
try {
|
||||
await testSmartshell.execSpawn('bash', ['-c', 'echo stdout-value; echo stderr-value >&2; exit 7'], {
|
||||
strict: true,
|
||||
silent: true,
|
||||
});
|
||||
} catch (error) {
|
||||
caughtError = error as smartshell.SmartshellError;
|
||||
}
|
||||
|
||||
expect(caughtError).toBeInstanceOf(smartshell.SmartshellError);
|
||||
expect(caughtError!.command).toEqual('bash');
|
||||
expect(caughtError!.exitCode).toEqual(7);
|
||||
expect(caughtError!.stdout).toContain('stdout-value');
|
||||
expect(caughtError!.combinedOutput).toContain('stderr-value');
|
||||
expect(caughtError!.stderr).toContain('stderr-value');
|
||||
expect(caughtError!.result.exitCode).toEqual(7);
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with timeout should reject properly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'sleep 5 && echo "Too late"',
|
||||
/Too late/,
|
||||
false,
|
||||
{ timeout: 100 }
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('Timeout waiting for pattern');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with terminateOnMatch should stop process', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'echo "Match this" && sleep 5',
|
||||
/Match this/,
|
||||
false,
|
||||
{ terminateOnMatch: true }
|
||||
);
|
||||
const duration = Date.now() - start;
|
||||
|
||||
// Should terminate immediately after match, not wait for sleep
|
||||
expect(duration).toBeLessThan(2000);
|
||||
});
|
||||
|
||||
tap.test('should handle process ending without matching pattern', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'echo "Wrong text"',
|
||||
/Never appears/,
|
||||
false
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = getErrorMessage(error);
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('Process ended without matching pattern');
|
||||
});
|
||||
|
||||
tap.test('passthrough unpipe should handle destroyed stdin gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This should complete without throwing even if stdin operations fail
|
||||
const result = await testSmartshell.execPassthrough('echo "Test passthrough unpipe"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Test passthrough unpipe');
|
||||
});
|
||||
|
||||
tap.test('should handle write after stream destroyed', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const interactive = await testSmartshell.execInteractiveControl('true'); // Exits immediately
|
||||
|
||||
// Wait for process to exit
|
||||
await interactive.finalPromise;
|
||||
|
||||
// Try to write after process has exited
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await interactive.sendLine('This should fail');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(getErrorMessage(error)).toContain('destroyed');
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('debug mode should log additional information', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Capture console.log output
|
||||
const originalLog = console.log;
|
||||
let debugOutput = '';
|
||||
console.log = (msg: string) => {
|
||||
debugOutput += msg + '\n';
|
||||
};
|
||||
|
||||
try {
|
||||
const streaming = await testSmartshell.execSpawnStreaming('echo', ['Debug test'], {
|
||||
debug: true
|
||||
});
|
||||
await streaming.terminate();
|
||||
await streaming.finalPromise;
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
|
||||
// Should have logged debug messages
|
||||
expect(debugOutput).toContain('[smartshell]');
|
||||
});
|
||||
|
||||
tap.test('custom environment variables should be passed correctly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const result = await testSmartshell.execSpawn('bash', ['-c', 'echo $CUSTOM_VAR'], {
|
||||
env: {
|
||||
...process.env,
|
||||
CUSTOM_VAR: 'test_value_123'
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('test_value_123');
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
@@ -0,0 +1,84 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle programmatic input control with simple commands', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat which works well with pipe mode
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send input programmatically
|
||||
await interactive.sendLine('TestUser');
|
||||
interactive.endInput();
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('TestUser');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming interactive control with cat', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat for reliable pipe mode operation
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('cat');
|
||||
|
||||
// Send multiple inputs
|
||||
await streaming.sendLine('One');
|
||||
await streaming.sendLine('Two');
|
||||
streaming.endInput();
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('One');
|
||||
expect(result.stdout).toContain('Two');
|
||||
});
|
||||
|
||||
tap.test('should handle sendInput without newline', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat for testing input without newline
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send characters without newline, then newline, then EOF
|
||||
await interactive.sendInput('ABC');
|
||||
await interactive.sendInput('DEF');
|
||||
await interactive.sendInput('\n');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('ABCDEF');
|
||||
});
|
||||
|
||||
tap.test('should mix passthrough and interactive control modes', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test that passthrough still works
|
||||
const passthroughResult = await testSmartshell.execPassthrough('echo "Passthrough works"');
|
||||
expect(passthroughResult.exitCode).toEqual(0);
|
||||
expect(passthroughResult.stdout).toContain('Passthrough works');
|
||||
|
||||
// Test that interactive control works
|
||||
const interactiveResult = await testSmartshell.execInteractiveControl('echo "Interactive control works"');
|
||||
const finalResult = await interactiveResult.finalPromise;
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
expect(finalResult.stdout).toContain('Interactive control works');
|
||||
});
|
||||
|
||||
// Note: Tests requiring bash read with prompts should use PTY mode
|
||||
// See test.pty.ts for examples of testing commands that require terminal features
|
||||
|
||||
export default tap.start();
|
||||
@@ -0,0 +1,42 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle passthrough for interactive commands', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test with a simple echo command that doesn't need input
|
||||
const result = await testSmartshell.execPassthrough('echo "Testing passthrough"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Testing passthrough');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming passthrough', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test streaming passthrough with a simple command
|
||||
const streamingResult = await testSmartshell.execStreamingPassthrough('echo "Testing streaming passthrough"');
|
||||
const finalResult = await streamingResult.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
expect(finalResult.stdout).toContain('Testing streaming passthrough');
|
||||
});
|
||||
|
||||
tap.test('should allow normal exec without passthrough', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Regular exec should still work as before
|
||||
const result = await testSmartshell.exec('echo "Normal exec"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Normal exec');
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
@@ -0,0 +1,147 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
// Helper to check if node-pty is available
|
||||
const isPtyAvailable = async (): Promise<boolean> => {
|
||||
try {
|
||||
// @ts-ignore - node-pty is an optional runtime dependency.
|
||||
await import('node-pty');
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
tap.test('PTY: should handle bash read with prompts correctly', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This test should work with PTY (bash read with prompt)
|
||||
const interactive = await testSmartshell.execInteractiveControlPty("bash -c 'read -p \"Enter name: \" name && echo \"Hello, $name\"'");
|
||||
|
||||
// Send input programmatically
|
||||
await interactive.sendLine('TestUser');
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Enter name:'); // Prompt should be visible with PTY
|
||||
expect(result.stdout).toContain('Hello, TestUser');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle terminal colors and escape sequences', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// ls --color=auto should produce colors in PTY mode
|
||||
const result = await testSmartshell.execInteractiveControlPty('ls --color=always /tmp');
|
||||
const finalResult = await result.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
// Check for ANSI escape sequences (colors) in output
|
||||
const hasColors = /\x1b\[[0-9;]*m/.test(finalResult.stdout);
|
||||
expect(hasColors).toEqual(true);
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle interactive password prompt simulation', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Simulate a password prompt scenario
|
||||
const interactive = await testSmartshell.execStreamingInteractiveControlPty(
|
||||
"bash -c 'read -s -p \"Password: \" pass && echo && echo \"Got password of length ${#pass}\"'"
|
||||
);
|
||||
|
||||
await tools.delayFor(100);
|
||||
await interactive.sendLine('secretpass');
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Password:');
|
||||
expect(result.stdout).toContain('Got password of length 10');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle terminal size options', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Check terminal size using stty
|
||||
const result = await testSmartshell.execInteractiveControlPty('stty size');
|
||||
const finalResult = await result.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
// Default size should be 30 rows x 120 cols as set in _execCommandPty
|
||||
expect(finalResult.stdout).toContain('30 120');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle Ctrl+C (SIGINT) properly', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Start a long-running process
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControlPty('sleep 10');
|
||||
|
||||
// Send interrupt after a short delay
|
||||
await tools.delayFor(100);
|
||||
await streaming.keyboardInterrupt();
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
// Process should exit with non-zero code due to interrupt
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
});
|
||||
|
||||
tap.test('Regular pipe mode should still work alongside PTY', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Regular mode should work without PTY
|
||||
const interactive = await testSmartshell.execInteractiveControl('echo "Pipe mode works"');
|
||||
const result = await interactive.finalPromise;
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Pipe mode works');
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
@@ -0,0 +1,104 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
let testSmartshell: smartshell.Smartshell;
|
||||
|
||||
tap.test('setup for silent execution tests', async () => {
|
||||
testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture output without printing to console', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Hidden from console"');
|
||||
expect(result.stdout).toContain('Hidden from console');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture multi-line output', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Line 1" && echo "Line 2" && echo "Line 3"');
|
||||
const lines = result.stdout.trim().split('\n');
|
||||
expect(lines).toHaveLength(3);
|
||||
expect(lines[0]).toEqual('Line 1');
|
||||
expect(lines[1]).toEqual('Line 2');
|
||||
expect(lines[2]).toEqual('Line 3');
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture error output', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "This works" && exit 1');
|
||||
expect(result.stdout).toContain('This works');
|
||||
expect(result.exitCode).toEqual(1);
|
||||
});
|
||||
|
||||
tap.test('execSilent should parse command output programmatically', async () => {
|
||||
// Test that we can programmatically process the captured output
|
||||
const result = await testSmartshell.execSilent('echo "apple,banana,cherry"');
|
||||
const items = result.stdout.trim().split(',');
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0]).toEqual('apple');
|
||||
expect(items[1]).toEqual('banana');
|
||||
expect(items[2]).toEqual('cherry');
|
||||
});
|
||||
|
||||
tap.test('execStrictSilent should capture output and throw on error', async () => {
|
||||
// Test successful command
|
||||
const successResult = await testSmartshell.execStrictSilent('echo "Success"');
|
||||
expect(successResult.stdout).toContain('Success');
|
||||
expect(successResult.exitCode).toEqual(0);
|
||||
|
||||
// Test that it throws on error
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await testSmartshell.execStrictSilent('echo "Error output" && exit 1');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('execStreamingSilent should capture streaming output without console display', async () => {
|
||||
const streamingResult = await testSmartshell.execStreamingSilent('echo "Line 1" && sleep 0.1 && echo "Line 2"');
|
||||
|
||||
let capturedData = '';
|
||||
streamingResult.childProcess.stdout!.on('data', (data) => {
|
||||
capturedData += data.toString();
|
||||
});
|
||||
|
||||
await streamingResult.finalPromise;
|
||||
expect(capturedData).toContain('Line 1');
|
||||
expect(capturedData).toContain('Line 2');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLineSilent should wait for pattern without console output', async () => {
|
||||
// This should complete without printing to console
|
||||
await testSmartshell.execAndWaitForLineSilent('echo "Starting..." && echo "Ready to go"', /Ready to go/);
|
||||
});
|
||||
|
||||
tap.test('execSilent should handle commands with quotes', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Hello World"');
|
||||
expect(result.stdout.trim()).toEqual('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture large output', async () => {
|
||||
// Generate 100 lines of output
|
||||
const result = await testSmartshell.execSilent('for i in {1..100}; do echo "Line $i"; done');
|
||||
const lines = result.stdout.trim().split('\n');
|
||||
expect(lines).toHaveLength(100);
|
||||
expect(lines[0]).toEqual('Line 1');
|
||||
expect(lines[99]).toEqual('Line 100');
|
||||
});
|
||||
|
||||
tap.test('execSilent vs exec output comparison', async () => {
|
||||
// Both should capture the same output, but exec prints to console
|
||||
const silentResult = await testSmartshell.execSilent('echo "Test output"');
|
||||
const normalResult = await testSmartshell.exec('echo "Test output"');
|
||||
|
||||
expect(silentResult.stdout).toEqual(normalResult.stdout);
|
||||
expect(silentResult.exitCode).toEqual(normalResult.exitCode);
|
||||
});
|
||||
|
||||
export default tap.start({
|
||||
throwOnError: true,
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should send input to cat command', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat which simply echoes what it receives
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send some text and close stdin
|
||||
await interactive.sendLine('Hello World');
|
||||
interactive.endInput(); // Close stdin properly
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('should work with simple echo', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This should work without any input
|
||||
const interactive = await testSmartshell.execInteractiveControl('echo "Direct test"');
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Direct test');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming with input control', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test with streaming and cat
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('cat');
|
||||
|
||||
await streaming.sendLine('Line 1');
|
||||
await streaming.sendLine('Line 2');
|
||||
streaming.endInput(); // Close stdin
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Line 1');
|
||||
expect(result.stdout).toContain('Line 2');
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
@@ -0,0 +1,244 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
|
||||
tap.test('execSpawn should execute commands with args array (shell:false)', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test basic command with args
|
||||
const result = await testSmartshell.execSpawn('echo', ['Hello', 'World']);
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should run in the configured cwd', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartshell-cwd-'));
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSpawn('node', ['-e', 'console.log(process.cwd())'], {
|
||||
cwd: tmpDir,
|
||||
silent: true,
|
||||
});
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout.trim()).toEqual(tmpDir);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('execSilent should run shell commands in the configured cwd', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartshell-shell-cwd-'));
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSilent('pwd', { cwd: tmpDir });
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout.trim()).toEqual(tmpDir);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('execSpawn should handle command not found errors', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await testSmartshell.execSpawn('nonexistentcommand123', ['arg1']);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect((error as NodeJS.ErrnoException).code).toEqual('ENOENT');
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('execSpawn should properly escape arguments', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test that shell metacharacters are treated as literals
|
||||
const result = await testSmartshell.execSpawn('echo', ['$HOME', '&&', 'ls']);
|
||||
expect(result.exitCode).toEqual(0);
|
||||
// Should output literal strings, not expanded/executed
|
||||
expect(result.stdout).toContain('$HOME && ls');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should support inherited stdio for interactive CLIs', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const result = await testSmartshell.execSpawn('node', ['-e', 'console.log("inherited stdio works")'], {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toEqual('');
|
||||
expect(result.stderr).toEqual('');
|
||||
});
|
||||
|
||||
tap.test('execSpawn streaming should work', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execSpawnStreaming('echo', ['Streaming test']);
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Streaming test');
|
||||
});
|
||||
|
||||
tap.test('execSpawn interactive control should work', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const interactive = await testSmartshell.execSpawnInteractiveControl('cat', []);
|
||||
|
||||
await interactive.sendLine('Input line');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Input line');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should capture stderr', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// ls on non-existent directory should produce stderr
|
||||
const result = await testSmartshell.execSpawn('ls', ['/nonexistent/directory/path']);
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.stderr).toBeTruthy();
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with timeout should terminate process', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
const result = await testSmartshell.execSpawn('sleep', ['10'], { timeout: 100 });
|
||||
const duration = Date.now() - start;
|
||||
|
||||
// Process should be terminated by timeout
|
||||
expect(duration).toBeLessThan(500);
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.signal).toBeTruthy(); // Should have been killed by signal
|
||||
});
|
||||
|
||||
tap.test('execSpawn timeout should terminate the spawned process tree', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const markerPath = path.join(os.tmpdir(), `smartshell-spawn-timeout-${process.pid}-${Date.now()}`);
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSpawn(
|
||||
'bash',
|
||||
['-c', `(sleep 0.6; touch "${markerPath}") & wait`],
|
||||
{ timeout: 100, silent: true },
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(fs.existsSync(markerPath)).toBeFalse();
|
||||
} finally {
|
||||
fs.rmSync(markerPath, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('exec timeout should terminate the shell process tree', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
const markerPath = path.join(os.tmpdir(), `smartshell-shell-timeout-${process.pid}-${Date.now()}`);
|
||||
|
||||
try {
|
||||
const result = await testSmartshell.execSilent(`(sleep 0.6; touch "${markerPath}") & wait`, {
|
||||
timeout: 100,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(fs.existsSync(markerPath)).toBeFalse();
|
||||
} finally {
|
||||
fs.rmSync(markerPath, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('execSpawn with maxBuffer should truncate output', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Generate large output
|
||||
const result = await testSmartshell.execSpawn('bash', ['-c', 'for i in {1..1000}; do echo "Line $i with some padding text to make it longer"; done'], {
|
||||
maxBuffer: 1024, // Very small buffer
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('[Output truncated - exceeded maxBuffer]');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with onData callback should stream data', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let dataReceived = '';
|
||||
const result = await testSmartshell.execSpawn('echo', ['Test data'], {
|
||||
onData: (chunk) => {
|
||||
dataReceived += chunk.toString();
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(dataReceived).toContain('Test data');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with signal should report signal in result', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execSpawnStreaming('sleep', ['10']);
|
||||
|
||||
// Send SIGTERM after a short delay
|
||||
setTimeout(() => streaming.terminate(), 100);
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.signal).toEqual('SIGTERM');
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
|
||||
import * as smartshell from '../ts/index.js';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
@@ -26,7 +26,7 @@ tap.test('smartshell should run async and silent', async () => {
|
||||
tap.test('smartshell should stream a shell execution', async () => {
|
||||
let done = smartpromise.defer();
|
||||
let execStreamingResponse = await testSmartshell.execStreaming('npm -v');
|
||||
execStreamingResponse.childProcess.stdout.on('data', (data) => {
|
||||
execStreamingResponse.childProcess.stdout!.on('data', (data) => {
|
||||
done.resolve(data);
|
||||
});
|
||||
let data = await done.promise;
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartshell',
|
||||
version: '3.0.6',
|
||||
version: '3.5.0',
|
||||
description: 'A library for executing shell commands using promises.'
|
||||
}
|
||||
|
||||
@@ -28,29 +28,38 @@ export class ShellEnv {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect if running under Windows Subsystem for Linux
|
||||
*/
|
||||
private static _isWSL(): boolean {
|
||||
return !!(
|
||||
process.env.WSL_DISTRO_NAME ||
|
||||
process.env.WSLENV ||
|
||||
(process.platform === 'linux' && process.env.PATH?.includes('/mnt/c/'))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* imports path into the shell from env if available and returns it with
|
||||
*/
|
||||
private _setPath(commandStringArg: string): string {
|
||||
let commandResult = commandStringArg;
|
||||
let commandPaths: string[] = [];
|
||||
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
|
||||
commandPaths = commandPaths.concat(process.env.PATH?.split(':') ?? []);
|
||||
if (process.env.SMARTSHELL_PATH) {
|
||||
commandPaths = commandPaths.concat(process.env.SMARTSHELL_PATH.split(':'));
|
||||
}
|
||||
|
||||
// lets filter for unwanted paths
|
||||
// Windows WSL
|
||||
// Only filter out WSL-specific paths when actually running under WSL
|
||||
if (ShellEnv._isWSL()) {
|
||||
commandPaths = commandPaths.filter((commandPathArg) => {
|
||||
const filterResult =
|
||||
return (
|
||||
!commandPathArg.startsWith('/mnt/c/') &&
|
||||
!commandPathArg.startsWith('Files/1E') &&
|
||||
!commandPathArg.includes(' ');
|
||||
if (!filterResult) {
|
||||
// console.log(`${commandPathArg} will be filtered!`);
|
||||
}
|
||||
return filterResult;
|
||||
!commandPathArg.includes(' ')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
commandResult = `PATH=${commandPaths.join(':')} && ${commandStringArg}`;
|
||||
return commandResult;
|
||||
@@ -89,14 +98,12 @@ export class ShellEnv {
|
||||
}
|
||||
pathString += ` && `;
|
||||
|
||||
switch (this.executor) {
|
||||
case 'bash':
|
||||
commandResult = `bash -c '${pathString}${sourceString}${commandArg}'`;
|
||||
break;
|
||||
case 'sh':
|
||||
// For both bash and sh executors, build the command string directly.
|
||||
// The shell nesting is handled by spawn() using the appropriate shell binary.
|
||||
// Previously bash executor wrapped in `bash -c '...'` which caused triple
|
||||
// shell nesting (Node spawn sh -> bash -c -> command). Now spawn() uses
|
||||
// shell: '/bin/bash' directly, so we don't need the extra wrapping.
|
||||
commandResult = `${pathString}${sourceString}${commandArg}`;
|
||||
break;
|
||||
}
|
||||
commandResult = this._setPath(commandResult);
|
||||
return commandResult;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
/**
|
||||
* a log handler for spawned logs
|
||||
* making sure the process doesn't run out of memory
|
||||
*/
|
||||
export class ShellLog {
|
||||
private chunks: Buffer[] = [];
|
||||
private totalLength = 0;
|
||||
|
||||
/**
|
||||
* Get the accumulated log as a single Buffer.
|
||||
* Concatenation happens lazily only when accessed.
|
||||
*/
|
||||
public get logStore(): Buffer {
|
||||
if (this.chunks.length === 0) {
|
||||
return Buffer.alloc(0);
|
||||
}
|
||||
if (this.chunks.length === 1) {
|
||||
return this.chunks[0];
|
||||
}
|
||||
// Flatten chunks into a single buffer
|
||||
const combined = Buffer.concat(this.chunks, this.totalLength);
|
||||
// Replace chunks array with the single combined buffer for future access
|
||||
this.chunks = [combined];
|
||||
return combined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the log store directly (used for truncation).
|
||||
*/
|
||||
public set logStore(value: Buffer) {
|
||||
this.chunks = [value];
|
||||
this.totalLength = value.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current total length of buffered data without concatenating.
|
||||
*/
|
||||
public get logLength(): number {
|
||||
return this.totalLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* log data to console
|
||||
* @param dataArg
|
||||
*/
|
||||
public writeToConsole(dataArg: string | Buffer): void {
|
||||
// make sure we have the data as string
|
||||
process.stdout.write(dataArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* add data to Buffer for later consumption
|
||||
* @param dataArg
|
||||
*/
|
||||
public addToBuffer(dataArg: string | Buffer): void {
|
||||
// make sure we have the data as Buffer
|
||||
const dataBuffer: Buffer = Buffer.isBuffer(dataArg) ? dataArg : Buffer.from(dataArg);
|
||||
this.chunks.push(dataBuffer);
|
||||
this.totalLength += dataBuffer.length;
|
||||
}
|
||||
|
||||
public logAndAdd(dataArg: string | Buffer): void {
|
||||
this.writeToConsole(dataArg);
|
||||
this.addToBuffer(dataArg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import { Smartshell, type IExecResultStreaming } from './classes.smartshell.js';
|
||||
|
||||
export interface IDeferred<T> {
|
||||
resolve: (value?: T | PromiseLike<T>) => void;
|
||||
reject: (reason?: any) => void;
|
||||
promise: Promise<T>;
|
||||
}
|
||||
|
||||
export class SmartExecution {
|
||||
public smartshell!: Smartshell;
|
||||
public currentStreamingExecution!: IExecResultStreaming;
|
||||
public commandString: string;
|
||||
|
||||
private isRestartInProgress = false;
|
||||
private isAnotherRestartRequested = false;
|
||||
|
||||
constructor(commandStringArg: string) {
|
||||
this.commandString = commandStringArg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a restart. If a restart is currently in progress, any additional calls
|
||||
* to restart will merge into a single additional restart request, which will only execute
|
||||
* once the current restart completes.
|
||||
*/
|
||||
public async restart(): Promise<void> {
|
||||
if (this.isRestartInProgress) {
|
||||
// If there's already a restart in progress, just mark that another restart was requested
|
||||
this.isAnotherRestartRequested = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.isRestartInProgress = true;
|
||||
try {
|
||||
if (!this.smartshell) {
|
||||
this.smartshell = new Smartshell({
|
||||
executor: 'bash',
|
||||
});
|
||||
}
|
||||
if (this.currentStreamingExecution) {
|
||||
await this.currentStreamingExecution.kill();
|
||||
}
|
||||
this.currentStreamingExecution = await this.smartshell.execStreaming(this.commandString);
|
||||
} finally {
|
||||
this.isRestartInProgress = false;
|
||||
}
|
||||
|
||||
// If another restart was requested while we were busy, we handle it now
|
||||
if (this.isAnotherRestartRequested) {
|
||||
this.isAnotherRestartRequested = false;
|
||||
await this.restart();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,985 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import { ShellEnv } from './classes.shellenv.js';
|
||||
import type { IShellEnvContructorOptions, TExecutor } from './classes.shellenv.js';
|
||||
import { ShellLog } from './classes.shelllog.js';
|
||||
import * as cp from 'child_process';
|
||||
|
||||
// -- interfaces --
|
||||
export interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
/** stdout currently preserves smartshell's legacy combined stdout/stderr buffer. */
|
||||
combinedOutput?: string;
|
||||
signal?: NodeJS.Signals;
|
||||
stderr?: string;
|
||||
}
|
||||
|
||||
export class SmartshellError extends Error {
|
||||
public command: string;
|
||||
public result: IExecResult;
|
||||
public exitCode: number;
|
||||
public stdout: string;
|
||||
public combinedOutput?: string;
|
||||
public stderr?: string;
|
||||
public signal?: NodeJS.Signals;
|
||||
|
||||
constructor(command: string, result: IExecResult) {
|
||||
const reason = result.signal
|
||||
? `terminated by signal ${result.signal}`
|
||||
: `exited with code ${result.exitCode}`;
|
||||
super(`Command "${command}" ${reason}`);
|
||||
this.name = 'SmartshellError';
|
||||
this.command = command;
|
||||
this.result = result;
|
||||
this.exitCode = result.exitCode;
|
||||
this.stdout = result.stdout;
|
||||
this.combinedOutput = result.combinedOutput;
|
||||
this.stderr = result.stderr;
|
||||
this.signal = result.signal;
|
||||
}
|
||||
}
|
||||
|
||||
export interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
|
||||
export interface IExecResultStreaming {
|
||||
childProcess: cp.ChildProcess;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signal: plugins.smartexit.TProcessSignal) => Promise<void>;
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
}
|
||||
|
||||
export interface IExecRuntimeOptions {
|
||||
ptyCols?: number;
|
||||
ptyRows?: number;
|
||||
ptyTerm?: string;
|
||||
ptyShell?: string;
|
||||
maxBuffer?: number;
|
||||
onData?: (chunk: Buffer | string) => void;
|
||||
timeout?: number;
|
||||
debug?: boolean;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
cwd?: string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface IExecOptions extends IExecRuntimeOptions {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
}
|
||||
|
||||
export interface ISpawnOptions extends IExecRuntimeOptions {
|
||||
command: string;
|
||||
args?: string[];
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
/**
|
||||
* When set to `inherit`, the child process uses the parent terminal directly.
|
||||
* This is useful for trusted interactive CLIs while still avoiding shell parsing.
|
||||
*/
|
||||
stdio?: 'pipe' | 'inherit';
|
||||
}
|
||||
|
||||
export type TExecCommandOptions = IExecRuntimeOptions;
|
||||
|
||||
export class Smartshell {
|
||||
public shellEnv: ShellEnv;
|
||||
public smartexit = new plugins.smartexit.SmartExit();
|
||||
|
||||
constructor(optionsArg: IShellEnvContructorOptions) {
|
||||
this.shellEnv = new ShellEnv(optionsArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a given command asynchronously.
|
||||
*/
|
||||
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive | void> {
|
||||
if (options.interactive) {
|
||||
return await this._execInteractive({
|
||||
commandString: options.commandString,
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
});
|
||||
}
|
||||
return await this._execCommand(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an interactive command.
|
||||
*/
|
||||
private async _execInteractive(options: Pick<IExecOptions, 'commandString' | 'cwd' | 'env'>): Promise<void> {
|
||||
// Skip interactive execution in CI environments.
|
||||
if (process.env.CI) {
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
const shell = cp.spawn(options.commandString, {
|
||||
stdio: 'inherit',
|
||||
shell: true,
|
||||
detached: true,
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(shell);
|
||||
|
||||
shell.on('close', (code) => {
|
||||
console.log(`Interactive shell terminated with code ${code}`);
|
||||
this.smartexit.removeProcess(shell);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array (shell:false) for security
|
||||
*/
|
||||
private async _execSpawn(options: ISpawnOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const shellLogInstance = new ShellLog();
|
||||
let stderrBuffer = '';
|
||||
const maxBuffer = options.maxBuffer || 200 * 1024 * 1024; // Default 200MB
|
||||
let bufferExceeded = false;
|
||||
const inheritStdio = options.stdio === 'inherit';
|
||||
|
||||
// Handle PTY mode if requested
|
||||
if (options.usePty) {
|
||||
throw new Error('PTY mode is not yet supported with execSpawn. Use exec methods with shell:true for PTY.');
|
||||
}
|
||||
|
||||
if (inheritStdio && (options.streaming || options.interactiveControl)) {
|
||||
throw new Error('execSpawn stdio: inherit cannot be combined with streaming or interactiveControl.');
|
||||
}
|
||||
|
||||
const execChildProcess = cp.spawn(options.command, options.args || [], {
|
||||
shell: false, // SECURITY: Never use shell with untrusted input
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
stdio: inheritStdio ? 'inherit' : 'pipe',
|
||||
detached: inheritStdio ? false : true, // Inherited TTY needs normal terminal signal handling.
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
// Handle timeout
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
void this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Connect stdin if passthrough is enabled (but not for interactive control)
|
||||
if (!inheritStdio && options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
process.stdin.pipe(execChildProcess.stdin);
|
||||
}
|
||||
|
||||
// Create input methods for interactive control
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
if (!execChildProcess.stdin) {
|
||||
throw new Error('stdin is not available for this process');
|
||||
}
|
||||
const childStdin = execChildProcess.stdin;
|
||||
if (childStdin.destroyed || !childStdin.writable) {
|
||||
throw new Error('stdin has been destroyed or is not writable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
childStdin.write(input, 'utf8', (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
return sendInput(line + '\n');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
execChildProcess.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
// Capture stdout and stderr output
|
||||
execChildProcess.stdout?.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
execChildProcess.stderr?.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
const dataStr = data.toString();
|
||||
stderrBuffer += dataStr;
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap child process termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
const handleExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process ends if passthrough was enabled
|
||||
if (!inheritStdio && options.passthrough && !options.interactiveControl) {
|
||||
try {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const combinedOutput = shellLogInstance.logStore.toString();
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: combinedOutput,
|
||||
combinedOutput,
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
reject(new SmartshellError(options.command, execResult));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('close', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process errors if passthrough was enabled
|
||||
if (!inheritStdio && options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
try {
|
||||
if (!execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin on error: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGKILL', options.debug);
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGINT', options.debug);
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, signal, options.debug);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command and returns either a non-streaming result or a streaming interface.
|
||||
*/
|
||||
private async _execCommand(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
|
||||
const shellLogInstance = new ShellLog();
|
||||
let stderrBuffer = '';
|
||||
const maxBuffer = options.maxBuffer || 200 * 1024 * 1024; // Default 200MB
|
||||
let bufferExceeded = false;
|
||||
|
||||
// Handle PTY mode if requested
|
||||
if (options.usePty) {
|
||||
return await this._execCommandPty(options, commandToExecute, shellLogInstance);
|
||||
}
|
||||
|
||||
// Use the executor's shell binary directly to avoid triple shell nesting.
|
||||
// Previously: Node spawn(shell:true) → /bin/sh → bash -c → command (3 layers)
|
||||
// Now: Node spawn(shell:bash) → command (1 layer)
|
||||
const shellBinary = this.shellEnv.executor === 'bash' ? '/bin/bash' : true;
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: shellBinary,
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
detached: true, // Own process group — immune to terminal SIGINT, managed by smartexit
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
// Handle timeout
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
void this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Connect stdin if passthrough is enabled (but not for interactive control)
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
process.stdin.pipe(execChildProcess.stdin);
|
||||
}
|
||||
|
||||
// Create input methods for interactive control
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
if (!execChildProcess.stdin) {
|
||||
throw new Error('stdin is not available for this process');
|
||||
}
|
||||
if (execChildProcess.stdin.destroyed || !execChildProcess.stdin.writable) {
|
||||
throw new Error('stdin has been destroyed or is not writable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
execChildProcess.stdin.write(input, 'utf8', (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
return sendInput(line + '\n');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
execChildProcess.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
// Capture stdout and stderr output
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
execChildProcess.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
const dataStr = data.toString();
|
||||
stderrBuffer += dataStr;
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logLength > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap child process termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
const handleExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process ends if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl) {
|
||||
try {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const combinedOutput = shellLogInstance.logStore.toString();
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: combinedOutput,
|
||||
combinedOutput,
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
reject(new SmartshellError(options.commandString, execResult));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('close', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process errors if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
try {
|
||||
if (!execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin on error: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGKILL', options.debug);
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, 'SIGINT', options.debug);
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await this.killProcessTree(execChildProcess.pid, signal, options.debug);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete.
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
private async killProcessTree(
|
||||
pid: number | undefined,
|
||||
signal: plugins.smartexit.TProcessSignal,
|
||||
debug?: boolean,
|
||||
): Promise<void> {
|
||||
if (!pid) {
|
||||
return;
|
||||
}
|
||||
if (debug) {
|
||||
console.log(`[smartshell] Killing process tree ${pid} with ${signal}`);
|
||||
}
|
||||
try {
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(pid, signal);
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.log(`[smartshell] Tree kill failed for ${pid}: ${error}`);
|
||||
}
|
||||
try {
|
||||
process.kill(pid, signal as NodeJS.Signals);
|
||||
} catch {
|
||||
// Process already exited or is not accessible.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async exec(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
const result = await this._exec({ commandString, ...options });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
public async execSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, ...options, silent: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrict(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, ...options, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrictSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, ...options, silent: true, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreaming(
|
||||
commandString: string,
|
||||
silent: boolean = false,
|
||||
options: TExecCommandOptions = {},
|
||||
): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, ...options, silent, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execStreamingSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, ...options, silent: true, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractive(commandString: string, options: TExecCommandOptions = {}): Promise<void> {
|
||||
await this._exec({ commandString, ...options, interactive: true });
|
||||
}
|
||||
|
||||
public async execPassthrough(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
|
||||
return await this._exec({ commandString, ...options, passthrough: true }) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreamingPassthrough(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, ...options, streaming: true, passthrough: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControl(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, ...options, interactiveControl: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControl(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, ...options, streaming: true, interactiveControl: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControlPty(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, ...options, interactiveControl: true, usePty: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControlPty(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, ...options, streaming: true, interactiveControl: true, usePty: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array (shell:false) for security
|
||||
* This is the recommended API for untrusted input
|
||||
*/
|
||||
public async execSpawn(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args'> = {}): Promise<IExecResult> {
|
||||
const result = await this._execSpawn({ command, args, ...options });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array in streaming mode
|
||||
*/
|
||||
public async execSpawnStreaming(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'streaming'> = {}): Promise<IExecResultStreaming> {
|
||||
return await this._execSpawn({ command, args, ...options, streaming: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array with interactive control
|
||||
*/
|
||||
public async execSpawnInteractiveControl(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'interactiveControl'> = {}): Promise<IExecResultInteractive> {
|
||||
return await this._execSpawn({ command, args, ...options, interactiveControl: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execAndWaitForLine(
|
||||
commandString: string,
|
||||
regex: RegExp,
|
||||
silent: boolean = false,
|
||||
options: { timeout?: number; terminateOnMatch?: boolean; cwd?: string; env?: NodeJS.ProcessEnv } = {}
|
||||
): Promise<void> {
|
||||
const execStreamingResult = await this.execStreaming(commandString, silent, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
});
|
||||
const stdout = execStreamingResult.childProcess.stdout;
|
||||
if (!stdout) {
|
||||
await execStreamingResult.terminate();
|
||||
throw new Error('stdout is not available for this process');
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let matched = false;
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
|
||||
// Set up timeout if specified
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(async () => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
// Remove listener to prevent memory leak
|
||||
stdout.removeAllListeners('data');
|
||||
await execStreamingResult.terminate();
|
||||
reject(new Error(`Timeout waiting for pattern after ${options.timeout}ms`));
|
||||
}
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
const dataHandler = async (chunk: Buffer | string) => {
|
||||
const data = typeof chunk === 'string' ? chunk : chunk.toString();
|
||||
if (!matched && regex.test(data)) {
|
||||
matched = true;
|
||||
|
||||
// Clear timeout if set
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
|
||||
// Remove listener to prevent memory leak
|
||||
stdout.removeListener('data', dataHandler);
|
||||
|
||||
// Terminate process if requested
|
||||
if (options.terminateOnMatch) {
|
||||
await execStreamingResult.terminate();
|
||||
await execStreamingResult.finalPromise;
|
||||
}
|
||||
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
stdout.on('data', dataHandler);
|
||||
|
||||
// Also resolve/reject when process ends
|
||||
execStreamingResult.finalPromise.then(() => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
reject(new Error('Process ended without matching pattern'));
|
||||
}
|
||||
}).catch((err) => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public async execAndWaitForLineSilent(commandString: string, regex: RegExp, options?: { timeout?: number; terminateOnMatch?: boolean; cwd?: string; env?: NodeJS.ProcessEnv }): Promise<void> {
|
||||
return this.execAndWaitForLine(commandString, regex, true, options);
|
||||
}
|
||||
|
||||
private nodePty: any = null;
|
||||
|
||||
private async lazyLoadNodePty(): Promise<any> {
|
||||
if (this.nodePty) {
|
||||
return this.nodePty;
|
||||
}
|
||||
|
||||
try {
|
||||
// Try to load node-pty if available
|
||||
// @ts-ignore - node-pty is optional
|
||||
this.nodePty = await import('node-pty');
|
||||
return this.nodePty;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
'node-pty is required for PTY support but is not installed.\n' +
|
||||
'Please install it as an optional dependency:\n' +
|
||||
' pnpm add --save-optional node-pty\n' +
|
||||
'Note: node-pty requires compilation and may have platform-specific requirements.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async _execCommandPty(
|
||||
options: IExecOptions,
|
||||
commandToExecute: string,
|
||||
shellLogInstance: ShellLog
|
||||
): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const pty = await this.lazyLoadNodePty();
|
||||
|
||||
// Platform-aware shell selection
|
||||
let shell: string;
|
||||
let shellArgs: string[];
|
||||
|
||||
if (options.ptyShell) {
|
||||
// User-provided shell override
|
||||
shell = options.ptyShell;
|
||||
shellArgs = ['-c', commandToExecute];
|
||||
} else if (process.platform === 'win32') {
|
||||
// Windows: Use PowerShell by default, or cmd as fallback
|
||||
const powershell = process.env.PROGRAMFILES
|
||||
? `${process.env.PROGRAMFILES}\\PowerShell\\7\\pwsh.exe`
|
||||
: 'powershell.exe';
|
||||
|
||||
// Check if PowerShell Core exists, otherwise use Windows PowerShell
|
||||
const fs = await import('fs');
|
||||
if (fs.existsSync(powershell)) {
|
||||
shell = powershell;
|
||||
shellArgs = ['-NoProfile', '-NonInteractive', '-Command', commandToExecute];
|
||||
} else if (process.env.COMSPEC) {
|
||||
shell = process.env.COMSPEC;
|
||||
shellArgs = ['/d', '/s', '/c', commandToExecute];
|
||||
} else {
|
||||
shell = 'cmd.exe';
|
||||
shellArgs = ['/d', '/s', '/c', commandToExecute];
|
||||
}
|
||||
} else {
|
||||
// POSIX: Use SHELL env var or bash as default
|
||||
shell = process.env.SHELL || '/bin/bash';
|
||||
shellArgs = ['-c', commandToExecute];
|
||||
}
|
||||
|
||||
// Create PTY process
|
||||
const ptyProcess = pty.spawn(shell, shellArgs, {
|
||||
name: options.ptyTerm || 'xterm-256color',
|
||||
cols: options.ptyCols || 120,
|
||||
rows: options.ptyRows || 30,
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
});
|
||||
|
||||
// Add to smartexit (wrap in a minimal object with pid)
|
||||
this.smartexit.addProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
// Handle output (stdout and stderr are combined in PTY)
|
||||
ptyProcess.onData((data: string) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for PTY process ${ptyProcess.pid}, terminating...`);
|
||||
}
|
||||
ptyProcess.kill('SIGTERM');
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Wrap PTY termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
ptyProcess.onExit(({ exitCode, signal }: { exitCode: number; signal?: number }) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
const combinedOutput = shellLogInstance.logStore.toString();
|
||||
const execResult: IExecResult = {
|
||||
exitCode: exitCode ?? (signal ? 1 : 0),
|
||||
stdout: combinedOutput,
|
||||
combinedOutput,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
reject(new SmartshellError(options.commandString, execResult));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Create input methods for PTY
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
ptyProcess.write(input);
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
// Use \r for PTY (carriage return is typical for terminal line discipline)
|
||||
return sendInput(line + '\r');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
// Send EOF (Ctrl+D) to PTY
|
||||
ptyProcess.write('\x04');
|
||||
};
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: { pid: ptyProcess.pid } as any, // Minimal compatibility object
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Killing PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill();
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Terminating PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill('SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Sending SIGINT to PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill('SIGINT');
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Sending ${signal} to PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill(signal as any);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete
|
||||
return await childProcessEnded;
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -1,2 +1,3 @@
|
||||
export * from './smartshell.classes.smartshell.js';
|
||||
export { which } from './smartshell.plugins.js';
|
||||
export * from './classes.smartshell.js';
|
||||
export * from './classes.smartexecution.js';
|
||||
export { which } from './plugins.js';
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import * as plugins from './smartshell.plugins.js';
|
||||
|
||||
/**
|
||||
* a log handler for spawned logs
|
||||
* making sure the process doesn't run out of memory
|
||||
*/
|
||||
export class ShellLog {
|
||||
public logStore = Buffer.from('');
|
||||
|
||||
/**
|
||||
* log data to console
|
||||
* @param dataArg
|
||||
*/
|
||||
public writeToConsole(dataArg: string | Buffer): void {
|
||||
// make sure we have the data as string
|
||||
process.stdout.write(dataArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* add data to Buffer for later consumption
|
||||
* @param dataArg
|
||||
*/
|
||||
public addToBuffer(dataArg: string | Buffer): void {
|
||||
// make sure we have the data as Buffer
|
||||
const dataBuffer: Buffer = (() => {
|
||||
if (!Buffer.isBuffer(dataArg)) {
|
||||
return Buffer.from(dataArg);
|
||||
}
|
||||
return dataArg;
|
||||
})();
|
||||
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
|
||||
}
|
||||
|
||||
public logAndAdd(dataArg: string | Buffer): void {
|
||||
this.writeToConsole(dataArg);
|
||||
this.addToBuffer(dataArg);
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
import * as plugins from './smartshell.plugins.js';
|
||||
import { ShellEnv } from './smartshell.classes.shellenv.js';
|
||||
import type { IShellEnvContructorOptions, TExecutor } from './smartshell.classes.shellenv.js';
|
||||
import { ShellLog } from './smartshell.classes.shelllog.js';
|
||||
|
||||
import * as cp from 'child_process';
|
||||
|
||||
// -- interfaces --
|
||||
export interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
}
|
||||
|
||||
export interface IExecResultStreaming {
|
||||
childProcess: cp.ChildProcess;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signalArg: plugins.smartexit.TProcessSignal) => Promise<void>;
|
||||
}
|
||||
|
||||
export class Smartshell {
|
||||
public shellEnv: ShellEnv;
|
||||
public smartexit = new plugins.smartexit.SmartExit();
|
||||
|
||||
constructor(optionsArg: IShellEnvContructorOptions) {
|
||||
this.shellEnv = new ShellEnv(optionsArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a given command async
|
||||
*/
|
||||
private async _exec(options: {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
}): Promise<IExecResult | IExecResultStreaming | void> {
|
||||
if (options.interactive) {
|
||||
return await this._execInteractive(options);
|
||||
}
|
||||
|
||||
return await this._execCommand(options);
|
||||
}
|
||||
|
||||
private async _execInteractive(options: {
|
||||
commandString: string;
|
||||
interactive?: boolean;
|
||||
}): Promise<void> {
|
||||
if (process.env.CI) {
|
||||
return;
|
||||
}
|
||||
|
||||
const done = plugins.smartpromise.defer();
|
||||
|
||||
const shell = cp.spawn(options.commandString, {
|
||||
stdio: 'inherit',
|
||||
shell: true,
|
||||
detached: true
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(shell);
|
||||
|
||||
shell.on('close', (code) => {
|
||||
console.log(`interactive shell terminated with code ${code}`);
|
||||
this.smartexit.removeProcess(shell);
|
||||
done.resolve();
|
||||
});
|
||||
|
||||
await done.promise;
|
||||
}
|
||||
|
||||
private async _execCommand(options: {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
}): Promise<IExecResult | IExecResultStreaming> {
|
||||
const done = plugins.smartpromise.defer<IExecResult | IExecResultStreaming>();
|
||||
const childProcessEnded = plugins.smartpromise.defer<IExecResult>();
|
||||
|
||||
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
|
||||
|
||||
const shellLogInstance = new ShellLog();
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: true,
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
detached: false,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
execChildProcess.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
execChildProcess.on('exit', (code, signal) => {
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
if (options.strict && code === 1) {
|
||||
done.reject();
|
||||
}
|
||||
|
||||
const execResult = {
|
||||
exitCode: code,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
};
|
||||
|
||||
if (!options.streaming) {
|
||||
done.resolve(execResult);
|
||||
}
|
||||
childProcessEnded.resolve(execResult);
|
||||
});
|
||||
|
||||
if (options.streaming) {
|
||||
done.resolve({
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded.promise,
|
||||
kill: async () => {
|
||||
console.log(`running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
},
|
||||
terminate: async () => {
|
||||
console.log(`running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
console.log(`running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
},
|
||||
customSignal: async (signalArg: plugins.smartexit.TProcessSignal) => {
|
||||
console.log(`running tree kill with custom signal ${signalArg} on process ${execChildProcess.pid}`);
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signalArg);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return await done.promise;
|
||||
}
|
||||
|
||||
public async exec(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrict(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrictSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreaming(
|
||||
commandString: string,
|
||||
silent: boolean = false
|
||||
): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({
|
||||
commandString,
|
||||
silent: true,
|
||||
streaming: true,
|
||||
})) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractive(commandString: string) {
|
||||
await this._exec({ commandString, interactive: true });
|
||||
}
|
||||
|
||||
public async execAndWaitForLine(
|
||||
commandString: string,
|
||||
regexArg: RegExp,
|
||||
silentArg: boolean = false
|
||||
) {
|
||||
let done = plugins.smartpromise.defer();
|
||||
let execStreamingResult = await this.execStreaming(commandString, silentArg);
|
||||
execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
|
||||
if (regexArg.test(stdOutChunk)) {
|
||||
done.resolve();
|
||||
}
|
||||
});
|
||||
return done.promise;
|
||||
}
|
||||
|
||||
public async execAndWaitForLineSilent(commandString: string, regexArg: RegExp) {
|
||||
return this.execAndWaitForLine(commandString, regexArg, true);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"types": ["node"],
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user