<div align="center">
    <!-- SVG Icon for Visual Appeal -->
    <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z" fill="#007ACC"/>
        <path d="M12 11.5L15 15H9l3-3.5z" fill="#007ACC"/>
        <path d="M12 15.5L15 19H9l3-3.5z" fill="#007ACC"/>
    </svg>
    <h1>@xbibzlibrary/teraboxscraper</h1>
    <p><strong>The Ultimate, Highly-Optimized, and Complex Terabox Downloader and Scraper Library for Node.js.</strong></p>
    <p>
        <a href="https://www.npmjs.com/package/@xbibzlibrary/teraboxscraper"><img src="https://img.shields.io/npm/v/@xbibzlibrary/teraboxscraper.svg?style=for-the-badge&logo=npm" alt="NPM Version"></a>
        <a href="https://github.com/XbibzOfficial/terabox-scraper/actions"><img src="https://img.shields.io/github/actions/workflow/status/XbibzOfficial/terabox-scraper/node.js.yml?branch=main&style=for-the-badge&logo=github" alt="Build Status"></a>
        <a href="https://github.com/XbibzOfficial/terabox-scraper/blob/main/LICENSE"><img src="https://img.shields.io/github/license/XbibzOfficial/terabox-scraper.svg?style=for-the-badge" alt="License"></a>
    </p>
</div>

---

## 🚀 Fitur Utama (Bukan Fitur Sederhana!)

Library ini dirancang untuk melampaui batas-batas *scraper* biasa, menawarkan **kompleksitas** dan **keandalan** tingkat tinggi:

1.  **Mekanisme Multi-Tahap Canggih**: Menggunakan kombinasi *Web Scraping* (`cheerio`) untuk mengekstrak parameter tersembunyi (`shareid`, `uk`, `sign`, `timestamp`) dari halaman HTML, diikuti dengan panggilan ke *Internal Terabox API* untuk mendapatkan *direct download link* yang valid.
2.  **Manajemen Koneksi Powerfull**: Menggunakan `axios` dengan *custom HTTP client* yang mendukung konfigurasi **Proxy** dan **User-Agent** kustom untuk menghindari *rate-limiting* dan *blocking*.
3.  **Logging Terstruktur dan Menarik**: Integrasi `pino` dan `pino-pretty` untuk sistem *logging* yang cepat, terstruktur, dan disajikan dengan indah di terminal (tanpa emoji!).
4.  **Download Stream-Based dengan Progress Bar**: Mendukung pengunduhan file berbasis *stream* yang efisien, lengkap dengan *callback* untuk membuat *progress bar* yang **informatif** (kecepatan, ETA, persentase) di terminal.
5.  **Penanganan Error Maksimal**: Setiap fungsi dikemas dalam objek `ScraperResponse<T>` yang secara eksplisit mengelola status `success`, `data`, dan `error` dengan kode kesalahan yang terperinci (`E_NETWORK_FAIL`, `E_PARSING_FAIL`, dll.).
6.  **Dibangun dengan TypeScript**: Memberikan *type safety* dan *developer experience* terbaik untuk proyek-proyek modern.

## 🛠️ Instalasi

Pastikan Anda memiliki **Node.js (v18+)** terinstal.

```bash
npm install @xbibzlibrary/teraboxscraper
# atau
yarn add @xbibzlibrary/teraboxscraper
```

## 📚 Dokumentasi & Cara Kerja

### 1. Mendapatkan Cookie (Kunci Utama)

Terabox memerlukan otentikasi untuk mengakses *direct download link*. Anda **wajib** menyediakan cookie `ndus` dari sesi Terabox yang sudah login.

1.  Buka [Terabox](https://www.terabox.app) di browser Anda (disarankan Chrome/Edge).
2.  Login ke akun Anda.
3.  Buka *Developer Tools* (F12), buka tab **Application** -> **Storage** -> **Cookies**.
4.  Cari cookie dengan nama `ndus` dan salin nilainya.
5.  Format cookie yang digunakan adalah: `"lang=en; ndus=NILAI_NDUS_ANDA;"`

### 2. Penggunaan Dasar

Berikut adalah contoh penggunaan yang **kompleks** namun **jelas** untuk mendapatkan info file dan mengunduhnya.

```typescript
import { TeraboxScraper, DownloadProgress, Logger, bytesToHuman } from '@xbibzlibrary/teraboxscraper';
import * as path from 'path';

// Inisialisasi Logger untuk output terminal yang menarik
const logger = Logger.getInstance({ level: 'info', prettyPrint: true }).getLogger();

// Konfigurasi Anda
const YOUR_COOKIE = "lang=en; ndus=YOUR_NDUS_COOKIE_HERE;";
const SHARE_LINK = "https://www.terabox.app/s/xxxxxxxxxxxxxxxx";

/**
 * Fungsi progress bar kustom yang powerfull untuk terminal
 */
function customProgressBar(progress: DownloadProgress): void {
    const totalSizeHuman = bytesToHuman(progress.totalSize);
    const downloadedHuman = bytesToHuman(progress.downloaded);
    const speedHuman = bytesToHuman(progress.speedBps) + '/s';
    const eta = progress.etaSeconds === Infinity ? 'N/A' : `${progress.etaSeconds.toFixed(0)}s`;

    const barLength = 40;
    const filledLength = Math.round(barLength * progress.percentage / 100);
    const emptyLength = barLength - filledLength;
    const bar = '█'.repeat(filledLength) + '░'.repeat(emptyLength);

    process.stdout.write(
        `\r[${bar}] ${progress.percentage.toFixed(2)}% | ${downloadedHuman} / ${totalSizeHuman} | Speed: ${speedHuman} | ETA: ${eta}`
    );
}

async function startDownload() {
    try {
        // 1. Inisialisasi Scraper
        const scraper = new TeraboxScraper({
            cookie: YOUR_COOKIE,
            timeout: 60000,
            // proxy: 'http://user:pass@host:port', // Opsi Proxy
        });

        // 2. Ambil Informasi File (Tahap Scraping & API)
        logger.info(`Memproses link: ${SHARE_LINK}`);
        const infoResponse = await scraper.getFileInfo(SHARE_LINK);

        if (!infoResponse.success || !infoResponse.data) {
            logger.error('Gagal mendapatkan info file.', infoResponse.error);
            return;
        }

        const fileInfo = infoResponse.data;
        logger.info('Info File Ditemukan:', {
            Nama: fileInfo.fileName,
            Ukuran: fileInfo.fileSizeHuman,
        });

        // 3. Unduh File (Tahap Download Stream)
        const downloadDir = path.join(process.cwd(), 'downloads');
        logger.info(`Memulai pengunduhan ke: ${downloadDir}`);

        const downloadResponse = await scraper.downloadFile(
            fileInfo,
            downloadDir,
            customProgressBar // Callback progress bar
        );

        // Bersihkan baris progress bar
        process.stdout.write('\r' + ' '.repeat(100) + '\r');

        if (!downloadResponse.success || !downloadResponse.data) {
            logger.error('Pengunduhan gagal total.', downloadResponse.error);
            return;
        }

        logger.info('✅ Pengunduhan Selesai!', {
            path: downloadResponse.data.filePath,
            durasi: `${(downloadResponse.data.durationMs / 1000).toFixed(2)} detik`,
        });

    } catch (e) {
        logger.fatal('Terjadi kesalahan kritis tak terduga.', { error: e });
    }
}

startDownload();
```

## 👤 Informasi Pengembang

| Kategori | Detail |
| :--- | :--- |
| **Author** | Xbibz Official |
| **Telegram** | [t.me/XbibzOfficial](https://t.me/XbibzOfficial) |
| **TikTok** | [tiktok.com/@XbibzOfficiall](https://tiktok.com/@XbibzOfficiall) |
| **Donasi** | [ko-fi.com/XbibzOfficial](https://ko-fi.com/XbibzOfficial) |

<div align="center">
    <img src="https://github.com/Habibzz01/XbibzAssets-/releases/download/Nexo444/mylogobulat.png" alt="Xbibz Official Logo" width="100"/>
    <p>Dibuat dengan dedikasi oleh Xbibz Official.</p>
</div>

---

## 📄 Lisensi

Library ini dirilis di bawah lisensi **ISC**.

<style>
    h1 { color: #007ACC; border-bottom: 3px solid #007ACC; padding-bottom: 10px; }
    h2 { color: #333; border-left: 5px solid #FF9800; padding-left: 10px; margin-top: 30px; }
    code { background-color: #f0f0f0; padding: 2px 4px; border-radius: 3px; }
    pre { background-color: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 8px; overflow-x: auto; }
</style>
