本文へ移動
SDK ガイド / 接続と共有

接続と共有

Console で接続設定を取得し、World に参加者を招待します。

接続設定

  1. 運営者の招待リンクから Console のアカウントを作成します。
  2. Console でプロジェクトを作成します。
  3. 詳細画面から tablebox.json をダウンロードし、アプリに配置します。

アプリの利用者が Console にログインする必要はありません。接続先の Relay Node が稼働し、プロジェクトの接続資格の発行が許可されている必要があります。

接続資格を取得する

次を connection.ts として保存します。SDK は必要に応じて access 関数を呼び、資格を更新します。JSON の import には resolveJsonModule に対応したバンドラー設定が必要です。

connection.ts
import { connect, type Identity, type RelayAccess } from "@tablebox/sdk";
import configuration from "./tablebox.json";

export async function openConnection(identity: Identity) {
  const { issuer, key, ...location } = configuration;
  return connect({
    identity,
    ...location,
    access: async () => {
      const request = {
        subject: identity.subject,
        key,
        nonce: crypto.randomUUID(),
      };
      const proof = await identity.sign("relay-request/1", request);
      const response = await fetch(new URL("/access", issuer), {
        method: "POST",
        headers: { "content-type": "application/json" },
        credentials: "omit",
        body: JSON.stringify({ ...request, proof }),
      });
      if (!response.ok) throw new Error("接続資格を取得できませんでした");
      return await response.json() as RelayAccess;
    },
  });
}

共有と参加

World を作る例の続きです。World を公開し、招待を発行します。

作成者 · 前の例の続き
import { openConnection } from "./connection";

const connection = await openConnection(identity);
const session = await connection.world.publish(world);
const invitation = await world.invitations.create({
  actions: { read: [rootScope], send: [rootScope] },
});
// invitation を JSON として参加者へ渡す

参加者は別のブラウザープロファイルで、受け取った招待を join 関数に渡します。招待を参加資格に交換してから World に参加します。招待は既定で1回・24時間、発行される資格は1時間です。

参加者 · join の戻り値で終了処理
import { Identity, type Invitation } from "@tablebox/sdk";
import { openConnection } from "./connection";

async function join(invitation: Invitation) {
  if (!invitation.issuer || !invitation.token) throw new Error("標準招待を指定してください");
  const identity = await Identity.generate();
  const connection = await openConnection(identity);
  const access = await connection.invitation.request({
    world: invitation.world,
    issuer: invitation.issuer,
    invitation: invitation.token,
  });
  const session = await connection.world.join(invitation.world, { access });
  const world = session.model;
  const stop = world.watch({ from: "objects" }, (page) => {
    console.log(page.items);
  });
  return async () => {
    stop();
    await session.leave();
    await world.close();
    connection.close();
  };
}

接続設定は Relay の利用、招待は World への参加を許可します。招待は参加させたい相手にだけ渡してください。