> ## 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.

# JavaScript クライアントライブラリ

> 公式 JS/TS SDK octoparse-client。

`octoparse-client` は Data Hub 公式 JavaScript/TypeScript クライアント。公開 `/v1` REST のみ。メソッドは 1 対 1、パラメータ名は REST、戻り値は `data`。

## インストール

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

## 初期化

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

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

| Option    | Description                                                                                |
| --------- | ------------------------------------------------------------------------------------------ |
| `apiKey`  | Data Hub API キー。省略時は `OCTOPARSE_API_KEY`。それでも無ければ匿名で匿名エンドポイントのみ。                           |
| `baseUrl` | サービス URL。省略時は `OCTOPARSE_BASE_URL`、既定 `https://api-datahub.octoparse.com`。ローカル／ステージングでは明示。 |
| `timeout` | リクエストあたり HTTP タイムアウト（ミリ秒）。既定 90000。                                                        |

## メソッドとエンドポイントの対応

| Method                                                              | Endpoint                                  | Notes                                           |
| ------------------------------------------------------------------- | ----------------------------------------- | ----------------------------------------------- |
| `meta()`                                                            | `GET /v1/meta`                            | Platform constants                              |
| `search(q, { limit, offset, ... })`                                 | `GET /v1/data-apps`                       | One page of cards, including `pagination`       |
| `getApp(appId)`                                                     | `GET /v1/data-apps/{app_id}`              | Full app detail                                 |
| `run(appId, inputs, { wait, maxRecords, version, build })`          | `POST /v1/data-apps/{app_id}/runs`        | Start a run                                     |
| `call(appId, inputs, { maxRecords, timeout, raiseOnFailure, ... })` | `POST` + poll                             | Blocking helper: wait until terminal or timeout |
| `getRun(runId, { wait })`                                           | `GET /v1/runs/{run_id}`                   | 状態と課金スナップショット                                   |
| `listRunsPage(filters)`                                             | `GET /v1/runs`                            | One page of runs, including `pagination`        |
| `listRuns(filters)`                                                 | `GET /v1/runs`                            | 実行 1 ページ（items のみ）                              |
| `iterateRuns(filters)`                                              | `GET /v1/runs`                            | 自動ページング非同期イテレータ                                 |
| `cancel(runId)`                                                     | `POST /v1/runs/{run_id}/cancel`           | Cancel a run                                    |
| `getRecords(runId, { offset, limit, fields })`                      | `GET /v1/runs/{run_id}/records`           | One page of result records                      |
| `iterateRecords(runId, { batch, fields })`                          | `GET /v1/runs/{run_id}/records`           | 自動ページング非同期イテレータ                                 |
| `exportRecords(runId, format)`                                      | `GET /v1/runs/{run_id}/records`           | Full export as `jsonl` / `csv` text             |
| `listDatasets({ offset, limit })`                                   | `GET /v1/datasets`                        | データセット一覧                                        |
| `setDatasetRetention(datasetId, retained)`                          | `PUT /v1/datasets/{dataset_id}/retention` | Set retention flag                              |
| `getDatasetRecords(datasetId, { offset, limit, fields })`           | `GET /v1/datasets/{dataset_id}/records`   | One page of dataset records                     |
| `iterateDatasetRecords(datasetId, { batch, fields })`               | `GET /v1/datasets/{dataset_id}/records`   | 自動ページング非同期イテレータ                                 |
| `account()`                                                         | `GET /v1/account`                         | アカウント情報と累計支出                                    |
| `billing({ groupBy, createdFrom, createdTo, tzOffset })`            | `GET /v1/billing`                         | Billing aggregation                             |

実行一覧 `filters` は `status`、`dataApp`、`triggeredBy`、`runKind`、`credential`、`createdFrom`、`createdTo` と `offset`/`limit`。公開・運用・シークレットは未ラップ — REST 直接。

## 典型的な使い方

```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);
```

## エラー処理

API エラーは `ApiError`（`Error` 拡張）を throw。フィールドは REST `error` と同じ:

| Property     | Meaning                                                               |
| ------------ | --------------------------------------------------------------------- |
| `statusCode` | HTTP status                                                           |
| `code`       | 分岐用の安定エラー id                                                          |
| `category`   | Broad class                                                           |
| `message`    | English description                                                   |
| `retryable`  | 同一リクエストを再試行できるか                                                       |
| `details`    | Field-level issues on input validation failure, otherwise `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;
  }
}
```

`call()` が `raiseOnFailure: true` で `FAILED` / `CANCELLED` / `EXPIRED` 終了時に `RunFailed`。`run` に実行オブジェクト全文。

## App 参照

`getApp()`、`run()`、`call()`、実行一覧の `dataApp` フィルタは両形式を受付: 2 段 `<namespace>/<app_name>`（人が読める、改名で壊れる）と安定 `app_id`（`app_<hex>`、改名耐性）。長期連携は `app_id` 推奨。
