@usions/sdk 2.24.1 → 3.0.0-next.7

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.
Files changed (58) hide show
  1. package/README.md +45 -277
  2. package/dist/browser.global.js +1972 -0
  3. package/dist/browser.global.js.map +1 -0
  4. package/dist/index.d.ts +337 -0
  5. package/dist/index.js +1955 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/testing.d.ts +23 -0
  8. package/dist/testing.js +63 -0
  9. package/dist/testing.js.map +1 -0
  10. package/dist/types-G075L8Nl.d.ts +83 -0
  11. package/package.json +27 -43
  12. package/src/browser.js +0 -6665
  13. package/src/index.js +0 -10
  14. package/src/modules/back-button.js +0 -26
  15. package/src/modules/backend-channel.js +0 -109
  16. package/src/modules/bot.js +0 -52
  17. package/src/modules/chat.js +0 -35
  18. package/src/modules/cloud.js +0 -67
  19. package/src/modules/core.js +0 -424
  20. package/src/modules/errors.js +0 -120
  21. package/src/modules/file-storage.js +0 -46
  22. package/src/modules/game-core.js +0 -278
  23. package/src/modules/game-direct.js +0 -267
  24. package/src/modules/game-methods.js +0 -753
  25. package/src/modules/game-netcode.js +0 -349
  26. package/src/modules/game-proxy.js +0 -182
  27. package/src/modules/game-reliability.js +0 -278
  28. package/src/modules/game-resilience.js +0 -245
  29. package/src/modules/game-socket.js +0 -212
  30. package/src/modules/index.js +0 -78
  31. package/src/modules/leaderboard.js +0 -46
  32. package/src/modules/lobby.js +0 -103
  33. package/src/modules/matchmaking.js +0 -140
  34. package/src/modules/misc.js +0 -152
  35. package/src/modules/netcode/binary.js +0 -113
  36. package/src/modules/netcode/delta.js +0 -236
  37. package/src/modules/netcode/index.js +0 -43
  38. package/src/modules/netcode/interest-grid.js +0 -227
  39. package/src/modules/netcode/interpolation.js +0 -235
  40. package/src/modules/netcode/lagcomp.js +0 -104
  41. package/src/modules/netcode/lockstep.js +0 -103
  42. package/src/modules/netcode/mesh-network.js +0 -103
  43. package/src/modules/netcode/mesh.js +0 -188
  44. package/src/modules/netcode/netsim.js +0 -77
  45. package/src/modules/netcode/ping.js +0 -69
  46. package/src/modules/netcode/prediction.js +0 -113
  47. package/src/modules/netcode/sender.js +0 -102
  48. package/src/modules/netcode/webtransport.js +0 -195
  49. package/src/modules/notify.js +0 -70
  50. package/src/modules/permissions.js +0 -157
  51. package/src/modules/results.js +0 -34
  52. package/src/modules/session.js +0 -62
  53. package/src/modules/storage.js +0 -64
  54. package/src/modules/ui.js +0 -111
  55. package/src/modules/user.js +0 -61
  56. package/src/modules/wallet.js +0 -253
  57. package/types/browser.d.ts +0 -5
  58. package/types/index.d.ts +0 -1306
package/README.md CHANGED
@@ -1,299 +1,67 @@
1
- # @usions/sdk
1
+ # Usion SDK v3
2
2
 
3
- Client SDK for building mini-apps and games on the [Usion](https://usions.com) platform.
3
+ The creator SDK for new Usion mini-apps. It provides trusted app context,
4
+ deadline-aware requests, scoped authentication, cloud state, and recoverable
5
+ multiplayer game state without exposing the host socket or identity fields.
4
6
 
5
- Provides access to user info, storage, wallet, chat, sessions, and real-time multiplayer game features.
7
+ SDK v3 is currently an allowlisted preview. Existing SDK v2 mini-apps continue
8
+ to use their current runtime and do not need to migrate.
6
9
 
7
- ## Documentation
10
+ ## Start
8
11
 
9
- - [Guides](../../docs/sdk-guides/README.md) — first game in 30 min, the reliability contract, netcode, money, cloud saves
10
- - [API reference](../../docs/sdk-api/README.md) (generated from the type declarations)
11
- - [Platform behavior spec](../../docs/sdk-guides/06-platform-spec.md) — delivery guarantees, quotas, security model
12
- - [CHANGELOG](CHANGELOG.md) · [versioning policy](../../docs/sdk-versioning-policy.md)
13
- - Local development: [`@usions/devkit`](../devkit/README.md) — build and chaos-test without a Usion account
12
+ ```ts
13
+ import Usion, { UsionError } from '@usions/sdk';
14
14
 
15
- ## Install
15
+ const app = await Usion.init();
16
16
 
17
- ```bash
18
- npm install @usions/sdk
19
- ```
20
-
21
- Or load via script tag:
22
-
23
- ```html
24
- <script src="https://usions.com/usion-sdk.js"></script>
25
- ```
26
-
27
- ## Quick Start
28
-
29
- ```javascript
30
- import Usion from '@usions/sdk';
31
-
32
- Usion.init((config) => {
33
- console.log('User:', Usion.user.getName());
34
- console.log('Room:', config.roomId);
35
- });
36
- ```
37
-
38
- ## Modules
39
-
40
- ### User
41
-
42
- ```javascript
43
- Usion.user.getId() // User ID
44
- Usion.user.getName() // Display name
45
- Usion.user.getAvatar() // Avatar URL
46
- Usion.user.getToken() // Auth JWT
47
- Usion.user.getProfile() // Promise<{ id, name, avatar }>
48
- ```
49
-
50
- ### Storage (persistent, per-user, per-service)
51
-
52
- ```javascript
53
- await Usion.storage.set('highscore', 1500)
54
- await Usion.storage.get('highscore') // 1500
55
- await Usion.storage.remove('highscore')
56
- await Usion.storage.keys() // ['key1', 'key2']
57
- await Usion.storage.clear()
58
- ```
59
-
60
- ### Wallet
61
-
62
- ```javascript
63
- await Usion.wallet.getBalance() // 500
64
- await Usion.wallet.hasCredits(100) // true
65
- await Usion.wallet.requestPayment(50, 'Power-up')
66
- Usion.wallet.onBalanceChange((balance) => { ... })
67
- ```
68
-
69
- ### Session (ephemeral)
70
-
71
- ```javascript
72
- Usion.session.getId()
73
- Usion.session.getData('key')
74
- Usion.session.setData('key', 'value')
75
- Usion.session.clear()
76
- ```
77
-
78
- ### Chat
79
-
80
- ```javascript
81
- await Usion.chat.sendMessage(recipientId, 'Hello!')
82
- await Usion.chat.createPersonalChat(peerUserId)
83
- ```
84
-
85
- ### Game (Multiplayer)
86
-
87
- #### Platform Mode (relay through Usion backend)
88
-
89
- ```javascript
90
- await Usion.game.connect()
91
- await Usion.game.join(roomId)
92
-
93
- // Send actions (validated, sequenced)
94
- await Usion.game.action('move', { cell: 4 })
95
-
96
- // Send real-time updates (fire-and-forget)
97
- Usion.game.realtime('position', { x: 100, y: 200 })
98
- ```
99
-
100
- #### Direct Mode (connect to game creator's server)
101
-
102
- ```javascript
103
- await Usion.game.connectDirect()
104
- await Usion.game.join(roomId)
105
- ```
106
-
107
- #### Event Handlers
108
-
109
- ```javascript
110
- Usion.game.onPlayerJoined((data) => { ... })
111
- Usion.game.onPlayerLeft((data) => { ... })
112
- Usion.game.onStateUpdate((data) => { ... })
113
- Usion.game.onAction((data) => { ... })
114
- Usion.game.onRealtime((data) => { ... })
115
- Usion.game.onGameFinished((data) => { ... })
116
- Usion.game.onGameRestarted((data) => { ... })
117
- Usion.game.onError((data) => { ... })
118
- Usion.game.onDisconnect((reason) => { ... })
119
- Usion.game.onReconnect((attempt) => { ... })
120
- Usion.game.onPlayerConnection((d) => { ... }) // d.state: 'connected' | 'reconnecting' | 'gone'
17
+ try {
18
+ const save = await app.cloud.get<{ level: number }>('save');
19
+ await app.cloud.set('save', { level: (save?.level ?? 0) + 1 });
20
+ } catch (error) {
21
+ if (error instanceof UsionError) {
22
+ console.error(error.code, error.message);
23
+ }
24
+ }
121
25
  ```
122
26
 
123
- #### Reliability contract (read this before shipping multiplayer)
124
-
125
- The platform recovers from connection blips for you — your game just has to
126
- follow four rules so both screens always agree:
27
+ In a hosted browser mini-app, load the exact asset stored in the app's SDK
28
+ descriptor and call `window.Usion.init()`. Do not use a `latest` URL.
127
29
 
128
- 1. **Apply moves only in `onAction`** — never optimistically on send. Every
129
- action (including your own) is echoed back with the authoritative
130
- `sequence`; the SDK deduplicates, so each action is delivered exactly once
131
- even across reconnect replays.
132
- 2. **Turn-based? Pass `{ nextTurn }`** on every move and trust `current_turn`
133
- from the join result / `onSync` instead of deriving the turn locally:
134
- ```javascript
135
- await Usion.game.action('move', { cell: 4 }, { nextTurn: opponentId })
136
- ```
137
- 3. **Handle `onDisconnect` / `onReconnect`** — pause input and show a
138
- "reconnecting…" hint. The platform rejoins the room and replays missed
139
- actions automatically. Use `onPlayerConnection` for the opponent's status;
140
- don't end the match on `'reconnecting'` (a ~15s grace window applies),
141
- treat `'gone'` as the opponent having left.
142
- 4. **Checkpoint with `setState`** — any participant (not just the host)
143
- should checkpoint at meaningful transitions so a rejoining client restores
144
- instantly (delivered as `game_state` in the join result and `onSync`; max
145
- 64 KB). Letting whoever made the move persist state keeps the snapshot
146
- fresh even while the host is backgrounded:
147
- ```javascript
148
- await Usion.game.setState(fullGameState)
149
- ```
30
+ ## Simple multiplayer state
150
31
 
151
- #### Other
32
+ ```ts
33
+ const game = app.game.createState({ score: 0 });
152
34
 
153
- ```javascript
154
- Usion.game.requestSync(lastSequence) // Recover missed actions
155
- Usion.game.requestRematch()
156
- Usion.game.forfeit()
157
- Usion.game.disconnect()
158
- Usion.game.isConnected() // boolean
35
+ game.onChange((state) => render(state));
36
+ await app.game.join();
37
+ await game.commit('score', { score: game.get().score + 1 });
159
38
  ```
160
39
 
161
- ### Netcode (low-latency realtime toolkit)
40
+ The SDK restores the latest checkpoint, replays missing actions in sequence,
41
+ and retains offline actions until the server acknowledges each operation.
42
+ `app.game.status.connection === 'ready'` means recovery is complete.
162
43
 
163
- Zero-dependency, transport-agnostic helpers for smooth, lossless multiplayer.
164
- They work across all connection modes (platform / direct / proxy) and both
165
- platforms. Adopt incrementally. Full guide: [`docs/realtime-netcode.md`](../../docs/realtime-netcode.md).
166
-
167
- ```javascript
168
- // 1. Snapshot interpolation — smooth rendering, absorbs jitter & packet loss
169
- const interp = Usion.game.createInterpolation({ serverFps: 20 });
170
- Usion.game.onRealtime((m) => { if (m.action_type === 'state') interp.add(m.action_data); });
171
- function render() {
172
- const players = interp.calc('x y angle(deg)'); // entities at "now - bufferMs"
173
- if (players) draw(players);
174
- requestAnimationFrame(render);
175
- }
44
+ Call `await app.game.leave()` when leaving a room. Call `game.destroy()` for a
45
+ created state store and `await app.destroy()` when the mini-app is torn down.
176
46
 
177
- // 2. Sequence-guarded, delta-compressed snapshot sender (cuts bandwidth + flood)
178
- const snap = Usion.game.createSnapshotSender({ hz: 20, channel: 'state', precision: 2 });
179
- loop(() => snap.send(world));
180
- // receiver (drops stale/out-of-order frames; never patches the wrong base):
181
- const rx = Usion.game.createSnapshotReceiver();
182
- let world = {};
183
- Usion.game.onRealtime((m) => { if (m.action_type === 'state') world = rx.receive(m.action_data); });
47
+ ## Cancellation and deadlines
184
48
 
185
- // 3. Client-side prediction + reconciliation + smooth error blending
186
- const p = Usion.game.createPredictor({ apply: (s, i) => move(s, i), initialState, smooth: { keys: 'x y' } });
187
- const { seq } = p.predict(input); // apply locally, send seq
188
- Usion.game.onStateUpdate((s) => p.reconcile(s.game_state.me, s.game_state.ackSeq));
189
- function render() { draw(p.view()); requestAnimationFrame(render); } // blended, no snaps
49
+ ```ts
50
+ const controller = new AbortController();
190
51
 
191
- // 4. WebRTC peer-to-peer (UDP) — escapes TCP head-of-line blocking
192
- const mesh = Usion.game.createMesh({
193
- role: amHost ? 'host' : 'guest',
194
- iceServers: Usion.netcode.MeshConnection.iceServers({ turn: 'turn:host:3478', turnUsername: 'u', turnCredential: 'p' }),
52
+ await app.cloud.get('save', {
53
+ timeoutMs: 5_000,
54
+ signal: controller.signal,
195
55
  });
196
- mesh.onMessage = (d) => applyRemote(d);
197
- await mesh.start();
198
- mesh.send({ x, y }); // unreliable + unordered + sequenced (drops stale)
199
- mesh.sendReliable({ event }); // ordered, must-arrive
200
-
201
- // 4b. N-player mesh
202
- const net = Usion.game.createMeshNetwork();
203
- await net.setRoster(allPlayerIds);
204
- net.onMessage = (peerId, d) => applyRemote(peerId, d);
205
- net.broadcast({ x, y });
206
-
207
- // 4c. WebTransport (HTTP/3) — lowest-latency client-server (no TCP HOL blocking)
208
- const wt = Usion.game.createWebTransport({ url: 'https://game.example.com:4433/wt' });
209
- wt.onMessage = (m, ch) => { if (ch === 'datagram') applyState(m); };
210
- await wt.connect();
211
- wt.send(stateBytes); // UDP-like datagram (unreliable, sequenced)
212
- wt.sendReliable({ event }); // reliable stream
213
- // (server: use the open-source @fails-components/webtransport Node HTTP/3 server)
214
-
215
- // 4d. Declarative replication — mutate a plain object, it auto-syncs (host)
216
- const world = Usion.game.replicate({ players: [] }, { channel: 'world', hz: 20, precision: 2 });
217
- world.state.players.push({ id: myId, x: 0, y: 0 }); // just mutate it
218
- // client:
219
- const remote = Usion.game.replica({ channel: 'world', interpolate: { keys: 'x y', group: 'players' } });
220
- function render() { draw(remote.view()); requestAnimationFrame(render); }
221
-
222
- // 4e. Test under a bad network locally (latency / jitter / loss)
223
- Usion.game.simulateNetwork({ latencyMs: 120, jitterMs: 30, lossPct: 5 });
224
- Usion.game.simulateNetwork(null); // off
225
-
226
- // 4f. Deterministic lockstep (inputs-only sim + free replays) — MOBA/RTS
227
- const ls = Usion.game.createLockstep({ playerId: myId, players, step: (frame, inputs) => sim(frame, inputs) });
228
- gameLoop(() => { ls.submit(localInput); ls.tick(); });
229
- // replay later: Usion.netcode.Lockstep.replay(ls.getReplay(), sim);
230
-
231
- // 4g. Server-side lag compensation (server rewind) — fair hits across pings
232
- const lag = Usion.game.createLagCompensator({ historyMs: 1000 });
233
- serverTick(() => lag.record(allEntities)); // each tick
234
- function onShot(shooter, ray) { const past = lag.rewindForClient(shooter.rtt, shooter.interpMs); resolveHit(ray, past); }
235
-
236
- // 5. Telemetry, delta + binary helpers
237
- await Usion.game.ping(); Usion.game.getRtt(); // ms
238
- const d = Usion.game.diff(prev, next); const next2 = Usion.game.patch(prev, d);
239
- const bytes = Usion.game.encode(state); const back = Usion.game.decode(bytes);
240
56
  ```
241
57
 
242
- Also available directly: `Usion.netcode.{ SnapshotInterpolation, Predictor,
243
- Coalescer, PingMeter, MeshConnection, MeshNetwork, diff, patch, quantize,
244
- encode, decode }`.
245
-
246
- ### Utility
247
-
248
- ```javascript
249
- Usion.requestPayment(amount, reason)
250
- Usion.share('image', { imageUrl, text })
251
- Usion.exit() // Close the mini-app
252
- Usion.log(message) // Debug log
253
- ```
254
-
255
- ### Leaderboard (opt-in per game)
256
-
257
- Enable on the service (`leaderboard: { enabled: true, order: 'desc' }`), then:
258
-
259
- ```javascript
260
- await Usion.leaderboard.submit(1500, { level: 3 }); // best score is kept
261
- const friends = await Usion.leaderboard.friends(); // people you've messaged + you
262
- const top = await Usion.leaderboard.top({ limit: 20 });// global top
263
- const me = await Usion.leaderboard.me(); // { score, rank, total }
264
- // entry: { user_id, name, avatar, score, rank, is_me, metadata }
265
- ```
266
- `friends()` is scoped to users you've chatted with (your conversations) plus
267
- yourself. Works in standalone *and* embedded games (rides the backend channel).
268
-
269
- ### Matchmaking (play with online strangers)
270
-
271
- Pair players who don't know each other into a game:
272
-
273
- ```javascript
274
- const match = await Usion.matchmaking.find(); // resolves when matched
275
- // match = { roomId, players, serviceId }
276
- await Usion.game.connect();
277
- await Usion.game.join(match.roomId);
278
-
279
- // while waiting you can stop:
280
- Usion.matchmaking.cancel();
281
- // or react to matches:
282
- Usion.matchmaking.onMatch(({ roomId, players }) => { /* ... */ });
283
- ```
284
- `find({ size })` controls party size (default 2). Works standalone *and*
285
- embedded (rides the backend channel). Pair this with `Usion.lobby` for
286
- invite-a-friend, and `Usion.matchmaking` for quick-match with strangers.
287
-
288
- ## TypeScript
289
-
290
- Full type declarations included:
291
-
292
- ```typescript
293
- import Usion from '@usions/sdk';
294
- import type { UsionConfig, GameModule, PlayerJoinedData } from '@usions/sdk';
295
- ```
58
+ Every request resolves or rejects by its deadline. Errors use stable
59
+ `UsionError.code` values such as `CANCELLED`, `REQUEST_TIMEOUT`,
60
+ `PERMISSION_DENIED`, `RATE_LIMITED`, and `UNAVAILABLE`.
296
61
 
297
- ## License
62
+ ## Security model
298
63
 
299
- MIT
64
+ - User, service, room, and token identity come from the trusted Usion host.
65
+ - `app.fetch()` sends a scoped credential only to the mini-app's own origin.
66
+ - Capabilities must be declared in the exact SDK descriptor.
67
+ - Mini-app code never receives the host's general Socket.IO connection.