@usions/sdk 2.24.2 → 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 (59) 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 +25 -46
  12. package/src/browser.js +0 -6725
  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-ack.js +0 -32
  23. package/src/modules/game-core.js +0 -278
  24. package/src/modules/game-direct.js +0 -267
  25. package/src/modules/game-methods.js +0 -782
  26. package/src/modules/game-netcode.js +0 -349
  27. package/src/modules/game-proxy.js +0 -184
  28. package/src/modules/game-reliability.js +0 -278
  29. package/src/modules/game-resilience.js +0 -245
  30. package/src/modules/game-socket.js +0 -214
  31. package/src/modules/index.js +0 -78
  32. package/src/modules/leaderboard.js +0 -46
  33. package/src/modules/lobby.js +0 -103
  34. package/src/modules/matchmaking.js +0 -140
  35. package/src/modules/misc.js +0 -152
  36. package/src/modules/netcode/binary.js +0 -113
  37. package/src/modules/netcode/delta.js +0 -236
  38. package/src/modules/netcode/index.js +0 -43
  39. package/src/modules/netcode/interest-grid.js +0 -227
  40. package/src/modules/netcode/interpolation.js +0 -235
  41. package/src/modules/netcode/lagcomp.js +0 -104
  42. package/src/modules/netcode/lockstep.js +0 -103
  43. package/src/modules/netcode/mesh-network.js +0 -103
  44. package/src/modules/netcode/mesh.js +0 -188
  45. package/src/modules/netcode/netsim.js +0 -77
  46. package/src/modules/netcode/ping.js +0 -69
  47. package/src/modules/netcode/prediction.js +0 -113
  48. package/src/modules/netcode/sender.js +0 -102
  49. package/src/modules/netcode/webtransport.js +0 -195
  50. package/src/modules/notify.js +0 -70
  51. package/src/modules/permissions.js +0 -157
  52. package/src/modules/results.js +0 -34
  53. package/src/modules/session.js +0 -62
  54. package/src/modules/storage.js +0 -64
  55. package/src/modules/ui.js +0 -111
  56. package/src/modules/user.js +0 -61
  57. package/src/modules/wallet.js +0 -253
  58. package/types/browser.d.ts +0 -5
  59. package/types/index.d.ts +0 -1308
package/dist/index.js ADDED
@@ -0,0 +1,1955 @@
1
+ // ../sdk-protocol/dist/src/generated/catalog.js
2
+ var PROTOCOL_VERSION = 3;
3
+ var CAPABILITIES = ["auth", "cloud", "game"];
4
+ var PROTOCOL_ERROR_CODES = ["CAPABILITY_DENIED", "CONFLICT", "DEADLINE_EXCEEDED", "INTERNAL", "INVALID_PAYLOAD", "INVALID_REQUEST", "PAYLOAD_TOO_LARGE", "PROTOCOL_MISMATCH", "QUOTA_EXCEEDED", "RATE_LIMITED", "SESSION_MISMATCH", "UNAUTHENTICATED", "UNAVAILABLE", "UNKNOWN_COMMAND", "UNKNOWN_EVENT"];
5
+ var COMMAND_NAMES = ["auth.getToken", "cloud.get", "cloud.keys", "cloud.remove", "cloud.set", "cloud.subscribe", "cloud.unsubscribe", "game.action", "game.checkpoint", "game.input", "game.join", "game.leave", "game.recover"];
6
+ var COMMAND_METADATA = {
7
+ "auth.getToken": {
8
+ "capability": "auth",
9
+ "target": "host",
10
+ "operation": "auth.getToken",
11
+ "maxPayloadBytes": 2,
12
+ "maxResultBytes": 8192,
13
+ "deadlineMs": 3e3,
14
+ "policy": "read",
15
+ "idempotent": true
16
+ },
17
+ "cloud.get": {
18
+ "capability": "cloud",
19
+ "target": "platform",
20
+ "operation": "kv:get",
21
+ "maxPayloadBytes": 256,
22
+ "maxResultBytes": 66560,
23
+ "deadlineMs": 3e3,
24
+ "policy": "read",
25
+ "idempotent": true
26
+ },
27
+ "cloud.keys": {
28
+ "capability": "cloud",
29
+ "target": "platform",
30
+ "operation": "kv:keys",
31
+ "maxPayloadBytes": 2,
32
+ "maxResultBytes": 132096,
33
+ "deadlineMs": 3e3,
34
+ "policy": "read",
35
+ "idempotent": true
36
+ },
37
+ "cloud.remove": {
38
+ "capability": "cloud",
39
+ "target": "platform",
40
+ "operation": "kv:remove",
41
+ "maxPayloadBytes": 256,
42
+ "maxResultBytes": 64,
43
+ "deadlineMs": 5e3,
44
+ "policy": "mutation",
45
+ "idempotent": true
46
+ },
47
+ "cloud.set": {
48
+ "capability": "cloud",
49
+ "target": "platform",
50
+ "operation": "kv:set",
51
+ "maxPayloadBytes": 66560,
52
+ "maxResultBytes": 128,
53
+ "deadlineMs": 5e3,
54
+ "policy": "mutation",
55
+ "idempotent": true
56
+ },
57
+ "cloud.subscribe": {
58
+ "capability": "cloud",
59
+ "target": "platform",
60
+ "operation": "kv:subscribe",
61
+ "maxPayloadBytes": 256,
62
+ "maxResultBytes": 256,
63
+ "deadlineMs": 5e3,
64
+ "policy": "subscription",
65
+ "idempotent": false
66
+ },
67
+ "cloud.unsubscribe": {
68
+ "capability": "cloud",
69
+ "target": "platform",
70
+ "operation": "kv:unsubscribe",
71
+ "maxPayloadBytes": 256,
72
+ "maxResultBytes": 64,
73
+ "deadlineMs": 5e3,
74
+ "policy": "subscription",
75
+ "idempotent": true
76
+ },
77
+ "game.action": {
78
+ "capability": "game",
79
+ "target": "platform",
80
+ "operation": "game:action",
81
+ "maxPayloadBytes": 66560,
82
+ "maxResultBytes": 384,
83
+ "deadlineMs": 5e3,
84
+ "policy": "mutation",
85
+ "idempotent": true
86
+ },
87
+ "game.checkpoint": {
88
+ "capability": "game",
89
+ "target": "platform",
90
+ "operation": "game:checkpoint",
91
+ "maxPayloadBytes": 263168,
92
+ "maxResultBytes": 128,
93
+ "deadlineMs": 1e4,
94
+ "policy": "mutation",
95
+ "idempotent": true
96
+ },
97
+ "game.input": {
98
+ "capability": "game",
99
+ "target": "platform",
100
+ "operation": "game:input",
101
+ "maxPayloadBytes": 16384,
102
+ "maxResultBytes": 2,
103
+ "deadlineMs": 1e3,
104
+ "policy": "ephemeral",
105
+ "idempotent": false
106
+ },
107
+ "game.join": {
108
+ "capability": "game",
109
+ "target": "platform",
110
+ "operation": "game:join",
111
+ "maxPayloadBytes": 64,
112
+ "maxResultBytes": 1048576,
113
+ "deadlineMs": 1e4,
114
+ "policy": "mutation",
115
+ "idempotent": true
116
+ },
117
+ "game.leave": {
118
+ "capability": "game",
119
+ "target": "platform",
120
+ "operation": "game:leave",
121
+ "maxPayloadBytes": 2,
122
+ "maxResultBytes": 32,
123
+ "deadlineMs": 5e3,
124
+ "policy": "mutation",
125
+ "idempotent": true
126
+ },
127
+ "game.recover": {
128
+ "capability": "game",
129
+ "target": "platform",
130
+ "operation": "game:recover",
131
+ "maxPayloadBytes": 64,
132
+ "maxResultBytes": 2097152,
133
+ "deadlineMs": 1e4,
134
+ "policy": "read",
135
+ "idempotent": true
136
+ }
137
+ };
138
+ var EVENT_NAMES = ["cloud.changed", "game.action", "game.connection", "game.realtime", "game.snapshot"];
139
+ var ENVELOPE_FIELDS = {
140
+ "SDK_CONTEXT_UPDATE": {
141
+ "required": [
142
+ "type",
143
+ "protocol",
144
+ "sessionId",
145
+ "context"
146
+ ],
147
+ "allowed": [
148
+ "type",
149
+ "protocol",
150
+ "sessionId",
151
+ "context"
152
+ ]
153
+ },
154
+ "SDK_DESTROY": {
155
+ "required": [
156
+ "type",
157
+ "protocol",
158
+ "sessionId"
159
+ ],
160
+ "allowed": [
161
+ "type",
162
+ "protocol",
163
+ "sessionId",
164
+ "reason"
165
+ ]
166
+ },
167
+ "SDK_EVENT": {
168
+ "required": [
169
+ "type",
170
+ "protocol",
171
+ "sessionId",
172
+ "event",
173
+ "payload"
174
+ ],
175
+ "allowed": [
176
+ "type",
177
+ "protocol",
178
+ "sessionId",
179
+ "event",
180
+ "payload"
181
+ ]
182
+ },
183
+ "SDK_HELLO": {
184
+ "required": [
185
+ "type",
186
+ "protocol",
187
+ "sessionId",
188
+ "sdk"
189
+ ],
190
+ "allowed": [
191
+ "type",
192
+ "protocol",
193
+ "sessionId",
194
+ "sdk"
195
+ ]
196
+ },
197
+ "SDK_INIT": {
198
+ "required": [
199
+ "type",
200
+ "protocol",
201
+ "sessionId",
202
+ "context"
203
+ ],
204
+ "allowed": [
205
+ "type",
206
+ "protocol",
207
+ "sessionId",
208
+ "context"
209
+ ]
210
+ },
211
+ "SDK_REQUEST": {
212
+ "required": [
213
+ "type",
214
+ "protocol",
215
+ "sessionId",
216
+ "requestId",
217
+ "command",
218
+ "payload"
219
+ ],
220
+ "allowed": [
221
+ "type",
222
+ "protocol",
223
+ "sessionId",
224
+ "requestId",
225
+ "command",
226
+ "payload",
227
+ "deadlineMs",
228
+ "idempotencyKey"
229
+ ]
230
+ },
231
+ "SDK_RESPONSE": {
232
+ "required": [
233
+ "type",
234
+ "protocol",
235
+ "sessionId",
236
+ "requestId"
237
+ ],
238
+ "allowed": [
239
+ "type",
240
+ "protocol",
241
+ "sessionId",
242
+ "requestId",
243
+ "data",
244
+ "error"
245
+ ]
246
+ }
247
+ };
248
+
249
+ // ../sdk-protocol/dist/src/generated/schemas.js
250
+ var SCHEMAS = { "definitions": { "SdkError": { "type": "object", "additionalProperties": false, "required": ["code", "message"], "properties": { "code": { "$ref": "ProtocolErrorCode" }, "message": { "type": "string", "minLength": 1, "maxLength": 512 }, "retryAfter": { "type": "number", "minimum": 0, "maximum": 3600 } } }, "SdkDescriptor": { "type": "object", "additionalProperties": false, "required": ["major", "protocol", "version", "capabilities"], "properties": { "major": { "const": 3 }, "protocol": { "const": 3 }, "version": { "type": "string", "minLength": 5, "maxLength": 64, "pattern": "^3\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" }, "capabilities": { "type": "array", "items": { "$ref": "Capability" }, "maxItems": 32, "uniqueItems": true } } }, "SdkUser": { "type": "object", "additionalProperties": false, "required": ["id"], "properties": { "id": { "type": "string", "minLength": 1, "maxLength": 128 }, "name": { "type": "string", "maxLength": 128 }, "avatar": { "type": "string", "maxLength": 2048 } } }, "SdkService": { "type": "object", "additionalProperties": false, "required": ["id"], "properties": { "id": { "type": "string", "minLength": 1, "maxLength": 128 }, "name": { "type": "string", "maxLength": 128 }, "origin": { "type": "string", "maxLength": 2048 } } }, "SdkLaunch": { "type": "object", "additionalProperties": false, "properties": { "roomId": { "type": "string", "minLength": 1, "maxLength": 128 }, "mode": { "enum": ["single", "multiplayer"] }, "path": { "type": "string", "maxLength": 2048 }, "ref": { "type": "string", "maxLength": 256 } } }, "SdkContext": { "type": "object", "additionalProperties": false, "required": ["user", "service", "launch", "capabilities"], "properties": { "user": { "$ref": "SdkUser" }, "service": { "$ref": "SdkService" }, "launch": { "$ref": "SdkLaunch" }, "capabilities": { "type": "array", "items": { "$ref": "Capability" }, "maxItems": 32, "uniqueItems": true }, "balance": { "type": "number" }, "theme": { "enum": ["light", "dark", "system"] }, "locale": { "type": "string", "minLength": 2, "maxLength": 32 } } }, "GameAction": { "type": "object", "additionalProperties": false, "required": ["playerId", "type", "data", "sequence"], "properties": { "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, "playerId": { "type": "string", "minLength": 1, "maxLength": 128 }, "type": { "type": "string", "minLength": 1, "maxLength": 64 }, "data": { "type": "json" }, "sequence": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "currentTurn": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "GameState": { "type": "object", "additionalProperties": false, "required": ["roomId", "playerIds", "status", "checkpoint", "checkpointSequence", "serverSequence"], "properties": { "roomId": { "type": "string", "minLength": 1, "maxLength": 128 }, "hostId": { "type": "string", "minLength": 1, "maxLength": 128 }, "playerIds": { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128 }, "maxItems": 128, "uniqueItems": true }, "status": { "type": "string", "minLength": 1, "maxLength": 64 }, "currentTurn": { "type": "string", "minLength": 1, "maxLength": 128 }, "checkpoint": { "type": "json" }, "checkpointSequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "serverSequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } }, "GameRecovery": { "type": "object", "additionalProperties": false, "required": ["roomId", "playerIds", "status", "checkpoint", "checkpointSequence", "serverSequence", "actions"], "properties": { "roomId": { "type": "string", "minLength": 1, "maxLength": 128 }, "hostId": { "type": "string", "minLength": 1, "maxLength": 128 }, "playerIds": { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128 }, "maxItems": 128, "uniqueItems": true }, "status": { "type": "string", "minLength": 1, "maxLength": 64 }, "currentTurn": { "type": "string", "minLength": 1, "maxLength": 128 }, "checkpoint": { "type": "json" }, "checkpointSequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "serverSequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "actions": { "type": "array", "items": { "$ref": "GameAction" }, "maxItems": 1e3 } } } }, "envelopeBase": { "required": ["type", "protocol", "sessionId"], "properties": { "type": { "type": "string" }, "protocol": { "const": 3 }, "sessionId": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "envelopes": { "SDK_HELLO": { "required": ["sdk"], "properties": { "sdk": { "$ref": "SdkDescriptor" } } }, "SDK_INIT": { "required": ["context"], "properties": { "context": { "$ref": "SdkContext" } } }, "SDK_REQUEST": { "required": ["requestId", "command", "payload"], "properties": { "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, "command": { "type": "string", "minLength": 1, "maxLength": 128 }, "payload": { "type": "object" }, "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 12e4 }, "idempotencyKey": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "SDK_RESPONSE": { "required": ["requestId"], "properties": { "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, "data": { "type": "json" }, "error": { "$ref": "SdkError" } } }, "SDK_EVENT": { "required": ["event", "payload"], "properties": { "event": { "type": "string", "minLength": 1, "maxLength": 128 }, "payload": { "type": "object" } } }, "SDK_CONTEXT_UPDATE": { "required": ["context"], "properties": { "context": { "$ref": "SdkContext" } } }, "SDK_DESTROY": { "required": [], "properties": { "reason": { "type": "string", "maxLength": 256 } } } }, "commands": { "auth.getToken": { "capability": "auth", "maxPayloadBytes": 2, "maxResultBytes": 8192, "input": { "type": "object", "additionalProperties": false, "properties": {} }, "output": { "type": "object", "additionalProperties": false, "required": ["token", "expiresAt"], "properties": { "token": { "type": "string", "minLength": 10, "maxLength": 4096 }, "expiresAt": { "type": "integer", "minimum": 0 } } } }, "cloud.get": { "capability": "cloud", "maxPayloadBytes": 256, "maxResultBytes": 66560, "input": { "type": "object", "additionalProperties": false, "required": ["key"], "properties": { "key": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "output": { "type": "object", "additionalProperties": false, "required": ["value"], "properties": { "value": { "type": "json" } } } }, "cloud.keys": { "capability": "cloud", "maxPayloadBytes": 2, "maxResultBytes": 132096, "input": { "type": "object", "additionalProperties": false, "properties": {} }, "output": { "type": "object", "additionalProperties": false, "required": ["keys"], "properties": { "keys": { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 128 }, "maxItems": 1e3, "uniqueItems": true } } } }, "cloud.remove": { "capability": "cloud", "maxPayloadBytes": 256, "maxResultBytes": 64, "input": { "type": "object", "additionalProperties": false, "required": ["key"], "properties": { "key": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "output": { "type": "object", "additionalProperties": false, "required": ["removed"], "properties": { "removed": { "type": "boolean" } } } }, "cloud.set": { "capability": "cloud", "maxPayloadBytes": 66560, "maxResultBytes": 128, "input": { "type": "object", "additionalProperties": false, "required": ["key", "value"], "properties": { "key": { "type": "string", "minLength": 1, "maxLength": 128 }, "value": { "type": "json" } } }, "output": { "type": "object", "additionalProperties": false, "required": ["size"], "properties": { "size": { "type": "integer", "minimum": 0 } } } }, "cloud.subscribe": { "capability": "cloud", "maxPayloadBytes": 256, "maxResultBytes": 256, "input": { "type": "object", "additionalProperties": false, "properties": { "key": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "output": { "type": "object", "additionalProperties": false, "required": ["subscriptionId"], "properties": { "subscriptionId": { "type": "string", "minLength": 1, "maxLength": 128 } } } }, "cloud.unsubscribe": { "capability": "cloud", "maxPayloadBytes": 256, "maxResultBytes": 64, "input": { "type": "object", "additionalProperties": false, "required": ["subscriptionId"], "properties": { "subscriptionId": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "output": { "type": "object", "additionalProperties": false, "required": ["removed"], "properties": { "removed": { "type": "boolean" } } } }, "game.action": { "capability": "game", "maxPayloadBytes": 66560, "maxResultBytes": 384, "input": { "type": "object", "additionalProperties": false, "required": ["operationId", "type", "data"], "properties": { "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, "type": { "type": "string", "minLength": 1, "maxLength": 64 }, "data": { "type": "json" }, "nextTurn": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "output": { "type": "object", "additionalProperties": false, "required": ["operationId", "sequence"], "properties": { "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, "sequence": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } } } }, "game.checkpoint": { "capability": "game", "maxPayloadBytes": 263168, "maxResultBytes": 128, "input": { "type": "object", "additionalProperties": false, "required": ["state", "sequence"], "properties": { "state": { "type": "json" }, "sequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } }, "output": { "type": "object", "additionalProperties": false, "required": ["sequence"], "properties": { "sequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } } }, "game.input": { "capability": "game", "maxPayloadBytes": 16384, "maxResultBytes": 2, "input": { "type": "object", "additionalProperties": false, "required": ["inputSequence", "data"], "properties": { "inputSequence": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "data": { "type": "json" } } }, "output": { "type": "object", "additionalProperties": false, "properties": {} } }, "game.join": { "capability": "game", "maxPayloadBytes": 64, "maxResultBytes": 1048576, "input": { "type": "object", "additionalProperties": false, "properties": { "appliedSequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } }, "output": { "$ref": "GameState" } }, "game.leave": { "capability": "game", "maxPayloadBytes": 2, "maxResultBytes": 32, "input": { "type": "object", "additionalProperties": false, "properties": {} }, "output": { "type": "object", "additionalProperties": false, "required": ["left"], "properties": { "left": { "type": "boolean" } } } }, "game.recover": { "capability": "game", "maxPayloadBytes": 64, "maxResultBytes": 2097152, "input": { "type": "object", "additionalProperties": false, "required": ["appliedSequence"], "properties": { "appliedSequence": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } }, "output": { "$ref": "GameRecovery" } } }, "events": { "cloud.changed": { "capability": "cloud", "maxPayloadBytes": 66560, "payload": { "type": "object", "additionalProperties": false, "required": ["subscriptionId", "key", "removed"], "properties": { "subscriptionId": { "type": "string", "minLength": 1, "maxLength": 128 }, "key": { "type": "string", "minLength": 1, "maxLength": 128 }, "value": { "type": "json" }, "removed": { "type": "boolean" } } } }, "game.action": { "capability": "game", "maxPayloadBytes": 66560, "payload": { "$ref": "GameAction" } }, "game.connection": { "capability": "game", "maxPayloadBytes": 512, "payload": { "type": "object", "additionalProperties": false, "required": ["state"], "properties": { "state": { "enum": ["disconnected", "recovering", "ready"] }, "reason": { "type": "string", "maxLength": 256 } } } }, "game.realtime": { "capability": "game", "maxPayloadBytes": 16384, "payload": { "type": "object", "additionalProperties": false, "required": ["playerId", "type", "data"], "properties": { "playerId": { "type": "string", "minLength": 1, "maxLength": 128 }, "type": { "type": "string", "minLength": 1, "maxLength": 64 }, "data": { "type": "json" } } } }, "game.snapshot": { "capability": "game", "maxPayloadBytes": 262144, "payload": { "type": "object", "additionalProperties": false, "required": ["sequence", "tick", "acknowledgedInput", "keyframe", "state"], "properties": { "sequence": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "tick": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "acknowledgedInput": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "keyframe": { "type": "boolean" }, "serverTime": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "state": { "type": "json" } } } } } };
251
+
252
+ // ../sdk-protocol/dist/src/schema.js
253
+ var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
254
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
255
+ function resolveRef(ref) {
256
+ if (ref === "Capability")
257
+ return { enum: CAPABILITIES };
258
+ if (ref === "ProtocolErrorCode")
259
+ return { enum: PROTOCOL_ERROR_CODES };
260
+ return SCHEMAS.definitions[ref];
261
+ }
262
+ function isJsonValue(value, state = { depth: 0, nodes: 0, seen: /* @__PURE__ */ new Set() }) {
263
+ state.nodes += 1;
264
+ if (state.nodes > 1e4 || state.depth > 64)
265
+ return false;
266
+ if (value === null)
267
+ return true;
268
+ if (typeof value === "string" || typeof value === "boolean")
269
+ return true;
270
+ if (typeof value === "number")
271
+ return Number.isFinite(value);
272
+ if (typeof value !== "object" || state.seen.has(value))
273
+ return false;
274
+ state.seen.add(value);
275
+ state.depth += 1;
276
+ const valid = Array.isArray(value) ? value.every((item) => isJsonValue(item, state)) : isRecord(value) && Object.values(value).every((item) => item !== void 0 && isJsonValue(item, state));
277
+ state.depth -= 1;
278
+ state.seen.delete(value);
279
+ return valid;
280
+ }
281
+ function uniqueIssue(values, path) {
282
+ const encoded = /* @__PURE__ */ new Set();
283
+ for (const value of values) {
284
+ let item;
285
+ try {
286
+ item = JSON.stringify(value);
287
+ } catch {
288
+ return `${path} contains invalid JSON data`;
289
+ }
290
+ if (item === void 0)
291
+ return `${path} contains invalid JSON data`;
292
+ if (encoded.has(item))
293
+ return `${path} must contain unique items`;
294
+ encoded.add(item);
295
+ }
296
+ return null;
297
+ }
298
+ function schemaIssue(value, schema, path) {
299
+ if (schema.$ref) {
300
+ const referenced = resolveRef(schema.$ref);
301
+ return referenced ? schemaIssue(value, referenced, path) : `${path} references an unknown schema`;
302
+ }
303
+ if (schema.const !== void 0 && value !== schema.const) {
304
+ return `${path} must equal ${JSON.stringify(schema.const)}`;
305
+ }
306
+ if (schema.enum && !schema.enum.includes(value)) {
307
+ return `${path} has an unsupported value`;
308
+ }
309
+ if (schema.oneOf) {
310
+ const matches = schema.oneOf.filter((candidate) => schemaIssue(value, candidate, path) === null).length;
311
+ return matches === 1 ? null : `${path} must match exactly one allowed shape`;
312
+ }
313
+ if (schema.type === "json") {
314
+ return isJsonValue(value) ? null : `${path} must be valid JSON data`;
315
+ }
316
+ if (schema.type === "null")
317
+ return value === null ? null : `${path} must be null`;
318
+ if (schema.type === "string") {
319
+ if (typeof value !== "string")
320
+ return `${path} must be a string`;
321
+ if (schema.minLength !== void 0 && value.length < schema.minLength) {
322
+ return `${path} is too short`;
323
+ }
324
+ if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
325
+ return `${path} is too long`;
326
+ }
327
+ if (schema.pattern && !new RegExp(schema.pattern, "u").test(value)) {
328
+ return `${path} has an invalid format`;
329
+ }
330
+ }
331
+ if (schema.type === "number" || schema.type === "integer") {
332
+ if (typeof value !== "number" || !Number.isFinite(value)) {
333
+ return `${path} must be a finite number`;
334
+ }
335
+ if (schema.type === "integer" && !Number.isInteger(value)) {
336
+ return `${path} must be an integer`;
337
+ }
338
+ if (schema.minimum !== void 0 && value < schema.minimum) {
339
+ return `${path} is below the minimum`;
340
+ }
341
+ if (schema.maximum !== void 0 && value > schema.maximum) {
342
+ return `${path} is above the maximum`;
343
+ }
344
+ }
345
+ if (schema.type === "boolean" && typeof value !== "boolean") {
346
+ return `${path} must be a boolean`;
347
+ }
348
+ if (schema.type === "array") {
349
+ if (!Array.isArray(value))
350
+ return `${path} must be an array`;
351
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
352
+ return `${path} has too many items`;
353
+ }
354
+ if (schema.uniqueItems) {
355
+ const issue = uniqueIssue(value, path);
356
+ if (issue)
357
+ return issue;
358
+ }
359
+ for (let index = 0; index < value.length; index += 1) {
360
+ const issue = schemaIssue(value[index], schema.items ?? {}, `${path}[${index}]`);
361
+ if (issue)
362
+ return issue;
363
+ }
364
+ }
365
+ if (schema.type === "object") {
366
+ if (!isRecord(value))
367
+ return `${path} must be an object`;
368
+ const properties = schema.properties ?? {};
369
+ for (const required of schema.required ?? []) {
370
+ if (!own(value, required))
371
+ return `${path}.${required} is required`;
372
+ }
373
+ if (schema.additionalProperties === false) {
374
+ const extra = Object.keys(value).find((key) => !own(properties, key));
375
+ if (extra)
376
+ return `${path}.${extra} is not allowed`;
377
+ }
378
+ for (const [key, item] of Object.entries(value)) {
379
+ if (own(properties, key)) {
380
+ const issue = schemaIssue(item, properties[key] ?? {}, `${path}.${key}`);
381
+ if (issue)
382
+ return issue;
383
+ } else if (!isJsonValue(item)) {
384
+ return `${path}.${key} must be valid JSON data`;
385
+ }
386
+ }
387
+ }
388
+ return null;
389
+ }
390
+ function jsonByteSize(value) {
391
+ try {
392
+ const json = JSON.stringify(value);
393
+ return json === void 0 ? null : new TextEncoder().encode(json).byteLength;
394
+ } catch {
395
+ return null;
396
+ }
397
+ }
398
+
399
+ // ../sdk-protocol/dist/src/validators.js
400
+ function invalid(code, message) {
401
+ return { ok: false, error: { code, message } };
402
+ }
403
+ function validateCommandPayloadUnsafe(command, payload, grantedCapabilities) {
404
+ if (!COMMAND_NAMES.includes(command)) {
405
+ return invalid("UNKNOWN_COMMAND", `Unknown SDK command: ${command}`);
406
+ }
407
+ const knownCommand = command;
408
+ const metadata = COMMAND_METADATA[knownCommand];
409
+ if (!grantedCapabilities.includes(metadata.capability)) {
410
+ return invalid("CAPABILITY_DENIED", `Missing capability: ${metadata.capability}`);
411
+ }
412
+ const size = jsonByteSize(payload);
413
+ if (size === null)
414
+ return invalid("INVALID_PAYLOAD", "Payload is not JSON data");
415
+ if (size > metadata.maxPayloadBytes) {
416
+ return invalid("PAYLOAD_TOO_LARGE", `Payload exceeds the ${metadata.maxPayloadBytes} byte limit`);
417
+ }
418
+ const schema = SCHEMAS.commands[knownCommand].input;
419
+ const issue = schemaIssue(payload, schema, "payload");
420
+ return issue ? invalid("INVALID_PAYLOAD", issue) : { ok: true, value: knownCommand };
421
+ }
422
+ function validateCommandPayload(command, payload, grantedCapabilities = []) {
423
+ try {
424
+ return validateCommandPayloadUnsafe(command, payload, grantedCapabilities);
425
+ } catch {
426
+ return invalid("INVALID_PAYLOAD", "Payload validation failed");
427
+ }
428
+ }
429
+ function validateCommandResult(command, result) {
430
+ try {
431
+ if (!COMMAND_NAMES.includes(command)) {
432
+ return invalid("UNKNOWN_COMMAND", `Unknown SDK command: ${command}`);
433
+ }
434
+ const knownCommand = command;
435
+ const size = jsonByteSize(result);
436
+ if (size === null)
437
+ return invalid("INVALID_PAYLOAD", "Result is not JSON data");
438
+ if (size > COMMAND_METADATA[knownCommand].maxResultBytes) {
439
+ return invalid("PAYLOAD_TOO_LARGE", `Result exceeds the ${COMMAND_METADATA[knownCommand].maxResultBytes} byte limit`);
440
+ }
441
+ const schema = SCHEMAS.commands[knownCommand].output;
442
+ const issue = schemaIssue(result, schema, "result");
443
+ return issue ? invalid("INVALID_PAYLOAD", issue) : { ok: true, value: knownCommand };
444
+ } catch {
445
+ return invalid("INVALID_PAYLOAD", "Result validation failed");
446
+ }
447
+ }
448
+ function validateEvent(event, payload, grantedCapabilities) {
449
+ if (!EVENT_NAMES.includes(event)) {
450
+ return invalid("UNKNOWN_EVENT", `Unknown SDK event: ${event}`);
451
+ }
452
+ const knownEvent = event;
453
+ const contract = SCHEMAS.events[knownEvent];
454
+ if (!grantedCapabilities.includes(contract.capability)) {
455
+ return invalid("CAPABILITY_DENIED", `Missing capability: ${contract.capability}`);
456
+ }
457
+ const size = jsonByteSize(payload);
458
+ if (size === null)
459
+ return invalid("INVALID_PAYLOAD", "Event payload is not JSON data");
460
+ if (size > contract.maxPayloadBytes) {
461
+ return invalid("PAYLOAD_TOO_LARGE", `Event payload exceeds the ${contract.maxPayloadBytes} byte limit`);
462
+ }
463
+ const issue = schemaIssue(payload, contract.payload, "payload");
464
+ return issue ? invalid("INVALID_PAYLOAD", issue) : { ok: true, value: knownEvent };
465
+ }
466
+ function validateEnvelopeUnsafe(input, options) {
467
+ if (!isRecord(input))
468
+ return invalid("INVALID_REQUEST", "Envelope must be an object");
469
+ if (input.protocol !== PROTOCOL_VERSION) {
470
+ return invalid("PROTOCOL_MISMATCH", `Expected protocol ${PROTOCOL_VERSION}`);
471
+ }
472
+ if (options.expectedSessionId !== void 0 && input.sessionId !== options.expectedSessionId) {
473
+ return invalid("SESSION_MISMATCH", "Envelope session does not match");
474
+ }
475
+ if (typeof input.type !== "string" || !own(ENVELOPE_FIELDS, input.type)) {
476
+ return invalid("INVALID_REQUEST", "Unknown envelope type");
477
+ }
478
+ const type = input.type;
479
+ const fields = ENVELOPE_FIELDS[type];
480
+ const extra = Object.keys(input).find((key) => !fields.allowed.includes(key));
481
+ if (extra)
482
+ return invalid("INVALID_REQUEST", `Envelope field is not allowed: ${extra}`);
483
+ const contract = SCHEMAS.envelopes[type];
484
+ const issue = schemaIssue(input, {
485
+ type: "object",
486
+ additionalProperties: false,
487
+ required: fields.required,
488
+ properties: {
489
+ ...SCHEMAS.envelopeBase.properties,
490
+ ...contract.properties
491
+ }
492
+ }, "envelope");
493
+ if (issue)
494
+ return invalid("INVALID_REQUEST", issue);
495
+ const capabilities = options.grantedCapabilities ?? [];
496
+ if (type === "SDK_REQUEST") {
497
+ const result = validateCommandPayloadUnsafe(String(input.command), input.payload, capabilities);
498
+ if (!result.ok)
499
+ return result;
500
+ }
501
+ if (type === "SDK_RESPONSE" && own(input, "data") === own(input, "error")) {
502
+ return invalid("INVALID_REQUEST", "Response must contain data or error, not both");
503
+ }
504
+ if (type === "SDK_EVENT") {
505
+ const result = validateEvent(String(input.event), input.payload, capabilities);
506
+ if (!result.ok)
507
+ return result;
508
+ }
509
+ return { ok: true, value: input };
510
+ }
511
+ function validateEnvelope(input, options = {}) {
512
+ try {
513
+ return validateEnvelopeUnsafe(input, options);
514
+ } catch {
515
+ return invalid("INVALID_REQUEST", "Envelope validation failed");
516
+ }
517
+ }
518
+
519
+ // src/errors.ts
520
+ var ERROR_CODES = {
521
+ CANCELLED: "CANCELLED",
522
+ CONFLICT: "CONFLICT",
523
+ DESTROYED: "DESTROYED",
524
+ INTERNAL: "INTERNAL",
525
+ INIT_TIMEOUT: "INIT_TIMEOUT",
526
+ INVALID_INPUT: "INVALID_INPUT",
527
+ INVALID_MESSAGE: "INVALID_MESSAGE",
528
+ NOT_AUTHENTICATED: "NOT_AUTHENTICATED",
529
+ PERMISSION_DENIED: "PERMISSION_DENIED",
530
+ PROTOCOL_MISMATCH: "PROTOCOL_MISMATCH",
531
+ QUOTA_EXCEEDED: "QUOTA_EXCEEDED",
532
+ RATE_LIMITED: "RATE_LIMITED",
533
+ REQUEST_TIMEOUT: "REQUEST_TIMEOUT",
534
+ TRUST_VIOLATION: "TRUST_VIOLATION",
535
+ UNAVAILABLE: "UNAVAILABLE",
536
+ UNSUPPORTED: "UNSUPPORTED",
537
+ UNKNOWN: "UNKNOWN"
538
+ };
539
+ var UsionError = class extends Error {
540
+ name = "UsionError";
541
+ code;
542
+ retryAfter;
543
+ constructor(code, message, options) {
544
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
545
+ this.code = code;
546
+ if (options?.retryAfter !== void 0) this.retryAfter = options.retryAfter;
547
+ }
548
+ };
549
+ function fromProtocolError(error) {
550
+ const aliases = {
551
+ CAPABILITY_DENIED: "PERMISSION_DENIED",
552
+ DEADLINE_EXCEEDED: "REQUEST_TIMEOUT",
553
+ INVALID_PAYLOAD: "INVALID_INPUT",
554
+ INVALID_REQUEST: "INVALID_MESSAGE",
555
+ PAYLOAD_TOO_LARGE: "INVALID_INPUT",
556
+ SESSION_MISMATCH: "TRUST_VIOLATION",
557
+ UNAUTHENTICATED: "NOT_AUTHENTICATED",
558
+ UNKNOWN_COMMAND: "UNSUPPORTED",
559
+ UNKNOWN_EVENT: "INVALID_MESSAGE"
560
+ };
561
+ const code = error.code in ERROR_CODES ? error.code : aliases[error.code] ?? "UNKNOWN";
562
+ return new UsionError(
563
+ code,
564
+ error.message,
565
+ error.retryAfter === void 0 ? void 0 : { retryAfter: error.retryAfter }
566
+ );
567
+ }
568
+
569
+ // src/event-bus.ts
570
+ var EventBus = class {
571
+ listeners = /* @__PURE__ */ new Map();
572
+ destroyed = false;
573
+ on(event, handler) {
574
+ if (this.destroyed) return () => {
575
+ };
576
+ const handlers = this.listeners.get(event) ?? /* @__PURE__ */ new Set();
577
+ handlers.add(handler);
578
+ this.listeners.set(event, handlers);
579
+ let active = true;
580
+ return () => {
581
+ if (!active) return;
582
+ active = false;
583
+ handlers.delete(handler);
584
+ if (handlers.size === 0) this.listeners.delete(event);
585
+ };
586
+ }
587
+ emit(event, data) {
588
+ for (const handler of [...this.listeners.get(event) ?? []]) {
589
+ try {
590
+ handler(data);
591
+ } catch {
592
+ }
593
+ }
594
+ }
595
+ destroy() {
596
+ this.destroyed = true;
597
+ this.listeners.clear();
598
+ }
599
+ };
600
+
601
+ // src/pending.ts
602
+ function requestId() {
603
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
604
+ return `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
605
+ }
606
+ var PendingRequestManager = class {
607
+ pending = /* @__PURE__ */ new Map();
608
+ closed = false;
609
+ create(send, options, defaultTimeoutMs, validate) {
610
+ if (this.closed) {
611
+ return Promise.reject(new UsionError("DESTROYED", "SDK client is destroyed"));
612
+ }
613
+ if (options.signal?.aborted) {
614
+ return Promise.reject(new UsionError("CANCELLED", "Request was cancelled"));
615
+ }
616
+ const id = requestId();
617
+ return new Promise((resolve, reject) => {
618
+ const finish = (callback) => {
619
+ const entry2 = this.pending.get(id);
620
+ if (!entry2) return;
621
+ clearTimeout(entry2.timer);
622
+ entry2.removeAbort?.();
623
+ this.pending.delete(id);
624
+ callback();
625
+ };
626
+ const timer = setTimeout(() => {
627
+ finish(() => reject(new UsionError("REQUEST_TIMEOUT", "SDK request timed out")));
628
+ }, options.timeoutMs ?? defaultTimeoutMs);
629
+ const entry = validate === void 0 ? { resolve, reject, timer } : { resolve, reject, timer, validate };
630
+ if (options.signal) {
631
+ const abort = () => {
632
+ finish(() => reject(new UsionError("CANCELLED", "Request was cancelled")));
633
+ };
634
+ options.signal.addEventListener("abort", abort, { once: true });
635
+ entry.removeAbort = () => options.signal?.removeEventListener("abort", abort);
636
+ }
637
+ this.pending.set(id, entry);
638
+ if (!send(id)) {
639
+ finish(() => reject(new UsionError("TRUST_VIOLATION", "Host bridge is unavailable")));
640
+ }
641
+ });
642
+ }
643
+ settle(requestIdValue, data, error) {
644
+ const entry = this.pending.get(requestIdValue);
645
+ if (!entry) return false;
646
+ clearTimeout(entry.timer);
647
+ entry.removeAbort?.();
648
+ this.pending.delete(requestIdValue);
649
+ if (error) {
650
+ entry.reject(fromProtocolError(error));
651
+ } else {
652
+ const validationError = entry.validate?.(data);
653
+ if (validationError) entry.reject(validationError);
654
+ else entry.resolve(data);
655
+ }
656
+ return true;
657
+ }
658
+ destroy(reason = "SDK client was destroyed") {
659
+ if (this.closed) return;
660
+ this.closed = true;
661
+ for (const entry of this.pending.values()) {
662
+ clearTimeout(entry.timer);
663
+ entry.removeAbort?.();
664
+ entry.reject(new UsionError("CANCELLED", reason));
665
+ }
666
+ this.pending.clear();
667
+ }
668
+ get size() {
669
+ return this.pending.size;
670
+ }
671
+ };
672
+
673
+ // src/types.ts
674
+ var SDK_VERSION = "3.0.0-next.7";
675
+ var PROTOCOL_VERSION2 = 3;
676
+ var SDK_CAPABILITIES = ["auth", "cloud", "game"];
677
+
678
+ // src/command-bus.ts
679
+ var CommandBus = class {
680
+ constructor(transport, getCapabilities, updateContext, remoteDestroy) {
681
+ this.transport = transport;
682
+ this.getCapabilities = getCapabilities;
683
+ this.updateContext = updateContext;
684
+ this.remoteDestroy = remoteDestroy;
685
+ this.offMessage = transport.onMessage((message) => {
686
+ if (message.type === "SDK_RESPONSE") {
687
+ this.pending.settle(message.requestId, message.data, message.error);
688
+ } else if (message.type === "SDK_EVENT") {
689
+ this.events.emit(message.event, message.payload);
690
+ } else if (message.type === "SDK_CONTEXT_UPDATE") {
691
+ this.updateContext(message.context);
692
+ } else if (message.type === "SDK_DESTROY") {
693
+ this.remoteDestroy(message.reason);
694
+ }
695
+ });
696
+ }
697
+ transport;
698
+ getCapabilities;
699
+ updateContext;
700
+ remoteDestroy;
701
+ pending = new PendingRequestManager();
702
+ events = new EventBus();
703
+ offMessage;
704
+ lifecycle = new AbortController();
705
+ destroyed = false;
706
+ send(command, payload) {
707
+ if (this.destroyed) return false;
708
+ const validation = validateCommandPayload(
709
+ command,
710
+ payload,
711
+ this.getCapabilities()
712
+ );
713
+ if (!validation.ok) throw fromProtocolError(validation.error);
714
+ return this.transport.post({
715
+ type: "SDK_REQUEST",
716
+ protocol: PROTOCOL_VERSION2,
717
+ sessionId: this.transport.sessionId,
718
+ requestId: operationId(),
719
+ command,
720
+ payload,
721
+ deadlineMs: COMMAND_METADATA[command].deadlineMs
722
+ });
723
+ }
724
+ async request(command, payload, options = {}) {
725
+ if (options.timeoutMs !== void 0 && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 12e4)) {
726
+ throw new UsionError(
727
+ "INVALID_INPUT",
728
+ "timeoutMs must be an integer between 1 and 120000"
729
+ );
730
+ }
731
+ if (options.idempotencyKey !== void 0 && (options.idempotencyKey.length < 1 || options.idempotencyKey.length > 128)) {
732
+ throw new UsionError(
733
+ "INVALID_INPUT",
734
+ "idempotencyKey must contain 1\u2013128 characters"
735
+ );
736
+ }
737
+ const validation = validateCommandPayload(
738
+ command,
739
+ payload,
740
+ this.getCapabilities()
741
+ );
742
+ if (!validation.ok) {
743
+ throw fromProtocolError(validation.error);
744
+ }
745
+ const metadata = COMMAND_METADATA[command];
746
+ const deadlineMs = options.timeoutMs ?? metadata.deadlineMs;
747
+ const deadlineAt = Date.now() + deadlineMs;
748
+ const retryable = metadata.policy === "read" || metadata.policy === "mutation" && metadata.idempotent;
749
+ const maxAttempts = retryable ? 3 : 1;
750
+ const idempotencyKey = options.idempotencyKey ?? (metadata.policy === "mutation" ? operationId() : void 0);
751
+ let lastError;
752
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
753
+ const remainingMs = deadlineAt - Date.now();
754
+ if (remainingMs < 1) break;
755
+ const attemptsLeft = maxAttempts - attempt;
756
+ const attemptTimeoutMs = attemptsLeft === 1 ? remainingMs : Math.max(1, Math.floor(remainingMs / attemptsLeft));
757
+ try {
758
+ return await this.pending.create(
759
+ (requestId2) => this.transport.post({
760
+ type: "SDK_REQUEST",
761
+ protocol: PROTOCOL_VERSION2,
762
+ sessionId: this.transport.sessionId,
763
+ requestId: requestId2,
764
+ command,
765
+ payload,
766
+ deadlineMs: remainingMs,
767
+ ...idempotencyKey ? { idempotencyKey } : {}
768
+ }),
769
+ {
770
+ ...options,
771
+ timeoutMs: attemptTimeoutMs
772
+ },
773
+ attemptTimeoutMs,
774
+ (value) => {
775
+ const result = validateCommandResult(command, value);
776
+ return result.ok ? void 0 : fromProtocolError(result.error);
777
+ }
778
+ );
779
+ } catch (error) {
780
+ lastError = error;
781
+ const canRetry = error instanceof UsionError && (error.code === "REQUEST_TIMEOUT" || error.code === "UNAVAILABLE") && attempt + 1 < maxAttempts;
782
+ if (!canRetry) throw error;
783
+ const remainingAfterAttempt = deadlineAt - Date.now();
784
+ if (remainingAfterAttempt < 2) break;
785
+ await this.waitBeforeRetry(
786
+ Math.min(50 * 2 ** attempt, Math.floor(remainingAfterAttempt / 4)),
787
+ options.signal
788
+ );
789
+ }
790
+ }
791
+ if (lastError instanceof UsionError) throw lastError;
792
+ throw new UsionError("REQUEST_TIMEOUT", "SDK request timed out");
793
+ }
794
+ on(event, handler) {
795
+ return this.events.on(event, handler);
796
+ }
797
+ destroy(reason = "SDK client was destroyed", notifyHost = true) {
798
+ if (this.destroyed) return;
799
+ this.destroyed = true;
800
+ this.lifecycle.abort();
801
+ if (notifyHost) {
802
+ this.transport.post({
803
+ type: "SDK_DESTROY",
804
+ protocol: PROTOCOL_VERSION2,
805
+ sessionId: this.transport.sessionId,
806
+ reason
807
+ });
808
+ }
809
+ this.offMessage();
810
+ this.pending.destroy(reason);
811
+ this.events.destroy();
812
+ this.transport.destroy();
813
+ }
814
+ get pendingCount() {
815
+ return this.pending.size;
816
+ }
817
+ waitBeforeRetry(ms, signal) {
818
+ if (this.destroyed || this.lifecycle.signal.aborted) {
819
+ return Promise.reject(new UsionError("DESTROYED", "SDK client is destroyed"));
820
+ }
821
+ if (signal?.aborted) {
822
+ return Promise.reject(new UsionError("CANCELLED", "Request was cancelled"));
823
+ }
824
+ return new Promise((resolve, reject) => {
825
+ const finish = (error) => {
826
+ clearTimeout(timer);
827
+ signal?.removeEventListener("abort", cancel);
828
+ this.lifecycle.signal.removeEventListener("abort", destroy);
829
+ if (error) reject(error);
830
+ else resolve();
831
+ };
832
+ const timer = setTimeout(() => finish(), Math.max(0, ms));
833
+ const cancel = () => finish(new UsionError("CANCELLED", "Request was cancelled"));
834
+ const destroy = () => finish(new UsionError("DESTROYED", "SDK client is destroyed"));
835
+ signal?.addEventListener("abort", cancel, { once: true });
836
+ this.lifecycle.signal.addEventListener("abort", destroy, { once: true });
837
+ });
838
+ }
839
+ };
840
+ function operationId() {
841
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
842
+ return `op_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
843
+ }
844
+
845
+ // src/modules/auth.ts
846
+ var AuthModule = class {
847
+ constructor(bus) {
848
+ this.bus = bus;
849
+ }
850
+ bus;
851
+ getToken(options) {
852
+ return this.bus.request("auth.getToken", {}, options);
853
+ }
854
+ };
855
+
856
+ // src/modules/cloud.ts
857
+ function validKey(key) {
858
+ if (typeof key !== "string" || key.length < 1 || key.length > 128) {
859
+ throw new UsionError("INVALID_INPUT", "Cloud key must contain 1\u2013128 characters");
860
+ }
861
+ }
862
+ var CloudModule = class {
863
+ constructor(bus) {
864
+ this.bus = bus;
865
+ }
866
+ bus;
867
+ get(key, options) {
868
+ validKey(key);
869
+ return this.bus.request("cloud.get", { key }, options).then((result) => result.value);
870
+ }
871
+ set(key, value, options) {
872
+ validKey(key);
873
+ if (value === void 0) {
874
+ return Promise.reject(new UsionError("INVALID_INPUT", "Cloud value cannot be undefined"));
875
+ }
876
+ return this.bus.request("cloud.set", { key, value }, options);
877
+ }
878
+ remove(key, options) {
879
+ validKey(key);
880
+ return this.bus.request("cloud.remove", { key }, options);
881
+ }
882
+ keys(options) {
883
+ return this.bus.request("cloud.keys", {}, options).then((result) => result.keys);
884
+ }
885
+ async subscribe(key, handler, options) {
886
+ if (key !== void 0) validKey(key);
887
+ const result = await this.bus.request(
888
+ "cloud.subscribe",
889
+ key === void 0 ? {} : { key },
890
+ options
891
+ );
892
+ const offEvent = this.bus.on("cloud.changed", (change) => {
893
+ if (change.subscriptionId === result.subscriptionId) handler(change);
894
+ });
895
+ let active = true;
896
+ return () => {
897
+ if (!active) return;
898
+ active = false;
899
+ offEvent();
900
+ void this.bus.request(
901
+ "cloud.unsubscribe",
902
+ { subscriptionId: result.subscriptionId },
903
+ { timeoutMs: 5e3 }
904
+ ).catch(() => {
905
+ });
906
+ };
907
+ }
908
+ };
909
+
910
+ // src/modules/game/offline-queue.ts
911
+ var OfflineActionQueue = class {
912
+ entries = [];
913
+ flushing = false;
914
+ closed = false;
915
+ enqueue(action, timeoutMs, signal) {
916
+ if (this.closed) {
917
+ return Promise.reject(new UsionError("DESTROYED", "Game module is destroyed"));
918
+ }
919
+ if (signal?.aborted) {
920
+ return Promise.reject(new UsionError("CANCELLED", "Game action was cancelled"));
921
+ }
922
+ return new Promise((resolve, reject) => {
923
+ const entry = {
924
+ action,
925
+ deadlineAt: Date.now() + timeoutMs,
926
+ resolve,
927
+ reject,
928
+ timer: setTimeout(() => {
929
+ this.remove(entry);
930
+ reject(new UsionError(
931
+ "REQUEST_TIMEOUT",
932
+ "Queued game action expired before reconnection"
933
+ ));
934
+ }, timeoutMs)
935
+ };
936
+ if (signal) {
937
+ const abort = () => {
938
+ this.remove(entry);
939
+ reject(new UsionError("CANCELLED", "Game action was cancelled"));
940
+ };
941
+ signal.addEventListener("abort", abort, { once: true });
942
+ entry.removeAbort = () => signal.removeEventListener("abort", abort);
943
+ }
944
+ this.entries.push(entry);
945
+ });
946
+ }
947
+ async flush(send) {
948
+ if (this.flushing || this.closed) return;
949
+ this.flushing = true;
950
+ try {
951
+ while (this.entries.length > 0 && !this.closed) {
952
+ const entry = this.entries[0];
953
+ if (!entry) break;
954
+ const remainingMs = entry.deadlineAt - Date.now();
955
+ if (remainingMs < 1) {
956
+ this.remove(entry);
957
+ entry.reject(new UsionError("REQUEST_TIMEOUT", "Queued game action expired"));
958
+ continue;
959
+ }
960
+ try {
961
+ const result = await send(entry.action, remainingMs);
962
+ this.remove(entry);
963
+ entry.resolve(result);
964
+ } catch (error) {
965
+ if (error instanceof UsionError && (error.code === "UNAVAILABLE" || error.code === "REQUEST_TIMEOUT")) {
966
+ return;
967
+ }
968
+ this.remove(entry);
969
+ entry.reject(error);
970
+ }
971
+ }
972
+ } finally {
973
+ this.flushing = false;
974
+ }
975
+ }
976
+ destroy(reason = "Game module was destroyed") {
977
+ if (this.closed) return;
978
+ this.closed = true;
979
+ this.clear(reason);
980
+ }
981
+ clear(reason = "Queued game action was cancelled") {
982
+ for (const entry of [...this.entries]) {
983
+ this.remove(entry);
984
+ entry.reject(new UsionError("CANCELLED", reason));
985
+ }
986
+ }
987
+ get size() {
988
+ return this.entries.length;
989
+ }
990
+ remove(entry) {
991
+ const index = this.entries.indexOf(entry);
992
+ if (index >= 0) this.entries.splice(index, 1);
993
+ clearTimeout(entry.timer);
994
+ entry.removeAbort?.();
995
+ }
996
+ };
997
+
998
+ // src/modules/game/action-request.ts
999
+ function createOperationId() {
1000
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
1001
+ return `game_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
1002
+ }
1003
+ function sendGameAction(transport, action, timeoutMs, signal) {
1004
+ return transport.request("game.action", {
1005
+ operationId: action.operationId,
1006
+ type: action.type,
1007
+ data: action.data,
1008
+ ...action.nextTurn === void 0 ? {} : { nextTurn: action.nextTurn }
1009
+ }, {
1010
+ timeoutMs: Math.min(timeoutMs, 5e3),
1011
+ idempotencyKey: action.operationId,
1012
+ ...signal === void 0 ? {} : { signal }
1013
+ });
1014
+ }
1015
+
1016
+ // src/modules/game/action-submission.ts
1017
+ var GameActionSubmission = class {
1018
+ constructor(transport, queue, state, scheduleRecovery) {
1019
+ this.transport = transport;
1020
+ this.queue = queue;
1021
+ this.state = state;
1022
+ this.scheduleRecovery = scheduleRecovery;
1023
+ }
1024
+ transport;
1025
+ queue;
1026
+ state;
1027
+ scheduleRecovery;
1028
+ async submit(type, data, options = {}) {
1029
+ if (typeof type !== "string" || type.length < 1 || type.length > 64) {
1030
+ throw new UsionError("INVALID_INPUT", "Game action type must contain 1\u201364 characters");
1031
+ }
1032
+ if (this.state.status.connection === "idle" || this.state.status.connection === "failed") {
1033
+ throw new UsionError("UNAVAILABLE", "Game is not ready; call game.join() first");
1034
+ }
1035
+ const timeoutMs = options.timeoutMs ?? 15e3;
1036
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 12e4) {
1037
+ throw new UsionError("INVALID_INPUT", "Game action timeout must be 1\u2013120000ms");
1038
+ }
1039
+ const action = {
1040
+ operationId: createOperationId(),
1041
+ type,
1042
+ data,
1043
+ ...options.nextTurn === void 0 ? {} : { nextTurn: options.nextTurn }
1044
+ };
1045
+ const deadlineAt = Date.now() + timeoutMs;
1046
+ if (this.state.status.connection === "ready") {
1047
+ try {
1048
+ const result = await sendGameAction(
1049
+ this.transport,
1050
+ action,
1051
+ timeoutMs,
1052
+ options.signal
1053
+ );
1054
+ this.scheduleRecovery(result.sequence);
1055
+ return result;
1056
+ } catch (error) {
1057
+ const retryLater = error instanceof UsionError && (error.code === "UNAVAILABLE" || error.code === "REQUEST_TIMEOUT") && options.queueIfOffline !== false;
1058
+ if (!retryLater) throw error;
1059
+ this.state.publish("disconnected", error);
1060
+ }
1061
+ } else if (options.queueIfOffline === false) {
1062
+ throw new UsionError("UNAVAILABLE", "Game is reconnecting");
1063
+ }
1064
+ const remainingMs = deadlineAt - Date.now();
1065
+ if (remainingMs < 1) {
1066
+ throw new UsionError("REQUEST_TIMEOUT", "Game action deadline expired");
1067
+ }
1068
+ const queued = this.queue.enqueue(action, remainingMs, options.signal);
1069
+ this.state.publish(this.state.status.connection);
1070
+ return queued.finally(() => this.state.publish(this.state.status.connection));
1071
+ }
1072
+ };
1073
+
1074
+ // src/modules/game/recovery-request.ts
1075
+ async function recoverGame(transport, state, isCurrent, deadlineAt, options) {
1076
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1077
+ const remainingMs = deadlineAt - Date.now();
1078
+ if (remainingMs < 1) {
1079
+ throw new UsionError("REQUEST_TIMEOUT", "Game recovery deadline expired");
1080
+ }
1081
+ const recovery = await transport.request("game.recover", {
1082
+ appliedSequence: state.status.appliedSequence
1083
+ }, {
1084
+ ...options,
1085
+ timeoutMs: remainingMs
1086
+ });
1087
+ if (!isCurrent()) return;
1088
+ state.setSession(recovery);
1089
+ const before = state.status.appliedSequence;
1090
+ state.applyRecovery(recovery, "recover");
1091
+ if (state.status.appliedSequence === recovery.serverSequence) return;
1092
+ if (state.status.appliedSequence <= before) break;
1093
+ }
1094
+ throw new UsionError("UNAVAILABLE", "Game recovery is missing an action range");
1095
+ }
1096
+
1097
+ // src/modules/game/synced-state.ts
1098
+ function cloneAndFreeze(value) {
1099
+ const cloned = typeof structuredClone === "function" ? structuredClone(value) : JSON.parse(JSON.stringify(value));
1100
+ const visit = (item) => {
1101
+ if (!item || typeof item !== "object" || Object.isFrozen(item)) return;
1102
+ for (const child of Object.values(item)) visit(child);
1103
+ Object.freeze(item);
1104
+ };
1105
+ visit(cloned);
1106
+ return cloned;
1107
+ }
1108
+ function defaultReducer(state, action) {
1109
+ if (state !== null && action.data !== null && typeof state === "object" && typeof action.data === "object" && !Array.isArray(state) && !Array.isArray(action.data)) {
1110
+ return { ...state, ...action.data };
1111
+ }
1112
+ return action.data;
1113
+ }
1114
+ function createSyncedState(game, initial, reducer, options) {
1115
+ const checkpointEvery = options.checkpointEvery ?? 1;
1116
+ if (!Number.isInteger(checkpointEvery) || checkpointEvery < 1 || checkpointEvery > 1e4) {
1117
+ throw new UsionError(
1118
+ "INVALID_INPUT",
1119
+ "checkpointEvery must be an integer between 1 and 10000"
1120
+ );
1121
+ }
1122
+ const reduce = reducer ?? defaultReducer;
1123
+ const authority = options.authority ?? "host";
1124
+ const listeners = /* @__PURE__ */ new Set();
1125
+ let state = cloneAndFreeze(initial);
1126
+ let appliedSinceCheckpoint = 0;
1127
+ let destroyed = false;
1128
+ const notify2 = (reason) => {
1129
+ for (const handler of [...listeners]) {
1130
+ try {
1131
+ handler(state, reason);
1132
+ } catch {
1133
+ }
1134
+ }
1135
+ };
1136
+ const offRecovery = game.onRecovery((notice) => {
1137
+ if (!notice.applyCheckpoint) return;
1138
+ const checkpoint2 = notice.recovery.checkpoint;
1139
+ if (checkpoint2 && typeof checkpoint2 === "object" && !Array.isArray(checkpoint2) && Object.prototype.hasOwnProperty.call(checkpoint2, "__usionV3State") && checkpoint2.__usionV3State === 1 && Object.prototype.hasOwnProperty.call(checkpoint2, "state")) {
1140
+ state = cloneAndFreeze(checkpoint2.state);
1141
+ appliedSinceCheckpoint = 0;
1142
+ notify2("recover");
1143
+ }
1144
+ });
1145
+ const offAction = game.onAppliedAction((action, source) => {
1146
+ try {
1147
+ state = cloneAndFreeze(reduce(state, action));
1148
+ } catch {
1149
+ return;
1150
+ }
1151
+ notify2(source === "recover" ? "recover" : "action");
1152
+ if (source !== "action") return;
1153
+ appliedSinceCheckpoint += 1;
1154
+ const isAuthority = authority === "all" || game.status.hostId !== void 0 && game.status.hostId === game.userId;
1155
+ if (isAuthority && appliedSinceCheckpoint >= checkpointEvery) {
1156
+ appliedSinceCheckpoint = 0;
1157
+ void checkpoint().catch(() => {
1158
+ });
1159
+ }
1160
+ });
1161
+ const checkpoint = (requestOptions) => game.checkpoint(
1162
+ { __usionV3State: 1, state },
1163
+ requestOptions
1164
+ );
1165
+ return {
1166
+ get: () => state,
1167
+ commit: (type, data, actionOptions) => game.action(type, data, actionOptions),
1168
+ checkpoint,
1169
+ onChange(handler) {
1170
+ if (destroyed) return () => {
1171
+ };
1172
+ listeners.add(handler);
1173
+ return () => listeners.delete(handler);
1174
+ },
1175
+ destroy() {
1176
+ if (destroyed) return;
1177
+ destroyed = true;
1178
+ listeners.clear();
1179
+ offRecovery();
1180
+ offAction();
1181
+ }
1182
+ };
1183
+ }
1184
+
1185
+ // src/modules/game/state-controller.ts
1186
+ function initialStatus(queueSize) {
1187
+ return Object.freeze({
1188
+ connection: "idle",
1189
+ playerIds: Object.freeze([]),
1190
+ serverSequence: 0,
1191
+ checkpointSequence: 0,
1192
+ appliedSequence: 0,
1193
+ queuedActions: queueSize
1194
+ });
1195
+ }
1196
+ function notify(listeners, value) {
1197
+ for (const listener of [...listeners]) {
1198
+ try {
1199
+ listener(value);
1200
+ } catch {
1201
+ }
1202
+ }
1203
+ }
1204
+ var GameStateController = class {
1205
+ constructor(queueSize, requestRecovery) {
1206
+ this.queueSize = queueSize;
1207
+ this.requestRecovery = requestRecovery;
1208
+ this.snapshot = initialStatus(queueSize());
1209
+ }
1210
+ queueSize;
1211
+ requestRecovery;
1212
+ snapshot;
1213
+ statusListeners = /* @__PURE__ */ new Set();
1214
+ actionListeners = /* @__PURE__ */ new Set();
1215
+ appliedListeners = /* @__PURE__ */ new Set();
1216
+ recoveryListeners = /* @__PURE__ */ new Set();
1217
+ buffered = /* @__PURE__ */ new Map();
1218
+ currentRecovery;
1219
+ get status() {
1220
+ return this.snapshot;
1221
+ }
1222
+ onStatus(handler) {
1223
+ this.statusListeners.add(handler);
1224
+ try {
1225
+ handler(this.snapshot);
1226
+ } catch {
1227
+ }
1228
+ return () => this.statusListeners.delete(handler);
1229
+ }
1230
+ onAction(handler) {
1231
+ this.actionListeners.add(handler);
1232
+ return () => this.actionListeners.delete(handler);
1233
+ }
1234
+ onRecovery(handler) {
1235
+ this.recoveryListeners.add(handler);
1236
+ if (this.currentRecovery) {
1237
+ try {
1238
+ handler(this.currentRecovery);
1239
+ } catch {
1240
+ }
1241
+ }
1242
+ return () => this.recoveryListeners.delete(handler);
1243
+ }
1244
+ onAppliedAction(handler) {
1245
+ this.appliedListeners.add(handler);
1246
+ return () => this.appliedListeners.delete(handler);
1247
+ }
1248
+ setSession(state) {
1249
+ this.snapshot = Object.freeze({
1250
+ ...this.snapshot,
1251
+ roomId: state.roomId,
1252
+ ...state.hostId === void 0 ? {} : { hostId: state.hostId },
1253
+ playerIds: Object.freeze([...state.playerIds]),
1254
+ roomStatus: state.status,
1255
+ ...state.currentTurn === void 0 ? {} : { currentTurn: state.currentTurn },
1256
+ serverSequence: state.serverSequence,
1257
+ checkpointSequence: state.checkpointSequence
1258
+ });
1259
+ }
1260
+ applyRecovery(recovery, source) {
1261
+ const applyCheckpoint = this.currentRecovery === void 0 || recovery.checkpointSequence > this.snapshot.appliedSequence;
1262
+ this.snapshot = Object.freeze({
1263
+ ...this.snapshot,
1264
+ appliedSequence: Math.max(
1265
+ recovery.checkpointSequence,
1266
+ this.snapshot.appliedSequence
1267
+ ),
1268
+ serverSequence: Math.max(recovery.serverSequence, this.snapshot.serverSequence),
1269
+ checkpointSequence: Math.max(
1270
+ recovery.checkpointSequence,
1271
+ this.snapshot.checkpointSequence
1272
+ )
1273
+ });
1274
+ this.currentRecovery = { recovery, source, applyCheckpoint };
1275
+ notify(this.recoveryListeners, this.currentRecovery);
1276
+ for (const action of [...recovery.actions].sort((a, b) => a.sequence - b.sequence)) {
1277
+ this.applyAction(action, "recover");
1278
+ }
1279
+ let next = this.buffered.get(this.snapshot.appliedSequence + 1);
1280
+ while (next) {
1281
+ this.buffered.delete(next.sequence);
1282
+ this.applyAction(next, "action");
1283
+ next = this.buffered.get(this.snapshot.appliedSequence + 1);
1284
+ }
1285
+ }
1286
+ receiveAction(action) {
1287
+ if (action.sequence <= this.snapshot.appliedSequence) return;
1288
+ if (action.sequence !== this.snapshot.appliedSequence + 1) {
1289
+ this.buffered.set(action.sequence, action);
1290
+ this.requestRecovery();
1291
+ return;
1292
+ }
1293
+ this.applyAction(action, "action");
1294
+ }
1295
+ publish(connection, error) {
1296
+ const { error: _previousError, ...status } = this.snapshot;
1297
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : void 0;
1298
+ this.snapshot = Object.freeze({
1299
+ ...status,
1300
+ connection,
1301
+ queuedActions: this.queueSize(),
1302
+ ...message === void 0 ? {} : { error: message }
1303
+ });
1304
+ notify(this.statusListeners, this.snapshot);
1305
+ }
1306
+ reset() {
1307
+ this.buffered.clear();
1308
+ this.currentRecovery = void 0;
1309
+ this.snapshot = initialStatus(this.queueSize());
1310
+ notify(this.statusListeners, this.snapshot);
1311
+ }
1312
+ destroy() {
1313
+ this.buffered.clear();
1314
+ this.statusListeners.clear();
1315
+ this.actionListeners.clear();
1316
+ this.appliedListeners.clear();
1317
+ this.recoveryListeners.clear();
1318
+ }
1319
+ applyAction(action, source) {
1320
+ if (action.sequence !== this.snapshot.appliedSequence + 1) return;
1321
+ this.snapshot = Object.freeze({
1322
+ ...this.snapshot,
1323
+ appliedSequence: action.sequence,
1324
+ serverSequence: Math.max(this.snapshot.serverSequence, action.sequence),
1325
+ ...action.currentTurn === void 0 ? {} : { currentTurn: action.currentTurn }
1326
+ });
1327
+ for (const listener of [...this.appliedListeners]) {
1328
+ try {
1329
+ listener(action, source);
1330
+ } catch {
1331
+ }
1332
+ }
1333
+ notify(this.actionListeners, action);
1334
+ this.publish(this.snapshot.connection);
1335
+ }
1336
+ };
1337
+
1338
+ // src/modules/game/realtime.ts
1339
+ var INPUT_INTERVAL_MS = 33;
1340
+ var RealtimeGameController = class {
1341
+ constructor(transport) {
1342
+ this.transport = transport;
1343
+ this.cleanups = [
1344
+ transport.on("game.snapshot", (snapshot) => {
1345
+ if (snapshot.sequence <= this.lastSnapshotSequence) return;
1346
+ if (this.awaitingKeyframe && !snapshot.keyframe) return;
1347
+ this.awaitingKeyframe = false;
1348
+ this.lastSnapshotSequence = snapshot.sequence;
1349
+ for (const listener of [...this.listeners]) listener(snapshot);
1350
+ }),
1351
+ transport.on("game.realtime", (event) => {
1352
+ for (const listener of [...this.legacyListeners]) listener(event);
1353
+ })
1354
+ ];
1355
+ }
1356
+ transport;
1357
+ listeners = /* @__PURE__ */ new Set();
1358
+ legacyListeners = /* @__PURE__ */ new Set();
1359
+ cleanups;
1360
+ inputSequence = 0;
1361
+ lastSnapshotSequence = 0;
1362
+ lastSentAt = 0;
1363
+ pending;
1364
+ timer;
1365
+ acceptingInput = false;
1366
+ awaitingKeyframe = true;
1367
+ setConnection(state) {
1368
+ this.acceptingInput = state === "ready";
1369
+ if (this.acceptingInput) return;
1370
+ this.awaitingKeyframe = true;
1371
+ this.pending = void 0;
1372
+ if (this.timer) clearTimeout(this.timer);
1373
+ this.timer = void 0;
1374
+ }
1375
+ sendInput(data) {
1376
+ if (!this.acceptingInput) return false;
1377
+ const sequence = ++this.inputSequence;
1378
+ this.pending = { sequence, data };
1379
+ const wait = Math.max(0, INPUT_INTERVAL_MS - (Date.now() - this.lastSentAt));
1380
+ if (wait === 0) return this.flush();
1381
+ if (!this.timer) {
1382
+ this.timer = setTimeout(() => {
1383
+ this.timer = void 0;
1384
+ this.flush();
1385
+ }, wait);
1386
+ }
1387
+ return true;
1388
+ }
1389
+ onSnapshot(listener) {
1390
+ this.listeners.add(listener);
1391
+ return () => this.listeners.delete(listener);
1392
+ }
1393
+ onLegacyEvent(listener) {
1394
+ this.legacyListeners.add(listener);
1395
+ return () => this.legacyListeners.delete(listener);
1396
+ }
1397
+ destroy() {
1398
+ this.cleanups.forEach((cleanup) => cleanup());
1399
+ if (this.timer) clearTimeout(this.timer);
1400
+ this.timer = void 0;
1401
+ this.pending = void 0;
1402
+ this.listeners.clear();
1403
+ this.legacyListeners.clear();
1404
+ }
1405
+ flush() {
1406
+ const input = this.pending;
1407
+ this.pending = void 0;
1408
+ if (!input || !this.acceptingInput) return false;
1409
+ const sent = this.transport.send("game.input", {
1410
+ inputSequence: input.sequence,
1411
+ data: input.data
1412
+ });
1413
+ if (sent) this.lastSentAt = Date.now();
1414
+ return sent;
1415
+ }
1416
+ };
1417
+
1418
+ // src/modules/game/game.ts
1419
+ var GameModule = class {
1420
+ constructor(transport, getContext) {
1421
+ this.transport = transport;
1422
+ this.getContext = getContext;
1423
+ this.realtime = new RealtimeGameController(transport);
1424
+ this.state = new GameStateController(
1425
+ () => this.queue.size,
1426
+ () => void this.recover().catch(() => {
1427
+ })
1428
+ );
1429
+ this.actions = new GameActionSubmission(
1430
+ transport,
1431
+ this.queue,
1432
+ this.state,
1433
+ (sequence) => this.scheduleRecoveryCheck(sequence)
1434
+ );
1435
+ this.cleanups = [
1436
+ transport.on("game.action", (action) => this.state.receiveAction(action)),
1437
+ transport.on("game.connection", (event) => this.receiveConnection(event))
1438
+ ];
1439
+ }
1440
+ transport;
1441
+ getContext;
1442
+ queue = new OfflineActionQueue();
1443
+ state;
1444
+ realtime;
1445
+ actions;
1446
+ recoveryTimers = /* @__PURE__ */ new Set();
1447
+ cleanups;
1448
+ joinPromise;
1449
+ recoveryPromise;
1450
+ generation = 0;
1451
+ destroyed = false;
1452
+ get status() {
1453
+ return this.state.status;
1454
+ }
1455
+ get userId() {
1456
+ return this.getContext().user.id;
1457
+ }
1458
+ join(options) {
1459
+ if (this.destroyed) {
1460
+ return Promise.reject(new UsionError("DESTROYED", "Game module is destroyed"));
1461
+ }
1462
+ if (this.status.connection === "ready") return Promise.resolve(this.status);
1463
+ if (this.joinPromise) return this.joinPromise;
1464
+ const generation = ++this.generation;
1465
+ this.state.publish("joining");
1466
+ const payload = this.status.appliedSequence > 0 ? { appliedSequence: this.status.appliedSequence } : {};
1467
+ const pending = this.transport.request("game.join", payload, options).then(async (state) => {
1468
+ if (generation !== this.generation) return this.status;
1469
+ this.state.setSession(state);
1470
+ this.state.applyRecovery({ ...state, actions: [] }, "join");
1471
+ if (this.status.appliedSequence < state.serverSequence) {
1472
+ await this.recover();
1473
+ }
1474
+ if (generation === this.generation) {
1475
+ this.state.publish("ready");
1476
+ this.realtime.setConnection("ready");
1477
+ await this.flushQueue();
1478
+ }
1479
+ return this.status;
1480
+ }).catch((error) => {
1481
+ if (generation === this.generation) this.state.publish("failed", error);
1482
+ throw error;
1483
+ }).finally(() => {
1484
+ if (this.joinPromise === pending) this.joinPromise = void 0;
1485
+ });
1486
+ this.joinPromise = pending;
1487
+ return this.joinPromise;
1488
+ }
1489
+ recover(options) {
1490
+ if (this.recoveryPromise) return this.recoveryPromise;
1491
+ if (!this.status.roomId) {
1492
+ return Promise.reject(new UsionError("INVALID_INPUT", "Join the game before recovery"));
1493
+ }
1494
+ const generation = this.generation;
1495
+ const timeoutMs = options?.timeoutMs ?? 15e3;
1496
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 12e4) {
1497
+ return Promise.reject(new UsionError(
1498
+ "INVALID_INPUT",
1499
+ "timeoutMs must be an integer between 1 and 120000"
1500
+ ));
1501
+ }
1502
+ this.state.publish("recovering");
1503
+ const pending = recoverGame(
1504
+ this.transport,
1505
+ this.state,
1506
+ () => generation === this.generation,
1507
+ Date.now() + timeoutMs,
1508
+ options
1509
+ ).then(async () => {
1510
+ if (generation !== this.generation) return;
1511
+ this.state.publish("ready");
1512
+ this.realtime.setConnection("ready");
1513
+ await this.flushQueue();
1514
+ }).catch((error) => {
1515
+ if (generation === this.generation) this.state.publish("failed", error);
1516
+ throw error;
1517
+ }).finally(() => {
1518
+ if (this.recoveryPromise === pending) this.recoveryPromise = void 0;
1519
+ });
1520
+ this.recoveryPromise = pending;
1521
+ return this.recoveryPromise;
1522
+ }
1523
+ async action(type, data, options = {}) {
1524
+ return this.actions.submit(type, data, options);
1525
+ }
1526
+ checkpoint(state, options) {
1527
+ if (this.status.connection !== "ready") {
1528
+ return Promise.reject(new UsionError("UNAVAILABLE", "Game is not ready"));
1529
+ }
1530
+ return this.transport.request("game.checkpoint", {
1531
+ state,
1532
+ sequence: this.status.appliedSequence
1533
+ }, options);
1534
+ }
1535
+ async leave(options) {
1536
+ if (this.status.connection === "idle") return;
1537
+ ++this.generation;
1538
+ this.joinPromise = void 0;
1539
+ this.recoveryPromise = void 0;
1540
+ this.state.publish("leaving");
1541
+ const leaving = this.transport.request("game.leave", {}, options);
1542
+ this.queue.clear("Game was left before queued action delivery");
1543
+ this.reset();
1544
+ try {
1545
+ await leaving;
1546
+ } catch (error) {
1547
+ if (!(error instanceof UsionError) || error.code !== "UNAVAILABLE") throw error;
1548
+ }
1549
+ }
1550
+ createState(initial, reducer, options = {}) {
1551
+ return createSyncedState(this, initial, reducer, options);
1552
+ }
1553
+ /**
1554
+ * Queues the newest realtime input for best-effort delivery. Inputs are
1555
+ * discarded while disconnected and are never replayed after reconnection.
1556
+ */
1557
+ sendInput(data) {
1558
+ return this.realtime.sendInput(data);
1559
+ }
1560
+ onSnapshot(handler) {
1561
+ return this.realtime.onSnapshot(handler);
1562
+ }
1563
+ onStatus(handler) {
1564
+ return this.state.onStatus(handler);
1565
+ }
1566
+ onAction(handler) {
1567
+ return this.state.onAction(handler);
1568
+ }
1569
+ onRealtime(handler) {
1570
+ return this.realtime.onLegacyEvent(handler);
1571
+ }
1572
+ onRecovery(handler) {
1573
+ return this.state.onRecovery(handler);
1574
+ }
1575
+ onAppliedAction(handler) {
1576
+ return this.state.onAppliedAction(handler);
1577
+ }
1578
+ destroy() {
1579
+ if (this.destroyed) return;
1580
+ this.destroyed = true;
1581
+ ++this.generation;
1582
+ this.cleanups.forEach((off) => off());
1583
+ this.realtime.destroy();
1584
+ this.transport.destroy();
1585
+ this.queue.destroy();
1586
+ this.state.destroy();
1587
+ this.recoveryTimers.forEach((timer) => clearTimeout(timer));
1588
+ this.recoveryTimers.clear();
1589
+ }
1590
+ receiveConnection(event) {
1591
+ if (event.state === "disconnected") {
1592
+ this.realtime.setConnection("disconnected");
1593
+ this.state.publish("disconnected", event.reason);
1594
+ return;
1595
+ }
1596
+ if (event.state === "recovering") {
1597
+ this.realtime.setConnection("recovering");
1598
+ this.state.publish("recovering");
1599
+ return;
1600
+ }
1601
+ if (this.status.connection === "ready") return;
1602
+ if (this.status.roomId) void this.recover().catch(() => {
1603
+ });
1604
+ }
1605
+ async flushQueue() {
1606
+ await this.queue.flush(async (action, remainingMs) => {
1607
+ try {
1608
+ const result = await sendGameAction(this.transport, action, remainingMs);
1609
+ this.scheduleRecoveryCheck(result.sequence);
1610
+ return result;
1611
+ } catch (error) {
1612
+ if (error instanceof UsionError && (error.code === "UNAVAILABLE" || error.code === "REQUEST_TIMEOUT")) {
1613
+ this.state.publish("disconnected", error);
1614
+ }
1615
+ throw error;
1616
+ }
1617
+ });
1618
+ this.state.publish(this.status.connection);
1619
+ }
1620
+ scheduleRecoveryCheck(sequence) {
1621
+ const timer = setTimeout(() => {
1622
+ this.recoveryTimers.delete(timer);
1623
+ if (!this.destroyed && this.status.appliedSequence < sequence) {
1624
+ void this.recover().catch(() => {
1625
+ });
1626
+ }
1627
+ }, 150);
1628
+ this.recoveryTimers.add(timer);
1629
+ }
1630
+ reset() {
1631
+ this.realtime.setConnection("disconnected");
1632
+ this.state.reset();
1633
+ }
1634
+ };
1635
+
1636
+ // src/modules/game/transport.ts
1637
+ var PlatformGameTransport = class {
1638
+ constructor(bus) {
1639
+ this.bus = bus;
1640
+ }
1641
+ bus;
1642
+ mode = "platform";
1643
+ connectionTransport = "websocket";
1644
+ subscriptions = /* @__PURE__ */ new Set();
1645
+ destroyed = false;
1646
+ request(command, payload, options) {
1647
+ if (this.destroyed) {
1648
+ return Promise.reject(new UsionError(
1649
+ "DESTROYED",
1650
+ "Game transport is destroyed"
1651
+ ));
1652
+ }
1653
+ return this.bus.request(command, payload, options);
1654
+ }
1655
+ send(command, payload) {
1656
+ if (this.destroyed) return false;
1657
+ return this.bus.send(command, payload);
1658
+ }
1659
+ on(event, handler) {
1660
+ if (this.destroyed) return () => {
1661
+ };
1662
+ const offBus = this.bus.on(event, handler);
1663
+ let active = true;
1664
+ const off = () => {
1665
+ if (!active) return;
1666
+ active = false;
1667
+ this.subscriptions.delete(off);
1668
+ offBus();
1669
+ };
1670
+ this.subscriptions.add(off);
1671
+ return off;
1672
+ }
1673
+ destroy() {
1674
+ if (this.destroyed) return;
1675
+ this.destroyed = true;
1676
+ for (const off of [...this.subscriptions]) off();
1677
+ this.subscriptions.clear();
1678
+ }
1679
+ };
1680
+
1681
+ // src/client.ts
1682
+ function freezeContext(context) {
1683
+ return Object.freeze({
1684
+ ...context,
1685
+ user: Object.freeze({ ...context.user }),
1686
+ service: Object.freeze({ ...context.service }),
1687
+ launch: Object.freeze({ ...context.launch }),
1688
+ capabilities: Object.freeze([...context.capabilities])
1689
+ });
1690
+ }
1691
+ var UsionClient = class {
1692
+ auth;
1693
+ cloud;
1694
+ game;
1695
+ snapshot;
1696
+ bus;
1697
+ closed = false;
1698
+ constructor(context, transport) {
1699
+ this.snapshot = freezeContext(context);
1700
+ this.bus = new CommandBus(
1701
+ transport,
1702
+ () => this.snapshot.capabilities,
1703
+ (next) => {
1704
+ if (!this.closed) this.snapshot = freezeContext(next);
1705
+ },
1706
+ (reason) => this.close(reason ?? "Host closed the SDK session", false)
1707
+ );
1708
+ this.auth = new AuthModule(this.bus);
1709
+ this.cloud = new CloudModule(this.bus);
1710
+ this.game = new GameModule(
1711
+ new PlatformGameTransport(this.bus),
1712
+ () => this.snapshot
1713
+ );
1714
+ }
1715
+ get context() {
1716
+ return this.snapshot;
1717
+ }
1718
+ async fetch(input, init = {}) {
1719
+ if (this.closed) throw new UsionError("DESTROYED", "SDK client is destroyed");
1720
+ const rawUrl = input instanceof Request ? input.url : String(input);
1721
+ const baseOrigin = typeof location !== "undefined" ? location.origin : this.snapshot.service.origin;
1722
+ if (!baseOrigin) {
1723
+ throw new UsionError("TRUST_VIOLATION", "Mini-app origin is unavailable");
1724
+ }
1725
+ const url = new URL(rawUrl, `${baseOrigin}/`);
1726
+ if (url.origin !== baseOrigin) {
1727
+ throw new UsionError(
1728
+ "PERMISSION_DENIED",
1729
+ "app.fetch() only sends credentials to the mini-app origin"
1730
+ );
1731
+ }
1732
+ const tokenOptions = init.signal === null || init.signal === void 0 ? void 0 : { signal: init.signal };
1733
+ const credential = await this.auth.getToken(tokenOptions);
1734
+ const headers = new Headers(input instanceof Request ? input.headers : void 0);
1735
+ new Headers(init.headers).forEach((value, key) => headers.set(key, value));
1736
+ headers.set("Authorization", `Bearer ${credential.token}`);
1737
+ return globalThis.fetch(input, { ...init, headers });
1738
+ }
1739
+ async destroy(reason = "Creator destroyed SDK client") {
1740
+ this.close(reason, true);
1741
+ }
1742
+ close(reason, notifyHost) {
1743
+ if (this.closed) return;
1744
+ this.closed = true;
1745
+ this.game.destroy();
1746
+ this.bus.destroy(reason, notifyHost);
1747
+ }
1748
+ };
1749
+
1750
+ // src/host-bridge.ts
1751
+ function sessionId() {
1752
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
1753
+ return `sdk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
1754
+ }
1755
+ function referrerOrigin() {
1756
+ if (typeof document === "undefined" || !document.referrer) return void 0;
1757
+ try {
1758
+ return new URL(document.referrer).origin;
1759
+ } catch {
1760
+ return void 0;
1761
+ }
1762
+ }
1763
+ var HostBridgeTransport = class {
1764
+ sessionId = sessionId();
1765
+ bridgeWindow;
1766
+ mobile;
1767
+ targetOrigin;
1768
+ handlers = /* @__PURE__ */ new Set();
1769
+ initResolve;
1770
+ initReject;
1771
+ grantedCapabilities = [];
1772
+ destroyed = false;
1773
+ constructor(options = {}) {
1774
+ const candidate = options.window ?? (typeof window === "undefined" ? void 0 : window);
1775
+ if (!candidate) {
1776
+ throw new UsionError("TRUST_VIOLATION", "Usion SDK requires an iframe host");
1777
+ }
1778
+ this.bridgeWindow = candidate;
1779
+ this.mobile = Boolean(candidate.ReactNativeWebView);
1780
+ this.targetOrigin = options.targetOrigin ?? referrerOrigin();
1781
+ if (!this.mobile && !this.targetOrigin) {
1782
+ throw new UsionError(
1783
+ "TRUST_VIOLATION",
1784
+ "Cannot establish a trusted parent origin"
1785
+ );
1786
+ }
1787
+ this.bridgeWindow.addEventListener("message", this.handleMessage);
1788
+ }
1789
+ start(options) {
1790
+ if (this.destroyed) {
1791
+ return Promise.reject(new UsionError("DESTROYED", "Host bridge is closed"));
1792
+ }
1793
+ if (options.signal?.aborted) {
1794
+ return Promise.reject(new UsionError("CANCELLED", "Initialization was cancelled"));
1795
+ }
1796
+ this.grantedCapabilities = options.capabilities;
1797
+ return new Promise((resolve, reject) => {
1798
+ let settled = false;
1799
+ const finish = (callback) => {
1800
+ if (settled) return;
1801
+ settled = true;
1802
+ clearTimeout(timer);
1803
+ options.signal?.removeEventListener("abort", abort);
1804
+ this.initResolve = void 0;
1805
+ this.initReject = void 0;
1806
+ callback();
1807
+ };
1808
+ const timer = setTimeout(() => {
1809
+ finish(() => reject(new UsionError("INIT_TIMEOUT", "SDK initialization timed out")));
1810
+ }, options.timeoutMs);
1811
+ const abort = () => {
1812
+ finish(() => reject(new UsionError("CANCELLED", "Initialization was cancelled")));
1813
+ };
1814
+ options.signal?.addEventListener("abort", abort, { once: true });
1815
+ this.initResolve = (context) => finish(() => resolve(context));
1816
+ this.initReject = (error) => finish(() => reject(error));
1817
+ if (!this.post({
1818
+ type: "SDK_HELLO",
1819
+ protocol: PROTOCOL_VERSION2,
1820
+ sessionId: this.sessionId,
1821
+ sdk: {
1822
+ major: 3,
1823
+ protocol: PROTOCOL_VERSION2,
1824
+ version: SDK_VERSION,
1825
+ capabilities: [...options.capabilities]
1826
+ }
1827
+ })) {
1828
+ finish(() => reject(new UsionError("TRUST_VIOLATION", "Host bridge is unavailable")));
1829
+ }
1830
+ });
1831
+ }
1832
+ post(message) {
1833
+ if (this.destroyed) return false;
1834
+ try {
1835
+ if (this.mobile) {
1836
+ this.bridgeWindow.ReactNativeWebView?.postMessage(JSON.stringify(message));
1837
+ } else {
1838
+ this.bridgeWindow.parent.postMessage(message, this.targetOrigin);
1839
+ }
1840
+ return true;
1841
+ } catch {
1842
+ return false;
1843
+ }
1844
+ }
1845
+ onMessage(handler) {
1846
+ this.handlers.add(handler);
1847
+ let active = true;
1848
+ return () => {
1849
+ if (!active) return;
1850
+ active = false;
1851
+ this.handlers.delete(handler);
1852
+ };
1853
+ }
1854
+ destroy() {
1855
+ if (this.destroyed) return;
1856
+ this.destroyed = true;
1857
+ this.bridgeWindow.removeEventListener("message", this.handleMessage);
1858
+ this.handlers.clear();
1859
+ this.initReject?.(new UsionError("CANCELLED", "Host bridge was destroyed"));
1860
+ }
1861
+ handleMessage = (event) => {
1862
+ if (this.destroyed) return;
1863
+ if (!this.mobile) {
1864
+ if (event.source !== this.bridgeWindow.parent) return;
1865
+ if (event.origin !== this.targetOrigin) return;
1866
+ }
1867
+ let value = event.data;
1868
+ if (typeof value === "string") {
1869
+ try {
1870
+ value = JSON.parse(value);
1871
+ } catch {
1872
+ return;
1873
+ }
1874
+ }
1875
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
1876
+ const message = value;
1877
+ if (message.sessionId !== this.sessionId) return;
1878
+ if (message.protocol !== PROTOCOL_VERSION2) {
1879
+ this.initReject?.(new UsionError(
1880
+ "PROTOCOL_MISMATCH",
1881
+ `Host protocol ${String(message.protocol)} is incompatible with SDK protocol 3`
1882
+ ));
1883
+ return;
1884
+ }
1885
+ const validation = validateEnvelope(value, {
1886
+ expectedSessionId: this.sessionId,
1887
+ grantedCapabilities: this.grantedCapabilities
1888
+ });
1889
+ if (!validation.ok) {
1890
+ if (message.type === "SDK_INIT") {
1891
+ this.initReject?.(fromProtocolError(validation.error));
1892
+ }
1893
+ return;
1894
+ }
1895
+ const validMessage = validation.value;
1896
+ if (validMessage.type === "SDK_INIT") {
1897
+ const init = validMessage;
1898
+ const requested = new Set(this.grantedCapabilities);
1899
+ if (init.context.capabilities.some((capability) => !requested.has(capability))) {
1900
+ this.initReject?.(new UsionError(
1901
+ "TRUST_VIOLATION",
1902
+ "Host granted a capability the mini-app did not request"
1903
+ ));
1904
+ return;
1905
+ }
1906
+ this.grantedCapabilities = init.context.capabilities;
1907
+ this.initResolve?.(init.context);
1908
+ return;
1909
+ }
1910
+ if (validMessage.type === "SDK_RESPONSE" || validMessage.type === "SDK_EVENT" || validMessage.type === "SDK_CONTEXT_UPDATE" || validMessage.type === "SDK_DESTROY") {
1911
+ if (validMessage.type === "SDK_CONTEXT_UPDATE") {
1912
+ const next = validMessage.context.capabilities;
1913
+ if (next.some((capability) => !this.grantedCapabilities.includes(capability))) return;
1914
+ this.grantedCapabilities = next;
1915
+ }
1916
+ for (const handler of [...this.handlers]) {
1917
+ handler(validMessage);
1918
+ }
1919
+ }
1920
+ };
1921
+ };
1922
+
1923
+ // src/index.ts
1924
+ function createTransport(options) {
1925
+ if (options.transport) return options.transport;
1926
+ const bridgeOptions = options.targetOrigin === void 0 ? {} : { targetOrigin: options.targetOrigin };
1927
+ return new HostBridgeTransport(bridgeOptions);
1928
+ }
1929
+ var Usion = Object.freeze({
1930
+ version: SDK_VERSION,
1931
+ async init(options = {}) {
1932
+ const transport = createTransport(options);
1933
+ try {
1934
+ const startOptions = {
1935
+ timeoutMs: options.timeoutMs ?? 1e4,
1936
+ capabilities: options.capabilities ?? SDK_CAPABILITIES,
1937
+ ...options.signal === void 0 ? {} : { signal: options.signal }
1938
+ };
1939
+ const context = await transport.start(startOptions);
1940
+ return new UsionClient(context, transport);
1941
+ } catch (error) {
1942
+ transport.destroy();
1943
+ throw error;
1944
+ }
1945
+ }
1946
+ });
1947
+ var src_default = Usion;
1948
+ export {
1949
+ ERROR_CODES,
1950
+ Usion,
1951
+ UsionClient,
1952
+ UsionError,
1953
+ src_default as default
1954
+ };
1955
+ //# sourceMappingURL=index.js.map