# Astro 向け Live Chat とリアルタイム機能

> Astro インテグレーション：astro.config に 1 行加えるだけで全ページに Hibira Live Chat が入り、ページのスクリプトは共有の 1 本の接続でイベント、プレゼンス、ストリーミングされる LLM の回答を受け取れます。Astro 4〜7 に対応。

Source: https://hibira.io/ja/guides/astro

Astro インテグレーション：astro.config に 1 行加えるだけで全ページに Hibira Live Chat が入り、ページのスクリプトは共有の 1 本の接続でイベント、プレゼンス、ストリーミングされる LLM の回答を受け取れます。Astro 4〜7 に対応。

Package: @hibira-io/astro

- チャットは一度だけ読み込まれ、ビュートランジションをまたいでも開いたままです。<LiveChatButton> や #hibira-live-chat へのリンクで開けます。
- <LiveChatUser> がサーバー側で識別シークレットを使って訪問者をサインインさせるので、受信箱に誰かが表示され、会話はデバイスをまたいで続きます。
- どの <script> や island でも onEvent、onPresence、onStream が使え、API ルートには channelAuth()、LLM の回答には streamToChannel() があります。

## 1. インストール

```shell
npx astro add @hibira-io/astro
npm install pusher-js
```

## 2. 設定する

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import hibira from '@hibira-io/astro';

export default defineConfig({
  integrations: [
    hibira({
      liveChat: 'ws_YOUR_WORKSPACE', // or PUBLIC_HIBIRA_LIVECHAT_WORKSPACE
      realtime: {
        key: import.meta.env.PUBLIC_HIBIRA_KEY,
        options: {
          wsHost: 'ws.hibira.io',
          channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
        },
      },
    }),
  ],
});
```

## 3. 使う

```xml
---
import { LiveChatUser, LiveChatButton } from '@hibira-io/astro/components';
const user = Astro.locals.user;
---
<LiveChatUser user={user && { id: user.id, name: user.name, email: user.email }} />
<LiveChatButton topic="sales">Talk to sales</LiveChatButton>
<p><span id="online">0</span> online</p>

<script>
  import { onEvent, onPresence } from '@hibira-io/astro/realtime';

  onEvent('orders', 'order.created', (order) => console.log(order));
  onPresence('presence-dashboard', ({ count }) => (document.getElementById('online').textContent = String(count)));
</script>
```

## 始める前に

- Live Chat コンソールでワークスペース ID を確認し、「設定」の「認証済み訪問者」で識別シークレットを作成します。HIBIRA_LIVECHAT_IDENTITY_SECRET に入れ、サーバーの外には出しません。
- Free プランでは、ページを読み込むすべてのオリジンをアプリの許可オリジンに登録してください（開発中は http://localhost:3000、その後は自分のドメイン）。"*" は有料プランで使えます。
- プライベートチャンネルとプレゼンスチャンネルには、pusher-js と同じく、アプリのシークレットで購読に署名する認可エンドポイントがバックエンドに必要です。
- Astro 5.14 以降をプロキシの後ろで動かす場合は、security.allowedDomains にドメインを登録してください。登録しないと Astro が認証リクエストを 403 で拒否します。

- [npm](https://www.npmjs.com/package/@hibira-io/astro)
- [GitHub](https://github.com/hibira-io/astro)
