> ## Documentation Index
> Fetch the complete documentation index at: https://www.octoparse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Libreria client JavaScript

> Installa, inizializza, mappa i metodi agli endpoint e gestisci gli errori con l’SDK JavaScript ufficiale octoparse-client.

`octoparse-client` è il client JavaScript/TypeScript ufficiale per Data Hub. Incapsula solo la REST API pubblica `/v1`. I metodi corrispondono uno a uno agli endpoint, i nomi dei parametri coincidono con REST e i valori restituiti sono il payload `data` grezzo. Richiede Node.js 18+ o un runtime browser moderno con `fetch`.

## Installazione

```bash theme={null}
npm install octoparse-client
```

## Inizializzazione

```js theme={null}
import { Client } from "octoparse-client";

const client = new Client({ apiKey: "<your API key>" });
```

| Opzione   | Descrizione                                                                                                                                                                         |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`  | API key di Data Hub. Se omessa, viene letta `OCTOPARSE_API_KEY`. Se manca ancora, il client è anonimo e può chiamare solo gli endpoint anonimi.                                     |
| `baseUrl` | URL del servizio. Se omesso, viene letto `OCTOPARSE_BASE_URL`, con valore predefinito `https://api-datahub.octoparse.com`. Passalo esplicitamente per ambienti locali o di staging. |
| `timeout` | Per-request HTTP timeout in millisecondi. Predefinito 90000.                                                                                                                        |

## Mappa metodo–endpoint

| Metodo                                                              | Endpoint                                  | Note                                          |
| ------------------------------------------------------------------- | ----------------------------------------- | --------------------------------------------- |
| `meta()`                                                            | `GET /v1/meta`                            | Costanti di piattaforma                       |
| `search(q, { limit, offset, ... })`                                 | `GET /v1/data-apps`                       | Una pagina di card, inclusa `pagination`      |
| `getApp(appId)`                                                     | `GET /v1/data-apps/{app_id}`              | Dettaglio app completo                        |
| `run(appId, inputs, { wait, maxRecords, version, build })`          | `POST /v1/data-apps/{app_id}/runs`        | Avvia un’esecuzione                           |
| `call(appId, inputs, { maxRecords, timeout, raiseOnFailure, ... })` | `POST` + polling                          | Helper bloccante: attendi terminale o timeout |
| `getRun(runId, { wait })`                                           | `GET /v1/runs/{run_id}`                   | Snapshot di stato e fatturazione              |
| `listRunsPage(filters)`                                             | `GET /v1/runs`                            | Una pagina di run, inclusa `pagination`       |
| `listRuns(filters)`                                                 | `GET /v1/runs`                            | Una pagina di run, solo items                 |
| `iterateRuns(filters)`                                              | `GET /v1/runs`                            | Iterator async che pagina automaticamente     |
| `cancel(runId)`                                                     | `POST /v1/runs/{run_id}/cancel`           | Annulla un’esecuzione                         |
| `getRecords(runId, { offset, limit, fields })`                      | `GET /v1/runs/{run_id}/records`           | Una pagina di record risultato                |
| `iterateRecords(runId, { batch, fields })`                          | `GET /v1/runs/{run_id}/records`           | Iterator async che pagina automaticamente     |
| `exportRecords(runId, format)`                                      | `GET /v1/runs/{run_id}/records`           | Export completo come testo `jsonl`/`csv`      |
| `listDatasets({ offset, limit })`                                   | `GET /v1/datasets`                        | Elenco dataset                                |
| `setDatasetRetention(datasetId, retained)`                          | `PUT /v1/datasets/{dataset_id}/retention` | Imposta flag di retention                     |
| `getDatasetRecords(datasetId, { offset, limit, fields })`           | `GET /v1/datasets/{dataset_id}/records`   | Una pagina di record dataset                  |
| `iterateDatasetRecords(datasetId, { batch, fields })`               | `GET /v1/datasets/{dataset_id}/records`   | Iterator async che pagina automaticamente     |
| `account()`                                                         | `GET /v1/account`                         | Info account e spesa cumulativa               |
| `billing({ groupBy, createdFrom, createdTo, tzOffset })`            | `GET /v1/billing`                         | Aggregazione fatturazione                     |

I `filters` della lista dei run supportano `status`, `dataApp`, `triggeredBy`, `runKind`, `credential`, `createdFrom`, `createdTo`, più `offset` / `limit`. Gli endpoint di pubblicazione, operativi e dei secret non sono incapsulati; chiama direttamente la REST API.

## Uso tipico

```js theme={null}
import { Client, ApiError, RunFailed } from "octoparse-client";

const client = new Client({ apiKey: "<your API key>" });

// Discover
const { items } = await client.search("reviews", { limit: 5 });
for (const card of items) console.log(card.app_id, card.namespace, card.app_name);
const detail = await client.getApp("carol/reviews-query");

// Run and consume. Timeouts are milliseconds. TimeoutError does not cancel the server-side run.
const run = await client.call("carol/reviews-query", { product: "p-9001" }, {
  maxRecords: 100, timeout: 120_000, raiseOnFailure: true,
});
for await (const record of client.iterateRecords(run.run_id)) {
  console.log(record);
}

// Non-blocking: start, then poll yourself
const started = await client.run("carol/reviews-query", { product: "p-9002" }, { wait: 0 });
const polled = await client.getRun(started.run_id, { wait: 60 });

// Reconcile spend
console.log(await client.billing({ groupBy: "data_app", tzOffset: 480 }));
for await (const r of client.iterateRuns({ createdFrom: "2026-09-01T00:00:00+08:00" })) {
  console.log(r.run_id, r.status, r.billing.total);
}

// Results are kept 90 days by default; mark datasets you need longer
await client.setDatasetRetention(run.dataset_id, true);
```

## Gestione errori

Le risposte di errore dell'API lanciano `ApiError` (estende `Error`). I campi corrispondono all'oggetto REST `error`:

| Proprietà    | Significato                                                                                   |
| ------------ | --------------------------------------------------------------------------------------------- |
| `statusCode` | Stato HTTP                                                                                    |
| `code`       | ID di errore stabile per la gestione dei casi                                                 |
| `category`   | Classe generale                                                                               |
| `message`    | Descrizione in inglese                                                                        |
| `retryable`  | Se la stessa request può essere ritentata                                                     |
| `details`    | Problemi a livello di campo quando la validazione dell'input fallisce, altrimenti `undefined` |

```js theme={null}
import { ApiError } from "octoparse-client";

try {
  await client.run("carol/reviews-query", {});
} catch (e) {
  if (e instanceof ApiError && e.code === "invalid-input") {
    for (const d of e.details ?? []) console.log(d.path, d.message);
  } else if (e instanceof ApiError && e.retryable) {
    // back off and retry
  } else {
    throw e;
  }
}
```

`RunFailed` viene lanciato quando `call()` usa `raiseOnFailure: true` e il run termina in `FAILED` / `CANCELLED` / `EXPIRED`. La sua proprietà `run` contiene l'oggetto run completo.

## Riferimenti app

`getApp()`, `run()`, `call()` e il filtro lista run `dataApp` accettano entrambe le forme: a due segmenti `<namespace>/<app_name>` (leggibile, si rompe dopo rename) e `app_id` stabile (`app_<hex>`, sopravvive al rename). Per integrazioni longeve salva `app_id`.
