Compare commits

...

28 Commits

Author SHA1 Message Date
jkunz ee94feddfa v3.5.0 2026-05-10 14:33:40 +00:00
jkunz 04517232e8 chore(config): migrate gitzone smartconfig 2026-05-10 14:33:14 +00:00
jkunz 0ff3596bd8 feat(spawn): support inherited stdio 2026-05-10 14:32:07 +00:00
jkunz a0010e7f0f v3.4.0 2026-05-09 13:48:16 +00:00
jkunz d65e1ed4f6 feat(smartshell): add cwd-aware execution options, structured strict-mode errors, and safer process tree termination 2026-05-09 13:48:16 +00:00
jkunz e61b352576 v3.3.8 2026-03-15 18:42:08 +00:00
jkunz b7882ef60f fix(repo): remove obsolete Serena project configuration files 2026-03-15 18:42:08 +00:00
jkunz cd5194c365 v3.3.7 2026-03-05 10:18:43 +00:00
jkunz 71cc64b6d9 fix(smartshell): avoid triple shell nesting, improve WSL path filtering, and use chunked log buffer to reduce memory usage 2026-03-05 10:18:43 +00:00
jkunz f254a9e078 v3.3.6 2026-03-04 18:13:53 +00:00
jkunz 3d6a33f8d2 fix(smartshell): use close event on child processes to ensure exit handling and update dependency versions 2026-03-04 18:13:53 +00:00
jkunz d37071dae0 fix(spawn): use detached:true so children are immune to terminal SIGINT
Children now get their own process group. Terminal Ctrl+C only reaches
the parent, which then does orderly tree-kill while children are still
alive and the process tree is intact.
2026-03-04 00:49:29 +00:00
jkunz 181d352e21 fix(deps): bump smartexit to ^2.0.1 for PID-tracking fix 2026-03-04 00:04:22 +00:00
jkunz 8a0a18f4da v3.3.3 2026-03-03 23:41:59 +00:00
jkunz bdc09afedd fix(deps): upgrade @push.rocks/smartexit to ^2.0.0 2026-03-03 23:41:49 +00:00
jkunz 68060e8565 v3.3.2 2026-03-03 22:36:40 +00:00
jkunz f2552cda79 fix(release): add @git.zone/cli release configuration with registries and public access 2026-03-03 22:36:40 +00:00
jkunz b898382305 v3.3.1 2026-03-03 22:35:20 +00:00
jkunz 5f8f38c2e6 fix(deps): bump @push.rocks/smartexit dependency to ^1.1.1 2026-03-03 22:35:20 +00:00
jkunz 61f76af7d1 3.3.0 2025-08-17 15:20:26 +00:00
jkunz 529b33fda1 feat(smartshell): Add secure spawn APIs, PTY support, interactive/streaming control, timeouts and buffer limits; update README and tests 2025-08-17 15:20:26 +00:00
jkunz f8e431f41e feat(smartshell): Add passthrough option for exec methods and corresponding tests 2025-08-17 14:01:04 +00:00
jkunz 5a32817349 3.2.4 2025-08-16 09:52:49 +00:00
jkunz 35d22175db fix(tests): Update tests & CI config, bump deps, add docs and project configs 2025-08-16 09:52:49 +00:00
philkunz cd3675280a 3.2.3 2025-02-20 12:37:11 +01:00
philkunz 7c14102324 fix(core): Refactor Smartshell class for improved code clarity and performance 2025-02-20 12:37:10 +01:00
philkunz cb41dbaf1c 3.2.2 2024-12-13 19:03:51 +01:00
philkunz 149eb800e7 fix(core): Fix minor code style and formatting issues 2024-12-13 19:03:50 +01:00
21 changed files with 7571 additions and 6999 deletions
+18 -8
View File
@@ -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"
}
}
},
"schemaVersion": 2
},
"tsdoc": {
"@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": []
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"fileMatch": ["/.smartconfig.json"],
"schema": {
"type": "object",
"properties": {
+87
View File
@@ -1,5 +1,92 @@
# 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
+21
View File
@@ -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.
+13 -14
View File
@@ -1,13 +1,13 @@
{
"name": "@push.rocks/smartshell",
"private": false,
"version": "3.2.1",
"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/)",
"test": "(tstest test/ --verbose --logfile --timeout 20)",
"build": "(tsbuild tsfolders --web)",
"buildDocs": "tsdoc"
},
@@ -33,19 +33,17 @@
},
"homepage": "https://code.foss.global/push.rocks/smartshell",
"devDependencies": {
"@git.zone/tsbuild": "^2.2.0",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.90",
"@push.rocks/tapbundle": "^5.5.3",
"@types/node": "^22.10.2"
"@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": "^5.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"
}
+4968 -6742
View File
File diff suppressed because it is too large Load Diff
+571 -84
View File
@@ -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 shells 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 result = await smartShellInstance.exec('echo $CUSTOM_VAR');
console.log(result.stdout); // Outputs the value of CUSTOM_VAR
})();
const streaming = await shell.execStreaming('pnpm install');
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.
+250
View File
@@ -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();
+84
View File
@@ -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();
+42
View File
@@ -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();
+147
View File
@@ -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();
+104
View File
@@ -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,
});
+54
View File
@@ -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();
+244
View File
@@ -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
View File
@@ -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;
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartshell',
version: '3.2.1',
version: '3.5.0',
description: 'A library for executing shell commands using promises.'
}
+28 -21
View File
@@ -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
commandPaths = commandPaths.filter((commandPathArg) => {
const filterResult =
!commandPathArg.startsWith('/mnt/c/') &&
!commandPathArg.startsWith('Files/1E') &&
!commandPathArg.includes(' ');
if (!filterResult) {
// console.log(`${commandPathArg} will be filtered!`);
}
return filterResult;
});
// Only filter out WSL-specific paths when actually running under WSL
if (ShellEnv._isWSL()) {
commandPaths = commandPaths.filter((commandPathArg) => {
return (
!commandPathArg.startsWith('/mnt/c/') &&
!commandPathArg.startsWith('Files/1E') &&
!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':
commandResult = `${pathString}${sourceString}${commandArg}`;
break;
}
// 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}`;
commandResult = this._setPath(commandResult);
return commandResult;
}
+38 -8
View File
@@ -5,7 +5,41 @@ import * as plugins from './plugins.js';
* making sure the process doesn't run out of memory
*/
export class ShellLog {
public logStore = Buffer.from('');
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
@@ -22,13 +56,9 @@ export class ShellLog {
*/
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]);
const dataBuffer: Buffer = Buffer.isBuffer(dataArg) ? dataArg : Buffer.from(dataArg);
this.chunks.push(dataBuffer);
this.totalLength += dataBuffer.length;
}
public logAndAdd(dataArg: string | Buffer): void {
+3 -3
View File
@@ -8,8 +8,8 @@ export interface IDeferred<T> {
}
export class SmartExecution {
public smartshell: Smartshell;
public currentStreamingExecution: IExecResultStreaming;
public smartshell!: Smartshell;
public currentStreamingExecution!: IExecResultStreaming;
public commandString: string;
private isRestartInProgress = false;
@@ -52,4 +52,4 @@ export class SmartExecution {
await this.restart();
}
}
}
}
+894 -115
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -5,6 +5,7 @@
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"types": ["node"],
"esModuleInterop": true,
"verbatimModuleSyntax": true
},