478 lines
14 KiB
Markdown
478 lines
14 KiB
Markdown
# @git.zone/tsrun
|
|
|
|
[](https://www.npmjs.com/package/@git.zone/tsrun)
|
|
[](https://opensource.org/licenses/MIT)
|
|
[](https://www.typescriptlang.org/)
|
|
[](https://nodejs.org/)
|
|
|
|
> Run TypeScript files instantly, without the compilation hassle ⚡
|
|
|
|
Execute TypeScript programs on-the-fly with zero configuration. Perfect for scripts, prototyping, and development workflows.
|
|
|
|
## Table of Contents
|
|
|
|
- [What is tsrun?](#what-is-tsrun)
|
|
- [Installation](#installation)
|
|
- [Usage](#usage)
|
|
- [CLI Usage](#-cli-usage)
|
|
- [Programmatic API](#-programmatic-api)
|
|
- [Features](#features)
|
|
- [Why tsrun?](#why-tsrun)
|
|
- [Common Use Cases](#common-use-cases)
|
|
- [API Reference](#api-reference)
|
|
- [Examples](#examples)
|
|
- [Package Information](#package-information)
|
|
- [Requirements](#requirements)
|
|
- [Troubleshooting](#troubleshooting)
|
|
- [License and Legal Information](#license-and-legal-information)
|
|
|
|
## What is tsrun?
|
|
|
|
**tsrun** is a lightweight TypeScript execution tool that lets you run `.ts` files directly—no build step required. It's like running JavaScript with `node`, but for TypeScript. Under the hood, tsrun uses [tsx](https://github.com/esbuild-kit/tsx) for lightning-fast execution while keeping your workflow simple and efficient.
|
|
|
|
## Installation
|
|
|
|
```bash
|
|
npm install -g @git.zone/tsrun
|
|
```
|
|
|
|
Or as a project dependency:
|
|
|
|
```bash
|
|
npm install --save-dev @git.zone/tsrun
|
|
```
|
|
|
|
## Usage
|
|
|
|
### 🚀 CLI Usage
|
|
|
|
Simply run any TypeScript file:
|
|
|
|
```bash
|
|
tsrun myScript.ts
|
|
```
|
|
|
|
Pass arguments to your script transparently:
|
|
|
|
```bash
|
|
tsrun myScript.ts --config production --verbose
|
|
```
|
|
|
|
All arguments are passed through to your TypeScript program, just as if you were running it with `node`.
|
|
|
|
### 💻 Programmatic API
|
|
|
|
tsrun provides three powerful functions for different execution needs:
|
|
|
|
#### runPath() - Simple Execution
|
|
|
|
Wait for a script to complete. Perfect for sequential workflows.
|
|
|
|
```typescript
|
|
import { runPath } from '@git.zone/tsrun';
|
|
|
|
// Run a TypeScript file (absolute or relative path)
|
|
await runPath('./scripts/build.ts');
|
|
|
|
// With path resolution relative to a file URL
|
|
await runPath('./build.ts', import.meta.url);
|
|
|
|
// With custom working directory
|
|
await runPath('./build.ts', import.meta.url, { cwd: '/path/to/project' });
|
|
```
|
|
|
|
#### runCli() - CLI Mode
|
|
|
|
Run with process.argv integration, as if invoked from command line.
|
|
|
|
```typescript
|
|
import { runCli } from '@git.zone/tsrun';
|
|
|
|
// Respects process.argv for argument passing
|
|
await runCli('./script.ts');
|
|
```
|
|
|
|
#### spawnPath() - Advanced Control
|
|
|
|
Full process control with stdio access, timeouts, and cancellation.
|
|
|
|
```typescript
|
|
import { spawnPath } from '@git.zone/tsrun';
|
|
|
|
// Returns immediately with process handle
|
|
const proc = spawnPath('./task.ts', import.meta.url, {
|
|
timeout: 30000,
|
|
cwd: '/path/to/project',
|
|
env: { NODE_ENV: 'production' },
|
|
args: ['--verbose']
|
|
});
|
|
|
|
// Access stdout/stderr streams
|
|
proc.stdout?.on('data', (chunk) => console.log(chunk.toString()));
|
|
|
|
// Wait for completion
|
|
const exitCode = await proc.exitCode;
|
|
```
|
|
|
|
## Features
|
|
|
|
✨ **Zero Configuration** - Just point and shoot. No tsconfig tweaking required.
|
|
|
|
⚡ **Fast Execution** - Powered by tsx for near-instant TypeScript execution.
|
|
|
|
🔄 **Transparent Arguments** - Command line arguments pass through seamlessly to your scripts.
|
|
|
|
📦 **Dual Interface** - Use as a CLI tool or import as a library in your code.
|
|
|
|
🎯 **TypeScript Native** - Full TypeScript support with excellent IntelliSense.
|
|
|
|
🔀 **Custom Working Directory** - Execute scripts with different cwds for parallel multi-project workflows.
|
|
|
|
🎛️ **Advanced Process Control** - Full control with spawnPath() for stdio access, timeouts, and cancellation.
|
|
|
|
## Why tsrun?
|
|
|
|
Sometimes you just want to run a TypeScript file without setting up a build pipeline, configuring webpack, or waiting for `tsc` to compile. That's where tsrun shines:
|
|
|
|
- **Quick Scripts**: Write and run TypeScript scripts as easily as bash scripts
|
|
- **Prototyping**: Test ideas without project setup overhead
|
|
- **Development Workflows**: Integrate TypeScript execution into your tooling
|
|
- **CI/CD**: Run TypeScript-based build scripts without pre-compilation
|
|
|
|
## Common Use Cases
|
|
|
|
### Development Scripts
|
|
|
|
```typescript
|
|
// scripts/dev-setup.ts
|
|
import { runPath } from '@git.zone/tsrun';
|
|
|
|
console.log('Setting up development environment...');
|
|
await runPath('./install-deps.ts', import.meta.url);
|
|
await runPath('./init-db.ts', import.meta.url);
|
|
await runPath('./seed-data.ts', import.meta.url);
|
|
console.log('✓ Development environment ready!');
|
|
```
|
|
|
|
### Multi-Project Builds
|
|
|
|
```typescript
|
|
// build-all-projects.ts
|
|
import { runPath } from '@git.zone/tsrun';
|
|
|
|
const projects = [
|
|
'/workspace/frontend',
|
|
'/workspace/backend',
|
|
'/workspace/shared'
|
|
];
|
|
|
|
await Promise.all(
|
|
projects.map(cwd =>
|
|
runPath('./build.ts', import.meta.url, { cwd })
|
|
)
|
|
);
|
|
```
|
|
|
|
### Long-Running Tasks with Monitoring
|
|
|
|
```typescript
|
|
// monitor-task.ts
|
|
import { spawnPath } from '@git.zone/tsrun';
|
|
|
|
const proc = spawnPath('./data-migration.ts', import.meta.url, {
|
|
timeout: 300000, // 5 minutes max
|
|
env: { LOG_LEVEL: 'verbose' }
|
|
});
|
|
|
|
let lineCount = 0;
|
|
proc.stdout?.on('data', (chunk) => {
|
|
lineCount++;
|
|
if (lineCount % 100 === 0) {
|
|
console.log(`Processed ${lineCount} lines...`);
|
|
}
|
|
});
|
|
|
|
try {
|
|
await proc.exitCode;
|
|
console.log('Migration completed successfully!');
|
|
} catch (error) {
|
|
console.error('Migration failed:', error.message);
|
|
process.exit(1);
|
|
}
|
|
```
|
|
|
|
## API Reference
|
|
|
|
Choose the right function for your use case:
|
|
|
|
| Function | Use When | Returns | Execution Mode |
|
|
|----------|----------|---------|----------------|
|
|
| `runPath()` | Simple script execution, sequential workflows | Promise (waits) | In-process (or child with cwd) |
|
|
| `runCli()` | Need process.argv integration | Promise (waits) | In-process |
|
|
| `spawnPath()` | Need process control, stdio access, timeout/cancel | Process handle | Child process |
|
|
|
|
**Quick decision guide:**
|
|
- 🎯 **Need to wait for completion?** → Use `runPath()` or `runCli()`
|
|
- 🎛️ **Need to capture output or control process?** → Use `spawnPath()`
|
|
- ⚡ **Running multiple scripts in parallel?** → Use `runPath()` with custom `cwd` or `spawnPath()`
|
|
- ⏱️ **Need timeout or cancellation?** → Use `spawnPath()`
|
|
|
|
## Examples
|
|
|
|
### Simple Script
|
|
|
|
```typescript
|
|
// hello.ts
|
|
console.log('Hello from TypeScript! 🎉');
|
|
|
|
const greet = (name: string): string => {
|
|
return `Welcome, ${name}!`;
|
|
};
|
|
|
|
console.log(greet('Developer'));
|
|
```
|
|
|
|
Run it:
|
|
|
|
```bash
|
|
tsrun hello.ts
|
|
# Output:
|
|
# Hello from TypeScript! 🎉
|
|
# Welcome, Developer!
|
|
```
|
|
|
|
### With Command Line Arguments
|
|
|
|
```typescript
|
|
// deploy.ts
|
|
const environment = process.argv[2] || 'development';
|
|
const verbose = process.argv.includes('--verbose');
|
|
|
|
console.log(`Deploying to ${environment}...`);
|
|
if (verbose) {
|
|
console.log('Verbose mode enabled');
|
|
}
|
|
```
|
|
|
|
Run it:
|
|
|
|
```bash
|
|
tsrun deploy.ts production --verbose
|
|
# Output:
|
|
# Deploying to production...
|
|
# Verbose mode enabled
|
|
```
|
|
|
|
### Programmatic Execution
|
|
|
|
```typescript
|
|
// runner.ts
|
|
import { runPath } from '@git.zone/tsrun';
|
|
|
|
const scripts = [
|
|
'./scripts/setup.ts',
|
|
'./scripts/migrate.ts',
|
|
'./scripts/seed.ts'
|
|
];
|
|
|
|
for (const script of scripts) {
|
|
console.log(`Running ${script}...`);
|
|
await runPath(script, import.meta.url);
|
|
console.log(`✓ ${script} completed`);
|
|
}
|
|
```
|
|
|
|
### Running with Custom Working Directory
|
|
|
|
Execute TypeScript files with a different working directory using the `cwd` option. This is especially useful for parallel execution across multiple projects:
|
|
|
|
```typescript
|
|
import { runPath } from '@git.zone/tsrun';
|
|
|
|
// Run with custom cwd
|
|
await runPath('./build.ts', undefined, { cwd: '/path/to/project-a' });
|
|
|
|
// Parallel execution with different cwds (safe and isolated)
|
|
await Promise.all([
|
|
runPath('./deploy.ts', undefined, { cwd: '/projects/frontend' }),
|
|
runPath('./deploy.ts', undefined, { cwd: '/projects/backend' }),
|
|
runPath('./deploy.ts', undefined, { cwd: '/projects/api' })
|
|
]);
|
|
```
|
|
|
|
**How it works:**
|
|
- When `cwd` is provided, the script executes in a **child process** for complete isolation
|
|
- Without `cwd`, execution happens **in-process** (faster, less overhead)
|
|
- Child processes inherit all environment variables and stdio connections
|
|
- Perfect for running the same script across multiple project directories
|
|
|
|
**Notes:**
|
|
- Output from parallel executions may interleave on the console
|
|
- Each child process runs with its own isolated working directory
|
|
- Exit codes and signals are properly forwarded
|
|
|
|
### Advanced Process Control with spawnPath()
|
|
|
|
For advanced use cases requiring full process control, stdio access, or timeout/cancellation support, use `spawnPath()`. Unlike `runPath()` which waits for completion, `spawnPath()` returns immediately with a process handle.
|
|
|
|
```typescript
|
|
import { spawnPath } from '@git.zone/tsrun';
|
|
|
|
// Basic spawning with output capture
|
|
const proc = spawnPath('./build.ts', import.meta.url);
|
|
|
|
proc.stdout?.on('data', (chunk) => {
|
|
console.log('Output:', chunk.toString());
|
|
});
|
|
|
|
proc.stderr?.on('data', (chunk) => {
|
|
console.error('Error:', chunk.toString());
|
|
});
|
|
|
|
const exitCode = await proc.exitCode;
|
|
console.log(`Process exited with code ${exitCode}`);
|
|
```
|
|
|
|
**With timeout and custom environment:**
|
|
|
|
```typescript
|
|
const proc = spawnPath('./long-running-task.ts', import.meta.url, {
|
|
timeout: 30000, // Kill after 30 seconds
|
|
cwd: '/path/to/project',
|
|
env: {
|
|
NODE_ENV: 'production',
|
|
API_KEY: 'secret'
|
|
},
|
|
args: ['--mode', 'fast']
|
|
});
|
|
|
|
try {
|
|
const exitCode = await proc.exitCode;
|
|
console.log('Task completed:', exitCode);
|
|
} catch (error) {
|
|
console.error('Task failed or timed out:', error.message);
|
|
}
|
|
```
|
|
|
|
**AbortController integration:**
|
|
|
|
```typescript
|
|
const controller = new AbortController();
|
|
const proc = spawnPath('./task.ts', import.meta.url, {
|
|
signal: controller.signal
|
|
});
|
|
|
|
// Cancel after 5 seconds
|
|
setTimeout(() => controller.abort(), 5000);
|
|
|
|
try {
|
|
await proc.exitCode;
|
|
} catch (error) {
|
|
console.log('Process was aborted');
|
|
}
|
|
```
|
|
|
|
**Graceful termination:**
|
|
|
|
```typescript
|
|
const proc = spawnPath('./server.ts', import.meta.url);
|
|
|
|
// Later: gracefully shut down
|
|
// Sends SIGTERM, waits 5s, then SIGKILL if still running
|
|
await proc.terminate();
|
|
```
|
|
|
|
**Key differences from runPath():**
|
|
|
|
| Feature | runPath() | spawnPath() |
|
|
|---------|-----------|-------------|
|
|
| Returns | Promise (waits) | Process handle (immediate) |
|
|
| Default execution | In-process (unless cwd) | Always child process |
|
|
| stdio | 'inherit' (transparent) | 'pipe' (capturable) |
|
|
| Process control | Limited | Full (streams, signals, timeout) |
|
|
| Use case | Simple script execution | Complex process management |
|
|
|
|
## Package Information
|
|
|
|
- **npmjs**: [@git.zone/tsrun](https://www.npmjs.com/package/@git.zone/tsrun)
|
|
- **Source**: [git.zone](https://git.zone/lossless/tsrun) | [GitLab Mirror](https://gitlab.com/gitzone/tsrun) | [GitHub Mirror](https://github.com/gitzone/tsrun)
|
|
- **Documentation**: [TypeDoc](https://gitzone.gitlab.io/tsrun/)
|
|
|
|
## Requirements
|
|
|
|
- **Node.js**: >= 16.x
|
|
- **TypeScript**: >= 3.x (automatically handled by tsx)
|
|
|
|
## Troubleshooting
|
|
|
|
### Common Issues
|
|
|
|
**"Cannot find module" errors**
|
|
|
|
Make sure you're using absolute paths or paths relative to `import.meta.url`:
|
|
|
|
```typescript
|
|
// ❌ Wrong - relative to cwd
|
|
await runPath('./script.ts');
|
|
|
|
// ✅ Correct - relative to current file
|
|
await runPath('./script.ts', import.meta.url);
|
|
```
|
|
|
|
**Process hangs or doesn't complete**
|
|
|
|
When using `spawnPath()`, make sure to await the `exitCode` promise:
|
|
|
|
```typescript
|
|
const proc = spawnPath('./script.ts', import.meta.url);
|
|
// Don't forget to await!
|
|
await proc.exitCode;
|
|
```
|
|
|
|
**Timeout not working**
|
|
|
|
Timeouts only work with `spawnPath()`, not with `runPath()`:
|
|
|
|
```typescript
|
|
// ❌ Wrong - timeout is ignored
|
|
await runPath('./script.ts', import.meta.url, { timeout: 5000 });
|
|
|
|
// ✅ Correct - use spawnPath for timeout support
|
|
const proc = spawnPath('./script.ts', import.meta.url, { timeout: 5000 });
|
|
await proc.exitCode;
|
|
```
|
|
|
|
**Environment variables not available**
|
|
|
|
The `env` option automatically merges with `process.env` - your custom values override parent values:
|
|
|
|
```typescript
|
|
// Parent env is automatically inherited
|
|
spawnPath('./script.ts', import.meta.url, {
|
|
env: {
|
|
CUSTOM_VAR: 'value' // Added to parent env
|
|
}
|
|
});
|
|
|
|
// Script will see both process.env AND CUSTOM_VAR
|
|
```
|
|
|
|
## 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.
|
|
|
|
**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.
|
|
|
|
### Company Information
|
|
|
|
Task Venture Capital GmbH
|
|
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.
|
|
|
|
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.
|