npm package: @irithell-js/file-toolkit
Description: Complete file conversion toolkit, image optimization, audio/video conversion, and document processing.
Author: Irithell
Latest version: 1.0.0

# @irithell-js/file-toolkit

Complete file conversion toolkit with support for images, audio, video, documents, and data formats. Zero configuration, auto-installs binaries.

## Features

- **Image Conversion** - PNG, JPG, WEBP, AVIF, GIF, TIFF, SVG
- **Audio Conversion** - MP3, WAV, OGG, FLAC, AAC, M4A
- **Video Conversion** - MP4, WEBM, AVI, MOV, MKV
- **Document Conversion** - PDF, DOCX, XLSX, PPTX, TXT, RTF, ODT, ODS
- **Data Conversion** - JSON, YAML, XML, CSV
- **Batch Processing** - Parallel conversion with progress tracking
- **Highly Configurable** - Sensible defaults with full customization
- **Auto-Install Binaries** - FFmpeg and LibreOffice (Linux) downloaded automatically
- **Quality Presets** - Fast, balanced, or best quality modes
- **Smart Caching** - Efficient temporary file management
- **Cross-Platform** - Linux (x64/arm64), macOS, Windows
- **TypeScript** - Full type definitions included
- **Dual Format** - ESM and CommonJS support

## Installation

```bash
npm install @irithell-js/file-toolkit
```

Binaries (FFmpeg + LibreOffice on Linux) are automatically downloaded during installation.

## Quick Start

### Basic Usage (ESM)

```typescript
import { FileToolkit } from "@irithell-js/file-toolkit";

const toolkit = new FileToolkit();

// Universal convert - auto-detects file type
await toolkit.convert("photo.jpg", "webp");
await toolkit.convert("song.mp3", "wav");
await toolkit.convert("video.mp4", "webm");
await toolkit.convert("document.docx", "pdf");
await toolkit.convert("data.json", "yaml");
```

### Basic Usage (CommonJS)

```javascript
const { FileToolkit } = require("@irithell-js/file-toolkit");

const toolkit = new FileToolkit();

async function convert() {
  const result = await toolkit.convert("image.png", "webp");
  console.log("Converted:", result.outputPath);
  console.log("Compression:", result.compressionRatio + "%");
}

convert();
```

### Batch Conversion

```typescript
const toolkit = new FileToolkit();

await toolkit.convertBatch(["img1.jpg", "img2.png", "img3.gif"], {
  format: "webp",
  outputDir: "./output",
  parallel: 3,
  onProgress: (current, total, file) => {
    console.log(`[${current}/${total}] Converting: ${file}`);
  },
  onComplete: (result) => {
    console.log(`✓ Saved: ${result.outputPath}`);
  },
});
```

## Configuration

### Constructor Options

```typescript
const toolkit = new FileToolkit({
  // Output settings
  outputDir: "./output", // Default output directory
  overwrite: true, // Overwrite existing files
  createOutputDir: true, // Auto-create output directory

  // Quality settings
  defaultQuality: 80, // Default quality (1-100)

  // Image defaults
  imageDefaults: {
    format: "webp", // png|jpg|webp|avif|gif|tiff
    quality: 85,
    progressive: true,
    compressionLevel: 6, // 0-9 (PNG)
    kernel: "lanczos3", // nearest|cubic|mitchell|lanczos2|lanczos3
  },

  // Audio defaults
  audioDefaults: {
    format: "mp3", // mp3|wav|ogg|flac|aac|m4a
    bitrate: "192k", // 64k|96k|128k|192k|256k|320k
    sampleRate: 44100, // 22050|44100|48000
    channels: 2, // 1 (mono) | 2 (stereo)
  },

  // Video defaults
  videoDefaults: {
    format: "mp4", // mp4|webm|avi|mov|mkv
    videoBitrate: "1M", // e.g. 500k, 1M, 2M
    audioBitrate: "128k",
    preset: "medium", // ultrafast|fast|medium|slow|veryslow
    fps: 30,
  },

  // Document defaults
  documentDefaults: {
    format: "pdf", // pdf|docx|txt|rtf|xlsx|pptx
  },

  // Data defaults
  dataDefaults: {
    format: "json", // json|yaml|xml|csv
    pretty: true, // Pretty print output
    indent: 2, // Indentation spaces
  },

  // Performance
  timeoutMs: 300000, // 5 minutes timeout
  maxConcurrent: 8, // Max parallel conversions
  tempDir: "/tmp", // Temporary files directory
  keepTemp: false, // Keep temp files after conversion

  // Binary paths (optional - auto-detected)
  ffmpegPath: "/usr/bin/ffmpeg",
  libreOfficePath: "/usr/bin/soffice",

  // Advanced
  ffmpegArgs: [], // Additional FFmpeg arguments
  libreOfficeArgs: [], // Additional LibreOffice arguments

  // Logging
  logger: console, // Logger instance (null to disable)
  verbose: true, // Verbose logging
});
```

### Configuration File

Create `.filetoolkitrc.json` in your project root:

```json
{
  "outputDir": "./converted",
  "overwrite": true,
  "defaultQuality": 85,
  "imageDefaults": {
    "format": "webp",
    "quality": 85
  },
  "audioDefaults": {
    "bitrate": "256k"
  },
  "verbose": false
}
```

The toolkit automatically loads configuration from:

1. `.filetoolkitrc.json` in current directory
2. `filetoolkit.config.json` in current directory
3. `.filetoolkitrc.json` in home directory

### Quality Presets

```typescript
// High quality (larger files)
const hq = new FileToolkit({
  imageDefaults: { quality: 95, format: "png" },
  audioDefaults: { bitrate: "320k" },
  videoDefaults: { videoBitrate: "3M", preset: "slow" },
});

// Balanced (recommended)
const balanced = new FileToolkit({
  imageDefaults: { quality: 85, format: "webp" },
  audioDefaults: { bitrate: "192k" },
  videoDefaults: { videoBitrate: "1M", preset: "medium" },
});

// Fast (smaller files, faster processing)
const fast = new FileToolkit({
  imageDefaults: { quality: 70, format: "webp" },
  audioDefaults: { bitrate: "128k" },
  videoDefaults: { videoBitrate: "500k", preset: "fast" },
});
```

## API Reference

### FileToolkit Methods

#### `convert(inputPath: string, outputFormat: string, options?): Promise<ConversionResult>`

Universal conversion method that auto-detects file type.

```typescript
const result = await toolkit.convert("input.png", "webp", {
  quality: 90,
  outputDir: "./output",
});

console.log(result.success); // true
console.log(result.outputPath); // './output/input.webp'
console.log(result.inputSize); // 1024000 (bytes)
console.log(result.outputSize); // 256000 (bytes)
console.log(result.compressionRatio); // 75.00 (%)
console.log(result.processingTime); // 125 (ms)
```

#### `convertImage(inputPath: string, outputFormat: string, options?): Promise<ConversionResult>`

Convert image files with advanced options.

```typescript
await toolkit.convertImage("photo.jpg", "webp", {
  quality: 85,
  width: 1920,
  height: 1080,
  fit: "cover", // cover|contain|fill|inside|outside
  background: "#ffffff",
  progressive: true,
});
```

#### `optimizeImage(inputPath: string, options?): Promise<ConversionResult>`

Optimize image for web (defaults to WebP).

```typescript
await toolkit.optimizeImage("photo.png", {
  quality: 85,
  format: "webp",
});
```

#### `resizeImage(inputPath: string, width: number, height?: number, options?): Promise<ConversionResult>`

Resize image while maintaining format.

```typescript
await toolkit.resizeImage("large.jpg", 800, 600, {
  fit: "cover",
  kernel: "lanczos3",
});
```

#### `convertAudio(inputPath: string, outputFormat: string, options?): Promise<ConversionResult>`

Convert audio files.

```typescript
await toolkit.convertAudio("song.mp3", "wav", {
  bitrate: "320k",
  sampleRate: 48000,
  channels: 2,
});
```

#### `extractAudio(videoPath: string, outputFormat?: string, options?): Promise<ConversionResult>`

Extract audio from video.

```typescript
await toolkit.extractAudio("movie.mp4", "mp3", {
  bitrate: "192k",
});
```

#### `convertVideo(inputPath: string, outputFormat: string, options?): Promise<ConversionResult>`

Convert video files.

```typescript
await toolkit.convertVideo("input.avi", "mp4", {
  videoBitrate: "2M",
  audioBitrate: "192k",
  fps: 30,
  preset: "medium",
  resolution: "1920x1080",
});
```

#### `videoToGif(videoPath: string, options?): Promise<ConversionResult>`

Convert video to GIF.

```typescript
await toolkit.videoToGif("clip.mp4", {
  fps: 15,
  resolution: "640x480",
});
```

#### `convertDocument(inputPath: string, outputFormat: string, options?): Promise<ConversionResult>`

Convert document files (requires LibreOffice).

```typescript
await toolkit.convertDocument("report.docx", "pdf");
```

#### `toPDF(inputPath: string, options?): Promise<ConversionResult>`

Convert any document to PDF.

```typescript
await toolkit.toPDF("presentation.pptx");
```

#### `convertData(inputPath: string, outputFormat: string, options?): Promise<ConversionResult>`

Convert between data formats.

```typescript
await toolkit.convertData("config.json", "yaml", {
  pretty: true,
  indent: 2,
});
```

#### `convertBatch(inputPaths: string[], options: BatchConversionOptions): Promise<ConversionResult[]>`

Batch convert multiple files in parallel.

```typescript
const results = await toolkit.convertBatch(
  ["img1.jpg", "img2.png", "img3.gif"],
  {
    format: "webp",
    outputDir: "./output",
    parallel: 3,
    onProgress: (current, total, file) => {
      console.log(`Processing ${current}/${total}: ${file}`);
    },
    onComplete: (result) => {
      if (result.success) {
        console.log(`✓ ${result.outputPath}`);
      }
    },
    onError: (file, error) => {
      console.error(`✗ ${file}: ${error.message}`);
    },
  },
);

// Check results
const successful = results.filter((r) => r.success).length;
const failed = results.filter((r) => !r.success).length;
console.log(`Success: ${successful}, Failed: ${failed}`);
```

#### `getCapabilities(): Capabilities`

Check which conversion types are available.

```typescript
const caps = toolkit.getCapabilities();
console.log(caps);
// {
//   hasFFmpeg: true,
//   hasLibreOffice: true,
//   canConvertImages: true,
//   canConvertAudio: true,
//   canConvertVideo: true,
//   canConvertDocuments: true,
//   canConvertData: true
// }
```

#### `getConfig(): FileToolkitConfig`

Get current configuration.

```typescript
const config = toolkit.getConfig();
console.log(config.imageDefaults.quality);
```

#### `updateConfig(config: Partial<FileToolkitConfig>): void`

Update configuration at runtime.

```typescript
toolkit.updateConfig({
  imageDefaults: {
    quality: 90,
  },
});
```

## Supported Formats

### Images

PNG, JPG/JPEG, WEBP, AVIF, GIF, TIFF, SVG

### Audio

MP3, WAV, OGG, FLAC, AAC, M4A

### Video

MP4, WEBM, AVI, MOV, MKV

### Documents

PDF, DOCX, DOC, XLSX, XLS, PPTX, PPT, TXT, RTF, ODT, ODS, ODP

### Data

JSON, YAML, XML, CSV

## Advanced Usage

### Custom Output Paths

```typescript
// Specific output path
await toolkit.convert("input.jpg", "webp", {
  outputPath: "./custom/path/output.webp",
});

// Custom output directory
await toolkit.convert("input.jpg", "webp", {
  outputDir: "./converted",
});
// Output: ./converted/input.webp
```

### Progressive Image Loading

```typescript
await toolkit.convertImage("large.jpg", "jpg", {
  progressive: true, // Enables progressive JPEG
  quality: 85,
});
```

### Video Quality Control

```typescript
// High quality
await toolkit.convertVideo("input.mp4", "mp4", {
  videoBitrate: "5M",
  audioBitrate: "320k",
  preset: "slow",
});

// Fast encoding
await toolkit.convertVideo("input.mp4", "mp4", {
  videoBitrate: "1M",
  preset: "ultrafast",
});
```

### Handle Conversion Errors

```typescript
try {
  const result = await toolkit.convert("input.xyz", "jpg");
  if (!result.success) {
    console.error("Conversion failed:", result.error);
  }
} catch (error) {
  console.error("Fatal error:", error.message);
}
```

### Performance Monitoring

```typescript
const results = await toolkit.convertBatch(files, {
  format: "webp",
  outputDir: "./output",
  onComplete: (result) => {
    const speedMBps =
      result.inputSize / 1024 / 1024 / (result.processingTime / 1000);
    console.log(`Speed: ${speedMBps.toFixed(2)} MB/s`);
  },
});
```

## Performance

Typical conversion times (varies by hardware and file size):

| Operation         | Small File (<1MB) | Medium (1-10MB) | Large (>10MB) |
| ----------------- | ----------------- | --------------- | ------------- |
| Image PNG→WEBP    | 5-10ms            | 25-50ms         | 50-500ms      |
| Audio MP3→WAV     | 50-100ms          | 500ms-1s        | 2-5s          |
| Video MP4→WEBM    | 1-3s              | 10-30s          | 1-3min        |
| Document DOCX→PDF | 200-500ms         | 1-2s            | 3-10s         |
| Data JSON→YAML    | <5ms              | 10-20ms         | 50-100ms      |

_Based on local tests. LibreOffice conversions are typically slower._

## Requirements

- Node.js >= 18.0.0
- ~300MB disk space for binaries (auto-downloaded)
- LibreOffice: Auto-installed on Linux, manual install required for macOS/Windows

## Binaries

The package automatically downloads and manages:

- **FFmpeg** - Audio/video conversion
- **LibreOffice** (Linux only) - Document conversion

### Supported Platforms

- Linux x64 / arm64 (auto-install FFmpeg + LibreOffice)
- macOS x64 / arm64 (auto-install FFmpeg, manual LibreOffice)
- Windows x64 (auto-install FFmpeg, manual LibreOffice)

### Manual Binary Installation

**macOS:**

```bash
brew install libreoffice
```

**Windows:**
Download from https://www.libreoffice.org/download

**Custom paths:**

```typescript
const toolkit = new FileToolkit({
  ffmpegPath: "/custom/path/ffmpeg",
  libreOfficePath: "/custom/path/soffice",
});
```

## Troubleshooting

### LibreOffice Not Found

```bash
# Linux
sudo apt install libreoffice

# macOS
brew install libreoffice

# Or specify path manually
const toolkit = new FileToolkit({
  libreOfficePath: '/Applications/LibreOffice.app/Contents/MacOS/soffice'
});
```

### FFmpeg Issues

```bash
# Reinstall binaries
npm rebuild @irithell-js/file-toolkit
```

### Slow Conversions

```typescript
// Increase parallel processing
const toolkit = new FileToolkit({
  maxConcurrent: 16, // Default: CPU count
});

// Use faster presets
toolkit.updateConfig({
  videoDefaults: {
    preset: "ultrafast",
  },
});
```

### Out of Memory

```typescript
// Process in smaller batches
const toolkit = new FileToolkit({
  maxConcurrent: 2,
  keepTemp: false, // Clean up immediately
});
```

## License

MIT

## Changelog

### 1.0.0 (Latest)

- Initial release
- Image conversion (Sharp)
- Audio/video conversion (FFmpeg)
- Document conversion (LibreOffice)
- Data conversion (JSON, YAML, XML, CSV)
- Batch processing with parallel execution
- Auto-install binaries system
- Flexible configuration system
- TypeScript support
- Cross-platform support