@faiber/faiber-state-sdk

中文文档
2.8.0发布于 2026/11/14TypeScriptES Module近 30 天下载 3994

Typed State worlds, rooms, WASM export bindings, server-authoritative games and ticket-authenticated WebSockets.

原始使用文档

@faiber/faiber-state-sdk

Typed State worlds, rooms, WASM export bindings, server-authoritative games and ticket-authenticated WebSockets.

npm install @faiber/faiber-state-sdk
import { FaiberClient } from "@faiber/sdk-core";
import { StateApi, StateRealtimeClient } from "@faiber/faiber-state-sdk";

const state = new StateApi(new FaiberClient("state", {
  domains: { state: "https://state.example.com" },
  authMode: "cookie",
}));
const options = { headers: { "x-organization-id": organizationId }, signal };
const world = await state.createWorld({ name: "Arena", slug: "arena" }, options);
const room = await state.createRoom(world.data.data.id, { name: "Room 1", capacity: 8 }, options);
const ticket = (await state.join(room.data.data.id, userId, options)).data.data;
const realtime = new StateRealtimeClient(ticket);
realtime.on("patch", patch => applyServerPatch(patch));
realtime.on("pong", ({ tick }) => observeServerTick(tick));
await realtime.connect();
realtime.sendInput({ move_x: 5, move_z: -1 });
// On leaving the room:
realtime.close();

Use secure HttpOnly cookies with withCredentials, or configure FaiberClient with a TokenProvider that supplies an in-memory Bearer token. Every HTTP call preserves the full Axios response, options, errors and cancellation signal. Catch Axios errors for validation (400/422), missing records (404), permission failures (401/403), conflicts (409), and transport failures. Aborting signal cancels HTTP requests. The complete facade is available as @faiber/faiber-ts-sdk.

v1 world/room/WASM operations require an authenticated user, a non-nil x-organization-id UUID, and state:read, state:write, or state:execute as documented per operation. State management, wildcard and admin aliases are also accepted. Joining/invoking for another user requires management authority. Managed game worlds expose managed: true and reject update/deletion with 409. All v1 and v2 success responses use { data }.

Browsers carry room input over WebSocket. Native hosts can inject DatagramTransport for the JSON UDP input gateway; each datagram includes the scoped room ticket. acked UDP delivery returns an acknowledgement. The room ticket expires after five minutes and is checked at upgrade; rejoining obtains a new player and ticket. close() stops retries. The backend may deliver a patch both as an input response and broadcast; consumers should track entity revisions/sequences. PredictionBuffer can replay pending inputs after authoritative updates.

The generated state.operations covers all mounted HTTP APIs and both WebSocket upgrades. v2 game catalog reads are public; protected game operations require state:execute and applicable owner/member checks. The SQL game runtime uses the tenant configured on the service. Game-operations summary, economy, session pages and event pages have named response models. Their query keys use snake_case (page_size, settlement_status, user_id); returned page metadata uses camelCase. Session pages default to 25 entries, event pages to 50, and both clamp sizes to 10–100.

const created = await state.operations.gamesRoutesCreateSessionPost(gameId, {
  difficulty: "11-14", paid: false,
}, { signal });
const page = await state.operations.routesGameOperationSessionsGet({
  page: 1, page_size: 25, paid: false,
}, options);
const connection = await state.createMatchConnection(matchId, { signal });
const socket = await state.operations.connectMatchRealtime(connection.data.data, { signal });

Game commands include a stable command UUID and the expected state version. Stale HTTP game versions return 409; match WebSocket command rejection uses a command_result frame and a fresh snapshot. Board, challenge, metrics, event payloads and game answer/action JSON deliberately vary by registered game/ruleset and are documented as GamePayload; component/input JSON varies by authored world schema.

connectMatchRealtime validates the configured service origin and sends a 30-second one-use connection ticket in the initial hello frame within five seconds. Acquire a fresh ticket after reconnecting. MatchRealtimeClient automatically reconnects only when supplied refreshTicket; a consumed ticket cannot be reused. The server validates allowed browser Origins. routesRealtimeGet(ticket, { signal }) opens v1 room replication against the configured service origin. Socket operations return a connected WebSocket/client.

health() and operations.mainProcessHealthGet() read the static /health advertisement (service, status, transports, rulesets, wasm). This advertises WebSocket and kheradgah.v1; it does not verify database, gameplay, persistence, gateway or WebSocket readiness.

版本与发布记录

@faiber/faiber-state-sdk 共发布 59 个版本,首次发布于 2026/07/28;过去 12 个月发布了 59 个版本。

版本发布日期距今
2.8.0latest2026/11/14今天
2.7.02026/11/059 天前
2.6.02026/11/049 天前
2.5.02026/11/049 天前
2.4.02026/11/0310 天前
2.3.02026/11/0211 天前

关于 @faiber/faiber-state-sdk 的常见问题

@faiber/faiber-state-sdk 是什么?

Typed State worlds, rooms, WASM export bindings, server-authoritative games and ticket-authenticated WebSockets.

如何安装 @faiber/faiber-state-sdk?

在项目目录运行 npm install @faiber/faiber-state-sdk,或使用 pnpm add / yarn add / bun add。

@faiber/faiber-state-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@faiber/faiber-state-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@faiber/faiber-state-sdk 可以商用吗?

@faiber/faiber-state-sdk 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@faiber/faiber-state-sdk 的下载量有多少?

根据 npm 官方下载统计,@faiber/faiber-state-sdk 在 2026/10/14 – 2026/11/12 这 30 天内被下载 3,994 次,日均约 133 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@faiber/faiber-state-sdk 还在维护吗?

最新版本 2.8.0 发布于 2026/11/14(今天);至今共发布 59 个版本,其中过去 12 个月发布了 59 个;首次发布于 2026/07/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。