@series-inc/venus-sdk 2.6.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,9 +1,243 @@
1
1
  'use strict';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
7
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
5
24
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
25
 
26
+ // src/rooms/RoomsApi.ts
27
+ var init_RoomsApi = __esm({
28
+ "src/rooms/RoomsApi.ts"() {
29
+ }
30
+ });
31
+
32
+ // src/rooms/VenusRoom.ts
33
+ exports.VenusRoom = void 0;
34
+ var init_VenusRoom = __esm({
35
+ "src/rooms/VenusRoom.ts"() {
36
+ exports.VenusRoom = class {
37
+ constructor(roomData) {
38
+ __publicField(this, "id");
39
+ __publicField(this, "name");
40
+ __publicField(this, "players");
41
+ __publicField(this, "maxPlayers");
42
+ __publicField(this, "gameType");
43
+ __publicField(this, "appId");
44
+ __publicField(this, "type");
45
+ __publicField(this, "createdBy");
46
+ __publicField(this, "createdAt");
47
+ __publicField(this, "updatedAt");
48
+ __publicField(this, "isPrivate");
49
+ __publicField(this, "currentPlayers");
50
+ __publicField(this, "status");
51
+ __publicField(this, "customMetadata");
52
+ __publicField(this, "admins");
53
+ __publicField(this, "roomCode");
54
+ __publicField(this, "description");
55
+ __publicField(this, "data");
56
+ __publicField(this, "version");
57
+ __publicField(this, "_subscriptions", /* @__PURE__ */ new Map());
58
+ this.id = roomData.id;
59
+ this.name = roomData.name;
60
+ this.players = roomData.currentPlayers || [];
61
+ this.maxPlayers = roomData.maxPlayers;
62
+ this.gameType = roomData.gameType;
63
+ this.appId = roomData.appId;
64
+ this.type = roomData.type;
65
+ this.createdBy = roomData.createdBy;
66
+ this.createdAt = roomData.createdAt;
67
+ this.updatedAt = roomData.updatedAt;
68
+ this.isPrivate = roomData.isPrivate;
69
+ this.currentPlayers = roomData.currentPlayers || [];
70
+ this.status = roomData.status;
71
+ this.customMetadata = roomData.customMetadata || {};
72
+ this.admins = roomData.admins || [];
73
+ this.roomCode = roomData.roomCode;
74
+ this.description = roomData.description;
75
+ this.data = roomData.data || {};
76
+ this.version = roomData.version;
77
+ console.log(`VenusRoom: Created room object for ${this.id}`, {
78
+ hasCustomMetadata: !!this.customMetadata,
79
+ hasGameState: !!this.customMetadata?.rules?.gameState,
80
+ gamePhase: this.customMetadata?.rules?.gameState?.phase,
81
+ currentPlayer: this.customMetadata?.rules?.gameState?.currentPlayer
82
+ });
83
+ }
84
+ updateFromRoomData(newRoomData) {
85
+ if (newRoomData.id === this.id) {
86
+ this.name = newRoomData.name || this.name;
87
+ this.players = newRoomData.currentPlayers || this.players;
88
+ this.maxPlayers = newRoomData.maxPlayers || this.maxPlayers;
89
+ this.gameType = newRoomData.gameType || this.gameType;
90
+ this.currentPlayers = newRoomData.currentPlayers || this.currentPlayers;
91
+ this.customMetadata = newRoomData.customMetadata || this.customMetadata;
92
+ this.data = newRoomData.data || this.data;
93
+ this.status = newRoomData.status || this.status;
94
+ this.updatedAt = newRoomData.updatedAt || this.updatedAt;
95
+ console.log(`VenusRoom: Updated room object ${this.id} with fresh data`, {
96
+ hasCustomMetadata: !!this.customMetadata,
97
+ hasGameState: !!this.customMetadata?.rules?.gameState,
98
+ gamePhase: this.customMetadata?.rules?.gameState?.phase,
99
+ currentPlayer: this.customMetadata?.rules?.gameState?.currentPlayer
100
+ });
101
+ }
102
+ }
103
+ };
104
+ }
105
+ });
106
+
107
+ // src/rooms/index.ts
108
+ var rooms_exports = {};
109
+ __export(rooms_exports, {
110
+ VenusRoom: () => exports.VenusRoom,
111
+ initializeRoomsApi: () => initializeRoomsApi,
112
+ setupRoomNotifications: () => setupRoomNotifications
113
+ });
114
+ function bindMethod(target, targetKey, source, sourceKey) {
115
+ const key = sourceKey ?? targetKey;
116
+ const fn = source?.[key];
117
+ if (typeof fn === "function") {
118
+ target[targetKey] = fn.bind(source);
119
+ return true;
120
+ }
121
+ return false;
122
+ }
123
+ function setupRoomNotifications(transport, getSubscriptions) {
124
+ console.log("[Venus Rooms] Setting up room notification listeners");
125
+ return transport.onVenusMessage((message) => {
126
+ const subscriptions = getSubscriptions();
127
+ if (!subscriptions) {
128
+ return;
129
+ }
130
+ if (message.type === "H5_ROOM_DATA_UPDATED") {
131
+ const messageData = message.data;
132
+ const { roomId, roomData } = messageData;
133
+ if (!roomId) return;
134
+ const callbacks = subscriptions.data?.[roomId] || [];
135
+ const allEventsCallbacks = subscriptions.allEvents?.[roomId] || [];
136
+ console.log(`[Venus Rooms] \u{1F514} Room data updated for ${roomId}, notifying ${callbacks.length} callbacks`, roomData);
137
+ callbacks.forEach((callback) => {
138
+ try {
139
+ callback(roomData);
140
+ } catch (error) {
141
+ console.error("[Venus Rooms] Error in room data callback:", error);
142
+ throw error;
143
+ }
144
+ });
145
+ allEventsCallbacks.forEach((callback) => {
146
+ try {
147
+ callback({ type: message.type, ...messageData });
148
+ } catch (error) {
149
+ console.error("[Venus Rooms] Error in allEvents callback:", error);
150
+ throw error;
151
+ }
152
+ });
153
+ }
154
+ if (message.type === "H5_ROOM_MESSAGE_RECEIVED" || message.type === "H5_ROOM_MESSAGE_UPDATED" || message.type === "H5_ROOM_MESSAGE_DELETED") {
155
+ const messageData = message.data;
156
+ const { roomId } = messageData;
157
+ if (!roomId) return;
158
+ const callbacks = subscriptions.messages?.[roomId] || [];
159
+ const allEventsCallbacks = subscriptions.allEvents?.[roomId] || [];
160
+ console.log(`[Venus Rooms] \u{1F514} Room message event for ${roomId}, notifying ${callbacks.length} callbacks`);
161
+ callbacks.forEach((callback) => {
162
+ try {
163
+ callback(messageData);
164
+ } catch (error) {
165
+ console.error("[Venus Rooms] Error in room message callback:", error);
166
+ throw error;
167
+ }
168
+ });
169
+ allEventsCallbacks.forEach((callback) => {
170
+ try {
171
+ callback({ type: message.type, ...messageData });
172
+ } catch (error) {
173
+ console.error("[Venus Rooms] Error in allEvents callback:", error);
174
+ throw error;
175
+ }
176
+ });
177
+ }
178
+ if (message.type === "app:h5:proposedMoveValidationUpdated") {
179
+ const messageData = message.data;
180
+ const { roomId } = messageData;
181
+ if (!roomId) return;
182
+ const callbacks = subscriptions.gameEvents?.[roomId] || [];
183
+ const allEventsCallbacks = subscriptions.allEvents?.[roomId] || [];
184
+ console.log(`[Venus Rooms] \u{1F514} Proposed move validation updated for ${roomId}, notifying ${callbacks.length} callbacks`);
185
+ callbacks.forEach((callback) => {
186
+ try {
187
+ callback(messageData);
188
+ } catch (error) {
189
+ console.error("[Venus Rooms] Error in game event callback:", error);
190
+ throw error;
191
+ }
192
+ });
193
+ allEventsCallbacks.forEach((callback) => {
194
+ try {
195
+ callback({ type: message.type, ...messageData });
196
+ } catch (error) {
197
+ console.error("[Venus Rooms] Error in allEvents callback:", error);
198
+ throw error;
199
+ }
200
+ });
201
+ }
202
+ });
203
+ }
204
+ function initializeRoomsApi(venusApi, host) {
205
+ const roomsApi = host?.rooms;
206
+ if (!roomsApi) {
207
+ console.warn(
208
+ "[Venus SDK] Host did not provide a rooms implementation. Rooms API will be unavailable."
209
+ );
210
+ return;
211
+ }
212
+ const venus = venusApi;
213
+ const existingNamespace = venus.rooms || {};
214
+ const roomsNamespace = Object.assign({}, existingNamespace);
215
+ const namespaceBindings = [
216
+ ["create", "createRoom"],
217
+ ["joinOrCreate", "joinOrCreateRoom"],
218
+ ["joinByCode", "joinRoomByCode"],
219
+ ["list", "getUserRooms"],
220
+ ["subscribeToRoom", "subscribe"],
221
+ ["updateRoomData", "updateData"],
222
+ ["getRoomData", "getData"],
223
+ ["sendRoomMessage", "sendMessage"],
224
+ ["leaveRoom", "leave"],
225
+ ["startRoomGame", "startGame"],
226
+ ["proposeMove"],
227
+ ["validateMove"]
228
+ ];
229
+ namespaceBindings.forEach(([targetKey, sourceKey]) => {
230
+ bindMethod(roomsNamespace, targetKey, roomsApi, sourceKey);
231
+ });
232
+ venus.rooms = roomsNamespace;
233
+ }
234
+ var init_rooms = __esm({
235
+ "src/rooms/index.ts"() {
236
+ init_RoomsApi();
237
+ init_VenusRoom();
238
+ }
239
+ });
240
+
7
241
  // src/VenusMessageId.ts
8
242
  var VenusMessageId = /* @__PURE__ */ ((VenusMessageId2) => {
9
243
  VenusMessageId2["H5_RESPONSE"] = "H5_RESPONSE";
@@ -54,7 +288,8 @@ var VenusMessageId = /* @__PURE__ */ ((VenusMessageId2) => {
54
288
  VenusMessageId2["TOGGLE_LIKE"] = "H5_TOGGLE_LIKE";
55
289
  VenusMessageId2["OPEN_COMMENTS"] = "H5_OPEN_COMMENTS";
56
290
  VenusMessageId2["TOGGLE_FOLLOW"] = "H5_TOGGLE_FOLLOW";
57
- VenusMessageId2["SHARE_POST"] = "H5_SHARE_POST";
291
+ VenusMessageId2["SHARE_LINK"] = "H5_SHARE_LINK";
292
+ VenusMessageId2["CREATE_SHARE_QRCODE"] = "H5_CREATE_SHARE_QRCODE";
58
293
  VenusMessageId2["AI_CHAT_COMPLETION"] = "H5_AI_CHAT_COMPLETION";
59
294
  VenusMessageId2["AI_GET_AVAILABLE_MODELS"] = "H5_AI_GET_AVAILABLE_MODELS";
60
295
  VenusMessageId2["TRIGGER_HAPTIC"] = "H5_TRIGGER_HAPTIC";
@@ -66,13 +301,11 @@ var VenusMessageId = /* @__PURE__ */ ((VenusMessageId2) => {
66
301
  VenusMessageId2["IAP_WALLET_UPDATE"] = "IAP_WALLET_UPDATE";
67
302
  VenusMessageId2["READY"] = "READY";
68
303
  VenusMessageId2["INIT_SDK"] = "INITIALIZE_SDK";
69
- VenusMessageId2["PLAY"] = "PLAY";
70
304
  VenusMessageId2["PAUSE"] = "PAUSE";
71
305
  VenusMessageId2["RESUME"] = "RESUME";
72
- VenusMessageId2["SHOWN"] = "SHOWN";
73
- VenusMessageId2["HIDDEN"] = "HIDDEN";
306
+ VenusMessageId2["AWAKE"] = "AWAKE";
307
+ VenusMessageId2["SLEEP"] = "SLEEP";
74
308
  VenusMessageId2["QUIT"] = "QUIT";
75
- VenusMessageId2["CLEANUP"] = "CLEANUP";
76
309
  VenusMessageId2["GET_EXPERIMENT"] = "H5_GET_EXPERIMENT";
77
310
  VenusMessageId2["GET_FEATURE_FLAG"] = "H5_GET_FEATURE_FLAG";
78
311
  VenusMessageId2["GET_FEATURE_GATE"] = "H5_GET_FEATURE_GATE";
@@ -96,6 +329,11 @@ var VenusMessageId = /* @__PURE__ */ ((VenusMessageId2) => {
96
329
  VenusMessageId2["H5_SIMULATION_GET_AVAILABLE_ITEMS"] = "H5_SIMULATION_GET_AVAILABLE_ITEMS";
97
330
  VenusMessageId2["H5_SIMULATION_VALIDATE_ASSIGNMENT"] = "H5_SIMULATION_VALIDATE_ASSIGNMENT";
98
331
  VenusMessageId2["H5_SIMULATION_BATCH_OPERATIONS"] = "H5_SIMULATION_BATCH_OPERATIONS";
332
+ VenusMessageId2["H5_LEADERBOARD_START_RUN"] = "H5_LEADERBOARD_START_RUN";
333
+ VenusMessageId2["H5_LEADERBOARD_SUBMIT_SCORE"] = "H5_LEADERBOARD_SUBMIT_SCORE";
334
+ VenusMessageId2["H5_LEADERBOARD_GET"] = "H5_LEADERBOARD_GET";
335
+ VenusMessageId2["H5_LEADERBOARD_GET_HIGHLIGHT"] = "H5_LEADERBOARD_GET_HIGHLIGHT";
336
+ VenusMessageId2["H5_LEADERBOARD_GET_PLAYER_STATS"] = "H5_LEADERBOARD_GET_PLAYER_STATS";
99
337
  VenusMessageId2["H5_ROOM_CREATE"] = "H5_ROOM_CREATE";
100
338
  VenusMessageId2["H5_ROOM_JOIN"] = "H5_ROOM_JOIN";
101
339
  VenusMessageId2["H5_ROOM_JOIN_OR_CREATE"] = "H5_ROOM_JOIN_OR_CREATE";
@@ -134,11 +372,11 @@ var RpcAdsApi = class {
134
372
  __publicField(this, "rpcClient");
135
373
  this.rpcClient = rpcClient;
136
374
  }
137
- async showInterstitialAd() {
375
+ async showInterstitialAd(options) {
138
376
  console.log(`[Venus SDK] [RpcAdsApi] showInterstitialAd`);
139
377
  const response = await this.rpcClient.call(
140
378
  "H5_SHOW_INTERSTITIAL_AD" /* SHOW_INTERSTITIAL_AD */,
141
- {},
379
+ options || {},
142
380
  -1
143
381
  );
144
382
  return response.shown;
@@ -150,11 +388,11 @@ var RpcAdsApi = class {
150
388
  );
151
389
  return response.ready;
152
390
  }
153
- async showRewardedAdAsync() {
391
+ async showRewardedAdAsync(options) {
154
392
  console.log("[Venus SDK] [RpcAdsApi] showRewardedAdAsync");
155
393
  const result = await this.rpcClient.call(
156
394
  "H5_SHOW_REWARDED_AD" /* SHOW_REWARDED_AD */,
157
- {},
395
+ options || {},
158
396
  -1
159
397
  );
160
398
  const resultAsString = JSON.stringify(result, null, 2);
@@ -189,15 +427,15 @@ var MockAdsApi = class {
189
427
  await createMockDelay(MOCK_DELAYS.short);
190
428
  return true;
191
429
  }
192
- async showRewardedAdAsync() {
430
+ async showRewardedAdAsync(options) {
193
431
  this.log("[MockAdsApi] showRewardedAdAsync called");
194
- await this.mockOverlay.showAdOverlay();
432
+ await this.mockOverlay.showAdOverlay(options);
195
433
  this.log("[MockAdsApi] Rewarded ad completed");
196
434
  return true;
197
435
  }
198
- async showInterstitialAd() {
436
+ async showInterstitialAd(options) {
199
437
  this.log(`[MockAdsApi] showInterstitialAd`);
200
- await this.mockOverlay.showAdOverlay();
438
+ await this.mockOverlay.showAdOverlay(options);
201
439
  this.log("[MockAdsApi] interstitial ad shown");
202
440
  return true;
203
441
  }
@@ -1246,59 +1484,73 @@ function initializeIap(venusApiInstance, host) {
1246
1484
  // src/lifecycles/MockLifecycleApi.ts
1247
1485
  var MockLifecycleApi = class {
1248
1486
  constructor() {
1249
- __publicField(this, "playCallbacks", []);
1250
- __publicField(this, "pauseCallbacks", []);
1251
- __publicField(this, "resumeCallbacks", []);
1252
- __publicField(this, "quitCallbacks", []);
1253
- __publicField(this, "showCallbacks", []);
1254
- __publicField(this, "hideCallbacks", []);
1255
- }
1256
- onCleanup(callback) {
1257
- }
1258
- onShow(callback) {
1259
- this.showCallbacks.push(callback);
1487
+ __publicField(this, "pauseCallbacks", /* @__PURE__ */ new Set());
1488
+ __publicField(this, "resumeCallbacks", /* @__PURE__ */ new Set());
1489
+ __publicField(this, "awakeCallbacks", /* @__PURE__ */ new Set());
1490
+ __publicField(this, "sleepCallbacks", /* @__PURE__ */ new Set());
1491
+ __publicField(this, "quitCallbacks", /* @__PURE__ */ new Set());
1492
+ }
1493
+ onSleep(callback) {
1494
+ this.sleepCallbacks.add(callback);
1495
+ return {
1496
+ unsubscribe: () => {
1497
+ this.sleepCallbacks.delete(callback);
1498
+ }
1499
+ };
1260
1500
  }
1261
- onHide(callback) {
1262
- this.hideCallbacks.push(callback);
1501
+ onAwake(callback) {
1502
+ this.awakeCallbacks.add(callback);
1503
+ return {
1504
+ unsubscribe: () => {
1505
+ this.awakeCallbacks.delete(callback);
1506
+ }
1507
+ };
1263
1508
  }
1264
1509
  onPause(callback) {
1265
- this.pauseCallbacks.push(callback);
1266
- }
1267
- onPlay(callback) {
1268
- this.playCallbacks.push(callback);
1269
- }
1270
- onQuit(callback) {
1271
- this.quitCallbacks.push(callback);
1510
+ this.pauseCallbacks.add(callback);
1511
+ return {
1512
+ unsubscribe: () => {
1513
+ this.pauseCallbacks.delete(callback);
1514
+ }
1515
+ };
1272
1516
  }
1273
1517
  onResume(callback) {
1274
- this.resumeCallbacks.push(callback);
1518
+ this.resumeCallbacks.add(callback);
1519
+ return {
1520
+ unsubscribe: () => {
1521
+ this.resumeCallbacks.delete(callback);
1522
+ }
1523
+ };
1275
1524
  }
1276
- triggerOnPlayCallbacks(context) {
1277
- for (const callback of this.playCallbacks) {
1278
- callback(context);
1279
- }
1525
+ onQuit(callback) {
1526
+ this.quitCallbacks.add(callback);
1527
+ return {
1528
+ unsubscribe: () => {
1529
+ this.quitCallbacks.delete(callback);
1530
+ }
1531
+ };
1280
1532
  }
1281
- triggerOnPauseCallbacks() {
1533
+ triggerPauseCallbacks() {
1282
1534
  for (const callback of this.pauseCallbacks) {
1283
1535
  callback();
1284
1536
  }
1285
1537
  }
1286
- triggerOnResumeCallbacks() {
1538
+ triggerResumeCallbacks() {
1287
1539
  for (const callback of this.resumeCallbacks) {
1288
1540
  callback();
1289
1541
  }
1290
1542
  }
1291
- triggerOnShowCallbacks(context) {
1292
- for (const callback of this.showCallbacks) {
1293
- callback(context);
1543
+ triggerAwakeCallbacks() {
1544
+ for (const callback of this.awakeCallbacks) {
1545
+ callback();
1294
1546
  }
1295
1547
  }
1296
- triggerOnHideCallbacks() {
1297
- for (const callback of this.hideCallbacks) {
1548
+ triggerSleepCallbacks() {
1549
+ for (const callback of this.sleepCallbacks) {
1298
1550
  callback();
1299
1551
  }
1300
1552
  }
1301
- triggerOnQuitCallbacks() {
1553
+ triggerQuitCallbacks() {
1302
1554
  for (const callback of this.quitCallbacks) {
1303
1555
  callback();
1304
1556
  }
@@ -1311,52 +1563,26 @@ var RpcLifecycleApi = class {
1311
1563
  __publicField(this, "rpcClient");
1312
1564
  this.rpcClient = rpcClient;
1313
1565
  }
1314
- onCleanup(callback) {
1315
- this.rpcClient.onNotification("CLEANUP" /* CLEANUP */, callback);
1316
- }
1317
- onHide(callback) {
1318
- this.rpcClient.onNotification("HIDDEN" /* HIDDEN */, callback);
1319
- }
1320
- onPause(callback) {
1321
- this.rpcClient.onNotification("PAUSE" /* PAUSE */, callback);
1566
+ onQuit(callback) {
1567
+ return this.rpcClient.onNotification("QUIT" /* QUIT */, callback);
1322
1568
  }
1323
- onPlay(callback) {
1324
- this.rpcClient.onNotification("PLAY" /* PLAY */, callback);
1569
+ onSleep(callback) {
1570
+ return this.rpcClient.onNotification("SLEEP" /* SLEEP */, callback);
1325
1571
  }
1326
- onQuit(callback) {
1327
- this.rpcClient.onNotification("QUIT" /* QUIT */, callback);
1572
+ onAwake(callback) {
1573
+ return this.rpcClient.onNotification("AWAKE" /* AWAKE */, callback);
1328
1574
  }
1329
1575
  onResume(callback) {
1330
- this.rpcClient.onNotification("RESUME" /* RESUME */, callback);
1576
+ return this.rpcClient.onNotification("RESUME" /* RESUME */, callback);
1331
1577
  }
1332
- onShow(callback) {
1333
- this.rpcClient.onNotification("SHOWN" /* SHOWN */, callback);
1578
+ onPause(callback) {
1579
+ return this.rpcClient.onNotification("PAUSE" /* PAUSE */, callback);
1334
1580
  }
1335
1581
  };
1336
1582
 
1337
1583
  // src/lifecycles/index.ts
1338
1584
  function initializeLifecycleApi(venusApi, host) {
1339
- venusApi.onPlay = (callback) => {
1340
- host.lifecycle.onPlay(callback);
1341
- };
1342
- venusApi.onPause = (callback) => {
1343
- host.lifecycle.onPause(callback);
1344
- };
1345
- venusApi.onResume = (callback) => {
1346
- host.lifecycle.onResume(callback);
1347
- };
1348
- venusApi.onShow = (callback) => {
1349
- host.lifecycle.onShow(callback);
1350
- };
1351
- venusApi.onHide = (callback) => {
1352
- host.lifecycle.onHide(callback);
1353
- };
1354
- venusApi.onQuit = (callback) => {
1355
- host.lifecycle.onQuit(callback);
1356
- };
1357
- venusApi.onCleanup = (callback) => {
1358
- host.lifecycle.onCleanup(callback);
1359
- };
1585
+ venusApi.lifecycles = host.lifecycle;
1360
1586
  }
1361
1587
 
1362
1588
  // src/logging/MockLoggingApi.ts
@@ -1604,22 +1830,23 @@ var MockNotificationsApi = class {
1604
1830
  const isEnabled = venusApi._mock.notificationsEnabled !== false;
1605
1831
  return isEnabled;
1606
1832
  }
1607
- async scheduleAsync(options) {
1833
+ async scheduleAsync(title, body, seconds, notificationId, options) {
1834
+ const { priority = 50, groupId, payload } = options || {};
1608
1835
  if (isWebPlatform()) {
1609
1836
  console.log(
1610
1837
  "[Venus Mock] Notifications not supported on web platform, simulating success"
1611
1838
  );
1612
1839
  console.info(
1613
1840
  "\u{1F514} [Venus Mock] Notification would be scheduled:",
1614
- options.title || "Untitled",
1841
+ title || "Untitled",
1615
1842
  "\n Body:",
1616
- options.body || "No body",
1843
+ body || "No body",
1617
1844
  "\n This is a simulation - real notifications require a native platform."
1618
1845
  );
1619
1846
  const mockId = `mock-web-notification-${Date.now()}`;
1620
1847
  return mockId;
1621
1848
  }
1622
- console.log("[Venus Mock] Schedule local notification:", options);
1849
+ console.log("[Venus Mock] Schedule local notification:", { title, body, seconds, options });
1623
1850
  const venusApi = this.venusApi;
1624
1851
  if (!venusApi._mock.pendingRequests) {
1625
1852
  console.log("[Venus Mock] Initializing pendingRequests");
@@ -1629,19 +1856,19 @@ var MockNotificationsApi = class {
1629
1856
  console.log("[Venus Mock] Creating request with ID:", requestId);
1630
1857
  return new Promise((resolve) => {
1631
1858
  venusApi._mock.pendingRequests[requestId] = { resolve };
1632
- const notificationId = `mock-notification-${Date.now()}`;
1859
+ const id = notificationId || `mock-notification-${Date.now()}`;
1633
1860
  if (!venusApi._mock.scheduledNotifications) {
1634
1861
  venusApi._mock.scheduledNotifications = {};
1635
1862
  }
1636
- venusApi._mock.scheduledNotifications[notificationId] = {
1637
- id: notificationId,
1638
- title: options.title,
1639
- body: options.body,
1640
- payload: options.payload,
1641
- trigger: options.trigger
1863
+ venusApi._mock.scheduledNotifications[id] = {
1864
+ id,
1865
+ title,
1866
+ body,
1867
+ payload,
1868
+ seconds
1642
1869
  };
1643
1870
  setTimeout(() => {
1644
- resolve(notificationId);
1871
+ resolve(id);
1645
1872
  }, MOCK_DELAYS.short);
1646
1873
  });
1647
1874
  }
@@ -1667,14 +1894,16 @@ var RpcNotificationsApi = class {
1667
1894
  __publicField(this, "rpcClient");
1668
1895
  this.rpcClient = rpcClient;
1669
1896
  }
1670
- async scheduleAsync(options) {
1897
+ async scheduleAsync(title, body, seconds, notificationId, options) {
1898
+ const { priority = 50, groupId, payload } = options || {};
1671
1899
  const request = {
1672
- title: options.title,
1673
- body: options.body,
1674
- data: options.payload,
1675
- key: options.groupId,
1676
- priority: options.priority || 1,
1677
- trigger: options.trigger
1900
+ title,
1901
+ body,
1902
+ priority,
1903
+ key: groupId,
1904
+ data: payload,
1905
+ seconds,
1906
+ notificationId
1678
1907
  };
1679
1908
  const response = await this.rpcClient.call(
1680
1909
  "H5_SCHEDULE_LOCAL_NOTIFICATION" /* SCHEDULE_LOCAL_NOTIFICATION */,
@@ -2020,236 +2249,47 @@ var RpcClient = class {
2020
2249
  }
2021
2250
  };
2022
2251
 
2023
- // src/rooms/VenusRoom.ts
2024
- var VenusRoom = class {
2025
- constructor(roomData) {
2026
- __publicField(this, "id");
2027
- __publicField(this, "name");
2028
- __publicField(this, "players");
2029
- __publicField(this, "maxPlayers");
2030
- __publicField(this, "gameType");
2031
- __publicField(this, "appId");
2032
- __publicField(this, "type");
2033
- __publicField(this, "createdBy");
2034
- __publicField(this, "createdAt");
2035
- __publicField(this, "updatedAt");
2036
- __publicField(this, "isPrivate");
2037
- __publicField(this, "currentPlayers");
2038
- __publicField(this, "status");
2039
- __publicField(this, "customMetadata");
2040
- __publicField(this, "admins");
2041
- __publicField(this, "roomCode");
2042
- __publicField(this, "description");
2043
- __publicField(this, "data");
2044
- __publicField(this, "version");
2045
- __publicField(this, "_subscriptions", /* @__PURE__ */ new Map());
2046
- this.id = roomData.id;
2047
- this.name = roomData.name;
2048
- this.players = roomData.currentPlayers || [];
2049
- this.maxPlayers = roomData.maxPlayers;
2050
- this.gameType = roomData.gameType;
2051
- this.appId = roomData.appId;
2052
- this.type = roomData.type;
2053
- this.createdBy = roomData.createdBy;
2054
- this.createdAt = roomData.createdAt;
2055
- this.updatedAt = roomData.updatedAt;
2056
- this.isPrivate = roomData.isPrivate;
2057
- this.currentPlayers = roomData.currentPlayers || [];
2058
- this.status = roomData.status;
2059
- this.customMetadata = roomData.customMetadata || {};
2060
- this.admins = roomData.admins || [];
2061
- this.roomCode = roomData.roomCode;
2062
- this.description = roomData.description;
2063
- this.data = roomData.data || {};
2064
- this.version = roomData.version;
2065
- console.log(`VenusRoom: Created room object for ${this.id}`, {
2066
- hasCustomMetadata: !!this.customMetadata,
2067
- hasGameState: !!this.customMetadata?.rules?.gameState,
2068
- gamePhase: this.customMetadata?.rules?.gameState?.phase,
2069
- currentPlayer: this.customMetadata?.rules?.gameState?.currentPlayer
2070
- });
2071
- }
2072
- updateFromRoomData(newRoomData) {
2073
- if (newRoomData.id === this.id) {
2074
- this.name = newRoomData.name || this.name;
2075
- this.players = newRoomData.currentPlayers || this.players;
2076
- this.maxPlayers = newRoomData.maxPlayers || this.maxPlayers;
2077
- this.gameType = newRoomData.gameType || this.gameType;
2078
- this.currentPlayers = newRoomData.currentPlayers || this.currentPlayers;
2079
- this.customMetadata = newRoomData.customMetadata || this.customMetadata;
2080
- this.data = newRoomData.data || this.data;
2081
- this.status = newRoomData.status || this.status;
2082
- this.updatedAt = newRoomData.updatedAt || this.updatedAt;
2083
- console.log(`VenusRoom: Updated room object ${this.id} with fresh data`, {
2084
- hasCustomMetadata: !!this.customMetadata,
2085
- hasGameState: !!this.customMetadata?.rules?.gameState,
2086
- gamePhase: this.customMetadata?.rules?.gameState?.phase,
2087
- currentPlayer: this.customMetadata?.rules?.gameState?.currentPlayer
2088
- });
2089
- }
2090
- }
2091
- };
2252
+ // src/index.ts
2253
+ init_rooms();
2092
2254
 
2093
- // src/rooms/index.ts
2094
- function bindMethod(target, targetKey, source, sourceKey) {
2095
- const key = sourceKey ?? targetKey;
2096
- const fn = source?.[key];
2097
- if (typeof fn === "function") {
2098
- target[targetKey] = fn.bind(source);
2099
- return true;
2255
+ // src/storage/MockStorageApi.ts
2256
+ function createMockStorageApi(storageType, appUrl) {
2257
+ const appIdentifier = appUrl ? generateAppIdentifier(appUrl) : null;
2258
+ let prefix;
2259
+ let syncDelay = 0;
2260
+ switch (storageType) {
2261
+ case "deviceCache":
2262
+ prefix = "venus:app";
2263
+ syncDelay = 0;
2264
+ break;
2265
+ case "appStorage":
2266
+ prefix = "venus:app";
2267
+ syncDelay = 100;
2268
+ break;
2269
+ case "globalStorage":
2270
+ prefix = "venus:global";
2271
+ syncDelay = 100;
2272
+ break;
2273
+ default:
2274
+ throw new Error(`Unknown storage type: ${storageType}`);
2100
2275
  }
2101
- return false;
2276
+ prefix = storageType === "globalStorage" || !appIdentifier ? `${prefix}:` : `${prefix}:${appIdentifier}:`;
2277
+ return new MockStorageApi(prefix, syncDelay);
2102
2278
  }
2103
- function setupRoomNotifications(transport, getSubscriptions) {
2104
- console.log("[Venus Rooms] Setting up room notification listeners");
2105
- return transport.onVenusMessage((message) => {
2106
- const subscriptions = getSubscriptions();
2107
- if (!subscriptions) {
2108
- return;
2109
- }
2110
- if (message.type === "H5_ROOM_DATA_UPDATED") {
2111
- const messageData = message.data;
2112
- const { roomId, roomData } = messageData;
2113
- if (!roomId) return;
2114
- const callbacks = subscriptions.data?.[roomId] || [];
2115
- const allEventsCallbacks = subscriptions.allEvents?.[roomId] || [];
2116
- console.log(`[Venus Rooms] \u{1F514} Room data updated for ${roomId}, notifying ${callbacks.length} callbacks`, roomData);
2117
- callbacks.forEach((callback) => {
2118
- try {
2119
- callback(roomData);
2120
- } catch (error) {
2121
- console.error("[Venus Rooms] Error in room data callback:", error);
2122
- throw error;
2123
- }
2124
- });
2125
- allEventsCallbacks.forEach((callback) => {
2126
- try {
2127
- callback({ type: message.type, ...messageData });
2128
- } catch (error) {
2129
- console.error("[Venus Rooms] Error in allEvents callback:", error);
2130
- throw error;
2131
- }
2132
- });
2133
- }
2134
- if (message.type === "H5_ROOM_MESSAGE_RECEIVED" || message.type === "H5_ROOM_MESSAGE_UPDATED" || message.type === "H5_ROOM_MESSAGE_DELETED") {
2135
- const messageData = message.data;
2136
- const { roomId } = messageData;
2137
- if (!roomId) return;
2138
- const callbacks = subscriptions.messages?.[roomId] || [];
2139
- const allEventsCallbacks = subscriptions.allEvents?.[roomId] || [];
2140
- console.log(`[Venus Rooms] \u{1F514} Room message event for ${roomId}, notifying ${callbacks.length} callbacks`);
2141
- callbacks.forEach((callback) => {
2142
- try {
2143
- callback(messageData);
2144
- } catch (error) {
2145
- console.error("[Venus Rooms] Error in room message callback:", error);
2146
- throw error;
2147
- }
2148
- });
2149
- allEventsCallbacks.forEach((callback) => {
2150
- try {
2151
- callback({ type: message.type, ...messageData });
2152
- } catch (error) {
2153
- console.error("[Venus Rooms] Error in allEvents callback:", error);
2154
- throw error;
2155
- }
2156
- });
2157
- }
2158
- if (message.type === "app:h5:proposedMoveValidationUpdated") {
2159
- const messageData = message.data;
2160
- const { roomId } = messageData;
2161
- if (!roomId) return;
2162
- const callbacks = subscriptions.gameEvents?.[roomId] || [];
2163
- const allEventsCallbacks = subscriptions.allEvents?.[roomId] || [];
2164
- console.log(`[Venus Rooms] \u{1F514} Proposed move validation updated for ${roomId}, notifying ${callbacks.length} callbacks`);
2165
- callbacks.forEach((callback) => {
2166
- try {
2167
- callback(messageData);
2168
- } catch (error) {
2169
- console.error("[Venus Rooms] Error in game event callback:", error);
2170
- throw error;
2171
- }
2172
- });
2173
- allEventsCallbacks.forEach((callback) => {
2174
- try {
2175
- callback({ type: message.type, ...messageData });
2176
- } catch (error) {
2177
- console.error("[Venus Rooms] Error in allEvents callback:", error);
2178
- throw error;
2179
- }
2180
- });
2181
- }
2182
- });
2183
- }
2184
- function initializeRoomsApi(venusApi, host) {
2185
- const roomsApi = host?.rooms;
2186
- if (!roomsApi) {
2187
- console.warn(
2188
- "[Venus SDK] Host did not provide a rooms implementation. Rooms API will be unavailable."
2189
- );
2190
- return;
2191
- }
2192
- const venus = venusApi;
2193
- const existingNamespace = venus.rooms || {};
2194
- const roomsNamespace = Object.assign({}, existingNamespace);
2195
- const namespaceBindings = [
2196
- ["create", "createRoom"],
2197
- ["joinOrCreate", "joinOrCreateRoom"],
2198
- ["joinByCode", "joinRoomByCode"],
2199
- ["list", "getUserRooms"],
2200
- ["subscribeToRoom", "subscribe"],
2201
- ["updateRoomData", "updateData"],
2202
- ["getRoomData", "getData"],
2203
- ["sendRoomMessage", "sendMessage"],
2204
- ["leaveRoom", "leave"],
2205
- ["startRoomGame", "startGame"],
2206
- ["proposeMove"],
2207
- ["validateMove"]
2208
- ];
2209
- namespaceBindings.forEach(([targetKey, sourceKey]) => {
2210
- bindMethod(roomsNamespace, targetKey, roomsApi, sourceKey);
2211
- });
2212
- venus.rooms = roomsNamespace;
2213
- }
2214
-
2215
- // src/storage/MockStorageApi.ts
2216
- function createMockStorageApi(storageType, appUrl) {
2217
- const appIdentifier = appUrl ? generateAppIdentifier(appUrl) : null;
2218
- let prefix;
2219
- let syncDelay = 0;
2220
- switch (storageType) {
2221
- case "deviceCache":
2222
- prefix = "venus:app";
2223
- syncDelay = 0;
2224
- break;
2225
- case "appStorage":
2226
- prefix = "venus:app";
2227
- syncDelay = 100;
2228
- break;
2229
- case "globalStorage":
2230
- prefix = "venus:global";
2231
- syncDelay = 100;
2232
- break;
2233
- default:
2234
- throw new Error(`Unknown storage type: ${storageType}`);
2235
- }
2236
- prefix = storageType === "globalStorage" || !appIdentifier ? `${prefix}:` : `${prefix}:${appIdentifier}:`;
2237
- return new MockStorageApi(prefix, syncDelay);
2238
- }
2239
- var MockStorageApi = class {
2240
- constructor(prefix, syncDelay) {
2241
- __publicField(this, "prefix");
2242
- __publicField(this, "syncDelay");
2243
- this.prefix = prefix;
2244
- this.syncDelay = syncDelay;
2245
- }
2246
- async clear() {
2247
- const fullLength = localStorage.length;
2248
- for (let i = 0; i < fullLength; i++) {
2249
- const fullKey = localStorage.key(i);
2250
- if (fullKey && fullKey.startsWith(this.prefix)) {
2251
- localStorage.removeItem(fullKey);
2252
- }
2279
+ var MockStorageApi = class {
2280
+ constructor(prefix, syncDelay) {
2281
+ __publicField(this, "prefix");
2282
+ __publicField(this, "syncDelay");
2283
+ this.prefix = prefix;
2284
+ this.syncDelay = syncDelay;
2285
+ }
2286
+ async clear() {
2287
+ const fullLength = localStorage.length;
2288
+ for (let i = 0; i < fullLength; i++) {
2289
+ const fullKey = localStorage.key(i);
2290
+ if (fullKey && fullKey.startsWith(this.prefix)) {
2291
+ localStorage.removeItem(fullKey);
2292
+ }
2253
2293
  }
2254
2294
  await this.simulateSyncDelay();
2255
2295
  }
@@ -3542,7 +3582,7 @@ function initializeTime(venusApi, host) {
3542
3582
  }
3543
3583
 
3544
3584
  // src/version.ts
3545
- var SDK_VERSION = "2.6.2";
3585
+ var SDK_VERSION = "3.0.0";
3546
3586
 
3547
3587
  // src/shared-assets/consts.ts
3548
3588
  var BurgerTimeAssetsCdnPath = "burger-time/Core.stow";
@@ -3613,6 +3653,238 @@ var MockSharedAssetsApi = class {
3613
3653
  }
3614
3654
  };
3615
3655
 
3656
+ // src/leaderboard/RpcLeaderboardApi.ts
3657
+ var RpcLeaderboardApi = class {
3658
+ constructor(rpcClient) {
3659
+ __publicField(this, "rpcClient");
3660
+ this.rpcClient = rpcClient;
3661
+ }
3662
+ startRun(mode) {
3663
+ return this.rpcClient.call(
3664
+ "H5_LEADERBOARD_START_RUN" /* H5_LEADERBOARD_START_RUN */,
3665
+ mode ? { mode } : {}
3666
+ );
3667
+ }
3668
+ submitScore(sessionId, score, durationSec, options) {
3669
+ return this.rpcClient.call(
3670
+ "H5_LEADERBOARD_SUBMIT_SCORE" /* H5_LEADERBOARD_SUBMIT_SCORE */,
3671
+ {
3672
+ sessionId,
3673
+ score,
3674
+ durationSec,
3675
+ mode: options?.mode,
3676
+ telemetry: options?.telemetry,
3677
+ metadata: options?.metadata,
3678
+ hash: options?.hash
3679
+ }
3680
+ );
3681
+ }
3682
+ getLeaderboard(options) {
3683
+ return this.rpcClient.call(
3684
+ "H5_LEADERBOARD_GET" /* H5_LEADERBOARD_GET */,
3685
+ options ?? {}
3686
+ );
3687
+ }
3688
+ getPlayerStats(options) {
3689
+ return this.rpcClient.call(
3690
+ "H5_LEADERBOARD_GET_PLAYER_STATS" /* H5_LEADERBOARD_GET_PLAYER_STATS */,
3691
+ options ?? {}
3692
+ );
3693
+ }
3694
+ getLeaderboardHighlight(options) {
3695
+ return this.rpcClient.call(
3696
+ "H5_LEADERBOARD_GET_HIGHLIGHT" /* H5_LEADERBOARD_GET_HIGHLIGHT */,
3697
+ options ?? {}
3698
+ );
3699
+ }
3700
+ };
3701
+
3702
+ // src/leaderboard/MockLeaderboardApi.ts
3703
+ var MockLeaderboardApi = class {
3704
+ constructor(options) {
3705
+ __publicField(this, "sessions", /* @__PURE__ */ new Map());
3706
+ __publicField(this, "entriesByMode", /* @__PURE__ */ new Map());
3707
+ __publicField(this, "sessionCounter", 0);
3708
+ __publicField(this, "requiresHash", false);
3709
+ if (options?.requiresHash) {
3710
+ this.requiresHash = true;
3711
+ }
3712
+ }
3713
+ configure(options) {
3714
+ if (typeof options.requiresHash === "boolean") {
3715
+ this.requiresHash = options.requiresHash;
3716
+ }
3717
+ }
3718
+ generateNonce() {
3719
+ return (Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)).slice(0, 64);
3720
+ }
3721
+ getModeKey(mode) {
3722
+ const normalizedMode = mode || "default";
3723
+ return `${normalizedMode}`;
3724
+ }
3725
+ getEntriesForMode(mode) {
3726
+ const key = this.getModeKey(mode);
3727
+ if (!this.entriesByMode.has(key)) {
3728
+ this.entriesByMode.set(key, []);
3729
+ }
3730
+ return this.entriesByMode.get(key);
3731
+ }
3732
+ async startRun(mode) {
3733
+ const sessionId = `mock_session_${++this.sessionCounter}`;
3734
+ const startTime = Date.now();
3735
+ const expiresAt = startTime + 36e5;
3736
+ const resolvedMode = mode || "default";
3737
+ const hashNonce = this.requiresHash ? this.generateNonce() : null;
3738
+ this.sessions.set(sessionId, {
3739
+ id: sessionId,
3740
+ expiresAt,
3741
+ mode: resolvedMode,
3742
+ hashNonce,
3743
+ used: false
3744
+ });
3745
+ return {
3746
+ sessionId,
3747
+ startTime,
3748
+ expiresAt,
3749
+ hashNonce,
3750
+ mode: resolvedMode
3751
+ };
3752
+ }
3753
+ async submitScore(sessionId, score, durationSec, options) {
3754
+ const session = this.sessions.get(sessionId);
3755
+ if (!session) {
3756
+ throw new Error("Invalid leaderboard session");
3757
+ }
3758
+ if (session.expiresAt < Date.now()) {
3759
+ throw new Error("Invalid or expired leaderboard session");
3760
+ }
3761
+ if (session.used) {
3762
+ throw new Error("Leaderboard session already used");
3763
+ }
3764
+ if (options?.mode && options.mode !== session.mode) {
3765
+ throw new Error("Submission mode does not match session mode");
3766
+ }
3767
+ if (session.hashNonce && !options?.hash) {
3768
+ throw new Error("Score hash is required for sealed leaderboard submissions");
3769
+ }
3770
+ const submittedAt = Date.now();
3771
+ const entry = {
3772
+ profileId: `mock_profile`,
3773
+ username: "Mock Player",
3774
+ avatarUrl: null,
3775
+ score,
3776
+ durationSec,
3777
+ submittedAt,
3778
+ sessionId,
3779
+ rank: null,
3780
+ zScore: null,
3781
+ isAnomaly: false,
3782
+ trustScore: 50,
3783
+ metadata: options?.metadata ?? null,
3784
+ isSeed: false
3785
+ };
3786
+ const modeEntries = this.getEntriesForMode(session.mode);
3787
+ modeEntries.push(entry);
3788
+ modeEntries.sort((a, b) => {
3789
+ if (b.score !== a.score) {
3790
+ return b.score - a.score;
3791
+ }
3792
+ return a.submittedAt - b.submittedAt;
3793
+ });
3794
+ modeEntries.forEach((e, index) => {
3795
+ modeEntries[index] = {
3796
+ ...e,
3797
+ rank: index + 1
3798
+ };
3799
+ });
3800
+ session.used = true;
3801
+ session.hashNonce = null;
3802
+ const inserted = modeEntries.find((e) => e.sessionId === sessionId && e.submittedAt === submittedAt);
3803
+ return {
3804
+ accepted: true,
3805
+ rank: inserted?.rank ?? null
3806
+ };
3807
+ }
3808
+ async getLeaderboard(options) {
3809
+ const limit = options?.limit ?? 10;
3810
+ const mode = options?.mode ?? "default";
3811
+ const modeEntries = [...this.getEntriesForMode(mode)];
3812
+ const entries = modeEntries.slice(0, limit).map((entry) => ({
3813
+ ...entry
3814
+ }));
3815
+ return {
3816
+ variant: "standard",
3817
+ entries,
3818
+ totalEntries: modeEntries.length,
3819
+ nextCursor: null,
3820
+ playerRank: null,
3821
+ periodInstance: options?.period ?? "alltime"
3822
+ };
3823
+ }
3824
+ async getPlayerStats(_options) {
3825
+ const mode = _options?.mode ?? "default";
3826
+ const modeEntries = this.getEntriesForMode(mode);
3827
+ const playerEntry = modeEntries[0] ?? null;
3828
+ return {
3829
+ rank: playerEntry?.rank ?? null,
3830
+ score: playerEntry?.score,
3831
+ totalPlayers: modeEntries.length,
3832
+ percentile: playerEntry ? Math.max(0, 1 - ((playerEntry.rank ?? 1) - 1) / Math.max(modeEntries.length, 1)) : void 0,
3833
+ trustScore: 50,
3834
+ periodInstance: _options?.period ?? "alltime"
3835
+ };
3836
+ }
3837
+ async getLeaderboardHighlight(options) {
3838
+ const mode = options?.mode ?? "default";
3839
+ const modeEntries = [...this.getEntriesForMode(mode)];
3840
+ const topCount = Math.max(1, Math.min(options?.topCount ?? 3, 10));
3841
+ const aheadCount = Math.max(0, Math.min(options?.contextAhead ?? 4, 10));
3842
+ const behindCount = Math.max(0, Math.min(options?.contextBehind ?? 2, 10));
3843
+ const topEntries = modeEntries.slice(0, topCount);
3844
+ const playerEntry = modeEntries[0] ?? null;
3845
+ const totalEntries = modeEntries.length;
3846
+ let playerRank = playerEntry?.rank ?? null;
3847
+ let beforePlayer = [];
3848
+ let afterPlayer = [];
3849
+ let totalBefore = playerRank ? playerRank - 1 : 0;
3850
+ let totalAfter = playerRank ? Math.max(totalEntries - playerRank, 0) : 0;
3851
+ let omittedBefore = totalBefore;
3852
+ let omittedAfter = totalAfter;
3853
+ if (playerRank && playerRank > 0) {
3854
+ const beforeStart = Math.max(playerRank - aheadCount - 1, 0);
3855
+ beforePlayer = modeEntries.slice(beforeStart, playerRank - 1);
3856
+ const afterEnd = Math.min(playerRank + behindCount, totalEntries);
3857
+ afterPlayer = modeEntries.slice(playerRank, afterEnd);
3858
+ const shownTopAhead = topEntries.filter((entry) => (entry.rank ?? 0) > 0 && (entry.rank ?? 0) < playerRank).length;
3859
+ omittedBefore = Math.max(totalBefore - (beforePlayer.length + shownTopAhead), 0);
3860
+ omittedAfter = Math.max(totalAfter - afterPlayer.length, 0);
3861
+ }
3862
+ return {
3863
+ variant: "highlight",
3864
+ entries: topEntries,
3865
+ totalEntries,
3866
+ nextCursor: null,
3867
+ playerRank: playerRank ?? null,
3868
+ periodInstance: options?.period ?? "alltime",
3869
+ context: {
3870
+ topEntries,
3871
+ beforePlayer,
3872
+ playerEntry: playerEntry ?? null,
3873
+ afterPlayer,
3874
+ totalBefore,
3875
+ totalAfter,
3876
+ omittedBefore,
3877
+ omittedAfter
3878
+ }
3879
+ };
3880
+ }
3881
+ };
3882
+
3883
+ // src/leaderboard/index.ts
3884
+ function initializeLeaderboard(venusApiInstance, host) {
3885
+ venusApiInstance.leaderboard = host.leaderboard;
3886
+ }
3887
+
3616
3888
  // src/game-preloader/MockPreloaderApi.ts
3617
3889
  var MockPreloaderApi = class {
3618
3890
  async showLoadScreen() {
@@ -3654,6 +3926,1384 @@ function initializePreloader(venusApi, host) {
3654
3926
  venusApi.preloader = host.preloader;
3655
3927
  }
3656
3928
 
3929
+ // src/post/MockPostApi.ts
3930
+ var MockPostApi = class {
3931
+ constructor(venusApi) {
3932
+ __publicField(this, "venusApi");
3933
+ this.venusApi = venusApi;
3934
+ }
3935
+ async getPostInfo() {
3936
+ const venusApi = this.venusApi;
3937
+ await createMockDelay(MOCK_DELAYS.short);
3938
+ return venusApi._mock.currentPostInteractions;
3939
+ }
3940
+ async openCommentsAsync() {
3941
+ await createMockDelay(MOCK_DELAYS.short);
3942
+ return {
3943
+ opened: true,
3944
+ commentsCount: 0
3945
+ };
3946
+ }
3947
+ async toggleFollowAsync() {
3948
+ const venusApi = this.venusApi;
3949
+ console.log("[Venus Mock] *Toggling follow status");
3950
+ await createMockDelay(MOCK_DELAYS.short);
3951
+ venusApi._mock.currentPostInteractions.isFollowing = !venusApi._mock.currentPostInteractions.isFollowing;
3952
+ const isFollowing = venusApi._mock.currentPostInteractions.isFollowing;
3953
+ return {
3954
+ isFollowing,
3955
+ action: isFollowing ? "followed" : "unfollowed"
3956
+ };
3957
+ }
3958
+ async toggleLikeAsync() {
3959
+ const venusApi = this.venusApi;
3960
+ await createMockDelay(MOCK_DELAYS.short);
3961
+ venusApi._mock.currentPostInteractions.isLiked = !venusApi._mock.currentPostInteractions.isLiked;
3962
+ const isLiked = venusApi._mock.currentPostInteractions.isLiked;
3963
+ if (isLiked) {
3964
+ venusApi._mock.currentPostInteractions.likesCount++;
3965
+ } else {
3966
+ venusApi._mock.currentPostInteractions.likesCount = Math.max(
3967
+ 0,
3968
+ venusApi._mock.currentPostInteractions.likesCount - 1
3969
+ );
3970
+ }
3971
+ return {
3972
+ isLiked,
3973
+ likesCount: venusApi._mock.currentPostInteractions.likesCount,
3974
+ action: isLiked ? "liked" : "unliked"
3975
+ };
3976
+ }
3977
+ };
3978
+
3979
+ // src/post/RpcPostApi.ts
3980
+ var RpcPostApi = class {
3981
+ constructor(rpcClient) {
3982
+ __publicField(this, "rpcClient");
3983
+ this.rpcClient = rpcClient;
3984
+ }
3985
+ getPostInfo() {
3986
+ return this.rpcClient.call("H5_GET_POST_INTERACTIONS" /* GET_POST_INTERACTIONS */, {});
3987
+ }
3988
+ openCommentsAsync() {
3989
+ return this.rpcClient.call("H5_OPEN_COMMENTS" /* OPEN_COMMENTS */, {});
3990
+ }
3991
+ toggleFollowAsync() {
3992
+ return this.rpcClient.call(
3993
+ "H5_TOGGLE_FOLLOW" /* TOGGLE_FOLLOW */,
3994
+ {}
3995
+ );
3996
+ }
3997
+ toggleLikeAsync() {
3998
+ return this.rpcClient.call("H5_TOGGLE_LIKE" /* TOGGLE_LIKE */, {});
3999
+ }
4000
+ };
4001
+
4002
+ // src/MockHost.ts
4003
+ init_rooms();
4004
+
4005
+ // src/social/MockSocialApi.ts
4006
+ var MOCK_QR_CODE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
4007
+ var MockSocialApi = class {
4008
+ async shareLinkAsync(options) {
4009
+ const shareUrl = this.createMockUrl(options.launchParams);
4010
+ if (typeof navigator !== "undefined" && navigator.clipboard) {
4011
+ try {
4012
+ await navigator.clipboard.writeText(shareUrl);
4013
+ console.log("[Venus SDK] (mock) Copied share URL to clipboard");
4014
+ } catch (error) {
4015
+ console.warn(
4016
+ "[Venus SDK] (mock) Failed to copy share URL to clipboard",
4017
+ error
4018
+ );
4019
+ }
4020
+ }
4021
+ return { shareUrl };
4022
+ }
4023
+ async createQRCodeAsync(options) {
4024
+ const shareUrl = this.createMockUrl(options.launchParams);
4025
+ return {
4026
+ shareUrl,
4027
+ qrCode: MOCK_QR_CODE
4028
+ };
4029
+ }
4030
+ createMockUrl(launchParams) {
4031
+ const params = new URLSearchParams(launchParams);
4032
+ return `https://mock-share.venus.test/share?${params.toString()}`;
4033
+ }
4034
+ };
4035
+
4036
+ // src/MockHost.ts
4037
+ var ROOMS_UNAVAILABLE_MESSAGE = "[Venus SDK] Rooms API is only available when running inside the Venus host environment.";
4038
+ function createUnavailableRoomsApi() {
4039
+ const roomsUnavailableError = () => new Error(ROOMS_UNAVAILABLE_MESSAGE);
4040
+ return {
4041
+ async createRoom() {
4042
+ throw roomsUnavailableError();
4043
+ },
4044
+ async joinOrCreateRoom() {
4045
+ throw roomsUnavailableError();
4046
+ },
4047
+ async getUserRooms() {
4048
+ throw roomsUnavailableError();
4049
+ },
4050
+ async joinRoomByCode() {
4051
+ throw roomsUnavailableError();
4052
+ },
4053
+ subscribe() {
4054
+ throw roomsUnavailableError();
4055
+ },
4056
+ async updateData() {
4057
+ throw roomsUnavailableError();
4058
+ },
4059
+ async getData() {
4060
+ throw roomsUnavailableError();
4061
+ },
4062
+ async sendMessage() {
4063
+ throw roomsUnavailableError();
4064
+ },
4065
+ async leave() {
4066
+ throw roomsUnavailableError();
4067
+ },
4068
+ async startGame() {
4069
+ throw roomsUnavailableError();
4070
+ },
4071
+ async proposeMove() {
4072
+ throw roomsUnavailableError();
4073
+ },
4074
+ async validateMove() {
4075
+ throw roomsUnavailableError();
4076
+ }
4077
+ };
4078
+ }
4079
+ var MockHost = class {
4080
+ constructor(venusApi) {
4081
+ __publicField(this, "ads");
4082
+ __publicField(this, "analytics");
4083
+ __publicField(this, "deviceCache");
4084
+ __publicField(this, "appStorage");
4085
+ __publicField(this, "globalStorage");
4086
+ __publicField(this, "avatar3d");
4087
+ __publicField(this, "navigation");
4088
+ __publicField(this, "notifications");
4089
+ __publicField(this, "popups");
4090
+ __publicField(this, "profile");
4091
+ __publicField(this, "cdn");
4092
+ __publicField(this, "time");
4093
+ __publicField(this, "post");
4094
+ __publicField(this, "ai");
4095
+ __publicField(this, "haptics");
4096
+ __publicField(this, "features");
4097
+ __publicField(this, "lifecycle");
4098
+ __publicField(this, "simulation");
4099
+ __publicField(this, "rooms");
4100
+ __publicField(this, "logging");
4101
+ __publicField(this, "iap");
4102
+ __publicField(this, "leaderboard");
4103
+ __publicField(this, "preloader");
4104
+ __publicField(this, "social");
4105
+ __publicField(this, "state", 0 /* PLAYING */);
4106
+ __publicField(this, "venusApi");
4107
+ __publicField(this, "_isInitialized", false);
4108
+ __publicField(this, "_overlay");
4109
+ __publicField(this, "_mockLifecyclesApi");
4110
+ __publicField(this, "_mockAdsApi");
4111
+ this.venusApi = venusApi;
4112
+ this._overlay = this.createOverlay();
4113
+ this._mockAdsApi = new MockAdsApi(this._overlay);
4114
+ this._mockLifecyclesApi = new MockLifecycleApi();
4115
+ this.ads = this._mockAdsApi;
4116
+ this.analytics = new MockAnalyticsApi();
4117
+ const appUrl = typeof window !== "undefined" ? window.location.href : "";
4118
+ this.deviceCache = createMockStorageApi("deviceCache", appUrl);
4119
+ this.appStorage = createMockStorageApi("appStorage", appUrl);
4120
+ this.globalStorage = createMockStorageApi("globalStorage");
4121
+ this.avatar3d = new MockAvatarApi(venusApi);
4122
+ this.navigation = new MockNavigationApi(venusApi);
4123
+ this.notifications = new MockNotificationsApi(venusApi);
4124
+ this.popups = new MockPopupsApi(this._overlay);
4125
+ this.profile = new MockProfileApi();
4126
+ this.cdn = new MockCdnApi();
4127
+ this.time = new MockTimeApi(venusApi);
4128
+ this.post = new MockPostApi(venusApi);
4129
+ this.ai = new MockAiApi();
4130
+ this.haptics = new MockHapticsApi(venusApi);
4131
+ this.features = new MockFeaturesApi();
4132
+ this.lifecycle = this._mockLifecyclesApi;
4133
+ this.simulation = new MockSimulationApi();
4134
+ this.rooms = createUnavailableRoomsApi();
4135
+ this.logging = new MockLoggingApi();
4136
+ this.iap = new MockIapApi();
4137
+ this.social = new MockSocialApi();
4138
+ this.leaderboard = new MockLeaderboardApi();
4139
+ initializeRoomsApi(this.venusApi, this);
4140
+ this.preloader = new MockPreloaderApi();
4141
+ venusApi.isMock = () => true;
4142
+ this.venusApi.sharedAssets = new MockSharedAssetsApi(this.venusApi);
4143
+ }
4144
+ get isInitialized() {
4145
+ return this._isInitialized;
4146
+ }
4147
+ initialize(options) {
4148
+ this._isInitialized = true;
4149
+ return Promise.resolve({
4150
+ initializeAsleep: false
4151
+ });
4152
+ }
4153
+ updateUiControls() {
4154
+ const controls = {
4155
+ closeButton: { x: 16, y: 16, width: 32, height: 32 },
4156
+ menuButton: {
4157
+ x: window.innerWidth - 48,
4158
+ y: 16,
4159
+ width: 32,
4160
+ height: 32
4161
+ },
4162
+ feedHeader: { x: 0, y: 0, width: window.innerWidth, height: 56 },
4163
+ playButton: {
4164
+ x: 0,
4165
+ y: window.innerHeight - 60,
4166
+ width: window.innerWidth,
4167
+ height: 60
4168
+ }
4169
+ };
4170
+ return controls;
4171
+ }
4172
+ createOverlay() {
4173
+ const venusApi = this.venusApi;
4174
+ venusApi.config.ui.controls = this.updateUiControls();
4175
+ const uiControls = venusApi.config.ui.controls;
4176
+ const overlayContainer = document.createElement("div");
4177
+ overlayContainer.id = "venus-mock-overlay";
4178
+ overlayContainer.style.cssText = `
4179
+ position: fixed;
4180
+ top: 0;
4181
+ left: 0;
4182
+ width: 100%;
4183
+ height: 100%;
4184
+ pointer-events: none;
4185
+ z-index: 10000;
4186
+ `;
4187
+ document.body.appendChild(overlayContainer);
4188
+ const menuButton = this.createOverlayButton(
4189
+ "close",
4190
+ "Menu",
4191
+ uiControls.menuButton,
4192
+ () => {
4193
+ this.handleMenuButtonClicked();
4194
+ },
4195
+ "rgba(59, 130, 246, 0.7)",
4196
+ // Blue background instead of black
4197
+ "#FFFFFF"
4198
+ );
4199
+ overlayContainer.appendChild(menuButton);
4200
+ const adOverlay = this.setupAdOverlay();
4201
+ const actionSheet = this.setupActionSheetOverlay();
4202
+ window.addEventListener("resize", () => {
4203
+ this.updateOverlayLayout();
4204
+ });
4205
+ return {
4206
+ container: overlayContainer,
4207
+ elements: {
4208
+ menuButton
4209
+ },
4210
+ appVisibilityState: "visible",
4211
+ actionSheetOverlay: actionSheet,
4212
+ adOverlay,
4213
+ showAdOverlay: () => {
4214
+ return this.showAdOverlay("REWARDED VIDEO AD");
4215
+ },
4216
+ showActionSheet: (items, options) => {
4217
+ return this.showActionSheetOverlay(items, options);
4218
+ }
4219
+ };
4220
+ }
4221
+ async handleMenuButtonClicked() {
4222
+ if (this.state === 0 /* PLAYING */) {
4223
+ this.triggerLifecycleEvent("PAUSE" /* PAUSE */);
4224
+ this.state = 1 /* PAUSED */;
4225
+ }
4226
+ const actionSheetItems = [];
4227
+ const awakeAction = {
4228
+ label: "\u23F0 Awake",
4229
+ id: "awakeAction"
4230
+ };
4231
+ const sleepAction = {
4232
+ label: "\u{1F4A4} Sleep",
4233
+ id: "sleepAction"
4234
+ };
4235
+ const quitAction = {
4236
+ label: "\u{1F6D1} Quit",
4237
+ id: "quitAction"
4238
+ };
4239
+ const playAction = {
4240
+ label: "\u25B6\uFE0F Play",
4241
+ id: "playAction"
4242
+ };
4243
+ if (this.state === 1 /* PAUSED */) {
4244
+ actionSheetItems.push(sleepAction);
4245
+ } else if (this.state === 2 /* SLEEPING */) {
4246
+ actionSheetItems.push(awakeAction);
4247
+ }
4248
+ if (this.state !== 3 /* TERMINATED */) {
4249
+ actionSheetItems.push(quitAction);
4250
+ } else if (this.state === 3 /* TERMINATED */) {
4251
+ actionSheetItems.push(playAction);
4252
+ }
4253
+ const action = await this.showActionSheetOverlay(actionSheetItems);
4254
+ if (action === awakeAction.id) {
4255
+ this.tryAwake();
4256
+ } else if (action === sleepAction.id) {
4257
+ this.trySleep();
4258
+ } else if (action === playAction.id) {
4259
+ this.tryPlay();
4260
+ } else if (action === quitAction.id) {
4261
+ this.tryQuit();
4262
+ } else {
4263
+ this.tryResume();
4264
+ }
4265
+ }
4266
+ tryAwake() {
4267
+ if (this.state === 2 /* SLEEPING */) {
4268
+ this.triggerLifecycleEvent("AWAKE" /* AWAKE */);
4269
+ this.state = 1 /* PAUSED */;
4270
+ }
4271
+ }
4272
+ trySleep() {
4273
+ if (this.state === 1 /* PAUSED */) {
4274
+ this.triggerLifecycleEvent("SLEEP" /* SLEEP */);
4275
+ this.state = 2 /* SLEEPING */;
4276
+ }
4277
+ }
4278
+ tryPlay() {
4279
+ if (this.state === 3 /* TERMINATED */) {
4280
+ this.triggerLifecycleEvent("AWAKE" /* AWAKE */);
4281
+ this.state = 1 /* PAUSED */;
4282
+ this.triggerLifecycleEvent("RESUME" /* RESUME */);
4283
+ this.state = 0 /* PLAYING */;
4284
+ }
4285
+ }
4286
+ tryQuit() {
4287
+ if (this.state === 0 /* PLAYING */) {
4288
+ this.triggerLifecycleEvent("PAUSE" /* PAUSE */);
4289
+ this.state = 1 /* PAUSED */;
4290
+ }
4291
+ if (this.state === 1 /* PAUSED */) {
4292
+ this.triggerLifecycleEvent("SLEEP" /* SLEEP */);
4293
+ this.state = 2 /* SLEEPING */;
4294
+ }
4295
+ if (this.state === 2 /* SLEEPING */) {
4296
+ this.triggerLifecycleEvent("QUIT" /* QUIT */);
4297
+ this.state = 3 /* TERMINATED */;
4298
+ }
4299
+ }
4300
+ tryResume() {
4301
+ if (this.state === 1 /* PAUSED */) {
4302
+ this.triggerLifecycleEvent("RESUME" /* RESUME */);
4303
+ }
4304
+ }
4305
+ async showAdOverlay(type) {
4306
+ return new Promise((resolve, reject) => {
4307
+ const overlay = this._overlay;
4308
+ const adOverlay = overlay.adOverlay;
4309
+ overlay.adOverlay.innerHTML = "";
4310
+ const heading = document.createElement("h1");
4311
+ heading.style.cssText = `
4312
+ font-size: 24px;
4313
+ margin-bottom: 20px;
4314
+ text-align: center;
4315
+ `;
4316
+ heading.innerText = type === "interstitial" ? "INTERSTITIAL AD" : "REWARDED VIDEO AD";
4317
+ overlay.adOverlay.appendChild(heading);
4318
+ const content = document.createElement("div");
4319
+ content.style.cssText = `
4320
+ width: 300px;
4321
+ height: 250px;
4322
+ background-color: #1e40af;
4323
+ display: flex;
4324
+ align-items: center;
4325
+ justify-content: center;
4326
+ margin-bottom: 20px;
4327
+ border-radius: 8px;
4328
+ `;
4329
+ content.innerText = "Mock Ad Content";
4330
+ adOverlay.appendChild(content);
4331
+ const timer = document.createElement("p");
4332
+ timer.style.cssText = `
4333
+ margin-bottom: 20px;
4334
+ font-size: 16px;
4335
+ `;
4336
+ timer.innerText = "Normally ads would have a timer...";
4337
+ adOverlay.appendChild(timer);
4338
+ const okButton = document.createElement("button");
4339
+ okButton.style.cssText = `
4340
+ padding: 10px 40px;
4341
+ background-color: #2563eb;
4342
+ color: white;
4343
+ border: none;
4344
+ border-radius: 4px;
4345
+ font-size: 16px;
4346
+ cursor: pointer;
4347
+ `;
4348
+ okButton.innerText = "Close Ad";
4349
+ adOverlay.appendChild(okButton);
4350
+ adOverlay.style.display = "flex";
4351
+ okButton.onclick = () => {
4352
+ this.hideAdOverlay();
4353
+ resolve(true);
4354
+ };
4355
+ });
4356
+ }
4357
+ hideAdOverlay() {
4358
+ const overlay = this._overlay;
4359
+ if (overlay.adOverlay) {
4360
+ overlay.adOverlay.style.display = "none";
4361
+ }
4362
+ }
4363
+ setupActionSheetOverlay() {
4364
+ const actionSheetOverlay = document.createElement("div");
4365
+ actionSheetOverlay.id = "venus-action-sheet-overlay";
4366
+ actionSheetOverlay.style.cssText = `
4367
+ position: fixed;
4368
+ top: 0;
4369
+ left: 0;
4370
+ width: 100%;
4371
+ height: 100%;
4372
+ background-color: rgba(0, 0, 0, 0.5);
4373
+ display: flex;
4374
+ align-items: center;
4375
+ justify-content: center;
4376
+ z-index: 10600;
4377
+ font-family: sans-serif;
4378
+ display: none;
4379
+ `;
4380
+ document.body.appendChild(actionSheetOverlay);
4381
+ return actionSheetOverlay;
4382
+ }
4383
+ createOverlayButton(id, text, position, onClick, background, color) {
4384
+ const button = document.createElement("button");
4385
+ button.id = `venus-mock-${id}-button`;
4386
+ button.innerText = text;
4387
+ button.style.cssText = `
4388
+ position: absolute;
4389
+ left: ${position.x}px;
4390
+ top: ${position.y}px;
4391
+ width: ${position.width}px;
4392
+ min-width: ${position.width}px;
4393
+ height: ${position.height}px;
4394
+ background: ${background};
4395
+ color: ${color};
4396
+ border: none;
4397
+ border-radius: 8px;
4398
+ font-family: sans-serif;
4399
+ font-weight: bold;
4400
+ font-size: ${Math.min(position.width, position.height) / 3}px;
4401
+ cursor: pointer;
4402
+ pointer-events: auto;
4403
+ display: flex;
4404
+ align-items: center;
4405
+ justify-content: center;
4406
+ opacity: 0.9;
4407
+ transition: opacity 0.2s;
4408
+ `;
4409
+ button.addEventListener("click", onClick);
4410
+ button.addEventListener("mouseover", () => {
4411
+ button.style.opacity = "1";
4412
+ });
4413
+ button.addEventListener("mouseout", () => {
4414
+ button.style.opacity = "0.9";
4415
+ });
4416
+ return button;
4417
+ }
4418
+ updateOverlayLayout() {
4419
+ const venusApi = this.venusApi;
4420
+ const overlay = this._overlay;
4421
+ venusApi.config.ui.controls = this.updateUiControls();
4422
+ const uiControls = venusApi.config.ui.controls;
4423
+ const menuBtn = overlay.elements.menuButton;
4424
+ const menuPos = uiControls.menuButton;
4425
+ menuBtn.style.left = `${menuPos.x}px`;
4426
+ menuBtn.style.top = `${menuPos.y}px`;
4427
+ menuBtn.style.width = `${menuPos.width}px`;
4428
+ menuBtn.style.minWidth = `${menuPos.width}px`;
4429
+ menuBtn.style.height = `${menuPos.height}px`;
4430
+ }
4431
+ triggerLifecycleEvent(name) {
4432
+ console.log("Trigger Lifecycle Event: ", name);
4433
+ if (name == "PAUSE" /* PAUSE */) {
4434
+ this._mockLifecyclesApi.triggerPauseCallbacks();
4435
+ } else if (name == "RESUME" /* RESUME */) {
4436
+ this._mockLifecyclesApi.triggerResumeCallbacks();
4437
+ } else if (name == "QUIT" /* QUIT */) {
4438
+ this._mockLifecyclesApi.triggerQuitCallbacks();
4439
+ } else if (name == "AWAKE" /* AWAKE */) {
4440
+ this._mockLifecyclesApi.triggerAwakeCallbacks();
4441
+ } else if (name == "SLEEP" /* SLEEP */) {
4442
+ this._mockLifecyclesApi.triggerSleepCallbacks();
4443
+ }
4444
+ }
4445
+ setOverlayElementVisibility(element, visible) {
4446
+ const overlay = this._overlay;
4447
+ const elements = overlay.elements;
4448
+ if (elements[element]) {
4449
+ elements[element].style.display = visible ? "flex" : "none";
4450
+ }
4451
+ }
4452
+ setupAdOverlay() {
4453
+ const adOverlay = document.createElement("div");
4454
+ adOverlay.id = "venus-ad-overlay";
4455
+ adOverlay.style.cssText = `
4456
+ position: fixed;
4457
+ top: 0;
4458
+ left: 0;
4459
+ width: 100%;
4460
+ height: 100%;
4461
+ background-color: rgba(37, 99, 235, 0.9);
4462
+ color: white;
4463
+ display: flex;
4464
+ flex-direction: column;
4465
+ align-items: center;
4466
+ justify-content: center;
4467
+ z-index: 10500;
4468
+ font-family: sans-serif;
4469
+ display: none;
4470
+ `;
4471
+ document.body.appendChild(adOverlay);
4472
+ return adOverlay;
4473
+ }
4474
+ log(msg, ...args) {
4475
+ console.log(`[Venus Mock] ${msg}`, ...args);
4476
+ }
4477
+ showActionSheetOverlay(items, options) {
4478
+ this.log("Showing ActionSheetOverlay...");
4479
+ return new Promise((resolve, reject) => {
4480
+ const overlay = this._overlay;
4481
+ overlay.actionSheetOverlay.innerHTML = "";
4482
+ overlay.actionSheetOverlay.style.display = "flex";
4483
+ const actionSheet = document.createElement("div");
4484
+ actionSheet.className = "venus-action-sheet";
4485
+ actionSheet.style.cssText = `
4486
+ background-color: white;
4487
+ border-radius: 8px;
4488
+ width: 80%;
4489
+ max-width: 400px;
4490
+ max-height: 80%;
4491
+ display: flex;
4492
+ flex-direction: column;
4493
+ overflow: hidden;
4494
+ color: black;
4495
+ `;
4496
+ if (options?.title) {
4497
+ const titleContainer = document.createElement("div");
4498
+ titleContainer.style.cssText = `
4499
+ padding: 16px;
4500
+ border-bottom: 1px solid #eaeaea;
4501
+ font-weight: bold;
4502
+ font-size: 18px;
4503
+ text-align: center;
4504
+ color: black;
4505
+ `;
4506
+ titleContainer.innerText = options.title;
4507
+ actionSheet.appendChild(titleContainer);
4508
+ }
4509
+ if (options?.message) {
4510
+ const messageContainer = document.createElement("div");
4511
+ messageContainer.style.cssText = `
4512
+ padding: 8px 16px;
4513
+ color: #666;
4514
+ font-size: 14px;
4515
+ text-align: center;
4516
+ `;
4517
+ messageContainer.innerText = options.message;
4518
+ actionSheet.appendChild(messageContainer);
4519
+ }
4520
+ const optionsContainer = document.createElement("div");
4521
+ optionsContainer.style.cssText = `
4522
+ overflow-y: auto;
4523
+ max-height: 300px;
4524
+ `;
4525
+ items.forEach((item, index) => {
4526
+ const optionItem = document.createElement("div");
4527
+ optionItem.style.cssText = `
4528
+ padding: 12px 16px;
4529
+ border-bottom: 1px solid #eaeaea;
4530
+ cursor: pointer;
4531
+ display: flex;
4532
+ align-items: center;
4533
+ transition: background-color 0.2s;
4534
+ color: black;
4535
+ `;
4536
+ optionItem.addEventListener("mouseover", () => {
4537
+ optionItem.style.backgroundColor = "#f5f5f5";
4538
+ });
4539
+ optionItem.addEventListener("mouseout", () => {
4540
+ optionItem.style.backgroundColor = "white";
4541
+ });
4542
+ if (item.icon) {
4543
+ const iconSpan = document.createElement("span");
4544
+ iconSpan.style.cssText = `
4545
+ margin-right: 12px;
4546
+ font-size: 16px;
4547
+ `;
4548
+ iconSpan.innerText = item.icon;
4549
+ optionItem.appendChild(iconSpan);
4550
+ }
4551
+ const labelSpan = document.createElement("span");
4552
+ labelSpan.style.cssText = `
4553
+ color: black;
4554
+ `;
4555
+ labelSpan.innerText = item.label;
4556
+ optionItem.appendChild(labelSpan);
4557
+ optionItem.addEventListener("click", () => {
4558
+ this.hideActionSheetOverlay();
4559
+ const optionId = item.id !== void 0 ? item.id : index;
4560
+ resolve(optionId);
4561
+ });
4562
+ optionsContainer.appendChild(optionItem);
4563
+ });
4564
+ actionSheet.appendChild(optionsContainer);
4565
+ if (!options?.disableCancel) {
4566
+ const cancelButton = document.createElement("div");
4567
+ cancelButton.style.cssText = `
4568
+ padding: 14px 16px;
4569
+ text-align: center;
4570
+ font-weight: bold;
4571
+ cursor: pointer;
4572
+ color: #3b82f6;
4573
+ border-top: 1px solid #eaeaea;
4574
+ `;
4575
+ cancelButton.innerText = options?.cancelButtonText || "Cancel";
4576
+ cancelButton.addEventListener("click", () => {
4577
+ this.hideActionSheetOverlay();
4578
+ resolve(null);
4579
+ });
4580
+ actionSheet.appendChild(cancelButton);
4581
+ }
4582
+ if (!options?.disableCancel) {
4583
+ const closeButton = document.createElement("div");
4584
+ closeButton.style.cssText = `
4585
+ position: absolute;
4586
+ top: 8px;
4587
+ right: 8px;
4588
+ width: 24px;
4589
+ height: 24px;
4590
+ border-radius: 12px;
4591
+ background-color: rgba(0,0,0,0.1);
4592
+ color: #666;
4593
+ display: flex;
4594
+ align-items: center;
4595
+ justify-content: center;
4596
+ cursor: pointer;
4597
+ font-size: 14px;
4598
+ `;
4599
+ closeButton.innerText = "\u2715";
4600
+ closeButton.addEventListener("click", () => {
4601
+ this.hideActionSheetOverlay();
4602
+ resolve(null);
4603
+ });
4604
+ actionSheet.appendChild(closeButton);
4605
+ overlay.actionSheetOverlay.appendChild(actionSheet);
4606
+ }
4607
+ });
4608
+ }
4609
+ hideActionSheetOverlay() {
4610
+ const overlay = this._overlay;
4611
+ if (overlay.actionSheetOverlay) {
4612
+ overlay.actionSheetOverlay.style.display = "none";
4613
+ }
4614
+ }
4615
+ };
4616
+
4617
+ // src/VenusTransport.ts
4618
+ var VenusTransport = class {
4619
+ constructor() {
4620
+ __publicField(this, "messageHandler");
4621
+ __publicField(this, "onNotificationCallbacks", []);
4622
+ __publicField(this, "onNotificationCallbacksToRemove", []);
4623
+ __publicField(this, "onVenusMessageCallbacks", []);
4624
+ __publicField(this, "onResponseCallbacks", []);
4625
+ __publicField(this, "onResponseCallbacksToRemove", []);
4626
+ __publicField(this, "_instanceId", null);
4627
+ __publicField(this, "isStarted", false);
4628
+ __publicField(this, "isProcessingMessage", false);
4629
+ this.messageHandler = async (event) => {
4630
+ this.isProcessingMessage = true;
4631
+ let message;
4632
+ if (typeof event.data === "string") {
4633
+ message = JSON.parse(event.data);
4634
+ } else {
4635
+ message = event.data;
4636
+ }
4637
+ if (!message) {
4638
+ this.logInfo("No message found. Ignoring message...");
4639
+ return;
4640
+ }
4641
+ this.notifyVenusMessageReceived(message);
4642
+ if (message.type === "PAUSE" /* PAUSE */ || message.type === "RESUME" /* RESUME */ || message.type === "AWAKE" /* AWAKE */ || message.type === "SLEEP" /* SLEEP */ || message.type === "QUIT" /* QUIT */) {
4643
+ const notification = {
4644
+ type: "rpc-notification",
4645
+ id: message.type,
4646
+ payload: message.data
4647
+ };
4648
+ this.handleNotification(notification);
4649
+ this.isProcessingMessage = false;
4650
+ return;
4651
+ }
4652
+ const messageData = message.data;
4653
+ if (!messageData) {
4654
+ this.logWarn("No data found. Ignoring message...");
4655
+ this.isProcessingMessage = false;
4656
+ return;
4657
+ }
4658
+ const requestId = messageData.requestId;
4659
+ if (!requestId) {
4660
+ this.logWarn("No requestId. Ignoring message...");
4661
+ this.isProcessingMessage = false;
4662
+ return;
4663
+ }
4664
+ if (message.type !== "H5_RESPONSE" /* H5_RESPONSE */) {
4665
+ this.logWarn(`Ignoring unknown message type: ${message.type}`);
4666
+ this.isProcessingMessage = false;
4667
+ return;
4668
+ }
4669
+ const success = messageData.success;
4670
+ let error = void 0;
4671
+ if (!success) {
4672
+ error = {
4673
+ message: messageData.error || "Unknown error"
4674
+ };
4675
+ }
4676
+ let result = messageData.value;
4677
+ if (result === void 0) {
4678
+ result = messageData.data;
4679
+ }
4680
+ const response = {
4681
+ type: "rpc-response",
4682
+ id: requestId,
4683
+ result,
4684
+ method: message.type,
4685
+ error
4686
+ };
4687
+ await this.handleResponse(response);
4688
+ this.isProcessingMessage = false;
4689
+ };
4690
+ }
4691
+ onNotification(callback) {
4692
+ this.onNotificationCallbacks.push(callback);
4693
+ return {
4694
+ unsubscribe: () => {
4695
+ if (this.isProcessingMessage) {
4696
+ this.onNotificationCallbacks.push(callback);
4697
+ } else {
4698
+ this.removeOnNotificationCallback(callback);
4699
+ }
4700
+ }
4701
+ };
4702
+ }
4703
+ onRequest(callback) {
4704
+ throw new Error("Method not implemented.");
4705
+ }
4706
+ onResponse(callback) {
4707
+ this.onResponseCallbacks.push(callback);
4708
+ return {
4709
+ unsubscribe: () => {
4710
+ if (this.isProcessingMessage) {
4711
+ this.onResponseCallbacksToRemove.push(callback);
4712
+ } else {
4713
+ this.removeOnResponseCallback(callback);
4714
+ }
4715
+ }
4716
+ };
4717
+ }
4718
+ get instanceId() {
4719
+ return this._instanceId;
4720
+ }
4721
+ set instanceId(instanceId) {
4722
+ this._instanceId = instanceId;
4723
+ }
4724
+ sendRequest(request) {
4725
+ const instanceId = this.instanceId || "unknown";
4726
+ const method = request.method;
4727
+ const message = {
4728
+ type: method,
4729
+ direction: "H5_TO_APP",
4730
+ data: {
4731
+ ...request.args,
4732
+ requestId: request.id
4733
+ },
4734
+ instanceId,
4735
+ timestamp: Date.now()
4736
+ };
4737
+ this.sendVenusMessage(message);
4738
+ }
4739
+ sendVenusMessage(message) {
4740
+ const messageAsString = JSON.stringify(message, null, 2);
4741
+ const reactNativeWebView = window.ReactNativeWebView;
4742
+ if (reactNativeWebView) {
4743
+ reactNativeWebView.postMessage(messageAsString);
4744
+ } else {
4745
+ window.parent.postMessage(messageAsString, "*");
4746
+ }
4747
+ }
4748
+ sendResponse(response) {
4749
+ throw new Error("Method not implemented.");
4750
+ }
4751
+ start() {
4752
+ if (this.isStarted) {
4753
+ return;
4754
+ }
4755
+ this.isStarted = true;
4756
+ window.addEventListener("message", this.messageHandler, true);
4757
+ this.logInfo(`Started`);
4758
+ }
4759
+ stop() {
4760
+ if (!this.isStarted) {
4761
+ return;
4762
+ }
4763
+ this.isStarted = false;
4764
+ window.removeEventListener("message", this.messageHandler);
4765
+ this.logInfo(`Stopped`);
4766
+ }
4767
+ handleNotification(notification) {
4768
+ for (const callback of this.onNotificationCallbacks) {
4769
+ callback(notification);
4770
+ }
4771
+ for (const callback of this.onNotificationCallbacksToRemove) {
4772
+ this.removeOnNotificationCallback(callback);
4773
+ }
4774
+ this.onNotificationCallbacksToRemove.length = 0;
4775
+ }
4776
+ async handleResponse(response) {
4777
+ for (const callback of this.onResponseCallbacks) {
4778
+ const consumed = await callback(response);
4779
+ if (consumed) {
4780
+ break;
4781
+ }
4782
+ }
4783
+ for (const callback of this.onResponseCallbacksToRemove) {
4784
+ this.removeOnResponseCallback(callback);
4785
+ }
4786
+ this.onResponseCallbacksToRemove.length = 0;
4787
+ }
4788
+ removeOnResponseCallback(callback) {
4789
+ this.onResponseCallbacks.splice(
4790
+ this.onResponseCallbacks.indexOf(callback),
4791
+ 1
4792
+ );
4793
+ }
4794
+ removeOnNotificationCallback(callback) {
4795
+ this.onNotificationCallbacks.splice(
4796
+ this.onNotificationCallbacks.indexOf(callback),
4797
+ 1
4798
+ );
4799
+ }
4800
+ logInfo(message, ...params) {
4801
+ console.log(`[Venus Transport] ${message}`, ...params);
4802
+ }
4803
+ logWarn(message, ...params) {
4804
+ console.warn(`[Venus Transport] ${message}`, ...params);
4805
+ }
4806
+ onVenusMessage(callback) {
4807
+ this.onVenusMessageCallbacks.push(callback);
4808
+ return {
4809
+ unsubscribe: () => {
4810
+ this.onVenusMessageCallbacks.splice(
4811
+ this.onVenusMessageCallbacks.indexOf(callback),
4812
+ 1
4813
+ );
4814
+ }
4815
+ };
4816
+ }
4817
+ notifyVenusMessageReceived(message) {
4818
+ for (const callback of this.onVenusMessageCallbacks) {
4819
+ callback(message);
4820
+ }
4821
+ }
4822
+ };
4823
+
4824
+ // src/RemoteHost.ts
4825
+ init_rooms();
4826
+
4827
+ // src/rooms/RpcRoomsApi.ts
4828
+ init_VenusRoom();
4829
+ var RpcRoomsApi = class {
4830
+ constructor(rpcClient) {
4831
+ __publicField(this, "rpcClient");
4832
+ __publicField(this, "subscriptions");
4833
+ __publicField(this, "transportSubscription", null);
4834
+ this.rpcClient = rpcClient;
4835
+ this.subscriptions = {
4836
+ data: {},
4837
+ messages: {},
4838
+ gameEvents: {},
4839
+ allEvents: {}
4840
+ };
4841
+ }
4842
+ /**
4843
+ * Get the subscription state for external access (used by setupRoomNotifications)
4844
+ */
4845
+ getSubscriptions() {
4846
+ return this.subscriptions;
4847
+ }
4848
+ /**
4849
+ * Set up room notification routing from the transport
4850
+ */
4851
+ setupNotifications(transport) {
4852
+ const { setupRoomNotifications: setupRoomNotifications2 } = (init_rooms(), __toCommonJS(rooms_exports));
4853
+ this.transportSubscription = setupRoomNotifications2(
4854
+ transport,
4855
+ () => this.getSubscriptions()
4856
+ );
4857
+ }
4858
+ /**
4859
+ * Clean up subscriptions and resources
4860
+ */
4861
+ dispose() {
4862
+ if (this.transportSubscription) {
4863
+ this.transportSubscription.unsubscribe();
4864
+ this.transportSubscription = null;
4865
+ console.log("[Venus Rooms] Cleaned up room notification subscription");
4866
+ }
4867
+ }
4868
+ async createRoom(options) {
4869
+ const response = await this.rpcClient.call(
4870
+ "H5_ROOM_CREATE" /* H5_ROOM_CREATE */,
4871
+ {
4872
+ options
4873
+ }
4874
+ );
4875
+ if (response.success === false) {
4876
+ throw new Error(response.error || "Failed to create room");
4877
+ }
4878
+ const roomData = response.roomData || response;
4879
+ const room = new exports.VenusRoom(roomData);
4880
+ return room;
4881
+ }
4882
+ async joinOrCreateRoom(options) {
4883
+ const response = await this.rpcClient.call(
4884
+ "H5_ROOM_JOIN_OR_CREATE" /* H5_ROOM_JOIN_OR_CREATE */,
4885
+ {
4886
+ options
4887
+ }
4888
+ );
4889
+ if (response.success === false) {
4890
+ throw new Error(response.error || "Failed to join or create room");
4891
+ }
4892
+ const data = response.value || response;
4893
+ const room = new exports.VenusRoom(data.roomData);
4894
+ return {
4895
+ action: data.action,
4896
+ room,
4897
+ playersJoined: data.playersJoined
4898
+ };
4899
+ }
4900
+ async joinRoomByCode(roomCode) {
4901
+ const response = await this.rpcClient.call(
4902
+ "H5_ROOM_JOIN_BY_CODE" /* H5_ROOM_JOIN_BY_CODE */,
4903
+ {
4904
+ roomCode
4905
+ }
4906
+ );
4907
+ if (response?.success === false) {
4908
+ throw new Error(response.error || "Failed to join room by code");
4909
+ }
4910
+ const roomData = response.roomData || response;
4911
+ const room = new exports.VenusRoom(roomData);
4912
+ return room;
4913
+ }
4914
+ // Get user's rooms with optional filtering
4915
+ async getUserRooms(includeArchived = false) {
4916
+ const response = await this.rpcClient.call(
4917
+ "H5_ROOM_GET_USER_ROOMS" /* H5_ROOM_GET_USER_ROOMS */,
4918
+ {
4919
+ includeArchived
4920
+ }
4921
+ );
4922
+ if (response?.success === false) {
4923
+ throw new Error(response.error || "Failed to get user rooms");
4924
+ }
4925
+ const rawRooms = response.rooms || [];
4926
+ const venusRooms = [];
4927
+ for (const roomData of rawRooms) {
4928
+ if (!roomData.id) {
4929
+ console.warn("getUserRooms: Skipping room with missing ID:", roomData);
4930
+ continue;
4931
+ }
4932
+ try {
4933
+ const venusRoom = new exports.VenusRoom(roomData);
4934
+ venusRooms.push(venusRoom);
4935
+ } catch (error) {
4936
+ console.warn(
4937
+ "getUserRooms: Failed to create VenusRoom object:",
4938
+ error,
4939
+ roomData
4940
+ );
4941
+ }
4942
+ }
4943
+ return venusRooms;
4944
+ }
4945
+ async updateData(room, updates, merge = true) {
4946
+ const response = await this.rpcClient.call(
4947
+ "H5_ROOM_UPDATE_DATA" /* H5_ROOM_UPDATE_DATA */,
4948
+ {
4949
+ roomId: room.id,
4950
+ updates,
4951
+ merge
4952
+ }
4953
+ );
4954
+ if (response?.success === false) {
4955
+ throw new Error(response.error || "Failed to update room data");
4956
+ }
4957
+ return response.data;
4958
+ }
4959
+ async getData(room) {
4960
+ const response = await this.rpcClient.call(
4961
+ "H5_ROOM_GET_DATA" /* H5_ROOM_GET_DATA */,
4962
+ {
4963
+ roomId: room.id
4964
+ }
4965
+ );
4966
+ if (response?.success === false) {
4967
+ throw new Error(response.error || "Failed to get room data");
4968
+ }
4969
+ return response.data;
4970
+ }
4971
+ async sendMessage(venusRoom, messageData) {
4972
+ const response = await this.rpcClient.call(
4973
+ "H5_ROOM_SEND_MESSAGE" /* H5_ROOM_SEND_MESSAGE */,
4974
+ {
4975
+ roomId: venusRoom.id,
4976
+ message: messageData
4977
+ }
4978
+ );
4979
+ if (response?.success === false) {
4980
+ throw new Error(response.error || "Failed to send message");
4981
+ }
4982
+ return response.messageId;
4983
+ }
4984
+ async leave(room) {
4985
+ const response = await this.rpcClient.call(
4986
+ "H5_ROOM_LEAVE" /* H5_ROOM_LEAVE */,
4987
+ {
4988
+ roomId: room.id
4989
+ }
4990
+ );
4991
+ if (response?.success === false) {
4992
+ throw new Error(response.error || "Failed to leave room");
4993
+ }
4994
+ return response;
4995
+ }
4996
+ async startGame(room, gameConfig = {}, turnOrder = null) {
4997
+ const response = await this.rpcClient.call(
4998
+ "H5_ROOM_START_GAME" /* H5_ROOM_START_GAME */,
4999
+ {
5000
+ roomId: room.id,
5001
+ gameConfig,
5002
+ turnOrder
5003
+ }
5004
+ );
5005
+ if (response?.success === false) {
5006
+ throw new Error(response.error || "Failed to start game");
5007
+ }
5008
+ return response.data;
5009
+ }
5010
+ async proposeMove(room, proposalPayload) {
5011
+ const response = await this.rpcClient.call(
5012
+ "h5:room:proposeMove" /* H5_ROOM_PROPOSE_MOVE */,
5013
+ {
5014
+ roomId: room.id,
5015
+ gameSpecificState: proposalPayload.gameSpecificState,
5016
+ moveType: proposalPayload.moveType,
5017
+ clientContext: proposalPayload.clientContext,
5018
+ clientProposalId: proposalPayload.clientProposalId
5019
+ }
5020
+ );
5021
+ if (response?.success === false) {
5022
+ throw new Error(response.error || "Failed to propose move");
5023
+ }
5024
+ return response.data;
5025
+ }
5026
+ async validateMove(room, moveId, isValid, reason = null, validatorId = null) {
5027
+ console.log(`[Venus Rooms] Validating move ${moveId}: ${isValid}`);
5028
+ return { success: true, moveId, isValid, reason };
5029
+ }
5030
+ async roomSubscribeToGameEvents(room, callback) {
5031
+ "game_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
5032
+ if (!this.subscriptions.gameEvents[room.id]) {
5033
+ this.subscriptions.gameEvents[room.id] = [];
5034
+ }
5035
+ this.subscriptions.gameEvents[room.id].push(callback);
5036
+ }
5037
+ subscribe(room, options = {}) {
5038
+ const subscriptionIds = [];
5039
+ const roomId = room.id;
5040
+ if (options.onData) {
5041
+ const dataSubId = "data_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
5042
+ if (!this.subscriptions.data[roomId]) {
5043
+ this.subscriptions.data[roomId] = [];
5044
+ }
5045
+ this.subscriptions.data[roomId].push(options.onData);
5046
+ subscriptionIds.push({
5047
+ type: "data",
5048
+ id: dataSubId,
5049
+ callback: options.onData
5050
+ });
5051
+ }
5052
+ if (options.onMessages) {
5053
+ const msgSubId = "messages_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
5054
+ if (!this.subscriptions.messages[roomId]) {
5055
+ this.subscriptions.messages[roomId] = [];
5056
+ }
5057
+ this.subscriptions.messages[roomId].push(options.onMessages);
5058
+ subscriptionIds.push({
5059
+ type: "messages",
5060
+ id: msgSubId,
5061
+ callback: options.onMessages
5062
+ });
5063
+ }
5064
+ if (options.onMoves || options.onGameEvents) {
5065
+ const handler = options.onMoves || options.onGameEvents;
5066
+ if (handler) {
5067
+ const gameSubId = "game_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
5068
+ if (!this.subscriptions.gameEvents[roomId]) {
5069
+ this.subscriptions.gameEvents[roomId] = [];
5070
+ }
5071
+ this.subscriptions.gameEvents[roomId].push(handler);
5072
+ subscriptionIds.push({
5073
+ type: "gameEvents",
5074
+ id: gameSubId,
5075
+ callback: handler
5076
+ });
5077
+ }
5078
+ }
5079
+ const needsSubscription = subscriptionIds.length > 0 && (this.subscriptions.data[roomId]?.length ?? 0) <= 1 && (this.subscriptions.messages[roomId]?.length ?? 0) <= 1 && (this.subscriptions.gameEvents[roomId]?.length ?? 0) <= 1;
5080
+ if (needsSubscription) {
5081
+ this.rpcClient.call("H5_ROOM_SUBSCRIBE" /* H5_ROOM_SUBSCRIBE */, {
5082
+ roomId,
5083
+ subscribeToData: !!options.onData,
5084
+ subscribeToMessages: !!options.onMessages,
5085
+ subscribeToProposedMoves: !!(options.onMoves || options.onGameEvents)
5086
+ }).catch((error) => {
5087
+ console.error("Failed to set up room subscription:", error);
5088
+ });
5089
+ }
5090
+ let called = false;
5091
+ return () => {
5092
+ if (called) return;
5093
+ called = true;
5094
+ subscriptionIds.forEach((sub) => {
5095
+ const bucket = this.subscriptions[sub.type];
5096
+ const callbacks = bucket && bucket[roomId] || [];
5097
+ const index = callbacks.indexOf(sub.callback);
5098
+ if (index > -1) callbacks.splice(index, 1);
5099
+ });
5100
+ const hasNoCallbacks = (this.subscriptions.data[roomId]?.length ?? 0) === 0 && (this.subscriptions.messages[roomId]?.length ?? 0) === 0 && (this.subscriptions.gameEvents[roomId]?.length ?? 0) === 0;
5101
+ if (hasNoCallbacks) {
5102
+ this.rpcClient.call("H5_ROOM_UNSUBSCRIBE" /* H5_ROOM_UNSUBSCRIBE */, {
5103
+ roomId
5104
+ }).catch((error) => {
5105
+ console.error("Failed to clean up room subscription:", error);
5106
+ });
5107
+ }
5108
+ };
5109
+ }
5110
+ };
5111
+
5112
+ // src/social/RpcSocialApi.ts
5113
+ var RpcSocialApi = class {
5114
+ constructor(rpcClient) {
5115
+ this.rpcClient = rpcClient;
5116
+ }
5117
+ async shareLinkAsync(options) {
5118
+ const result = await this.rpcClient.call("H5_SHARE_LINK" /* SHARE_LINK */, {
5119
+ launchParams: options.launchParams,
5120
+ metadata: options.metadata ?? {}
5121
+ });
5122
+ return {
5123
+ shareUrl: result.shareUrl
5124
+ };
5125
+ }
5126
+ async createQRCodeAsync(options) {
5127
+ const result = await this.rpcClient.call(
5128
+ "H5_CREATE_SHARE_QRCODE" /* CREATE_SHARE_QRCODE */,
5129
+ {
5130
+ launchParams: options.launchParams,
5131
+ metadata: options.metadata ?? {},
5132
+ qrOptions: options.qrOptions ?? {}
5133
+ }
5134
+ );
5135
+ return {
5136
+ shareUrl: result.shareUrl,
5137
+ qrCode: result.qrCode
5138
+ };
5139
+ }
5140
+ };
5141
+
5142
+ // src/RemoteHost.ts
5143
+ var getCdnBaseUrl = () => {
5144
+ return "https://venus-static-01293ak.web.app/";
5145
+ };
5146
+ var RemoteHost = class {
5147
+ constructor(venusApi) {
5148
+ __publicField(this, "ads");
5149
+ __publicField(this, "analytics");
5150
+ __publicField(this, "deviceCache");
5151
+ __publicField(this, "appStorage");
5152
+ __publicField(this, "globalStorage");
5153
+ __publicField(this, "avatar3d");
5154
+ __publicField(this, "navigation");
5155
+ __publicField(this, "notifications");
5156
+ __publicField(this, "popups");
5157
+ __publicField(this, "profile");
5158
+ __publicField(this, "cdn");
5159
+ __publicField(this, "time");
5160
+ __publicField(this, "post");
5161
+ __publicField(this, "ai");
5162
+ __publicField(this, "haptics");
5163
+ __publicField(this, "features");
5164
+ __publicField(this, "lifecycle");
5165
+ __publicField(this, "simulation");
5166
+ __publicField(this, "rooms");
5167
+ __publicField(this, "logging");
5168
+ __publicField(this, "iap");
5169
+ __publicField(this, "leaderboard");
5170
+ __publicField(this, "preloader");
5171
+ __publicField(this, "social");
5172
+ __publicField(this, "venusApi");
5173
+ __publicField(this, "rpcClient");
5174
+ __publicField(this, "_isInitialized", false);
5175
+ this.venusApi = venusApi;
5176
+ const rpcClient = new RpcClient();
5177
+ this.rpcClient = rpcClient;
5178
+ this.ads = new RpcAdsApi(rpcClient);
5179
+ this.analytics = new RpcAnalyticsApi(rpcClient);
5180
+ this.deviceCache = new RpcStorageApi(rpcClient, {
5181
+ clear: "H5_DEVICE_CACHE_CLEAR" /* DEVICE_CACHE_CLEAR */,
5182
+ getItem: "H5_DEVICE_CACHE_GET_ITEM" /* DEVICE_CACHE_GET_ITEM */,
5183
+ getKey: "H5_DEVICE_CACHE_KEY" /* DEVICE_CACHE_KEY */,
5184
+ length: "H5_DEVICE_CACHE_LENGTH" /* DEVICE_CACHE_LENGTH */,
5185
+ removeItem: "H5_DEVICE_CACHE_REMOVE_ITEM" /* DEVICE_CACHE_REMOVE_ITEM */,
5186
+ setItem: "H5_DEVICE_CACHE_SET_ITEM" /* DEVICE_CACHE_SET_ITEM */
5187
+ });
5188
+ this.appStorage = new RpcStorageApi(rpcClient, {
5189
+ clear: "H5_APP_STORAGE_CLEAR" /* APP_STORAGE_CLEAR */,
5190
+ getItem: "H5_APP_STORAGE_GET_ITEM" /* APP_STORAGE_GET_ITEM */,
5191
+ getKey: "H5_APP_STORAGE_KEY" /* APP_STORAGE_KEY */,
5192
+ length: "H5_APP_STORAGE_LENGTH" /* APP_STORAGE_LENGTH */,
5193
+ removeItem: "H5_APP_STORAGE_REMOVE_ITEM" /* APP_STORAGE_REMOVE_ITEM */,
5194
+ setItem: "H5_APP_STORAGE_SET_ITEM" /* APP_STORAGE_SET_ITEM */,
5195
+ getAllItems: "H5_APP_STORAGE_GET_ALL_ITEMS" /* APP_STORAGE_GET_ALL_ITEMS */,
5196
+ setMultipleItems: "H5_APP_STORAGE_SET_ITEM" /* APP_STORAGE_SET_ITEM */,
5197
+ removeMultipleItems: "H5_APP_STORAGE_REMOVE_ITEM" /* APP_STORAGE_REMOVE_ITEM */
5198
+ });
5199
+ this.globalStorage = new RpcStorageApi(rpcClient, {
5200
+ clear: "H5_GLOBAL_STORAGE_CLEAR" /* GLOBAL_STORAGE_CLEAR */,
5201
+ getItem: "H5_GLOBAL_STORAGE_GET_ITEM" /* GLOBAL_STORAGE_GET_ITEM */,
5202
+ getKey: "H5_GLOBAL_STORAGE_KEY" /* GLOBAL_STORAGE_KEY */,
5203
+ length: "H5_GLOBAL_STORAGE_LENGTH" /* GLOBAL_STORAGE_LENGTH */,
5204
+ removeItem: "H5_GLOBAL_STORAGE_REMOVE_ITEM" /* GLOBAL_STORAGE_REMOVE_ITEM */,
5205
+ setItem: "H5_GLOBAL_STORAGE_SET_ITEM" /* GLOBAL_STORAGE_SET_ITEM */,
5206
+ getAllItems: "H5_GLOBAL_STORAGE_GET_ALL_ITEMS" /* GLOBAL_STORAGE_GET_ALL_ITEMS */,
5207
+ setMultipleItems: "H5_GLOBAL_STORAGE_SET_MULTIPLE_ITEMS" /* GLOBAL_STORAGE_SET_MULTIPLE_ITEMS */,
5208
+ removeMultipleItems: "H5_GLOBAL_STORAGE_REMOVE_MULTIPLE_ITEMS" /* GLOBAL_STORAGE_REMOVE_MULTIPLE_ITEMS */
5209
+ });
5210
+ this.avatar3d = new RpcAvatarApi(rpcClient, venusApi);
5211
+ this.navigation = new RpcNavigationApi(rpcClient, venusApi);
5212
+ this.notifications = new RpcNotificationsApi(rpcClient);
5213
+ this.popups = new RpcPopupsApi(rpcClient);
5214
+ this.profile = new HostProfileApi();
5215
+ this.cdn = new HostCdnApi(getCdnBaseUrl());
5216
+ this.time = new HostTimeApi(rpcClient);
5217
+ this.post = new RpcPostApi(rpcClient);
5218
+ this.ai = new RpcAiApi(rpcClient);
5219
+ this.haptics = new RpcHapticsApi(rpcClient);
5220
+ this.features = new RpcFeaturesApi(rpcClient);
5221
+ this.lifecycle = new RpcLifecycleApi(rpcClient);
5222
+ this.simulation = new RpcSimulationApi(rpcClient);
5223
+ this.rooms = new RpcRoomsApi(rpcClient);
5224
+ this.logging = new RpcLoggingApi(this, rpcClient);
5225
+ this.iap = new RpcIapApi(rpcClient);
5226
+ this.leaderboard = new RpcLeaderboardApi(rpcClient);
5227
+ this.preloader = new RpcPreloaderApi(rpcClient);
5228
+ this.social = new RpcSocialApi(rpcClient);
5229
+ venusApi.isMock = () => false;
5230
+ this.venusApi.sharedAssets = new RpcSharedAssetsApi(rpcClient, venusApi);
5231
+ initializeRoomsApi(this.venusApi, this);
5232
+ console.log("[Venus SDK] Remote host created");
5233
+ }
5234
+ get isInitialized() {
5235
+ return this._isInitialized;
5236
+ }
5237
+ async initialize(options) {
5238
+ this.log("Initializing Remote Host...");
5239
+ const transport = new VenusTransport();
5240
+ transport.start();
5241
+ this.rpcClient.start(transport);
5242
+ const roomsApi = this.rooms;
5243
+ roomsApi.setupNotifications(transport);
5244
+ const response = await this.rpcClient.call(
5245
+ "INITIALIZE_SDK" /* INIT_SDK */,
5246
+ {},
5247
+ 5e3
5248
+ );
5249
+ transport.instanceId = response.instanceId;
5250
+ this.log(`Remote Host Initialized with id: ${transport.instanceId}`);
5251
+ if (response.profile) {
5252
+ const profile = response.profile;
5253
+ const sanitizedProfile = {
5254
+ id: profile.id,
5255
+ username: profile.username,
5256
+ avatarUrl: profile.avatarUrl ?? null,
5257
+ isAnonymous: Boolean(profile.isAnonymous)
5258
+ };
5259
+ if (typeof window !== "undefined") {
5260
+ const globalWindow = window;
5261
+ const venus = globalWindow.venus || (globalWindow.venus = {});
5262
+ venus.profile = sanitizedProfile;
5263
+ if (venus._config) {
5264
+ venus._config.profile = sanitizedProfile;
5265
+ }
5266
+ if (venus.config) {
5267
+ venus.config.profile = sanitizedProfile;
5268
+ }
5269
+ }
5270
+ }
5271
+ this._isInitialized = true;
5272
+ this.venusApi.launchParams = response.launchParams || {};
5273
+ await this.rpcClient.call("READY" /* READY */, {});
5274
+ const hudInsets = response.hudInsets;
5275
+ if (hudInsets) {
5276
+ this.venusApi.config.ui.safeArea = hudInsets;
5277
+ }
5278
+ return {
5279
+ hudInsets,
5280
+ initializeAsleep: response.initializeAsleep
5281
+ };
5282
+ }
5283
+ log(message) {
5284
+ console.log(`[Venus SDK] [Remote Host] ${message}`);
5285
+ }
5286
+ };
5287
+
5288
+ // src/Host.ts
5289
+ function createHost(venusApi, isMock) {
5290
+ if (isMock) {
5291
+ console.log("[Venus SDK] Creating Local Host");
5292
+ return new MockHost(venusApi);
5293
+ } else {
5294
+ console.log("[Venus SDK] Creating Remote Host");
5295
+ return new RemoteHost(venusApi);
5296
+ }
5297
+ }
5298
+
5299
+ // src/social/index.ts
5300
+ function initializeSocial(venusApi, host) {
5301
+ venusApi.social = host.social;
5302
+ venusApi.getLaunchParams = () => {
5303
+ return venusApi.launchParams || {};
5304
+ };
5305
+ }
5306
+
3657
5307
  exports.HapticFeedbackStyle = HapticFeedbackStyle;
3658
5308
  exports.HostCdnApi = HostCdnApi;
3659
5309
  exports.HostProfileApi = HostProfileApi;
@@ -3666,6 +5316,7 @@ exports.MockCdnApi = MockCdnApi;
3666
5316
  exports.MockFeaturesApi = MockFeaturesApi;
3667
5317
  exports.MockHapticsApi = MockHapticsApi;
3668
5318
  exports.MockIapApi = MockIapApi;
5319
+ exports.MockLeaderboardApi = MockLeaderboardApi;
3669
5320
  exports.MockLifecycleApi = MockLifecycleApi;
3670
5321
  exports.MockLoggingApi = MockLoggingApi;
3671
5322
  exports.MockNavigationApi = MockNavigationApi;
@@ -3675,8 +5326,10 @@ exports.MockPreloaderApi = MockPreloaderApi;
3675
5326
  exports.MockProfileApi = MockProfileApi;
3676
5327
  exports.MockSharedAssetsApi = MockSharedAssetsApi;
3677
5328
  exports.MockSimulationApi = MockSimulationApi;
5329
+ exports.MockSocialApi = MockSocialApi;
3678
5330
  exports.MockStorageApi = MockStorageApi;
3679
5331
  exports.MockTimeApi = MockTimeApi;
5332
+ exports.RemoteHost = RemoteHost;
3680
5333
  exports.RpcAdsApi = RpcAdsApi;
3681
5334
  exports.RpcAiApi = RpcAiApi;
3682
5335
  exports.RpcAnalyticsApi = RpcAnalyticsApi;
@@ -3685,6 +5338,7 @@ exports.RpcClient = RpcClient;
3685
5338
  exports.RpcFeaturesApi = RpcFeaturesApi;
3686
5339
  exports.RpcHapticsApi = RpcHapticsApi;
3687
5340
  exports.RpcIapApi = RpcIapApi;
5341
+ exports.RpcLeaderboardApi = RpcLeaderboardApi;
3688
5342
  exports.RpcLifecycleApi = RpcLifecycleApi;
3689
5343
  exports.RpcLoggingApi = RpcLoggingApi;
3690
5344
  exports.RpcNavigationApi = RpcNavigationApi;
@@ -3693,10 +5347,11 @@ exports.RpcPopupsApi = RpcPopupsApi;
3693
5347
  exports.RpcPreloaderApi = RpcPreloaderApi;
3694
5348
  exports.RpcSharedAssetsApi = RpcSharedAssetsApi;
3695
5349
  exports.RpcSimulationApi = RpcSimulationApi;
5350
+ exports.RpcSocialApi = RpcSocialApi;
3696
5351
  exports.RpcStorageApi = RpcStorageApi;
3697
5352
  exports.SDK_VERSION = SDK_VERSION;
3698
5353
  exports.VenusMessageId = VenusMessageId;
3699
- exports.VenusRoom = VenusRoom;
5354
+ exports.createHost = createHost;
3700
5355
  exports.createMockStorageApi = createMockStorageApi;
3701
5356
  exports.initializeAds = initializeAds;
3702
5357
  exports.initializeAi = initializeAi;
@@ -3706,6 +5361,7 @@ exports.initializeCdn = initializeCdn;
3706
5361
  exports.initializeFeaturesApi = initializeFeaturesApi;
3707
5362
  exports.initializeHaptics = initializeHaptics;
3708
5363
  exports.initializeIap = initializeIap;
5364
+ exports.initializeLeaderboard = initializeLeaderboard;
3709
5365
  exports.initializeLifecycleApi = initializeLifecycleApi;
3710
5366
  exports.initializeLocalNotifications = initializeLocalNotifications;
3711
5367
  exports.initializeLoggingApi = initializeLoggingApi;
@@ -3714,6 +5370,7 @@ exports.initializePreloader = initializePreloader;
3714
5370
  exports.initializeProfile = initializeProfile;
3715
5371
  exports.initializeRoomsApi = initializeRoomsApi;
3716
5372
  exports.initializeSimulation = initializeSimulation;
5373
+ exports.initializeSocial = initializeSocial;
3717
5374
  exports.initializeStackNavigation = initializeStackNavigation;
3718
5375
  exports.initializeStorage = initializeStorage;
3719
5376
  exports.initializeTime = initializeTime;