@unboxy/phaser-sdk 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/SDK-GUIDE.md CHANGED
@@ -6,8 +6,10 @@ Reference for AI agents building games on the Unboxy platform. Tracks the **inst
6
6
 
7
7
  - `createUnboxyGame(options)` — Phaser.Game factory with platform defaults (screenshot + recording wired up)
8
8
  - `UnboxyScene` — optional base scene with `createButton`, `shakeCamera`, `flashCamera` helpers
9
- - `Unboxy.init()` — platform services: identity, save data
10
- - (future: leaderboards, multiplayer lobbies)
9
+ - `Unboxy.init()` — platform services entry point
10
+ - `unboxy.saves` — **per-user** key-value store (only the owner sees/writes their data)
11
+ - `unboxy.gameData` — **per-game** key-value store (read by anyone; write requires auth)
12
+ - (future: multiplayer lobbies)
11
13
 
12
14
  ## Platform services
13
15
 
@@ -124,6 +126,63 @@ const saved = await unboxy.saves.get<number>('highScore').catch(() => null);
124
126
  this.highScore = typeof saved === 'number' ? saved : 0;
125
127
  ```
126
128
 
129
+ ### Game data — `unboxy.gameData`
130
+
131
+ Same API shape as `saves`, but **game-scope**: one value per key, shared by all players of the game. Use it for things the whole playerbase sees — scoreboards, shared inventories, tournament state, level-of-the-day.
132
+
133
+ ```ts
134
+ // Read — public. Works for anonymous visitors.
135
+ type Entry = { name: string; score: number; at: number };
136
+ const board = await unboxy.gameData.get<Entry[]>('leaderboard') ?? [];
137
+
138
+ // Write — requires an authenticated user. Throws RpcError('UNAUTHENTICATED') otherwise.
139
+ // Safe append: read + modify + write with ifVersion to avoid clobbering
140
+ // concurrent writers (two players finishing at the same time).
141
+ const { value: current, version } = await unboxy.gameData
142
+ .get<Entry[]>('leaderboard')
143
+ .then((v) => ({ value: v ?? [], version: null as number | null })) // null means "not yet written"
144
+
145
+ async function submitScore(name: string, score: number) {
146
+ if (!unboxy.isAuthenticated) return; // skip for anonymous
147
+ for (let attempt = 0; attempt < 3; attempt++) {
148
+ const raw = await unboxy.gameData.get<Entry[]>('leaderboard');
149
+ const list = Array.isArray(raw) ? raw : [];
150
+ const next = [...list, { name, score, at: Date.now() }]
151
+ .sort((a, b) => b.score - a.score)
152
+ .slice(0, 100); // cap to top 100 so we don't blow the 100 KB limit
153
+ try {
154
+ await unboxy.gameData.set('leaderboard', next);
155
+ return; // success
156
+ } catch (err: any) {
157
+ if (err?.code !== 'VERSION_MISMATCH') throw err;
158
+ // another writer landed first — re-read and retry
159
+ }
160
+ }
161
+ }
162
+ ```
163
+
164
+ ### Saves vs. gameData — which one?
165
+
166
+ | Need | Use | Why |
167
+ |---|---|---|
168
+ | My personal high score | `saves` | Only I write it, only I read it. Anonymous-friendly (localStorage fallback). |
169
+ | Progress through levels | `saves` | Per-user private state. |
170
+ | Character / loadout choice | `saves` | Per-user. |
171
+ | Scoreboard visible to everyone | `gameData` | Multiple users write; anyone reads. |
172
+ | Today's puzzle / daily challenge | `gameData` | Single global value read by all players. |
173
+ | Shared tournament bracket | `gameData` | Shared mutable state across players. |
174
+ | Player name in a chat log | `gameData` | But consider size caps — chat is noisy. |
175
+ | Current frame's enemy positions | *neither* — transient, don't persist | Wastes quota and confuses state after refresh. |
176
+
177
+ Rule of thumb: if two different players would write to the same key, it's `gameData`. If a write from player A should never be visible to player B, it's `saves`.
178
+
179
+ ### Concurrency + size (gameData specifics)
180
+
181
+ - **List writes race.** If two players append to `leaderboard` simultaneously, one overwrites the other's work. Use `ifVersion` for read-modify-write. On `VERSION_MISMATCH`, re-read and retry.
182
+ - **Truncate.** A single key caps at 100 KB — roughly 500-1000 compact JSON entries. Keep lists bounded (top N, drop older), or shard across keys.
183
+ - **Reads are cheap and public.** No auth needed — even logged-out players see `gameData`. Don't put anything secret here.
184
+ - **Trust is thin.** The backend stores what you write, verbatim. A player with devtools could submit any JSON. For casual games this is fine; for competitive stakes, a future typed leaderboards API with server-side validation is the right fix.
185
+
127
186
  ## Anti-patterns (don't do these)
128
187
 
129
188
  - Do **not** call `Unboxy.init()` inside a scene. Initialize at module load in `main.ts` and export the promise.
@@ -131,9 +190,12 @@ this.highScore = typeof saved === 'number' ? saved : 0;
131
190
  - Do **not** save on every frame / every score tick. Debounce or only save on meaningful events (game over, level clear).
132
191
  - Do **not** store large binary blobs (images, audio) as save values — use a dedicated blob API when it ships.
133
192
  - Do **not** use `localStorage` directly for persistent data when `unboxy.saves` is available — you'll lose cross-device sync when we ship provisional accounts.
193
+ - Do **not** put secrets, private messages, or per-user data in `gameData` — it's public. That's `saves`.
194
+ - Do **not** write to `gameData` on every score tick either — submit once at game-over or level-clear.
134
195
 
135
196
  ## Changelog
136
197
 
198
+ - **0.2.4** — added `unboxy.gameData` module (game-scope key-value store for scoreboards, shared state)
137
199
  - **0.2.3** — anonymous users now use localStorage even inside a host (was throwing UNAUTHENTICATED when calling `saves` in home-ui without login)
138
200
  - **0.2.2** — added `SDK-GUIDE.md`
139
201
  - **0.2.1** — added `Unboxy.init`, `unboxy.user`, `unboxy.saves`, Transport abstraction (PostMessage + LocalStorage backends)
@@ -1,5 +1,6 @@
1
1
  import type { TransportKind } from './Transport.js';
2
2
  import { SavesModule } from '../saves/SavesModule.js';
3
+ import { GameDataModule } from '../gamedata/GameDataModule.js';
3
4
  import type { UnboxyUser } from '../protocol.js';
4
5
  export interface UnboxyInitOptions {
5
6
  /** Handshake timeout in ms when running inside a host. Default 2000. */
@@ -20,6 +21,7 @@ export interface UnboxyInitOptions {
20
21
  export declare class Unboxy {
21
22
  private transport;
22
23
  readonly saves: SavesModule;
24
+ readonly gameData: GameDataModule;
23
25
  private constructor();
24
26
  /** The current authenticated user, or `null` if anonymous / standalone. */
25
27
  get user(): UnboxyUser | null;
@@ -1,8 +1,9 @@
1
1
  import { PostMessageTransport } from './transports/PostMessageTransport.js';
2
2
  import { LocalStorageTransport } from './transports/LocalStorageTransport.js';
3
3
  import { SavesModule } from '../saves/SavesModule.js';
4
+ import { GameDataModule } from '../gamedata/GameDataModule.js';
4
5
  // Kept in sync with package.json on each publish.
5
- const SDK_VERSION = '0.2.3';
6
+ const SDK_VERSION = '0.2.4';
6
7
  /**
7
8
  * Unboxy platform services bound to the current (game, user).
8
9
  *
@@ -13,14 +14,19 @@ const SDK_VERSION = '0.2.3';
13
14
  export class Unboxy {
14
15
  constructor(transport) {
15
16
  this.transport = transport;
16
- // Saves are per-user. When the viewer is anonymous (no logged-in user),
17
- // route save calls to localStorage even if a host is attached — the host
18
- // backend requires auth, so forwarding would 401. Other module surfaces
19
- // (future leaderboards, etc.) can still use the primary transport.
17
+ // Saves are per-user. When the viewer is anonymous, route save calls to
18
+ // localStorage even if a host is attached — the backend requires auth,
19
+ // so forwarding would 401. Games see the same `unboxy.saves` API either
20
+ // way and don't have to branch on auth state.
20
21
  const savesTransport = transport.user === null
21
22
  ? new LocalStorageTransport(transport.gameId || 'anonymous')
22
23
  : transport;
23
24
  this.saves = new SavesModule(savesTransport);
25
+ // gameData is game-scope: reads are public (anonymous OK), only writes
26
+ // need auth. The primary transport handles both; if it's a LocalStorage
27
+ // fallback (standalone mode) that also works — the module speaks the
28
+ // same RPC interface.
29
+ this.gameData = new GameDataModule(transport);
24
30
  }
25
31
  /** The current authenticated user, or `null` if anonymous / standalone. */
26
32
  get user() { return this.transport.user; }
@@ -11,11 +11,12 @@ export declare class LocalStorageTransport implements Transport {
11
11
  readonly user: UnboxyUser | null;
12
12
  constructor(gameId: string);
13
13
  call<T = unknown>(method: string, params?: unknown): Promise<T>;
14
- private prefix;
14
+ private savesPrefix;
15
+ private gameDataPrefix;
15
16
  private read;
16
17
  private write;
17
- private savesGet;
18
- private savesSet;
19
- private savesDelete;
20
- private savesList;
18
+ private kvGet;
19
+ private kvSet;
20
+ private kvDelete;
21
+ private kvList;
21
22
  }
@@ -12,18 +12,23 @@ export class LocalStorageTransport {
12
12
  }
13
13
  async call(method, params) {
14
14
  switch (method) {
15
- case 'saves.get': return this.savesGet(params);
16
- case 'saves.set': return this.savesSet(params);
17
- case 'saves.delete': return this.savesDelete(params);
18
- case 'saves.list': return this.savesList();
15
+ case 'saves.get': return this.kvGet(this.savesPrefix(), params);
16
+ case 'saves.set': return this.kvSet(this.savesPrefix(), params);
17
+ case 'saves.delete': return this.kvDelete(this.savesPrefix(), params);
18
+ case 'saves.list': return this.kvList(this.savesPrefix());
19
+ case 'gameData.get': return this.kvGet(this.gameDataPrefix(), params);
20
+ case 'gameData.set': return this.kvSet(this.gameDataPrefix(), params);
21
+ case 'gameData.delete': return this.kvDelete(this.gameDataPrefix(), params);
22
+ case 'gameData.list': return this.kvList(this.gameDataPrefix());
19
23
  default: throw new RpcError('UNKNOWN_METHOD', `Unknown method: ${method}`);
20
24
  }
21
25
  }
22
- prefix() { return `unboxy:saves:${this.gameId}:`; }
23
- read(key) {
26
+ savesPrefix() { return `unboxy:saves:${this.gameId}:`; }
27
+ gameDataPrefix() { return `unboxy:gameData:${this.gameId}:`; }
28
+ read(prefix, key) {
24
29
  if (typeof localStorage === 'undefined')
25
30
  return null;
26
- const raw = localStorage.getItem(this.prefix() + key);
31
+ const raw = localStorage.getItem(prefix + key);
27
32
  if (!raw)
28
33
  return null;
29
34
  try {
@@ -33,41 +38,40 @@ export class LocalStorageTransport {
33
38
  return null;
34
39
  }
35
40
  }
36
- write(key, rec) {
41
+ write(prefix, key, rec) {
37
42
  if (typeof localStorage === 'undefined')
38
43
  throw new RpcError('UNAVAILABLE', 'localStorage unavailable');
39
- localStorage.setItem(this.prefix() + key, JSON.stringify(rec));
44
+ localStorage.setItem(prefix + key, JSON.stringify(rec));
40
45
  }
41
- savesGet({ key }) {
42
- const rec = this.read(key);
46
+ kvGet(prefix, { key }) {
47
+ const rec = this.read(prefix, key);
43
48
  return rec ? { value: rec.value, version: rec.version } : { value: null, version: null };
44
49
  }
45
- savesSet({ key, value, ifVersion }) {
46
- const existing = this.read(key);
50
+ kvSet(prefix, { key, value, ifVersion }) {
51
+ const existing = this.read(prefix, key);
47
52
  if (ifVersion !== undefined && existing && existing.version !== ifVersion) {
48
53
  throw new RpcError('VERSION_MISMATCH', `Expected version ${ifVersion} but stored is ${existing.version}`);
49
54
  }
50
55
  const next = { value, version: (existing?.version ?? 0) + 1 };
51
- this.write(key, next);
56
+ this.write(prefix, key, next);
52
57
  return { version: next.version };
53
58
  }
54
- savesDelete({ key }) {
59
+ kvDelete(prefix, { key }) {
55
60
  if (typeof localStorage === 'undefined')
56
61
  return { deleted: false };
57
- const full = this.prefix() + key;
62
+ const full = prefix + key;
58
63
  const existed = localStorage.getItem(full) !== null;
59
64
  localStorage.removeItem(full);
60
65
  return { deleted: existed };
61
66
  }
62
- savesList() {
67
+ kvList(prefix) {
63
68
  if (typeof localStorage === 'undefined')
64
69
  return { keys: [] };
65
70
  const keys = [];
66
- const p = this.prefix();
67
71
  for (let i = 0; i < localStorage.length; i++) {
68
72
  const k = localStorage.key(i);
69
- if (k && k.startsWith(p))
70
- keys.push(k.slice(p.length));
73
+ if (k && k.startsWith(prefix))
74
+ keys.push(k.slice(prefix.length));
71
75
  }
72
76
  return { keys };
73
77
  }
@@ -0,0 +1,45 @@
1
+ import type { Transport } from '../core/Transport.js';
2
+ /**
3
+ * Game-scope key-value store shared by all players of a game.
4
+ *
5
+ * Unlike `unboxy.saves` (per-user), `gameData` lives at the game level — one
6
+ * value per key, visible to everyone. Reads are public (anonymous players
7
+ * see the same data). Writes require an authenticated user; calling
8
+ * `set()` or `delete()` when `unboxy.user === null` throws an `RpcError`
9
+ * with code `UNAUTHENTICATED`.
10
+ *
11
+ * Typical uses: scoreboards, shared inventories, tournament state, level
12
+ * of the day. Values are opaque JSON — primitive, object, or collection.
13
+ *
14
+ * Trust model (see SDK-GUIDE.md for details):
15
+ * - The backend does not enforce invariants INSIDE a value. If you store
16
+ * a list and append your entry, you own the read-modify-write loop —
17
+ * including not mutating other players' entries, truncating to cap
18
+ * the list size, and retrying on 409 conflicts.
19
+ * - Use `ifVersion` to avoid lost updates when concurrent writes race.
20
+ *
21
+ * Quotas (enforced at the backend):
22
+ * - 100 KB per value
23
+ * - 1 MB total per game
24
+ * - 64 keys per game
25
+ */
26
+ export declare class GameDataModule {
27
+ private transport;
28
+ constructor(transport: Transport);
29
+ /** Read the value under `key`. Returns `null` if unset. Public — works for anonymous viewers. */
30
+ get<T = unknown>(key: string): Promise<T | null>;
31
+ /**
32
+ * Write `value` under `key`. Requires an authenticated user.
33
+ * @param options.ifVersion — only succeed if the stored version matches; otherwise throws
34
+ * an RpcError with code `VERSION_MISMATCH`. Use this to implement safe read-modify-write
35
+ * loops for list values (scoreboards, shared lists).
36
+ * @returns the new version number.
37
+ */
38
+ set(key: string, value: unknown, options?: {
39
+ ifVersion?: number;
40
+ }): Promise<number>;
41
+ /** Delete the value at `key`. Requires an authenticated user. */
42
+ delete(key: string): Promise<boolean>;
43
+ /** List all keys that have a value set for this game. Public. */
44
+ list(): Promise<string[]>;
45
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Game-scope key-value store shared by all players of a game.
3
+ *
4
+ * Unlike `unboxy.saves` (per-user), `gameData` lives at the game level — one
5
+ * value per key, visible to everyone. Reads are public (anonymous players
6
+ * see the same data). Writes require an authenticated user; calling
7
+ * `set()` or `delete()` when `unboxy.user === null` throws an `RpcError`
8
+ * with code `UNAUTHENTICATED`.
9
+ *
10
+ * Typical uses: scoreboards, shared inventories, tournament state, level
11
+ * of the day. Values are opaque JSON — primitive, object, or collection.
12
+ *
13
+ * Trust model (see SDK-GUIDE.md for details):
14
+ * - The backend does not enforce invariants INSIDE a value. If you store
15
+ * a list and append your entry, you own the read-modify-write loop —
16
+ * including not mutating other players' entries, truncating to cap
17
+ * the list size, and retrying on 409 conflicts.
18
+ * - Use `ifVersion` to avoid lost updates when concurrent writes race.
19
+ *
20
+ * Quotas (enforced at the backend):
21
+ * - 100 KB per value
22
+ * - 1 MB total per game
23
+ * - 64 keys per game
24
+ */
25
+ export class GameDataModule {
26
+ constructor(transport) {
27
+ this.transport = transport;
28
+ }
29
+ /** Read the value under `key`. Returns `null` if unset. Public — works for anonymous viewers. */
30
+ async get(key) {
31
+ const res = await this.transport.call('gameData.get', { key });
32
+ return (res?.value ?? null);
33
+ }
34
+ /**
35
+ * Write `value` under `key`. Requires an authenticated user.
36
+ * @param options.ifVersion — only succeed if the stored version matches; otherwise throws
37
+ * an RpcError with code `VERSION_MISMATCH`. Use this to implement safe read-modify-write
38
+ * loops for list values (scoreboards, shared lists).
39
+ * @returns the new version number.
40
+ */
41
+ async set(key, value, options) {
42
+ const res = await this.transport.call('gameData.set', {
43
+ key,
44
+ value,
45
+ ifVersion: options?.ifVersion,
46
+ });
47
+ return res.version;
48
+ }
49
+ /** Delete the value at `key`. Requires an authenticated user. */
50
+ async delete(key) {
51
+ const res = await this.transport.call('gameData.delete', { key });
52
+ return res.deleted;
53
+ }
54
+ /** List all keys that have a value set for this game. Public. */
55
+ async list() {
56
+ const res = await this.transport.call('gameData.list');
57
+ return res.keys;
58
+ }
59
+ }
package/dist/index.d.ts CHANGED
@@ -6,7 +6,8 @@ export { setupRecordingListener } from './recording/RecordingManager.js';
6
6
  export { Unboxy } from './core/Unboxy.js';
7
7
  export type { UnboxyInitOptions } from './core/Unboxy.js';
8
8
  export { SavesModule } from './saves/SavesModule.js';
9
+ export { GameDataModule } from './gamedata/GameDataModule.js';
9
10
  export { RpcError } from './core/Transport.js';
10
11
  export type { Transport, TransportKind } from './core/Transport.js';
11
12
  export type { UnboxyUser } from './protocol.js';
12
- export { PROTOCOL_VERSION, type HelloMessage, type InitMessage, type RpcRequestMessage, type RpcResultOk, type RpcResultError, type HostToSdkMessage, type SdkToHostMessage, type RpcErrorPayload, type RpcMethod, type SavesGetParams, type SavesGetResult, type SavesSetParams, type SavesSetResult, type SavesDeleteParams, type SavesDeleteResult, type SavesListResult, } from './protocol.js';
13
+ export { PROTOCOL_VERSION, type HelloMessage, type InitMessage, type RpcRequestMessage, type RpcResultOk, type RpcResultError, type HostToSdkMessage, type SdkToHostMessage, type RpcErrorPayload, type RpcMethod, type SavesGetParams, type SavesGetResult, type SavesSetParams, type SavesSetResult, type SavesDeleteParams, type SavesDeleteResult, type SavesListResult, type GameDataGetParams, type GameDataGetResult, type GameDataSetParams, type GameDataSetResult, type GameDataDeleteParams, type GameDataDeleteResult, type GameDataListResult, } from './protocol.js';
package/dist/index.js CHANGED
@@ -8,5 +8,6 @@ export { setupRecordingListener } from './recording/RecordingManager.js';
8
8
  // Platform services (v0.2.1+)
9
9
  export { Unboxy } from './core/Unboxy.js';
10
10
  export { SavesModule } from './saves/SavesModule.js';
11
+ export { GameDataModule } from './gamedata/GameDataModule.js';
11
12
  export { RpcError } from './core/Transport.js';
12
13
  export { PROTOCOL_VERSION, } from './protocol.js';
@@ -40,7 +40,7 @@ export interface RpcResultError {
40
40
  error: RpcErrorPayload;
41
41
  }
42
42
  export type HostToSdkMessage = InitMessage | RpcResultOk | RpcResultError;
43
- export type RpcMethod = 'saves.get' | 'saves.set' | 'saves.delete' | 'saves.list';
43
+ export type RpcMethod = 'saves.get' | 'saves.set' | 'saves.delete' | 'saves.list' | 'gameData.get' | 'gameData.set' | 'gameData.delete' | 'gameData.list';
44
44
  export interface SavesGetParams {
45
45
  key: string;
46
46
  }
@@ -65,3 +65,27 @@ export type SavesDeleteResult = {
65
65
  export interface SavesListResult {
66
66
  keys: string[];
67
67
  }
68
+ export interface GameDataGetParams {
69
+ key: string;
70
+ }
71
+ export interface GameDataGetResult {
72
+ value: unknown | null;
73
+ version: number | null;
74
+ }
75
+ export interface GameDataSetParams {
76
+ key: string;
77
+ value: unknown;
78
+ ifVersion?: number;
79
+ }
80
+ export interface GameDataSetResult {
81
+ version: number;
82
+ }
83
+ export interface GameDataDeleteParams {
84
+ key: string;
85
+ }
86
+ export type GameDataDeleteResult = {
87
+ deleted: boolean;
88
+ };
89
+ export interface GameDataListResult {
90
+ keys: string[];
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unboxy/phaser-sdk",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Unboxy Phaser 3 SDK — game infrastructure for the Unboxy platform",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",