JSPM

flaresync

0.2.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 7
  • Score
    100M100P100Q42358F
  • License MIT

Durable Object state sync library for Cloudflare Workers — assign a variable, every client gets the diff.

Package Exports

  • flaresync
  • flaresync/client
  • flaresync/package.json

Readme

flaresync

npm version MIT License

Cloudflare Durable Objects 専用の状態同期ライブラリ(サーバー側)。Durable Object 内で変数に代入するだけで、接続中の全クライアントに差分が届く。

this.sync.state.hp -= 10;
// → 全クライアントに { hp: 90 } が自動で届く

インストール

npm install flaresync

@cloudflare/workers-types を peer dependency として使用します(Cloudflare Workers プロジェクトでは通常インストール済み)。

使い方

import { DurableSync } from "flaresync";
import { DurableObject } from "cloudflare:workers";

type State = { hp: number };

export class BattleRoom extends DurableObject {
  private sync: DurableSync<State>;

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.sync = new DurableSync({ hp: 100 }, ctx);
  }

  async fetch(request: Request): Promise<Response> {
    const { 0: client, 1: server } = new WebSocketPair();
    this.ctx.acceptWebSocket(server);
    return new Response(null, { status: 101, webSocket: client });
  }

  async alarm() {
    await this.sync.alarm();
  }
}

wrangler.toml

name = "my-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[[durable_objects.bindings]]
name = "ROOM"
class_name = "BattleRoom"

[[migrations]]
tag = "v1"
new_classes = ["BattleRoom"]

クライアント(ブラウザ / Node.js)

import { DurableSyncClient } from "flaresync/client";

const client = new DurableSyncClient("wss://your-worker.example.com/room", {
  hp: 100,
});

client.onChange((state) => {
  console.log("hp:", state.hp);
});

ライセンス

MIT — KOU050223