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

# Client

> SquareCloudAPI クラスは SDK へのエントリーポイントです。API キーで初期化され、アプリケーション、データベース、workspace、ユーザー、プラットフォームサービスといったすべてのモジュールを単一のクライアントを通して公開します。

<Info>
  このページは **`@squarecloud/api` v4** を解説しています。v3 からのアップグレードの場合は、まず [v3 → v4 移行ガイド](/ja/sdks/js/migrating_to_v4) をお読みください。
</Info>

## 要件

* **Node.js 20.0.0** 以降
* 有効な API キー — [Square Cloud ダッシュボード](https://squarecloud.app/ja/dashboard) でリクエストできます

## インストール

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @squarecloud/api
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @squarecloud/api
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @squarecloud/api
    ```
  </Tab>
</Tabs>

## クライアントの初期化

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { SquareCloudAPI } from "@squarecloud/api";

    const api = new SquareCloudAPI(process.env.SQUARE_API_KEY!);
    ```
  </Tab>

  <Tab title="JavaScript (ESM)">
    ```javascript theme={null}
    import { SquareCloudAPI } from "@squarecloud/api";

    const api = new SquareCloudAPI(process.env.SQUARE_API_KEY);
    ```
  </Tab>

  <Tab title="JavaScript (CommonJS)">
    ```javascript theme={null}
    const { SquareCloudAPI } = require("@squarecloud/api");

    const api = new SquareCloudAPI(process.env.SQUARE_API_KEY);
    ```
  </Tab>
</Tabs>

### コンストラクタ

| Parameter | Type     | Required | Description                                      |
| --------- | -------- | -------- | ------------------------------------------------ |
| `apiKey`  | `string` | Yes      | Square Cloud の API キー。文字列でない場合、クライアントは例外をスローします。 |

## モジュール

クライアントは v2 プラットフォーム全体を専用のモジュールを通して公開します。各モジュールは `SquareCloudAPI` インスタンスのプロパティです。

| Property           | Module                      | Documentation                                   |
| ------------------ | --------------------------- | ----------------------------------------------- |
| `api.user`         | 認証済みユーザー、プラン、所有するアプリとデータベース | このページ                                           |
| `api.applications` | アプリケーションの一覧取得、取得、アップロード、検査  | [アプリケーションの管理](/ja/sdks/js/managing_application) |
| `api.databases`    | データベースの作成、取得、管理             | [Databases](/ja/sdks/js/databases)              |
| `api.workspaces`   | workspace の作成、一覧取得、管理       | [Workspaces](/ja/sdks/js/workspaces)            |
| `api.service`      | プラットフォームステータスの集約            | このページ                                           |
| `api.cache`        | SDK イベントによって設定されるインメモリキャッシュ | このページ                                           |

## 認証済みユーザーの取得

`api.user.get()` は、アカウント詳細、現在のプラン、所有するアプリケーション、所有するデータベースを含む [`User`](https://github.com/squarecloudofc/sdk-api-js/blob/main/src/structures/user.ts) インスタンスを返します。

```typescript theme={null}
const user = await api.user.get();

console.log(user.id);          // "abcdef0123456789abcdef01"
console.log(user.name);        // "John Doe"
console.log(user.email);       // "john@example.com"
console.log(user.locale);      // "en-US"
console.log(user.plan.name);   // "free" | "standard" | ...
console.log(user.createdAt);   // Date

console.log(user.applications); // Collection<string, BaseApplication>
console.log(user.databases);    // Collection<string, Database>
```

`user.applications` と `user.databases` は [`Collection`](https://github.com/squarecloudofc/sdk-api-js/blob/main/src/structures/collection.ts) インスタンス（`Map` のサブクラス）です。通常の `Map` と同じように反復処理できます:

```typescript theme={null}
for (const [id, app] of user.applications) {
    console.log(`${app.name} (${id}) — ${app.ram}MB ${app.language}`);
}
```

## 単一のアプリケーションの取得

`api.applications.fetch(id)` を使うと、完全に読み込まれた `Application`（アプリにウェブサイトドメインがある場合は `WebsiteApplication`）を取得できます。

```typescript theme={null}
const app = await api.applications.fetch("abc123def456abc123def456");

console.log(app.id, app.name, app.cluster, app.createdAt);

if (app.isWebsite()) {
    // WebsiteApplication に絞り込まれる — `.network` が利用可能
    await app.network.purgeCache();
}
```

レガシーの `api.applications.get(id)` オーバーロードも依然として存在しますが、これはより軽量な `BaseApplication` を返し、後方互換性のためだけに残されています。**v4 では `.fetch()` を優先してください。**

## snapshot 履歴の一覧取得（アカウント全体）

```typescript theme={null}
const appSnapshots = await api.user.snapshots("applications");
const dbSnapshots  = await api.user.snapshots("databases");
```

snapshot ペイロードの詳細については [Snapshots](/ja/sdks/js/snapshots) を参照してください。

## プラットフォームステータス

`api.service.status()` は、集約されたプラットフォームの健全性（公開ステータスページに表示されるものと同じデータ）を公開します。

```typescript theme={null}
const status = await api.service.status();

console.log(status.status);  // "ok" | "degraded" | "down"
console.log(status.message); // 人間が読める要約
```

<Note>
  ほとんどの v2 エンドポイントとは異なり、このルートはペイロードを標準の `{ status, response }` エンベロープで **ラップしません**。
</Note>

## クライアントキャッシュ

クライアントは、呼び出しを行うたびに SDK が同期を保つインメモリキャッシュを維持します:

```typescript theme={null}
api.cache.user;   // 最後に取得した User
// 各アプリケーションインスタンスも app.cache.status / .logs / .snapshots を公開します
```

SDK は、サブスクライブできる型付きイベントを発行します:

```typescript theme={null}
api.on("userUpdate", (previous, current) => {
    console.log("user changed:", current.name);
});

api.on("statusUpdate", (application, previous, current) => {
    console.log(`${application.name} → ${current.status}`);
});

api.on("logsUpdate", (application, previous, current) => {
    console.log(`new logs for ${application.name}`);
});

api.on("snapshotsUpdate", (application, previous, current) => {
    console.log(`${current.length} snapshots for ${application.name}`);
});
```

## エラーハンドリング

失敗したリクエストは `SquareCloudAPIError` をスローします。このエラーは、失敗モードを判別するために switch できる安定した `code` プロパティを公開します。

```typescript theme={null}
import { SquareCloudAPI, SquareCloudAPIError } from "@squarecloud/api";

try {
    const app = await api.applications.fetch("invalid-id");
} catch (err) {
    if (err instanceof SquareCloudAPIError) {
        console.error(err.code);    // 例: "APP_NOT_FOUND"
        console.error(err.message);
    }
}
```
