# Node.js/NPM

より細かい制御が必要で、アプリケーションレベルで作業したい場合は、npm から GitBook の埋め込みパッケージをインストールできます。このアプローチは、サーバーサイドレンダリング、ビルド時の統合、またはカスタム iframe 管理に最適です。

## 手順

{% stepper %}
{% step %}

#### パッケージをインストールする

追加する `@gitbook/embed` をプロジェクトに追加します：

```bash
npm install @gitbook/embed
```

完全な API リファレンスとソースコードについては、GitHub 上の次のものを参照してください： [`@gitbook/embed` パッケージ](https://github.com/GitbookIO/gitbook/tree/main/packages/embed).
{% endstep %}

{% step %}

#### パッケージをインポートする

アプリケーションコードで、 `createGitBook` 関数をインポートします：

```javascript
import { createGitBook } from "@gitbook/embed";
```

または CommonJS を使用する場合：

```javascript
const { createGitBook } = require("@gitbook/embed");
```

{% endstep %}

{% step %}

#### GitBook を初期化する

docs サイトの URL を使って GitBook インスタンスを作成します：

```javascript
const gitbook = createGitBook({
  siteURL: "https://docs.company.com",
});
```

{% endstep %}

{% step %}

#### iframe を作成する

iframe 要素を生成し、そのソースを埋め込み URL に設定します：

```javascript
const iframe = document.createElement("iframe");
iframe.src = gitbook.getFrameURL({
  visitor: {
    token: 'your-jwt-token', // 任意: Adaptive Content または認証済みアクセス用
    unsignedClaims: { // 任意: 動的式用のカスタムクレーム
      userId: '123',
      plan: 'premium'
    }
  }
});
iframe.id = "gitbook-embed-container";
iframe.style.border = "none";
iframe.style.width = "100%";
iframe.style.height = "600px";
```

{% endstep %}

{% step %}

#### フレームを追加する

GitBook フレームインスタンスを作成し、ページにマウントします：

```javascript
const frame = gitbook.createFrame(iframe);
document.getElementById("gitbook-embed-container").appendChild(iframe);
```

{% endstep %}

{% step %}

#### 埋め込みをプログラムで制御する

フレームインスタンスを使って埋め込みとやり取りします：

```javascript
// ドキュメントタブ内の特定のページへ移動
frame.navigateToPage("/getting-started");

// アシスタント タブに切り替える
frame.navigateToAssistant();

// チャットにメッセージを送信
frame.postUserMessage("How do I get started?");

// チャット履歴をクリア
frame.clearChat();
```

{% endstep %}

{% step %}

#### 埋め込みを設定する

カスタマイズオプションを使って埋め込みを設定します：

```javascript
frame.configure({
  trademark: false,
  tabs: ['assistant', 'docs'],
  actions: [
    {
      icon: 'circle-question',
      label: 'サポートに連絡',
      onClick: () => window.open('https://support.example.com', '_blank')
    }
  ],
  greeting: { title: 'ようこそ！', subtitle: 'どのようにお手伝いできますか？' },
  suggestions: ['What is GitBook?', 'How do I get started?'],
  tools: [/* ... */]
});
```

{% endstep %}

{% step %}

#### イベントを監視する

埋め込みイベントに応答するためにイベントリスナーを登録します：

```javascript
frame.on('close', () => {
  console.log('フレームが閉じられました');
});

// 完了したら購読解除
const unsubscribe = frame.on('navigate', (data) => {
  console.log('Navigated to:', data.path);
});
```

{% endstep %}
{% endstepper %}

## API リファレンス

### クライアント ファクトリ

* `createGitBook(options: { siteURL: string })` → `GitBookClient`
* `client.getFrameURL(options?: { visitor?: {...} })` → `string` - 認証付きアクセスをオプションで指定して iframe の URL を取得します
* `client.createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - iframe と通信するためのフレームクライアントを作成します

### フレーム クライアントのメソッド

* `frame.navigateToPage(path: string)` → `void` - ドキュメントタブ内の特定のページへ移動します
* `frame.navigateToAssistant()` → `void` - アシスタントタブに切り替えます
* `frame.postUserMessage(message: string)` → `void` - チャットにメッセージを送信します
* `frame.clearChat()` → `void` - チャット履歴をクリアします
* `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void` - 埋め込みを設定します
* `frame.on(event: string, listener: Function)` → `() => void` - イベントリスナーを登録します（unsubscribe 関数を返します）

## 設定オプション

設定オプションは次で利用できます `frame.configure({...})`:

### `tabs`

表示するタブを上書きします。既定値はサイトの設定です。

* **入力**: `('assistant' | 'docs')[]`

### `actions`

タブの横にあるサイドバーに表示されるカスタムアクションボタンです。各アクションボタンはクリック時にコールバックをトリガーします。

**注意**：以前はこれを `buttons`と呼んでいました。 `actions` の使用を検討してください。

* **入力**: `Array<{ icon: string, label: string, onClick: () => void }>`

### `greeting`

アシスタンタブに表示されるウェルカムメッセージ。

* **入力**: `{ title: string, subtitle: string }`

### `suggestions`

アシスタントのウェルカム画面に表示される提案質問。

* **入力**: `string[]`

### `trademark`

埋め込み UI で GitBook の商標を表示または非表示にします — Docs Embed のフッターと Assistant のブランド表示を含みます。

* **入力**: `boolean`
* **デフォルト**: `true`

### `tools`

アシスタントを拡張するためのカスタム AI ツールです。詳細は [カスタムツールの作成](https://gitbook-open-v2-preview.gitbook.workers.dev/url/gitbook.com/docs/documentation/ja-gitbook-documentation/publishing-documentation/embedding/configuration/creating-custom-tools) をご覧ください。

* **入力**: `Array<{ name: string, description: string, inputSchema: object, execute: Function, confirmation?: {...} }>`

### `visitor` （認証済みアクセス）

次に渡します `getFrameURL({ visitor: {...} })`。用途は [Adaptive Content](https://gitbook-open-v2-preview.gitbook.workers.dev/url/gitbook.com/docs/documentation/ja-gitbook-documentation/publishing-documentation/adaptive-content) 、 [認証済みアクセス](https://gitbook-open-v2-preview.gitbook.workers.dev/url/gitbook.com/docs/documentation/ja-gitbook-documentation/publishing-documentation/authenticated-access).

* **入力**: `{ token?: string, unsignedClaims?: Record<string, unknown> }`

## よくある落とし穴

* **パッケージのインストールを忘れる** – 実行してください `npm install @gitbook/embed` をインポートする前に。
* **siteURL がない** – `siteURL` オプションは必須で、公開済みの docs サイトと一致している必要があります。
* **iFrame がレンダリングされない** – 親コンテナに、iframe を表示するのに十分な幅/高さがあることを確認してください。
* **初期化前にフレームメソッドが呼ばれる** – まで待ってから `createFrame()` を呼び出してからフレームメソッドを実行してください。
* **イベントの購読解除をしない** – 次で返される unsubscribe 関数を呼び出すことを忘れないでください `frame.on()` メモリリークを防ぐためです。
* **古い API メソッドを使用している** – 次のようなメソッドは `open()`, `close()`, `toggle()`、および `destroy()` NPM パッケージでは利用できません。代わりにフレームクライアントのメソッドを使用してください。
