@series-inc/venus-sdk 2.2.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 ADDED
@@ -0,0 +1,3205 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
7
+ // src/ads/RpcAdsApi.ts
8
+ var RpcAdsApi = class {
9
+ constructor(rpcClient) {
10
+ __publicField(this, "rpcClient");
11
+ this.rpcClient = rpcClient;
12
+ }
13
+ async showInterstitialAd() {
14
+ console.log(`[Venus SDK] [RpcAdsApi] showInterstitialAd`);
15
+ return await this.rpcClient.call(
16
+ "H5_SHOW_INTERSTITIAL_AD" /* SHOW_INTERSTITIAL_AD */
17
+ );
18
+ }
19
+ async isRewardedAdReadyAsync() {
20
+ console.log(`[Venus SDK] [RpcAdsApi] isRewardedAdReadyAsync`);
21
+ return await this.rpcClient.call(
22
+ "H5_IS_REWARDED_AD_READY" /* IS_REWARDED_AD_READY */
23
+ );
24
+ }
25
+ async showRewardedAdAsync() {
26
+ console.log("[Venus SDK] [RpcAdsApi] showRewardedAdAsync");
27
+ const result = await this.rpcClient.call(
28
+ "H5_SHOW_REWARDED_AD" /* SHOW_REWARDED_AD */
29
+ );
30
+ const resultAsString = JSON.stringify(result, null, 2);
31
+ console.log(
32
+ `[Venus SDK] [RpcAdsApi] rewarded ad shown with result as JSON:
33
+ ${resultAsString}`
34
+ );
35
+ return result.rewardEarned;
36
+ }
37
+ };
38
+
39
+ // src/venus-api/systems/core.js
40
+ function isWebPlatform() {
41
+ return typeof window !== "undefined" && !window.ReactNativeWebView;
42
+ }
43
+ var MOCK_DELAYS = {
44
+ short: 100,
45
+ // Quick operations (get/set preferences, etc.)
46
+ medium: 500};
47
+ function createMockDelay(ms = MOCK_DELAYS.short) {
48
+ return new Promise((resolve) => setTimeout(resolve, ms));
49
+ }
50
+
51
+ // src/ads/MockAdsApi.ts
52
+ var MockAdsApi = class {
53
+ constructor(mockOverlay) {
54
+ __publicField(this, "mockOverlay");
55
+ this.mockOverlay = mockOverlay;
56
+ }
57
+ async isRewardedAdReadyAsync() {
58
+ this.log("[MockAdsApi] isRewardedAdReadyAsync called");
59
+ await createMockDelay(MOCK_DELAYS.short);
60
+ return true;
61
+ }
62
+ async showRewardedAdAsync() {
63
+ this.log("[MockAdsApi] showRewardedAdAsync called");
64
+ await this.mockOverlay.showAdOverlay();
65
+ this.log("[MockAdsApi] Rewarded ad completed");
66
+ return true;
67
+ }
68
+ async showInterstitialAd() {
69
+ this.log(`[MockAdsApi] showInterstitialAd`);
70
+ return true;
71
+ }
72
+ log(message, ...args) {
73
+ console.log(`[Venus SDK] ${message}`, ...args);
74
+ }
75
+ };
76
+
77
+ // src/ads/index.ts
78
+ function initializeAds(venusApiInstance, host) {
79
+ venusApiInstance.isRewardedAdReadyAsync = host.ads.isRewardedAdReadyAsync.bind(host.ads);
80
+ venusApiInstance.showRewardedAdAsync = host.ads.showRewardedAdAsync.bind(
81
+ host.ads
82
+ );
83
+ venusApiInstance.ads = host.ads;
84
+ }
85
+
86
+ // src/ai/RpcAiApi.ts
87
+ var RpcAiApi = class {
88
+ constructor(rpcClient) {
89
+ __publicField(this, "rpcClient");
90
+ this.rpcClient = rpcClient;
91
+ }
92
+ async requestChatCompletionAsync(request) {
93
+ const response = await this.rpcClient.call(
94
+ "H5_AI_CHAT_COMPLETION" /* AI_CHAT_COMPLETION */,
95
+ {
96
+ request: (() => {
97
+ const { apiKey, ...requestWithoutApiKey } = request;
98
+ return requestWithoutApiKey;
99
+ })()
100
+ }
101
+ );
102
+ return response;
103
+ }
104
+ async getAvailableCompletionModels() {
105
+ const response = await this.rpcClient.call(
106
+ "H5_AI_GET_AVAILABLE_MODELS" /* AI_GET_AVAILABLE_MODELS */
107
+ );
108
+ return response;
109
+ }
110
+ };
111
+
112
+ // src/ai/MockAiApi.ts
113
+ var MockAiApi = class {
114
+ async requestChatCompletionAsync(request) {
115
+ const { apiKey, ...requestBody } = request;
116
+ if (!apiKey) {
117
+ throw new Error("An API key is required for a chat completion request when developing locally.");
118
+ }
119
+ const response = await fetch("https://series.ullm.rho.live/api/v1/completions", {
120
+ method: "POST",
121
+ headers: {
122
+ "Content-Type": "application/json",
123
+ "Authorization": `Bearer ${apiKey}`
124
+ },
125
+ body: JSON.stringify(requestBody)
126
+ });
127
+ if (!response.ok) {
128
+ throw new Error(`HTTP error! status: ${response.status}`);
129
+ }
130
+ const data = await response.json();
131
+ return data;
132
+ }
133
+ async getAvailableCompletionModels() {
134
+ const response = await fetch("https://series.ullm.rho.live/api/v1/models", {
135
+ method: "GET",
136
+ headers: {
137
+ "Content-Type": "application/json"
138
+ }
139
+ });
140
+ if (!response.ok) {
141
+ throw new Error(`HTTP error! status: ${response.status}`);
142
+ }
143
+ const data = await response.json();
144
+ return data;
145
+ }
146
+ };
147
+
148
+ // src/ai/index.ts
149
+ function initializeAi(venusApi, host) {
150
+ venusApi.ai = host.ai;
151
+ }
152
+
153
+ // src/analytics/MockAnalyticsApi.ts
154
+ var MockAnalyticsApi = class {
155
+ async recordCustomEvent(eventName, payload) {
156
+ console.log(
157
+ `[Venus Mock] Logging event with ${eventName}, params ${payload}`
158
+ );
159
+ await createMockDelay(MOCK_DELAYS.short);
160
+ }
161
+ async trackFunnelStep(stepNumber, stepName, funnelName) {
162
+ console.log(`[Venus Mock] tracking funnel step ${stepName} (step ${stepNumber}) for funnel ${funnelName ?? "game"}`);
163
+ await createMockDelay(MOCK_DELAYS.short);
164
+ }
165
+ };
166
+
167
+ // src/analytics/RpcAnalyticsApi.ts
168
+ var RpcAnalyticsApi = class {
169
+ constructor(rpcClient) {
170
+ __publicField(this, "rpcClient");
171
+ this.rpcClient = rpcClient;
172
+ }
173
+ async recordCustomEvent(eventName, payload) {
174
+ console.log(
175
+ `[Venus SDK] [RpcAnalyticsApi] recordCustomEvent: ${eventName} payload:
176
+ ${JSON.stringify(payload, null, 2)}`
177
+ );
178
+ await this.rpcClient.call("H5_LOG_ANALYTICS_EVENT" /* LOG_ANALYTICS_EVENT */, {
179
+ eventName,
180
+ params: payload
181
+ });
182
+ }
183
+ async trackFunnelStep(stepNumber, stepName, funnelName) {
184
+ console.log(
185
+ `[Venus SDK] [RpcAnalyticsApi] trackFunnelStep: stepNumber: ${stepNumber} stepName: ${stepName} funnelName: ${funnelName}`
186
+ );
187
+ await this.rpcClient.call("H5_TRACK_FUNNEL_STEP" /* TRACK_FUNNEL_STEP */, {
188
+ stepNumber,
189
+ stepName,
190
+ funnelName
191
+ });
192
+ }
193
+ };
194
+
195
+ // src/analytics/index.ts
196
+ function initializeAnalytics(venusApiInstance, host) {
197
+ venusApiInstance.logCustomEvent = async (options) => {
198
+ await host.analytics.recordCustomEvent(
199
+ options.eventName,
200
+ options.params
201
+ );
202
+ };
203
+ venusApiInstance.analytics = host.analytics;
204
+ }
205
+
206
+ // src/avatar3d/MockAvatarApi.ts
207
+ var MockAvatarApi = class {
208
+ constructor(venusApi) {
209
+ __publicField(this, "_venusApi");
210
+ __publicField(this, "cachedAssets", null);
211
+ __publicField(this, "cachedVersion", "");
212
+ this._venusApi = venusApi;
213
+ }
214
+ downloadAssetPaths() {
215
+ console.log("[Venus Mock] Downloading avatar3d asset paths...");
216
+ return this.getAllAssetPaths();
217
+ }
218
+ async deleteAvatar() {
219
+ console.log(`[Venus Mock] Deleting avatar3d config`);
220
+ const venusApi = this._venusApi;
221
+ const currentProfile = venusApi.getCurrentProfile();
222
+ const profileId = currentProfile?.id || "default_profile";
223
+ localStorage.removeItem(`venus-mock-avatar3d-${profileId}`);
224
+ console.log(
225
+ `[Venus Mock] Avatar3d config deleted from localStorage for profile: ${profileId}`
226
+ );
227
+ }
228
+ async loadAvatar(avatar3dId) {
229
+ console.log(`[Venus Mock] Loading avatar3d`, { avatar3dId });
230
+ const venusApi = this._venusApi;
231
+ let config;
232
+ if (avatar3dId) {
233
+ console.log(`[Venus Mock] Loading shared avatar3d by ID: ${avatar3dId}`);
234
+ config = await this.selectAvatarConfig(avatar3dId, false);
235
+ } else {
236
+ const currentProfile = venusApi.getCurrentProfile();
237
+ const profileId = currentProfile?.id || "default_profile";
238
+ console.log(`[Venus Mock] Loading avatar3d for profile: ${profileId}`);
239
+ console.log(
240
+ "[Venus Mock] Generating fresh avatar config with current CDN URLs"
241
+ );
242
+ if (profileId === "default_profile") {
243
+ config = await this.selectAvatarConfig(null, true);
244
+ } else {
245
+ config = await this.selectAvatarConfig(profileId, false);
246
+ }
247
+ }
248
+ return config || null;
249
+ }
250
+ async saveAvatar(config) {
251
+ console.log(`[Venus Mock] Saving avatar3d config:`, config);
252
+ const venusApi = this._venusApi;
253
+ const currentProfile = venusApi.getCurrentProfile();
254
+ const profileId = currentProfile?.id || "default_profile";
255
+ localStorage.setItem(
256
+ `venus-mock-avatar3d-${profileId}`,
257
+ JSON.stringify(config)
258
+ );
259
+ const mockAvatar3dId = `mock_avatar3d_${profileId}_${Date.now()}`;
260
+ console.log(
261
+ `[Venus Mock] Avatar3d config saved to localStorage with mock ID: ${mockAvatar3dId}`
262
+ );
263
+ return mockAvatar3dId;
264
+ }
265
+ downloadManifest() {
266
+ return this.loadAssetsManifest();
267
+ }
268
+ async showEditor(options) {
269
+ console.log(
270
+ `[Venus Mock] showAvatar3dEditorAsync called with options:`,
271
+ options
272
+ );
273
+ if (window.VenusPrototyping) {
274
+ return new Promise((resolve) => {
275
+ window.VenusPrototyping.showAvatarEditorOverlay(options, resolve);
276
+ });
277
+ }
278
+ console.log("[Venus Mock] Simulating avatar editor opening...");
279
+ await createMockDelay(MOCK_DELAYS.medium);
280
+ const mockAvatarConfig = await this.selectAvatarConfig(null, false);
281
+ const userSavedChanges = Math.random() > 0.3;
282
+ console.log(
283
+ "[Venus Mock] Avatar editor simulation complete - user would use requestPopOrQuit() with result data"
284
+ );
285
+ if (userSavedChanges) {
286
+ const mockAvatarId = `mock_avatar_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
287
+ return {
288
+ wasChanged: true,
289
+ config: mockAvatarConfig,
290
+ savedAvatarId: mockAvatarId
291
+ };
292
+ } else {
293
+ return {
294
+ wasChanged: false,
295
+ config: null,
296
+ savedAvatarId: null
297
+ };
298
+ }
299
+ }
300
+ async getAssets() {
301
+ let cachedAssets = this.cachedAssets;
302
+ if (!cachedAssets) {
303
+ this.log("No cached assets found, loading new manifest...");
304
+ cachedAssets = (await this.loadAssetsManifest()).categories;
305
+ }
306
+ return cachedAssets;
307
+ }
308
+ async loadAssetsManifest() {
309
+ this.log("Loading avatar3d assets manifest from CDN...");
310
+ const venusApi = this._venusApi;
311
+ const baseManifestUrl = venusApi.resolveAvatarAssetUrl("assets.json");
312
+ const separator = baseManifestUrl.includes("?") ? "&" : "?";
313
+ const manifestUrl = `${baseManifestUrl}${separator}v=${Date.now()}`;
314
+ console.log("[Venus Mock] Fetching manifest from URL:", manifestUrl);
315
+ try {
316
+ const response = await fetch(manifestUrl, {
317
+ method: "GET",
318
+ headers: {
319
+ Accept: "application/json, text/plain, */*",
320
+ "Content-Type": "application/json"
321
+ },
322
+ mode: "cors",
323
+ cache: "no-cache"
324
+ });
325
+ console.log(
326
+ "[Venus Mock] Fetch response status:",
327
+ response.status,
328
+ response.statusText
329
+ );
330
+ console.log(
331
+ "[Venus Mock] Response headers:",
332
+ Object.fromEntries(response.headers.entries())
333
+ );
334
+ if (!response.ok) {
335
+ throw new Error(
336
+ `Failed to fetch assets manifest: ${response.status} ${response.statusText}`
337
+ );
338
+ }
339
+ const manifest = await response.json();
340
+ console.log("[Venus Mock] Loaded assets manifest:", {
341
+ version: manifest.version,
342
+ generatedAt: manifest.generatedAt,
343
+ categories: Object.keys(manifest.categories || {})
344
+ });
345
+ this.cachedAssets = manifest.categories || {};
346
+ this.cachedVersion = manifest.version;
347
+ return manifest;
348
+ } catch (error) {
349
+ console.error("[Venus Mock] Failed to load assets manifest:", error);
350
+ console.log(
351
+ "[Venus Mock] Using fallback minimal manifest for development"
352
+ );
353
+ const fallbackManifest = {
354
+ version: "dev-fallback",
355
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
356
+ categories: {
357
+ head: {
358
+ type: "mesh",
359
+ assets: [
360
+ {
361
+ id: "head_default",
362
+ filename: "head_default.glb",
363
+ displayName: "Default Head"
364
+ },
365
+ {
366
+ id: "head_variant1",
367
+ filename: "head_variant1.glb",
368
+ displayName: "Head Variant 1"
369
+ }
370
+ ]
371
+ },
372
+ outfit: {
373
+ type: "mesh",
374
+ assets: [
375
+ {
376
+ id: "outfit_default",
377
+ filename: "outfit_default.glb",
378
+ displayName: "Default Outfit"
379
+ },
380
+ {
381
+ id: "outfit_casual",
382
+ filename: "outfit_casual.glb",
383
+ displayName: "Casual Outfit"
384
+ }
385
+ ]
386
+ },
387
+ hat: {
388
+ type: "mesh",
389
+ assets: [
390
+ {
391
+ id: "hat_none",
392
+ filename: "hat_none.glb",
393
+ displayName: "No Hat"
394
+ },
395
+ {
396
+ id: "hat_cap",
397
+ filename: "hat_cap.glb",
398
+ displayName: "Baseball Cap"
399
+ }
400
+ ]
401
+ },
402
+ hair: {
403
+ type: "mesh",
404
+ assets: [
405
+ {
406
+ id: "hair_default",
407
+ filename: "hair_default.glb",
408
+ displayName: "Default Hair"
409
+ },
410
+ {
411
+ id: "hair_long",
412
+ filename: "hair_long.glb",
413
+ displayName: "Long Hair"
414
+ }
415
+ ]
416
+ },
417
+ "face-accessory": {
418
+ type: "mesh",
419
+ assets: [
420
+ {
421
+ id: "glasses_none",
422
+ filename: "glasses_none.glb",
423
+ displayName: "No Glasses"
424
+ },
425
+ {
426
+ id: "glasses_regular",
427
+ filename: "glasses_regular.glb",
428
+ displayName: "Regular Glasses"
429
+ }
430
+ ]
431
+ },
432
+ animation: {
433
+ type: "mesh",
434
+ assets: [
435
+ {
436
+ id: "idle_default",
437
+ filename: "idle_default.glb",
438
+ displayName: "Default Idle"
439
+ },
440
+ {
441
+ id: "wave",
442
+ filename: "wave.glb",
443
+ displayName: "Wave Animation"
444
+ }
445
+ ]
446
+ }
447
+ }
448
+ };
449
+ this.cachedAssets = fallbackManifest.categories;
450
+ this.cachedVersion = fallbackManifest.version;
451
+ return fallbackManifest;
452
+ }
453
+ }
454
+ async selectAvatarConfig(avatarId = null, useDefaults = false) {
455
+ const categories = await this.getAssets();
456
+ this.log(`Manifest ${JSON.stringify(categories, null, 2)}`);
457
+ const rng = avatarId ? this.seededRandom(avatarId) : () => Math.random();
458
+ const headAsset = this.selectAsset(
459
+ categories,
460
+ "head",
461
+ rng,
462
+ avatarId,
463
+ useDefaults
464
+ );
465
+ const outfitAsset = this.selectAsset(
466
+ categories,
467
+ "outfit",
468
+ rng,
469
+ avatarId,
470
+ useDefaults
471
+ );
472
+ const hatAsset = this.selectAsset(
473
+ categories,
474
+ "hat",
475
+ rng,
476
+ avatarId,
477
+ useDefaults
478
+ );
479
+ const hairAsset = this.selectAsset(
480
+ categories,
481
+ "hair",
482
+ rng,
483
+ avatarId,
484
+ useDefaults
485
+ );
486
+ const faceAccessoryAsset = this.selectAsset(
487
+ categories,
488
+ "face-accessory",
489
+ rng,
490
+ avatarId,
491
+ useDefaults
492
+ );
493
+ const animationAsset = this.selectAsset(
494
+ categories,
495
+ "animation",
496
+ rng,
497
+ avatarId,
498
+ useDefaults
499
+ );
500
+ const config = {
501
+ headAsset: headAsset.filename,
502
+ outfitAsset: outfitAsset.filename,
503
+ animationAsset: animationAsset.filename,
504
+ faceAccessoryAsset: faceAccessoryAsset.filename,
505
+ hairAsset: hairAsset.filename,
506
+ hatAsset: hatAsset.filename,
507
+ skinColor: null
508
+ // NOTE(Zee): This was not selected anywhere?
509
+ };
510
+ console.log(
511
+ `[Venus Mock] Selected avatar config for ${avatarId || "default"}:`,
512
+ config
513
+ );
514
+ return config;
515
+ }
516
+ selectAsset(manifest, categoryId, rng, avatarId, useDefaults = false) {
517
+ const categoryAssets = manifest[categoryId].assets;
518
+ if (useDefaults) {
519
+ const selectedAsset2 = categoryAssets[0];
520
+ console.log(
521
+ `[Venus Mock] Using default asset for ${categoryId}:`,
522
+ selectedAsset2.id
523
+ );
524
+ return selectedAsset2;
525
+ }
526
+ if (avatarId) {
527
+ const index = Math.floor(rng() * categoryAssets.length);
528
+ const selectedAsset2 = categoryAssets[index];
529
+ console.log(
530
+ `[Venus Mock] Seeded selection for ${avatarId} ${categoryId}:`,
531
+ selectedAsset2.id,
532
+ `(index ${index}/${categoryAssets.length})`
533
+ );
534
+ return selectedAsset2;
535
+ }
536
+ const selectedAsset = categoryAssets[0];
537
+ this.log(`Fallback to first asset for ${categoryId}:`, selectedAsset.id);
538
+ return selectedAsset;
539
+ }
540
+ seededRandom(seed) {
541
+ const hash = this.simpleHash(seed);
542
+ let state = hash;
543
+ return function() {
544
+ state = (state * 1664525 + 1013904223) % 4294967296;
545
+ return state / 4294967296;
546
+ };
547
+ }
548
+ simpleHash(str) {
549
+ let hash = 0;
550
+ for (let i = 0; i < str.length; i++) {
551
+ const char = str.charCodeAt(i);
552
+ hash = (hash << 5) - hash + char;
553
+ hash = hash & hash;
554
+ }
555
+ return Math.abs(hash);
556
+ }
557
+ async getAllAssetPaths() {
558
+ const venusApi = this._venusApi;
559
+ const assets = await this.getAssets();
560
+ const allPaths = {};
561
+ for (const [category, categoryData] of Object.entries(assets)) {
562
+ allPaths[category] = (categoryData?.assets || []).map(
563
+ (asset) => venusApi.resolveAvatarAssetUrl(`${category}/${asset.filename}`)
564
+ );
565
+ }
566
+ this.log("All available asset paths:", allPaths);
567
+ return allPaths;
568
+ }
569
+ log(message, ...args) {
570
+ console.log(`"[Venus Mock] ${message}`, args);
571
+ }
572
+ };
573
+
574
+ // src/avatar3d/RpcAvatarApi.ts
575
+ var RpcAvatarApi = class {
576
+ constructor(rpcClient, venusApi) {
577
+ __publicField(this, "venusApi");
578
+ __publicField(this, "rpcClient");
579
+ this.rpcClient = rpcClient;
580
+ this.venusApi = venusApi;
581
+ }
582
+ async downloadAssetPaths() {
583
+ const venusApi = this.venusApi;
584
+ console.log("[Venus] Downloading avatar3d asset paths...");
585
+ const manifestUrl = venusApi.resolveAvatarAssetUrl("assets.json");
586
+ console.log("[Venus] \u{1F50D} Manifest URL resolved to:", manifestUrl);
587
+ const manifest = await this.fetchFromCdn(manifestUrl);
588
+ console.log("[Venus] \u{1F4E6} Manifest loaded successfully:", {
589
+ version: manifest.version,
590
+ categories: Object.keys(manifest.categories || {}),
591
+ totalAssets: Object.values(manifest.categories || {}).reduce(function(sum, cat) {
592
+ return sum + (cat.assets?.length || 0);
593
+ }, 0)
594
+ });
595
+ const categories = manifest.categories || {};
596
+ const assetPaths = {};
597
+ for (const categoryKey in categories) {
598
+ const categoryData = categories[categoryKey];
599
+ const categoryPath = categoryKey;
600
+ const assetUrls = (categoryData?.assets || []).map((asset) => {
601
+ const url = venusApi.resolveAvatarAssetUrl(
602
+ categoryPath + "/" + asset.filename
603
+ );
604
+ console.log("[Venus] \u{1F3A8} Asset URL:", asset.filename, "->", url);
605
+ return url;
606
+ });
607
+ assetPaths[categoryKey] = assetUrls;
608
+ console.log(
609
+ "[Venus] \u{1F4C1} Category",
610
+ categoryKey,
611
+ "has",
612
+ assetUrls.length,
613
+ "assets"
614
+ );
615
+ }
616
+ console.log("[Venus] Avatar3d asset paths downloaded successfully");
617
+ return assetPaths;
618
+ }
619
+ async downloadManifest() {
620
+ console.log("[Venus] Downloading avatar3d manifest...");
621
+ const venusApi = this.venusApi;
622
+ const manifestUrl = venusApi.resolveAvatarAssetUrl("assets.json");
623
+ const manifest = await this.fetchFromCdn(manifestUrl);
624
+ console.log("[Venus] Avatar3d manifest downloaded successfully");
625
+ return manifest;
626
+ }
627
+ async loadAvatar(avatarId) {
628
+ const result = await this.rpcClient.call("H5_AVATAR3D_LOAD" /* AVATAR3D_LOAD */, {
629
+ avatar3dId: avatarId
630
+ });
631
+ this.log(
632
+ `Avatar loaded with the following result:
633
+ ${JSON.stringify(result, null, 2)}`
634
+ );
635
+ return result;
636
+ }
637
+ saveAvatar(config) {
638
+ return this.rpcClient.call("H5_AVATAR3D_SAVE" /* AVATAR3D_SAVE */, {
639
+ config
640
+ });
641
+ }
642
+ deleteAvatar() {
643
+ return this.rpcClient.call("H5_AVATAR3D_DELETE" /* AVATAR3D_DELETE */);
644
+ }
645
+ async showEditor(options) {
646
+ const rpcClient = this.rpcClient;
647
+ console.log(
648
+ "[Venus] \u{1F3A8} showAvatar3dEditorAsync called with options:",
649
+ options
650
+ );
651
+ console.log(
652
+ "[Venus] \u{1F4E4} Sending H5_STACK_PUSH_REQUEST for avatar3d using _sendRequest..."
653
+ );
654
+ const rawResult = await rpcClient.call(
655
+ "H5_STACK_PUSH_REQUEST" /* H5_STACK_PUSH_REQUEST */,
656
+ {
657
+ targetAppId: "AVATAR3D",
658
+ contextData: options?.contextData || {},
659
+ appParams: {
660
+ currentAvatar: options?.currentAvatar,
661
+ onSave: options?.onSave,
662
+ onCancel: options?.onCancel
663
+ }
664
+ }
665
+ );
666
+ console.log(
667
+ "[Venus] \u2705 Avatar editor completed with raw result:",
668
+ rawResult
669
+ );
670
+ return {
671
+ wasChanged: rawResult.wasChanged || false,
672
+ config: rawResult.config || null,
673
+ savedAvatarId: rawResult.savedAvatarId || null
674
+ };
675
+ }
676
+ async fetchFromCdn(url) {
677
+ const response = await fetch(url, {
678
+ method: "GET",
679
+ headers: {
680
+ Accept: "application/json, text/plain, */*",
681
+ "Content-Type": "application/json"
682
+ },
683
+ mode: "cors",
684
+ cache: "no-cache"
685
+ });
686
+ if (!response.ok) {
687
+ throw new Error(
688
+ `CDN fetch failed: ${response.status} ${response.statusText}`
689
+ );
690
+ }
691
+ return await response.json();
692
+ }
693
+ log(message, ...options) {
694
+ console.log(`[Venus] ${message}`, options);
695
+ }
696
+ };
697
+
698
+ // src/avatar3d/index.ts
699
+ function initializeAvatar3d(venusApi, host) {
700
+ venusApi.loadAvatar3dAsync = host.avatar3d.loadAvatar.bind(host.avatar3d);
701
+ venusApi.saveAvatar3dAsync = host.avatar3d.saveAvatar.bind(host.avatar3d);
702
+ venusApi.deleteAvatar3dAsync = host.avatar3d.deleteAvatar.bind(host.avatar3d);
703
+ venusApi.downloadAvatar3dManifestAsync = host.avatar3d.downloadManifest.bind(
704
+ host.avatar3d
705
+ );
706
+ venusApi.showAvatar3dEditorAsync = host.avatar3d.showEditor.bind(
707
+ host.avatar3d
708
+ );
709
+ venusApi.downloadAvatar3dAssetPathsAsync = host.avatar3d.downloadAssetPaths.bind(host.avatar3d);
710
+ }
711
+
712
+ // src/cdn/HostCdnApi.ts
713
+ var HostCdnApi = class {
714
+ constructor(baseUrl) {
715
+ __publicField(this, "baseUrl");
716
+ this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
717
+ }
718
+ async fetchBlob(path, options) {
719
+ const controller = new AbortController();
720
+ const timeoutId = setTimeout(
721
+ () => controller.abort(),
722
+ options?.timeout ?? 3e4
723
+ );
724
+ try {
725
+ const url = this.resolveAssetUrl(path);
726
+ const response = await fetch(url, {
727
+ mode: "cors",
728
+ credentials: "omit",
729
+ headers: { Accept: "/*" },
730
+ signal: controller.signal
731
+ });
732
+ clearTimeout(timeoutId);
733
+ if (!response.ok) {
734
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
735
+ }
736
+ return await response.blob();
737
+ } catch (error) {
738
+ clearTimeout(timeoutId);
739
+ throw error;
740
+ }
741
+ }
742
+ async fetchFromCdn(url, request) {
743
+ const response = await fetch(url, {
744
+ method: "GET",
745
+ headers: {
746
+ Accept: "application/json, text/plain, */*",
747
+ "Content-Type": "application/json"
748
+ },
749
+ mode: "cors",
750
+ cache: "no-cache"
751
+ });
752
+ if (!response.ok) {
753
+ throw new Error(
754
+ `CDN fetch failed: \${response.status} \${response.statusText}`
755
+ );
756
+ }
757
+ return response;
758
+ }
759
+ getAssetCdnBaseUrl() {
760
+ return this.baseUrl;
761
+ }
762
+ resolveAssetUrl(subPath) {
763
+ const cleanSubPath = subPath.startsWith("/") ? subPath.slice(1) : subPath;
764
+ const pathParts = cleanSubPath.split("/");
765
+ const encodedParts = pathParts.map((part, index) => {
766
+ return index === pathParts.length - 1 ? encodeURIComponent(part) : part;
767
+ });
768
+ const encodedSubPath = encodedParts.join("/");
769
+ const fullUrl = this.baseUrl + "/" + encodedSubPath;
770
+ return fullUrl;
771
+ }
772
+ resolveAvatarAssetUrl(subPath) {
773
+ const avatarSubPath = "avatar3d/" + subPath;
774
+ return this.resolveAssetUrl(avatarSubPath);
775
+ }
776
+ resolveSharedLibUrl(subPath) {
777
+ const libSubPath = "libs/" + subPath;
778
+ return this.resolveAssetUrl(libSubPath);
779
+ }
780
+ };
781
+
782
+ // src/cdn/MockCdnApi.ts
783
+ var MockCdnApi = class {
784
+ constructor() {
785
+ __publicField(this, "baseUrl");
786
+ this.baseUrl = "https://venus-static-01293ak.web.app/";
787
+ }
788
+ async fetchBlob(path, options) {
789
+ const controller = new AbortController();
790
+ const timeoutId = setTimeout(
791
+ () => controller.abort(),
792
+ options?.timeout ?? 3e4
793
+ );
794
+ try {
795
+ const url = this.resolveAssetUrl(path);
796
+ const response = await fetch(url, {
797
+ mode: "cors",
798
+ credentials: "omit",
799
+ headers: { Accept: "/*" },
800
+ signal: controller.signal
801
+ });
802
+ clearTimeout(timeoutId);
803
+ if (!response.ok) {
804
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
805
+ }
806
+ return await response.blob();
807
+ } catch (error) {
808
+ clearTimeout(timeoutId);
809
+ throw error;
810
+ }
811
+ }
812
+ getAssetCdnBaseUrl() {
813
+ return this.baseUrl;
814
+ }
815
+ resolveAssetUrl(subPath) {
816
+ if (subPath.startsWith("http://") || subPath.startsWith("https://")) {
817
+ return subPath;
818
+ }
819
+ if (subPath.startsWith("cdn/")) {
820
+ return subPath;
821
+ }
822
+ const cleanSubPath = subPath.startsWith("/") ? subPath.slice(1) : subPath;
823
+ const pathParts = cleanSubPath.split("/");
824
+ const encodedParts = pathParts.map((part, index) => {
825
+ return index === pathParts.length - 1 ? encodeURIComponent(part) : part;
826
+ });
827
+ const encodedSubPath = encodedParts.join("/");
828
+ const fullUrl = `${this.baseUrl}${encodedSubPath}`;
829
+ return fullUrl;
830
+ }
831
+ resolveAvatarAssetUrl(subPath) {
832
+ if (subPath.startsWith("http://") || subPath.startsWith("https://")) {
833
+ return subPath;
834
+ }
835
+ const avatarSubPath = `avatar3d/${subPath}`;
836
+ return this.resolveAssetUrl(avatarSubPath);
837
+ }
838
+ resolveSharedLibUrl(subPath) {
839
+ if (subPath.startsWith("http://") || subPath.startsWith("https://")) {
840
+ return subPath;
841
+ }
842
+ const libSubPath = `libs/${subPath}`;
843
+ return this.resolveAssetUrl(libSubPath);
844
+ }
845
+ async fetchFromCdn(url, options) {
846
+ const allowedDomains = [
847
+ "venus-static-01293ak.web.app",
848
+ "firebasestorage.googleapis.com",
849
+ "cdn.venusapp.com",
850
+ "storage.googleapis.com"
851
+ ];
852
+ let urlObj = null;
853
+ try {
854
+ let isAllowed = true;
855
+ if (url.startsWith("http://") || url.startsWith("https://")) {
856
+ urlObj = new URL(url);
857
+ isAllowed = allowedDomains.some(
858
+ (domain) => urlObj.hostname === domain || urlObj.hostname.endsWith("." + domain)
859
+ );
860
+ if (!isAllowed) {
861
+ const error = `Domain not allowed: ${urlObj.hostname}. Allowed domains: ${allowedDomains.join(", ")}`;
862
+ console.error("[Venus Network Mock] Security error:", error);
863
+ throw new Error(error);
864
+ }
865
+ } else {
866
+ urlObj = null;
867
+ }
868
+ const fetchUrl = urlObj ? urlObj.href : url;
869
+ const response = await fetch(fetchUrl, {
870
+ method: options?.method || "GET",
871
+ headers: {
872
+ Accept: "text/plain, application/octet-stream, application/json, */*",
873
+ ...options?.headers
874
+ },
875
+ cache: options?.cache || "default",
876
+ mode: "cors"
877
+ });
878
+ if (!response.ok) {
879
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
880
+ }
881
+ return response;
882
+ } catch (error) {
883
+ if (error instanceof Error && error.message && (error.message.includes("CORS") || error.message.includes("preflight") || error.message.includes("Access-Control") || error.message.includes("cache-control"))) {
884
+ try {
885
+ const fallbackUrl = urlObj ? urlObj.href : url;
886
+ const fallbackResponse = await fetch(fallbackUrl, {
887
+ method: "GET",
888
+ mode: "cors",
889
+ cache: "default"
890
+ });
891
+ if (!fallbackResponse.ok) {
892
+ throw new Error(
893
+ `HTTP ${fallbackResponse.status}: ${fallbackResponse.statusText}`
894
+ );
895
+ }
896
+ const fallbackText = await fallbackResponse.text();
897
+ return fallbackResponse;
898
+ } catch (fallbackError) {
899
+ console.error(
900
+ "[Venus Network Mock] CORS fallback also failed (from network.js):",
901
+ {
902
+ url,
903
+ originalError: error.message,
904
+ fallbackError,
905
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
906
+ }
907
+ );
908
+ throw new Error(
909
+ `CORS error: ${error.message}. Fallback also failed: ${fallbackError}`
910
+ );
911
+ }
912
+ }
913
+ console.error("[Venus Network Mock] Fetch failed (from network.js):", {
914
+ url,
915
+ error,
916
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
917
+ });
918
+ throw error;
919
+ }
920
+ }
921
+ };
922
+
923
+ // src/cdn/index.ts
924
+ function initializeCdn(venusApi, host) {
925
+ venusApi.resolveAssetUrl = function(subPath) {
926
+ return host.cdn.resolveAssetUrl(subPath);
927
+ };
928
+ venusApi.resolveAvatarAssetUrl = function(subPath) {
929
+ return host.cdn.resolveAvatarAssetUrl(subPath);
930
+ };
931
+ venusApi.resolveSharedLibUrl = function(subPath) {
932
+ return host.cdn.resolveSharedLibUrl(subPath);
933
+ };
934
+ venusApi.getAssetCdnBaseUrl = function() {
935
+ return host.cdn.getAssetCdnBaseUrl();
936
+ };
937
+ venusApi.fetchFromCdn = (url, options) => {
938
+ return host.cdn.fetchFromCdn(url, options);
939
+ };
940
+ venusApi.cdn = host.cdn;
941
+ }
942
+
943
+ // src/features/RpcFeaturesApi.ts
944
+ var RpcFeaturesApi = class {
945
+ constructor(rcpClient) {
946
+ __publicField(this, "rpcClient");
947
+ this.rpcClient = rcpClient;
948
+ }
949
+ async getExperiment(experimentName) {
950
+ console.log("[Venus] Getting Experiment", experimentName);
951
+ return await this.rpcClient.call("H5_GET_EXPERIMENT" /* GET_EXPERIMENT */, {
952
+ experimentName
953
+ });
954
+ }
955
+ async getFeatureFlag(flagName) {
956
+ console.log("[Venus] Getting Feature Flag", flagName);
957
+ return await this.rpcClient.call("H5_GET_FEATURE_FLAG" /* GET_FEATURE_FLAG */, {
958
+ flagName
959
+ });
960
+ }
961
+ async getFeatureGate(gateName) {
962
+ console.log("[Venus] Getting Feature Gate", gateName);
963
+ return await this.rpcClient.call("H5_GET_FEATURE_GATE" /* GET_FEATURE_GATE */, {
964
+ gateName
965
+ });
966
+ }
967
+ };
968
+
969
+ // src/features/MockFeaturesApi.ts
970
+ var MockFeaturesApi = class {
971
+ async getExperiment(experimentName) {
972
+ return null;
973
+ }
974
+ async getFeatureFlag(flagName) {
975
+ return Promise.resolve(false);
976
+ }
977
+ getFeatureGate(gateName) {
978
+ return Promise.resolve(false);
979
+ }
980
+ };
981
+
982
+ // src/features/index.ts
983
+ function initializeFeaturesApi(venusApi, host) {
984
+ venusApi.getExperiment = (options) => {
985
+ return host.features.getExperiment(options.experimentName);
986
+ };
987
+ venusApi.getFeatureGate = (options) => {
988
+ return host.features.getFeatureGate(options.gateName);
989
+ };
990
+ venusApi.getFeatureFlag = (options) => {
991
+ return host.features.getFeatureFlag(options.flagName);
992
+ };
993
+ }
994
+
995
+ // src/haptics/HapticsApi.ts
996
+ var HapticFeedbackStyle = /* @__PURE__ */ ((HapticFeedbackStyle2) => {
997
+ HapticFeedbackStyle2["Light"] = "light";
998
+ HapticFeedbackStyle2["Medium"] = "medium";
999
+ HapticFeedbackStyle2["Heavy"] = "heavy";
1000
+ HapticFeedbackStyle2["Success"] = "success";
1001
+ HapticFeedbackStyle2["Warning"] = "warning";
1002
+ HapticFeedbackStyle2["Error"] = "error";
1003
+ return HapticFeedbackStyle2;
1004
+ })(HapticFeedbackStyle || {});
1005
+
1006
+ // src/haptics/RpcHapticsApi.ts
1007
+ var RpcHapticsApi = class {
1008
+ constructor(rpcClient) {
1009
+ __publicField(this, "rpcClient");
1010
+ this.rpcClient = rpcClient;
1011
+ }
1012
+ async triggerHapticAsync(style) {
1013
+ await this.rpcClient.call("H5_TRIGGER_HAPTIC" /* TRIGGER_HAPTIC */, {
1014
+ style
1015
+ });
1016
+ }
1017
+ };
1018
+
1019
+ // src/haptics/MockHapticsApi.ts
1020
+ var MockHapticsApi = class {
1021
+ constructor(venusApi) {
1022
+ __publicField(this, "venusApi");
1023
+ this.venusApi = venusApi;
1024
+ }
1025
+ async triggerHapticAsync(style) {
1026
+ const venusApi = this.venusApi;
1027
+ if (!venusApi._mock.device.supportsHaptics) {
1028
+ return;
1029
+ }
1030
+ }
1031
+ };
1032
+
1033
+ // src/haptics/index.ts
1034
+ function initializeHaptics(venusApi, host) {
1035
+ venusApi.triggerHapticAsync = (style) => {
1036
+ return host.haptics.triggerHapticAsync(style);
1037
+ };
1038
+ }
1039
+
1040
+ // src/iap/RpcIapApi.ts
1041
+ var RpcIapApi = class {
1042
+ constructor(rpcClient) {
1043
+ __publicField(this, "rpcClient");
1044
+ this.rpcClient = rpcClient;
1045
+ }
1046
+ async getHardCurrencyBalance() {
1047
+ const response = await this.rpcClient.call(
1048
+ "H5_IAP_GET_WALLET" /* H5_IAP_GET_WALLET */
1049
+ );
1050
+ return response;
1051
+ }
1052
+ async spendCurrency(productId, cost, options) {
1053
+ const result = await this.rpcClient.callT("H5_IAP_SPEND_CURRENCY" /* H5_IAP_SPEND_CURRENCY */, {
1054
+ amount: cost,
1055
+ productId,
1056
+ screenName: options?.screenName
1057
+ });
1058
+ if (!result.success) {
1059
+ throw new Error(result.error);
1060
+ }
1061
+ }
1062
+ };
1063
+
1064
+ // src/iap/MockIapApi.ts
1065
+ var MockIapApi = class {
1066
+ constructor() {
1067
+ __publicField(this, "_hardCurrency", 100);
1068
+ }
1069
+ get hardCurrency() {
1070
+ return this._hardCurrency;
1071
+ }
1072
+ set hardCurrency(value) {
1073
+ this._hardCurrency = value;
1074
+ }
1075
+ async spendCurrency(productId, cost, options) {
1076
+ console.log(`[Mock IAP] Spending ${cost} on ${productId})`);
1077
+ const remainingHardCurrency = this._hardCurrency - cost;
1078
+ if (remainingHardCurrency < 0) {
1079
+ throw new Error(
1080
+ `Not enough hard currency. Expected ${cost}, found ${this._hardCurrency}`
1081
+ );
1082
+ }
1083
+ this._hardCurrency = remainingHardCurrency;
1084
+ }
1085
+ async getHardCurrencyBalance() {
1086
+ console.log("[Mock IAP] get hard currency called");
1087
+ return this._hardCurrency;
1088
+ }
1089
+ };
1090
+
1091
+ // src/iap/index.ts
1092
+ function initializeIap(venusApiInstance, host) {
1093
+ venusApiInstance.iap = host.iap;
1094
+ }
1095
+
1096
+ // src/lifecycles/MockLifecycleApi.ts
1097
+ var MockLifecycleApi = class {
1098
+ constructor() {
1099
+ __publicField(this, "playCallbacks", []);
1100
+ __publicField(this, "pauseCallbacks", []);
1101
+ __publicField(this, "resumeCallbacks", []);
1102
+ __publicField(this, "quitCallbacks", []);
1103
+ __publicField(this, "showCallbacks", []);
1104
+ __publicField(this, "hideCallbacks", []);
1105
+ }
1106
+ onCleanup(callback) {
1107
+ }
1108
+ onShow(callback) {
1109
+ this.showCallbacks.push(callback);
1110
+ }
1111
+ onHide(callback) {
1112
+ this.hideCallbacks.push(callback);
1113
+ }
1114
+ onPause(callback) {
1115
+ this.pauseCallbacks.push(callback);
1116
+ }
1117
+ onPlay(callback) {
1118
+ this.playCallbacks.push(callback);
1119
+ }
1120
+ onQuit(callback) {
1121
+ this.quitCallbacks.push(callback);
1122
+ }
1123
+ onResume(callback) {
1124
+ this.resumeCallbacks.push(callback);
1125
+ }
1126
+ triggerOnPlayCallbacks(context) {
1127
+ for (const callback of this.playCallbacks) {
1128
+ callback(context);
1129
+ }
1130
+ }
1131
+ triggerOnPauseCallbacks() {
1132
+ for (const callback of this.pauseCallbacks) {
1133
+ callback();
1134
+ }
1135
+ }
1136
+ triggerOnResumeCallbacks() {
1137
+ for (const callback of this.resumeCallbacks) {
1138
+ callback();
1139
+ }
1140
+ }
1141
+ triggerOnShowCallbacks(context) {
1142
+ for (const callback of this.showCallbacks) {
1143
+ callback(context);
1144
+ }
1145
+ }
1146
+ triggerOnHideCallbacks() {
1147
+ for (const callback of this.hideCallbacks) {
1148
+ callback();
1149
+ }
1150
+ }
1151
+ triggerOnQuitCallbacks() {
1152
+ for (const callback of this.quitCallbacks) {
1153
+ callback();
1154
+ }
1155
+ }
1156
+ };
1157
+
1158
+ // src/lifecycles/RpcLifecycleApi.ts
1159
+ var RpcLifecycleApi = class {
1160
+ constructor(rpcClient) {
1161
+ __publicField(this, "rpcClient");
1162
+ this.rpcClient = rpcClient;
1163
+ }
1164
+ onCleanup(callback) {
1165
+ this.rpcClient.onNotification("CLEANUP" /* CLEANUP */, callback);
1166
+ }
1167
+ onHide(callback) {
1168
+ this.rpcClient.onNotification("HIDDEN" /* HIDDEN */, callback);
1169
+ }
1170
+ onPause(callback) {
1171
+ this.rpcClient.onNotification("PAUSE" /* PAUSE */, callback);
1172
+ }
1173
+ onPlay(callback) {
1174
+ this.rpcClient.onNotification("PLAY" /* PLAY */, callback);
1175
+ }
1176
+ onQuit(callback) {
1177
+ this.rpcClient.onNotification("QUIT" /* QUIT */, callback);
1178
+ }
1179
+ onResume(callback) {
1180
+ this.rpcClient.onNotification("RESUME" /* RESUME */, callback);
1181
+ }
1182
+ onShow(callback) {
1183
+ this.rpcClient.onNotification("SHOWN" /* SHOWN */, callback);
1184
+ }
1185
+ };
1186
+
1187
+ // src/lifecycles/index.ts
1188
+ function initializeLifecycleApi(venusApi, host) {
1189
+ venusApi.onPlay = (callback) => {
1190
+ host.lifecycle.onPlay(callback);
1191
+ };
1192
+ venusApi.onPause = (callback) => {
1193
+ host.lifecycle.onPause(callback);
1194
+ };
1195
+ venusApi.onResume = (callback) => {
1196
+ host.lifecycle.onResume(callback);
1197
+ };
1198
+ venusApi.onShow = (callback) => {
1199
+ host.lifecycle.onShow(callback);
1200
+ };
1201
+ venusApi.onHide = (callback) => {
1202
+ host.lifecycle.onHide(callback);
1203
+ };
1204
+ venusApi.onQuit = (callback) => {
1205
+ host.lifecycle.onQuit(callback);
1206
+ };
1207
+ venusApi.onCleanup = (callback) => {
1208
+ host.lifecycle.onCleanup(callback);
1209
+ };
1210
+ }
1211
+
1212
+ // src/logging/MockLoggingApi.ts
1213
+ var MockLoggingApi = class {
1214
+ logDebug(message, ...args) {
1215
+ console.log(`[Venus Mock] ${message}`, args);
1216
+ }
1217
+ logError(message, ...args) {
1218
+ console.error(`[Venus Mock] ${message}`, args);
1219
+ }
1220
+ };
1221
+
1222
+ // src/logging/RpcLoggingApi.ts
1223
+ var RpcLoggingApi = class {
1224
+ constructor(host, rpcClient) {
1225
+ __publicField(this, "host");
1226
+ __publicField(this, "rpcClient");
1227
+ this.host = host;
1228
+ this.rpcClient = rpcClient;
1229
+ }
1230
+ logDebug(message, ...args) {
1231
+ if (!this.host.isInitialized) {
1232
+ console.log(message, args);
1233
+ } else {
1234
+ message = this.buildMessage(message, ...args);
1235
+ this.rpcClient.call("H5_DEBUG" /* DEBUG */, { level: "log", message });
1236
+ }
1237
+ }
1238
+ logError(message, ...args) {
1239
+ if (!this.host.isInitialized) {
1240
+ console.log(message, ...args);
1241
+ } else {
1242
+ message = this.buildMessage(message, ...args);
1243
+ this.rpcClient.call("H5_DEBUG" /* DEBUG */, {
1244
+ level: "error",
1245
+ message
1246
+ });
1247
+ }
1248
+ }
1249
+ buildMessage(message, ...args) {
1250
+ if (args && args.length > 0) {
1251
+ const stringArgs = [];
1252
+ for (const arg of args) {
1253
+ const argAsString = this.toStringArg(arg);
1254
+ if (argAsString) {
1255
+ stringArgs.push(argAsString);
1256
+ }
1257
+ }
1258
+ message += stringArgs.join(" ");
1259
+ }
1260
+ return message;
1261
+ }
1262
+ toStringArg(arg) {
1263
+ if (arg) {
1264
+ if (typeof arg === "object") {
1265
+ try {
1266
+ return JSON.stringify(arg);
1267
+ } catch (e) {
1268
+ return String(arg);
1269
+ }
1270
+ }
1271
+ return String(arg);
1272
+ }
1273
+ return void 0;
1274
+ }
1275
+ };
1276
+
1277
+ // src/logging/index.ts
1278
+ function initializeLoggingApi(venusApi, host) {
1279
+ venusApi.log = (message, ...args) => {
1280
+ return host.logging.logDebug(message, ...args);
1281
+ };
1282
+ venusApi.error = (message, ...args) => {
1283
+ return host.logging.logError(message, ...args);
1284
+ };
1285
+ }
1286
+
1287
+ // src/navigation/MockNavigationApi.ts
1288
+ var MockNavigationApi = class {
1289
+ constructor(venusApi) {
1290
+ __publicField(this, "venusApi");
1291
+ this.venusApi = venusApi;
1292
+ }
1293
+ async requestPopOrQuit(options) {
1294
+ return true;
1295
+ }
1296
+ getStackInfo() {
1297
+ const venusApi = this.venusApi;
1298
+ const info = {
1299
+ isInStack: venusApi._mock.stackState.isInStack,
1300
+ stackPosition: venusApi._mock.stackState.stackPosition,
1301
+ isTopOfStack: venusApi._mock.stackState.isTopOfStack,
1302
+ stackDepth: venusApi._mock.stackState.stackDepth,
1303
+ parentInstanceId: venusApi._mock.stackState.parentInstanceId
1304
+ };
1305
+ return info;
1306
+ }
1307
+ async popApp() {
1308
+ const venusApi = this.venusApi;
1309
+ if (venusApi._mock.stackState.stackDepth <= 1) {
1310
+ console.warn("[Venus Mock] Cannot pop - at base of stack or not in stack");
1311
+ return;
1312
+ }
1313
+ await createMockDelay(MOCK_DELAYS.short);
1314
+ const poppedApp = venusApi._mock.stackState.stackHistory.pop();
1315
+ venusApi._mock.stackState.stackDepth--;
1316
+ venusApi._mock.stackState.stackPosition = Math.max(
1317
+ 0,
1318
+ venusApi._mock.stackState.stackDepth - 1
1319
+ );
1320
+ if (venusApi._mock.stackState.stackDepth === 0) {
1321
+ venusApi._mock.stackState.isInStack = false;
1322
+ venusApi._mock.stackState.isTopOfStack = false;
1323
+ venusApi._mock.stackState.parentInstanceId = null;
1324
+ }
1325
+ this.log("App popped: ", poppedApp);
1326
+ }
1327
+ async pushApp(appId, options) {
1328
+ const venusApi = this.venusApi;
1329
+ await createMockDelay(MOCK_DELAYS.medium);
1330
+ venusApi._mock.stackState.stackHistory.push({
1331
+ appId,
1332
+ pushedAt: Date.now(),
1333
+ contextData: options?.contextData,
1334
+ appParams: options?.appParams
1335
+ });
1336
+ venusApi._mock.stackState.isInStack = true;
1337
+ venusApi._mock.stackState.stackDepth++;
1338
+ venusApi._mock.stackState.stackPosition = venusApi._mock.stackState.stackDepth - 1;
1339
+ venusApi._mock.stackState.isTopOfStack = true;
1340
+ const pushedInstanceId = `mock-stack-${appId}-${Date.now()}`;
1341
+ this.log("PushedInstanceId: ", pushedInstanceId);
1342
+ }
1343
+ log(message, ...args) {
1344
+ console.log(`[Venus Mock] ${message}`, ...args);
1345
+ }
1346
+ };
1347
+
1348
+ // src/navigation/RpcNavigationApi.ts
1349
+ var RpcNavigationApi = class {
1350
+ constructor(rpcClient, venusApi) {
1351
+ __publicField(this, "venusApi");
1352
+ __publicField(this, "rpcClient");
1353
+ this.rpcClient = rpcClient;
1354
+ this.venusApi = venusApi;
1355
+ }
1356
+ async requestPopOrQuit(options) {
1357
+ const result = await this.rpcClient.call(
1358
+ "QUIT" /* QUIT */,
1359
+ options
1360
+ );
1361
+ return result.success;
1362
+ }
1363
+ getStackInfo() {
1364
+ this.venusApi;
1365
+ console.log("[Venus] getStackInfo called");
1366
+ const config = window.venus._config;
1367
+ const stackInfo = config.context?.stack || {
1368
+ isInStack: false,
1369
+ stackPosition: 0,
1370
+ parentInstanceId: null,
1371
+ appType: "standalone"
1372
+ };
1373
+ return stackInfo;
1374
+ }
1375
+ popApp() {
1376
+ const rpcClient = this.rpcClient;
1377
+ console.log("[Venus] popAppAsync called");
1378
+ return rpcClient.call("H5_STACK_POP_REQUEST" /* H5_STACK_POP_REQUEST */);
1379
+ }
1380
+ pushApp(appId, options) {
1381
+ const rpcClient = this.rpcClient;
1382
+ console.log("[Venus] pushAppAsync called", { appId, options });
1383
+ return rpcClient.call("H5_STACK_PUSH_REQUEST" /* H5_STACK_PUSH_REQUEST */, {
1384
+ targetAppId: appId,
1385
+ contextData: options?.contextData,
1386
+ appParams: options?.appParams
1387
+ });
1388
+ }
1389
+ };
1390
+
1391
+ // src/navigation/index.ts
1392
+ function initializeStackNavigation(venusApi, host) {
1393
+ venusApi._mock.stackState = {
1394
+ isInStack: false,
1395
+ stackPosition: 0,
1396
+ stackDepth: 0,
1397
+ isTopOfStack: false,
1398
+ parentInstanceId: null,
1399
+ stackHistory: []
1400
+ // Track navigation history for mock
1401
+ };
1402
+ venusApi.pushAppAsync = host.navigation.pushApp.bind(host.navigation);
1403
+ venusApi.popAppAsync = host.navigation.popApp.bind(host.navigation);
1404
+ venusApi.getStackInfo = host.navigation.getStackInfo.bind(host.navigation);
1405
+ venusApi.requestPopOrQuit = (options) => {
1406
+ return host.navigation.requestPopOrQuit(options);
1407
+ };
1408
+ }
1409
+
1410
+ // src/notifications/MockNotificationsApi.ts
1411
+ var MockNotificationsApi = class {
1412
+ constructor(venusApi) {
1413
+ __publicField(this, "venusApi");
1414
+ this.venusApi = venusApi;
1415
+ }
1416
+ async cancelLocalNotification(notificationId) {
1417
+ const venusApi = this.venusApi;
1418
+ if (isWebPlatform()) {
1419
+ console.log(
1420
+ "[Venus Mock] Cancel notification on web platform (simulated):",
1421
+ notificationId
1422
+ );
1423
+ return true;
1424
+ }
1425
+ console.log("[Venus Mock] Cancel local notification:", notificationId);
1426
+ await createMockDelay(MOCK_DELAYS.short);
1427
+ if (venusApi._mock.scheduledNotifications && venusApi._mock.scheduledNotifications[notificationId]) {
1428
+ delete venusApi._mock.scheduledNotifications[notificationId];
1429
+ return true;
1430
+ }
1431
+ return false;
1432
+ }
1433
+ async getAllScheduledLocalNotifications() {
1434
+ if (isWebPlatform()) {
1435
+ console.log(
1436
+ "[Venus Mock] Get notifications on web platform (returning empty list)"
1437
+ );
1438
+ return [];
1439
+ }
1440
+ console.log("[Venus Mock] Get all scheduled local notifications");
1441
+ await createMockDelay(MOCK_DELAYS.short);
1442
+ const venusApi = this.venusApi;
1443
+ const notifications = venusApi._mock.scheduledNotifications || {};
1444
+ return Object.values(notifications);
1445
+ }
1446
+ async isLocalNotificationsEnabled() {
1447
+ if (isWebPlatform()) {
1448
+ console.log("[Venus Mock] Notifications not available on web platform");
1449
+ return false;
1450
+ }
1451
+ console.log("[Venus Mock] Check if local notifications are enabled");
1452
+ await createMockDelay(MOCK_DELAYS.short);
1453
+ const venusApi = this.venusApi;
1454
+ const isEnabled = venusApi._mock.notificationsEnabled !== false;
1455
+ return isEnabled;
1456
+ }
1457
+ async scheduleLocalNotification(title, body, options) {
1458
+ if (isWebPlatform()) {
1459
+ console.log(
1460
+ "[Venus Mock] Notifications not supported on web platform, simulating success"
1461
+ );
1462
+ console.info(
1463
+ "\u{1F514} [Venus Mock] Notification would be scheduled:",
1464
+ title || "Untitled",
1465
+ "\n Body:",
1466
+ body || "No body",
1467
+ "\n This is a simulation - real notifications require a native platform."
1468
+ );
1469
+ const mockId = `mock-web-notification-${Date.now()}`;
1470
+ return mockId;
1471
+ }
1472
+ console.log("[Venus Mock] Schedule local notification:", options);
1473
+ const venusApi = this.venusApi;
1474
+ if (!venusApi._mock.pendingRequests) {
1475
+ console.log("[Venus Mock] Initializing pendingRequests");
1476
+ venusApi._mock.pendingRequests = {};
1477
+ }
1478
+ const requestId = Date.now().toString();
1479
+ console.log("[Venus Mock] Creating request with ID:", requestId);
1480
+ return new Promise((resolve) => {
1481
+ venusApi._mock.pendingRequests[requestId] = { resolve };
1482
+ const notificationId = `mock-notification-${Date.now()}`;
1483
+ if (!venusApi._mock.scheduledNotifications) {
1484
+ venusApi._mock.scheduledNotifications = {};
1485
+ }
1486
+ venusApi._mock.scheduledNotifications[notificationId] = {
1487
+ ...options,
1488
+ id: notificationId,
1489
+ createdAt: Date.now()
1490
+ };
1491
+ setTimeout(() => {
1492
+ resolve(notificationId);
1493
+ }, MOCK_DELAYS.short);
1494
+ });
1495
+ }
1496
+ async setLocalNotificationsEnabled(enabled) {
1497
+ const venusApi = this.venusApi;
1498
+ if (isWebPlatform()) {
1499
+ console.log(
1500
+ "[Venus Mock] Set notifications enabled on web platform (simulated):",
1501
+ enabled
1502
+ );
1503
+ return true;
1504
+ }
1505
+ console.log("[Venus Mock] Set local notifications enabled:", enabled);
1506
+ await createMockDelay(MOCK_DELAYS.short);
1507
+ venusApi._mock.notificationsEnabled = enabled;
1508
+ return enabled;
1509
+ }
1510
+ };
1511
+
1512
+ // src/notifications/index.ts
1513
+ function initializeLocalNotifications(venusApi, host) {
1514
+ venusApi.setLocalNotifEnabledAsync = async (enable) => {
1515
+ await host.notifications.setLocalNotificationsEnabled(enable);
1516
+ };
1517
+ venusApi.isLocalNotifEnabledAsync = async () => {
1518
+ return host.notifications.isLocalNotificationsEnabled();
1519
+ };
1520
+ venusApi.getAllLocalNotifsAsync = async () => {
1521
+ return host.notifications.getAllScheduledLocalNotifications();
1522
+ };
1523
+ venusApi.cancelLocalNotifAsync = async (notificationId) => {
1524
+ await host.notifications.cancelLocalNotification(notificationId);
1525
+ };
1526
+ venusApi.scheduleLocalNotifAsync = async (options) => {
1527
+ const id = await host.notifications.scheduleLocalNotification(
1528
+ options.title,
1529
+ options.body
1530
+ );
1531
+ if (id) {
1532
+ return id;
1533
+ }
1534
+ return "";
1535
+ };
1536
+ }
1537
+
1538
+ // src/popups/RpcPopupsApi.ts
1539
+ var RpcPopupsApi = class {
1540
+ constructor(rpcClient) {
1541
+ __publicField(this, "rpcClient");
1542
+ this.rpcClient = rpcClient;
1543
+ }
1544
+ async showActionSheet(items, options) {
1545
+ const result = await this.rpcClient.call(
1546
+ "H5_ACTION_SHEET_SHOW" /* ACTION_SHEET_SHOW */,
1547
+ {
1548
+ title: options?.title || "",
1549
+ message: options?.message || "",
1550
+ options: items,
1551
+ cancelButtonText: options?.cancelButtonText || "Cancel"
1552
+ }
1553
+ );
1554
+ return result;
1555
+ }
1556
+ async showAlert(title, message, options) {
1557
+ const buttonText = options?.buttonText || "OK";
1558
+ await this.rpcClient.call("H5_ALERT_DIALOG" /* ALERT_DIALOG */, {
1559
+ title,
1560
+ message,
1561
+ buttonText
1562
+ });
1563
+ }
1564
+ async showConfirm(title, message, options) {
1565
+ const confirmText = options?.confirmText || "OK";
1566
+ const cancelText = options?.cancelText || "Cancel";
1567
+ const result = await this.rpcClient.call(
1568
+ "H5_CONFIRM_DIALOG" /* CONFIRM_DIALOG */,
1569
+ {
1570
+ title,
1571
+ message,
1572
+ confirmText,
1573
+ cancelText
1574
+ }
1575
+ );
1576
+ return result;
1577
+ }
1578
+ async showToast(message, options) {
1579
+ const duration = options?.duration ?? 3e3;
1580
+ const variant = options?.variant ?? "info";
1581
+ const response = await this.rpcClient.call(
1582
+ "H5_TOAST" /* TOAST */,
1583
+ {
1584
+ message,
1585
+ duration,
1586
+ variant,
1587
+ action: options?.action
1588
+ },
1589
+ duration + 2e3
1590
+ );
1591
+ return response.actionTriggered;
1592
+ }
1593
+ };
1594
+
1595
+ // src/popups/MockPopupsApi.ts
1596
+ var MockPopupsApi = class {
1597
+ constructor(override) {
1598
+ __publicField(this, "overlay");
1599
+ this.overlay = override;
1600
+ }
1601
+ showActionSheet(items, options) {
1602
+ console.log(
1603
+ `[Venus Mock] Show Action sheet, items: ${JSON.stringify(items, null, 2)}, options: ${JSON.stringify(options, null, 2)}`
1604
+ );
1605
+ return this.overlay.showActionSheet(items, options);
1606
+ }
1607
+ async showAlert(title, message, options) {
1608
+ window.alert(`${title}
1609
+ ${message}`);
1610
+ }
1611
+ async showConfirm(title, message, options) {
1612
+ const result = window.confirm(`${title || "Confirm"}
1613
+ ${message}`);
1614
+ return result;
1615
+ }
1616
+ async showToast(message, options) {
1617
+ const variant = options?.variant ?? "info";
1618
+ const duration = options?.duration ?? 3e3;
1619
+ const action = options?.action;
1620
+ console.log("[Venus Mock] Toast:", message, {
1621
+ variant,
1622
+ duration,
1623
+ hasAction: !!action
1624
+ });
1625
+ if (action) {
1626
+ const actionResult = window.confirm(
1627
+ `${message}
1628
+
1629
+ [${action.label}] or [Cancel]`
1630
+ );
1631
+ if (actionResult) {
1632
+ console.log("[Venus Mock] Toast action triggered:", action.label);
1633
+ return true;
1634
+ }
1635
+ }
1636
+ return false;
1637
+ }
1638
+ };
1639
+
1640
+ // src/popups/index.ts
1641
+ function initializePopups(venusApi, host) {
1642
+ venusApi.showToast = async (input) => {
1643
+ if (typeof input === "string") {
1644
+ return await host.popups.showToast(input);
1645
+ } else {
1646
+ return await host.popups.showToast(input.message, {
1647
+ duration: input.duration,
1648
+ action: input.action,
1649
+ variant: "success"
1650
+ });
1651
+ }
1652
+ };
1653
+ venusApi.showAlert = async (input) => {
1654
+ await host.popups.showAlert(input.title, input.message, {
1655
+ buttonText: input.buttonText
1656
+ });
1657
+ };
1658
+ venusApi.showConfirm = async (input) => {
1659
+ const confirmed = await host.popups.showConfirm(
1660
+ input.title,
1661
+ input.message,
1662
+ {
1663
+ confirmText: input.confirmText,
1664
+ cancelText: input.cancelText
1665
+ }
1666
+ );
1667
+ return confirmed;
1668
+ };
1669
+ venusApi.showActionSheet = async (input) => {
1670
+ return await host.popups.showActionSheet(input.options, {
1671
+ title: input.title,
1672
+ message: input.message,
1673
+ cancelButtonText: input.cancelButtonText,
1674
+ disableCancel: input.disableCancel
1675
+ });
1676
+ };
1677
+ venusApi.popups = host.popups;
1678
+ }
1679
+
1680
+ // src/profile/HostProfileApi.ts
1681
+ var HostProfileApi = class {
1682
+ getCurrentProfile() {
1683
+ if (window.venus._config && window.venus._config.profile) {
1684
+ return {
1685
+ id: window.venus._config.profile.id || "unknown",
1686
+ name: window.venus._config.profile.username || "Unknown User",
1687
+ username: window.venus._config.profile.username || "unknown"
1688
+ };
1689
+ }
1690
+ return {
1691
+ id: "mock_profile_123",
1692
+ name: "Mock User",
1693
+ username: "mockuser"
1694
+ };
1695
+ }
1696
+ };
1697
+
1698
+ // src/profile/MockProfileApi.ts
1699
+ var MockProfileApi = class {
1700
+ getCurrentProfile() {
1701
+ return {
1702
+ id: "mock_profile_123",
1703
+ name: "Mock User",
1704
+ username: "mockuser"
1705
+ };
1706
+ }
1707
+ };
1708
+
1709
+ // src/profile/index.ts
1710
+ function initializeProfile(venusApi, host) {
1711
+ venusApi.getCurrentProfile = () => {
1712
+ return host.profile.getCurrentProfile();
1713
+ };
1714
+ }
1715
+
1716
+ // src/rpc/RpcClient.ts
1717
+ var RpcClient = class {
1718
+ constructor() {
1719
+ __publicField(this, "pendingCalls", /* @__PURE__ */ new Map());
1720
+ __publicField(this, "notificationCallbacks", /* @__PURE__ */ new Map());
1721
+ __publicField(this, "onResponseSub", null);
1722
+ __publicField(this, "onNotificationSub", null);
1723
+ __publicField(this, "transport", null);
1724
+ }
1725
+ start(transport) {
1726
+ this.transport = transport;
1727
+ this.onResponseSub = transport.onResponse(async (response) => {
1728
+ return this.handleRpcResponse(response);
1729
+ });
1730
+ this.onNotificationSub = transport.onNotification(async (notification) => {
1731
+ return this.handleRpcNotification(notification);
1732
+ });
1733
+ }
1734
+ stop() {
1735
+ if (this.onResponseSub) {
1736
+ this.onResponseSub.unsubscribe();
1737
+ this.onResponseSub = null;
1738
+ }
1739
+ if (this.onNotificationSub) {
1740
+ this.onNotificationSub.unsubscribe();
1741
+ this.onNotificationSub = null;
1742
+ }
1743
+ this.transport = null;
1744
+ }
1745
+ onNotification(id, callback) {
1746
+ this.notificationCallbacks.set(id, callback);
1747
+ return {
1748
+ unsubscribe: () => {
1749
+ this.notificationCallbacks.delete(id);
1750
+ }
1751
+ };
1752
+ }
1753
+ callT(method, args, timeout = 5e3) {
1754
+ return this.call(method, args, timeout);
1755
+ }
1756
+ async call(method, args, timeout = 5e3) {
1757
+ return new Promise((resolve, reject) => {
1758
+ const id = this.generateId();
1759
+ this.addPendingCall(id, resolve, reject);
1760
+ const request = {
1761
+ type: "rpc-request",
1762
+ id,
1763
+ method,
1764
+ args
1765
+ };
1766
+ if (this.transport) {
1767
+ this.transport.sendRequest(request);
1768
+ }
1769
+ setTimeout(() => {
1770
+ if (this.hasPendingCall(id)) {
1771
+ this.removePendingCall(id);
1772
+ reject(new Error(`RPC call ${method} timed out`));
1773
+ }
1774
+ }, timeout);
1775
+ });
1776
+ }
1777
+ hasPendingCall(id) {
1778
+ return this.pendingCalls.has(id);
1779
+ }
1780
+ addPendingCall(id, resolve, reject) {
1781
+ this.pendingCalls.set(id, {
1782
+ id,
1783
+ resolve,
1784
+ reject
1785
+ });
1786
+ }
1787
+ removePendingCall(id) {
1788
+ this.pendingCalls.delete(id);
1789
+ }
1790
+ getPendingCall(id) {
1791
+ return this.pendingCalls.get(id);
1792
+ }
1793
+ generateId() {
1794
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1795
+ }
1796
+ handleRpcResponse(response) {
1797
+ const pending = this.getPendingCall(response.id);
1798
+ if (!pending) {
1799
+ return false;
1800
+ }
1801
+ this.removePendingCall(response.id);
1802
+ if (response.error) {
1803
+ pending.reject(new Error(response.error.message));
1804
+ return true;
1805
+ }
1806
+ pending.resolve(response.result);
1807
+ return true;
1808
+ }
1809
+ handleRpcNotification(notification) {
1810
+ const callback = this.notificationCallbacks.get(notification.id);
1811
+ if (callback) {
1812
+ callback(notification.payload);
1813
+ }
1814
+ }
1815
+ };
1816
+
1817
+ // src/storage/MockStorageApi.ts
1818
+ function createMockStorageApi(storageType, appUrl) {
1819
+ const appIdentifier = appUrl ? generateAppIdentifier(appUrl) : null;
1820
+ let prefix;
1821
+ let syncDelay = 0;
1822
+ switch (storageType) {
1823
+ case "deviceCache":
1824
+ prefix = "venus:app";
1825
+ syncDelay = 0;
1826
+ break;
1827
+ case "appStorage":
1828
+ prefix = "venus:app";
1829
+ syncDelay = 100;
1830
+ break;
1831
+ case "globalStorage":
1832
+ prefix = "venus:global";
1833
+ syncDelay = 100;
1834
+ break;
1835
+ default:
1836
+ throw new Error(`Unknown storage type: ${storageType}`);
1837
+ }
1838
+ prefix = storageType === "globalStorage" || !appIdentifier ? `${prefix}:` : `${prefix}:${appIdentifier}:`;
1839
+ return new MockStorageApi(prefix, syncDelay);
1840
+ }
1841
+ var MockStorageApi = class {
1842
+ constructor(prefix, syncDelay) {
1843
+ __publicField(this, "prefix");
1844
+ __publicField(this, "syncDelay");
1845
+ this.prefix = prefix;
1846
+ this.syncDelay = syncDelay;
1847
+ }
1848
+ async clear() {
1849
+ const fullLength = localStorage.length;
1850
+ for (let i = 0; i < fullLength; i++) {
1851
+ const fullKey = localStorage.key(i);
1852
+ if (fullKey && fullKey.startsWith(this.prefix)) {
1853
+ localStorage.removeItem(fullKey);
1854
+ }
1855
+ }
1856
+ await this.simulateSyncDelay();
1857
+ }
1858
+ async getAllItems() {
1859
+ const items = new Array();
1860
+ const fullLength = localStorage.length;
1861
+ for (let i = 0; i < fullLength; i++) {
1862
+ const fullKey = localStorage.key(i);
1863
+ if (fullKey && fullKey.startsWith(this.prefix)) {
1864
+ const item = localStorage.getItem(fullKey);
1865
+ if (item) {
1866
+ items.push(item);
1867
+ }
1868
+ }
1869
+ }
1870
+ return items;
1871
+ }
1872
+ async getItem(key) {
1873
+ const fullKey = this.buildKey(key);
1874
+ await this.simulateSyncDelay();
1875
+ return localStorage.getItem(fullKey);
1876
+ }
1877
+ async key(index) {
1878
+ const keys = this.keys();
1879
+ if (index < 0 || index >= keys.length) {
1880
+ return null;
1881
+ }
1882
+ await this.simulateSyncDelay();
1883
+ return keys[index];
1884
+ }
1885
+ async length() {
1886
+ return this.keys().length;
1887
+ }
1888
+ async removeItem(key) {
1889
+ const fullKey = this.buildKey(key);
1890
+ await this.simulateSyncDelay();
1891
+ localStorage.removeItem(fullKey);
1892
+ }
1893
+ async setItem(key, item) {
1894
+ const fullKey = this.buildKey(key);
1895
+ await this.simulateSyncDelay();
1896
+ localStorage.setItem(fullKey, item);
1897
+ }
1898
+ async setMultipleItems(entries) {
1899
+ for (const entry of entries) {
1900
+ const fullKey = this.buildKey(entry.key);
1901
+ localStorage.setItem(fullKey, entry.value);
1902
+ }
1903
+ await this.simulateSyncDelay();
1904
+ }
1905
+ async removeMultipleItems(keys) {
1906
+ for (const key of keys) {
1907
+ const fullKey = this.buildKey(key);
1908
+ localStorage.removeItem(fullKey);
1909
+ }
1910
+ await this.simulateSyncDelay();
1911
+ }
1912
+ buildKey(key) {
1913
+ const prefix = this.prefix;
1914
+ return `${prefix}${key}`;
1915
+ }
1916
+ extractKey(fullKey) {
1917
+ const prefix = this.prefix;
1918
+ return fullKey.substring(prefix.length);
1919
+ }
1920
+ keys() {
1921
+ const keys = new Array();
1922
+ let length = localStorage.length;
1923
+ for (let i = 0; i < length; i++) {
1924
+ const fullKey = localStorage.key(i);
1925
+ if (fullKey && fullKey.startsWith(this.prefix)) {
1926
+ length++;
1927
+ const key = this.extractKey(fullKey);
1928
+ keys.push(key);
1929
+ }
1930
+ }
1931
+ return keys;
1932
+ }
1933
+ async simulateSyncDelay() {
1934
+ const syncDelay = this.syncDelay;
1935
+ if (syncDelay > 0) {
1936
+ await new Promise((resolve) => setTimeout(resolve, syncDelay));
1937
+ }
1938
+ }
1939
+ };
1940
+ function generateAppIdentifier(appUrl) {
1941
+ if (!appUrl) appUrl = "";
1942
+ const normalizedId = normalizeAppIdentifier(appUrl);
1943
+ let hash = 0;
1944
+ for (let i = 0; i < normalizedId.length; i++) {
1945
+ const char = normalizedId.charCodeAt(i);
1946
+ hash = (hash << 5) - hash + char;
1947
+ hash |= 0;
1948
+ }
1949
+ return Math.abs(hash).toString(16);
1950
+ }
1951
+ function normalizeAppIdentifier(input) {
1952
+ if (input.startsWith("http")) {
1953
+ try {
1954
+ const url = new URL(input);
1955
+ const pathParts = url.pathname.split("/");
1956
+ const h5Index = pathParts.findIndex((part) => part === "H5");
1957
+ if (h5Index !== -1 && h5Index < pathParts.length - 1) {
1958
+ const appId = pathParts[h5Index + 1];
1959
+ return appId;
1960
+ }
1961
+ return url.hostname;
1962
+ } catch (error) {
1963
+ console.error(`[Venus Mock] Error parsing URL: ${error}`, { input });
1964
+ return input;
1965
+ }
1966
+ }
1967
+ if (input.includes("/H5/")) {
1968
+ try {
1969
+ const pathParts = input.split("/");
1970
+ const h5Index = pathParts.findIndex((part) => part === "H5");
1971
+ if (h5Index !== -1 && h5Index < pathParts.length - 1) {
1972
+ const appId = pathParts[h5Index + 1];
1973
+ return appId;
1974
+ }
1975
+ } catch (error) {
1976
+ console.error(`[Venus Mock] Error parsing path-based URL: ${error}`, {
1977
+ input
1978
+ });
1979
+ }
1980
+ }
1981
+ return input;
1982
+ }
1983
+
1984
+ // src/storage/RpcStorageApi.ts
1985
+ var RpcStorageApi = class {
1986
+ constructor(rpcClient, methodIds) {
1987
+ __publicField(this, "rpcClient");
1988
+ __publicField(this, "methodIds");
1989
+ this.rpcClient = rpcClient;
1990
+ this.methodIds = methodIds;
1991
+ }
1992
+ clear() {
1993
+ return this.rpcClient.call(this.methodIds.clear);
1994
+ }
1995
+ getItem(key) {
1996
+ return this.rpcClient.call(this.methodIds.getItem, {
1997
+ key
1998
+ });
1999
+ }
2000
+ setItem(key, value) {
2001
+ return this.rpcClient.call(this.methodIds.setItem, {
2002
+ key,
2003
+ value
2004
+ });
2005
+ }
2006
+ key(index) {
2007
+ return this.rpcClient.call(this.methodIds.getKey, {
2008
+ index
2009
+ });
2010
+ }
2011
+ length() {
2012
+ return this.rpcClient.call(this.methodIds.length);
2013
+ }
2014
+ removeItem(key) {
2015
+ return this.rpcClient.call(this.methodIds.removeItem, {
2016
+ key
2017
+ });
2018
+ }
2019
+ removeMultipleItems(keys) {
2020
+ if (!this.methodIds.removeMultipleItems) {
2021
+ throw new Error("Method not implemented");
2022
+ }
2023
+ return this.rpcClient.call(this.methodIds.removeMultipleItems, {
2024
+ keys
2025
+ });
2026
+ }
2027
+ getAllItems() {
2028
+ if (!this.methodIds.getAllItems) {
2029
+ throw new Error("Method not implemented");
2030
+ }
2031
+ return this.rpcClient.call(this.methodIds.getAllItems);
2032
+ }
2033
+ setMultipleItems(items) {
2034
+ if (!this.methodIds.setMultipleItems) {
2035
+ throw new Error("Method not implemented");
2036
+ }
2037
+ return this.rpcClient.call(this.methodIds.setMultipleItems, {
2038
+ items
2039
+ });
2040
+ }
2041
+ };
2042
+
2043
+ // src/storage/index.ts
2044
+ function initializeStorage(venusApiInstance, host) {
2045
+ venusApiInstance.deviceCache = host.deviceCache;
2046
+ venusApiInstance.appStorage = host.appStorage;
2047
+ venusApiInstance.globalStorage = host.globalStorage;
2048
+ }
2049
+
2050
+ // src/simulation/utils.ts
2051
+ function sumContributions(contributions) {
2052
+ const totals = {};
2053
+ for (const profileId in contributions) {
2054
+ for (const entityId in contributions[profileId]) {
2055
+ const amount = contributions[profileId][entityId] || 0;
2056
+ totals[entityId] = (totals[entityId] || 0) + amount;
2057
+ }
2058
+ }
2059
+ return totals;
2060
+ }
2061
+
2062
+ // src/simulation/RpcSimulationApi.ts
2063
+ var RpcSimulationApi = class {
2064
+ constructor(rpcClient) {
2065
+ __publicField(this, "rpcClient");
2066
+ __publicField(this, "_simulationConfig", null);
2067
+ this.rpcClient = rpcClient;
2068
+ }
2069
+ async validateSlotAssignmentAsync(containerId, slotId, itemId) {
2070
+ return this.rpcClient.call(
2071
+ "H5_SIMULATION_VALIDATE_ASSIGNMENT" /* H5_SIMULATION_VALIDATE_ASSIGNMENT */,
2072
+ {
2073
+ containerId,
2074
+ slotId,
2075
+ itemId
2076
+ }
2077
+ );
2078
+ }
2079
+ sumContributions(contributions) {
2080
+ return sumContributions(contributions);
2081
+ }
2082
+ executeBatchOperationsAsync(operations, validateOnly) {
2083
+ return this.rpcClient.call("H5_SIMULATION_BATCH_OPERATIONS" /* H5_SIMULATION_BATCH_OPERATIONS */, {
2084
+ operations,
2085
+ validateOnly
2086
+ });
2087
+ }
2088
+ async getAvailableItemsAsync(containerId, slotId) {
2089
+ const response = await this.rpcClient.call(
2090
+ "H5_SIMULATION_GET_AVAILABLE_ITEMS" /* H5_SIMULATION_GET_AVAILABLE_ITEMS */,
2091
+ {
2092
+ containerId,
2093
+ slotId
2094
+ }
2095
+ );
2096
+ return response.availableItems || [];
2097
+ }
2098
+ calculatePowerPreviewAsync(containerId, slotId, candidateItemId) {
2099
+ return this.rpcClient.call(
2100
+ "H5_SIMULATION_CALCULATE_POWER_PREVIEW" /* H5_SIMULATION_CALCULATE_POWER_PREVIEW */,
2101
+ {
2102
+ containerId,
2103
+ slotId,
2104
+ candidateItemId
2105
+ }
2106
+ );
2107
+ }
2108
+ assignItemToSlotAsync(containerId, slotId, itemId) {
2109
+ return this.rpcClient.call("H5_SIMULATION_ASSIGN_ITEM" /* H5_SIMULATION_ASSIGN_ITEM */, {
2110
+ containerId,
2111
+ slotId,
2112
+ itemId
2113
+ });
2114
+ }
2115
+ removeItemFromSlotAsync(containerId, slotId) {
2116
+ return this.rpcClient.call("H5_SIMULATION_REMOVE_ITEM" /* H5_SIMULATION_REMOVE_ITEM */, {
2117
+ containerId,
2118
+ slotId
2119
+ });
2120
+ }
2121
+ async getSlotContainersAsync() {
2122
+ const response = await this.rpcClient.call(
2123
+ "H5_SIMULATION_GET_CONTAINERS" /* H5_SIMULATION_GET_CONTAINERS */,
2124
+ {}
2125
+ );
2126
+ return response.containers || [];
2127
+ }
2128
+ async getSlotAssignmentsAsync(containerId) {
2129
+ const response = await this.rpcClient.call(
2130
+ "H5_SIMULATION_GET_ASSIGNMENTS" /* H5_SIMULATION_GET_ASSIGNMENTS */,
2131
+ {
2132
+ containerId
2133
+ }
2134
+ );
2135
+ return Array.isArray(response) ? response : response.assignments || [];
2136
+ }
2137
+ async getStateAsync(roomId) {
2138
+ const response = await this.rpcClient.call(
2139
+ "H5_SIMULATION_GET_STATE" /* H5_SIMULATION_GET_STATE */,
2140
+ {
2141
+ roomId
2142
+ }
2143
+ );
2144
+ console.log("[Venus SDK] getStateAsync", response);
2145
+ if (response.configuration) {
2146
+ this._simulationConfig = response.configuration;
2147
+ }
2148
+ return response;
2149
+ }
2150
+ async getConfigAsync(roomId) {
2151
+ if (this._simulationConfig) {
2152
+ return this._simulationConfig;
2153
+ }
2154
+ const config = await this.rpcClient.call(
2155
+ "H5_SIMULATION_GET_CONFIG" /* H5_SIMULATION_GET_CONFIG */,
2156
+ {}
2157
+ );
2158
+ console.log("[Venus SDK] getConfigAsync", config);
2159
+ if (config) {
2160
+ this._simulationConfig = config;
2161
+ return config;
2162
+ }
2163
+ throw new Error("No simulation configuration available");
2164
+ }
2165
+ executeRecipeAsync(recipeId, inputs, options) {
2166
+ return this.rpcClient.call("H5_SIMULATION_EXECUTE_RECIPE" /* H5_SIMULATION_EXECUTE_RECIPE */, {
2167
+ recipeId,
2168
+ inputs,
2169
+ roomId: options?.roomId,
2170
+ batchAmount: options?.batchAmount,
2171
+ allowPartialBatch: options?.allowPartialBatch,
2172
+ entity: options?.entity
2173
+ });
2174
+ }
2175
+ collectRecipeAsync(runId) {
2176
+ return this.rpcClient.call("H5_SIMULATION_COLLECT_RECIPE" /* H5_SIMULATION_COLLECT_RECIPE */, {
2177
+ runId
2178
+ });
2179
+ }
2180
+ getActiveRunsAsync(options) {
2181
+ return this.rpcClient.call("H5_SIMULATION_GET_ACTIVE_RUNS" /* H5_SIMULATION_GET_ACTIVE_RUNS */, {
2182
+ roomId: options?.roomId
2183
+ });
2184
+ }
2185
+ executeScopedRecipeAsync(recipeId, entity, inputs, options) {
2186
+ return this.rpcClient.call(
2187
+ "H5_SIMULATION_EXECUTE_SCOPED_RECIPE" /* H5_SIMULATION_EXECUTE_SCOPED_RECIPE */,
2188
+ {
2189
+ recipeId,
2190
+ entity,
2191
+ inputs,
2192
+ roomId: options?.roomId ?? null,
2193
+ options
2194
+ }
2195
+ );
2196
+ }
2197
+ getAvailableRecipesAsync(options) {
2198
+ return this.rpcClient.call(
2199
+ "H5_SIMULATION_GET_AVAILABLE_RECIPES" /* H5_SIMULATION_GET_AVAILABLE_RECIPES */,
2200
+ {
2201
+ roomId: options?.roomId || null,
2202
+ includeActorRecipes: options?.includeActorRecipes || false
2203
+ }
2204
+ );
2205
+ }
2206
+ getRecipeRequirementsAsync(recipe) {
2207
+ return this.rpcClient.call(
2208
+ "H5_SIMULATION_GET_RECIPE_REQUIREMENTS" /* H5_SIMULATION_GET_RECIPE_REQUIREMENTS */,
2209
+ {
2210
+ recipeId: recipe.recipeId,
2211
+ entity: recipe.entity,
2212
+ batchAmount: recipe.batchAmount
2213
+ }
2214
+ );
2215
+ }
2216
+ getBatchRecipeRequirementsAsync(recipes) {
2217
+ return this.rpcClient.call(
2218
+ "H5_SIMULATION_GET_BATCH_RECIPE_REQUIREMENTS" /* H5_SIMULATION_GET_BATCH_RECIPE_REQUIREMENTS */,
2219
+ {
2220
+ recipes
2221
+ }
2222
+ );
2223
+ }
2224
+ triggerRecipeChainAsync(recipeId, options) {
2225
+ return this.rpcClient.call(
2226
+ "H5_SIMULATION_TRIGGER_RECIPE_CHAIN" /* H5_SIMULATION_TRIGGER_RECIPE_CHAIN */,
2227
+ {
2228
+ triggerRecipeId: recipeId,
2229
+ context: options?.context,
2230
+ roomId: options?.roomId
2231
+ }
2232
+ );
2233
+ }
2234
+ getEntityMetadataAsync(entityId) {
2235
+ return this.rpcClient.call(
2236
+ "H5_SIMULATION_GET_ENTITY_METADATA" /* H5_SIMULATION_GET_ENTITY_METADATA */,
2237
+ {
2238
+ entityId
2239
+ }
2240
+ );
2241
+ }
2242
+ async resolveFieldValueAsync(entityId, fieldPath, entity) {
2243
+ const response = await this.rpcClient.call(
2244
+ "H5_SIMULATION_RESOLVE_VALUE" /* H5_SIMULATION_RESOLVE_VALUE */,
2245
+ {
2246
+ entityId,
2247
+ fieldPath,
2248
+ entity
2249
+ }
2250
+ );
2251
+ return response.value;
2252
+ }
2253
+ };
2254
+
2255
+ // src/simulation/MockSimulationApi.ts
2256
+ function generateAppIdentifier2() {
2257
+ if (typeof window === "undefined") return "unknown-app";
2258
+ const url = window.location.href;
2259
+ const match = url.match(/\/H5\/([^\/]+)/);
2260
+ return match ? match[1] : "unknown-app";
2261
+ }
2262
+ var MockSimulationApi = class {
2263
+ constructor(simulationConfig = null) {
2264
+ __publicField(this, "mockSimulationConfigs", /* @__PURE__ */ new Map());
2265
+ // appIdentifier -> config
2266
+ __publicField(this, "mockSimulationStates", /* @__PURE__ */ new Map());
2267
+ // appIdentifier -> config
2268
+ __publicField(this, "mockActiveTimers", /* @__PURE__ */ new Map());
2269
+ // appIdentifier -> timers[]
2270
+ __publicField(this, "appId");
2271
+ __publicField(this, "providedSimulationConfig");
2272
+ this.appId = generateAppIdentifier2();
2273
+ this.providedSimulationConfig = simulationConfig;
2274
+ }
2275
+ sumContributions(contributions) {
2276
+ return sumContributions(contributions);
2277
+ }
2278
+ async validateSlotAssignmentAsync(containerId, slotId, itemId) {
2279
+ this.log("validateSlotAssignmentAsync called:", {
2280
+ containerId,
2281
+ slotId,
2282
+ itemId
2283
+ });
2284
+ return { valid: true, message: "Mock validation successful" };
2285
+ }
2286
+ async executeBatchOperationsAsync(operations, validateOnly) {
2287
+ this.log("executeBatchOperationsAsync called:", {
2288
+ operations,
2289
+ validateOnly
2290
+ });
2291
+ return {
2292
+ success: true,
2293
+ results: operations.map(() => ({ success: true }))
2294
+ };
2295
+ }
2296
+ async getAvailableItemsAsync(containerId, slotId) {
2297
+ console.log("[Venus Simulation Mock] getAvailableItemsAsync called:", {
2298
+ containerId,
2299
+ slotId
2300
+ });
2301
+ const appIdentifier = generateAppIdentifier2();
2302
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2303
+ const config = mockSimulationConfigs.get(appIdentifier) || {
2304
+ entities: {}
2305
+ };
2306
+ const availableItems = Object.entries(config.entities).slice(0, 3).map(([entityId, entity]) => ({
2307
+ entityId,
2308
+ quantity: 1,
2309
+ metadata: entity.metadata,
2310
+ powerPreview: 100
2311
+ // Mock power value
2312
+ }));
2313
+ return availableItems;
2314
+ }
2315
+ async calculatePowerPreviewAsync(containerId, slotId, candidateItemId) {
2316
+ this.log("calculatePowerPreviewAsync called:", {
2317
+ containerId,
2318
+ slotId,
2319
+ candidateItemId
2320
+ });
2321
+ return {
2322
+ currentPower: 1e3,
2323
+ previewPower: 1200,
2324
+ powerDelta: 200,
2325
+ breakdown: { base: 800, weapon: 200, armor: 200 }
2326
+ };
2327
+ }
2328
+ async getSlotContainersAsync() {
2329
+ this.log("getSlotContainersAsync called");
2330
+ const appIdentifier = this.appId;
2331
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2332
+ const config = mockSimulationConfigs.get(appIdentifier) || {
2333
+ entities: {}
2334
+ };
2335
+ const containers = Object.entries(config.entities).filter(([_, entity]) => entity.metadata?.slots).map(([entityId, entity]) => ({
2336
+ entityId,
2337
+ slots: entity.metadata?.slots,
2338
+ isOwned: true
2339
+ // Mock: assume all containers are owned
2340
+ }));
2341
+ return containers;
2342
+ }
2343
+ async getSlotAssignmentsAsync(containerId) {
2344
+ this.log("getSlotAssignmentsAsync called for:", containerId);
2345
+ return [];
2346
+ }
2347
+ async resolveFieldValueAsync(entityId, fieldPath, entity) {
2348
+ this.log("resolveFieldValueAsync called:", {
2349
+ entityId,
2350
+ fieldPath,
2351
+ entity
2352
+ });
2353
+ const mockValues = {
2354
+ basePower: 850,
2355
+ weaponPower: 300,
2356
+ armorPower: 150,
2357
+ total_power: 1300,
2358
+ total_defense_power: 5e3
2359
+ };
2360
+ return mockValues[fieldPath] || 100;
2361
+ }
2362
+ async getEntityMetadataAsync(entityId) {
2363
+ this.log("getEntityMetadataAsync called for:", entityId);
2364
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2365
+ const appIdentifier = this.appId;
2366
+ const config = mockSimulationConfigs.get(
2367
+ appIdentifier
2368
+ ) || {
2369
+ entities: {}};
2370
+ const entity = config.entities[entityId];
2371
+ return entity?.metadata || {};
2372
+ }
2373
+ async collectRecipeAsync(runId) {
2374
+ this.log("collectRecipeAsync called:", { runId });
2375
+ const mockRewards = {
2376
+ cash: Math.floor(Math.random() * 1e3) + 500,
2377
+ experience: Math.floor(Math.random() * 50) + 25
2378
+ };
2379
+ return {
2380
+ success: true,
2381
+ runId,
2382
+ rewards: mockRewards,
2383
+ message: "Rewards collected successfully"
2384
+ };
2385
+ }
2386
+ executeRecipeAsync(recipeId, inputs, options) {
2387
+ this.log("executeRecipeAsync called:", {
2388
+ recipeId,
2389
+ inputs,
2390
+ options
2391
+ });
2392
+ const appIdentifier = this.appId;
2393
+ return this.executeRecipe(appIdentifier, recipeId, inputs);
2394
+ }
2395
+ async executeScopedRecipeAsync(recipeId, entity, inputs, options) {
2396
+ this.log("executeScopedRecipeAsync called:", {
2397
+ recipeId,
2398
+ entity,
2399
+ inputs,
2400
+ roomId: options?.roomId,
2401
+ options
2402
+ });
2403
+ return {
2404
+ success: true,
2405
+ message: "Mock scoped recipe execution successful"
2406
+ };
2407
+ }
2408
+ async getActiveRunsAsync(options) {
2409
+ this.log("getActiveRunsAsync called:", options);
2410
+ const appIdentifier = this.appId;
2411
+ let state = this.mockSimulationStates.get(appIdentifier);
2412
+ if (!state) {
2413
+ state = await this.initializeSimulationState(appIdentifier);
2414
+ }
2415
+ return state.activeRuns || [];
2416
+ }
2417
+ async getAvailableRecipesAsync(options) {
2418
+ this.log("getAvailableRecipesAsync called:", options);
2419
+ const baseRecipes = [
2420
+ { id: "collect_resources", scope: "player", clientViewable: true },
2421
+ { id: "upgrade_equipment", scope: "player", clientViewable: true }
2422
+ ];
2423
+ if (options?.roomId) {
2424
+ baseRecipes.push(
2425
+ { id: "room_upgrade", scope: "room", clientViewable: true },
2426
+ { id: "cooperative_project", scope: "room", clientViewable: true }
2427
+ );
2428
+ }
2429
+ if (options?.includeActorRecipes && options?.roomId) {
2430
+ baseRecipes.push(
2431
+ { id: "trade_with_npc", scope: "actor", clientViewable: true },
2432
+ { id: "attack_monster", scope: "actor", clientViewable: true }
2433
+ );
2434
+ }
2435
+ return { success: true, recipes: baseRecipes };
2436
+ }
2437
+ async getBatchRecipeRequirementsAsync(recipes) {
2438
+ this.log("getBatchRecipeRequirementsAsync called:", {
2439
+ count: recipes?.length
2440
+ });
2441
+ const results = (recipes || []).map((q) => ({
2442
+ recipeId: q.recipeId,
2443
+ entity: q.entity || null,
2444
+ amount: q.batchAmount || 1,
2445
+ inputs: { cash: "BE:0" },
2446
+ canAfford: true,
2447
+ disabled: false
2448
+ }));
2449
+ return { success: true, results };
2450
+ }
2451
+ async getRecipeRequirementsAsync(recipe) {
2452
+ this.log("getRecipeRequirementsAsync called:", recipe);
2453
+ return {
2454
+ recipeId: recipe.recipeId,
2455
+ entity: recipe.entity || null,
2456
+ amount: recipe.batchAmount,
2457
+ inputs: { cash: "BE:0" },
2458
+ canAfford: true,
2459
+ disabled: false
2460
+ };
2461
+ }
2462
+ async triggerRecipeChainAsync(recipeId, options) {
2463
+ this.log("triggerRecipeChainAsync called:", { recipeId, ...options });
2464
+ return {
2465
+ success: true,
2466
+ message: "Mock recipe chain triggered successfully"
2467
+ };
2468
+ }
2469
+ log(message, ...args) {
2470
+ console.log(`[Venus Sim Mock] ${message}`, args);
2471
+ }
2472
+ async executeRecipe(appIdentifier, recipeId, inputs) {
2473
+ this.log(`Executing recipe ${recipeId} for ${appIdentifier}`, inputs);
2474
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2475
+ const mockSimulationStates = this.mockSimulationStates;
2476
+ let config = mockSimulationConfigs.get(appIdentifier);
2477
+ let state = mockSimulationStates.get(appIdentifier);
2478
+ if (!config || !state) {
2479
+ state = await this.initializeSimulationState(appIdentifier);
2480
+ config = mockSimulationConfigs.get(appIdentifier);
2481
+ if (!config) {
2482
+ throw new Error("Failed to initialize simulation config");
2483
+ }
2484
+ }
2485
+ const recipe = config.recipes?.[recipeId];
2486
+ if (!recipe) {
2487
+ throw new Error(`Recipe ${recipeId} not found`);
2488
+ }
2489
+ if (state.disabledRecipes?.includes(recipeId)) {
2490
+ throw new Error(`Recipe ${recipeId} is disabled`);
2491
+ }
2492
+ if (recipe.inputs) {
2493
+ for (const [entityId, required] of Object.entries(recipe.inputs)) {
2494
+ const available = state.inventory[entityId] || 0;
2495
+ if (available < required) {
2496
+ throw new Error(
2497
+ `Insufficient ${entityId}: required ${required}, available ${available}`
2498
+ );
2499
+ }
2500
+ }
2501
+ }
2502
+ if (recipe.inputs) {
2503
+ for (const [entityId, input] of Object.entries(recipe.inputs)) {
2504
+ const inventoryValue = state.inventory[entityId] || 0;
2505
+ if (typeof input === "number" && typeof inventoryValue === "number") {
2506
+ state.inventory[entityId] = inventoryValue - input;
2507
+ }
2508
+ }
2509
+ }
2510
+ if (recipe.beginEffects) {
2511
+ this.applyEffects(state, recipe.beginEffects);
2512
+ }
2513
+ const runId = this.generateRunId();
2514
+ const now = Date.now();
2515
+ const expiresAt = now + (recipe.duration || 0);
2516
+ const run = {
2517
+ id: runId,
2518
+ recipeId,
2519
+ status: "running",
2520
+ startTime: now,
2521
+ expiresAt,
2522
+ inputs: recipe.inputs || {}
2523
+ };
2524
+ state.activeRuns.push(run);
2525
+ if (recipe.duration === 0) {
2526
+ this.completeRun(appIdentifier, runId);
2527
+ return { status: "completed", runId };
2528
+ } else {
2529
+ const mockActiveTimers = this.mockActiveTimers;
2530
+ const timer = setTimeout(() => {
2531
+ this.completeRun(appIdentifier, runId);
2532
+ }, recipe.duration);
2533
+ const timers = mockActiveTimers.get(appIdentifier) || [];
2534
+ timers.push(timer);
2535
+ mockActiveTimers.set(appIdentifier, timers);
2536
+ return {
2537
+ status: "running",
2538
+ runId,
2539
+ expiresAt: new Date(expiresAt).toISOString()
2540
+ };
2541
+ }
2542
+ }
2543
+ async initializeSimulationState(appIdentifier) {
2544
+ this.log(`Initializing simulation state for ${appIdentifier}`);
2545
+ const providedSimulationConfig = this.providedSimulationConfig;
2546
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2547
+ const mockSimulationStates = this.mockSimulationStates;
2548
+ const mockActiveTimers = this.mockActiveTimers;
2549
+ const config = providedSimulationConfig || {
2550
+ version: "1.0",
2551
+ entities: {},
2552
+ recipes: {}
2553
+ };
2554
+ mockSimulationConfigs.set(appIdentifier, config);
2555
+ const initialInventory = {};
2556
+ if (providedSimulationConfig && config.entities) {
2557
+ Object.keys(config.entities).forEach((entityId) => {
2558
+ initialInventory[entityId] = 0;
2559
+ });
2560
+ }
2561
+ const state = {
2562
+ inventory: initialInventory,
2563
+ activeRuns: [],
2564
+ disabledRecipes: new Array()
2565
+ };
2566
+ if (config.recipes) {
2567
+ Object.entries(config.recipes).forEach(([recipeId, recipe]) => {
2568
+ if (recipe.metadata?.startsDisabled) {
2569
+ state.disabledRecipes.push(recipeId);
2570
+ }
2571
+ });
2572
+ }
2573
+ mockSimulationStates.set(appIdentifier, state);
2574
+ mockActiveTimers.set(appIdentifier, []);
2575
+ console.log(
2576
+ `[Venus Simulation Mock] Initialized state for ${appIdentifier}:`,
2577
+ state
2578
+ );
2579
+ if (config.recipes) {
2580
+ Object.entries(config.recipes).forEach(([recipeId, recipe]) => {
2581
+ const isAutoRestart = recipe.autoRestart || recipe.metadata?.autoRestart;
2582
+ if (isAutoRestart && recipe.outputs) {
2583
+ this.log(`Found auto-restart recipe: ${recipeId}`, {
2584
+ topLevelAutoRestart: recipe.autoRestart,
2585
+ metadataAutoRestart: recipe.metadata?.autoRestart,
2586
+ hasOutputs: !!recipe.outputs,
2587
+ duration: recipe.duration
2588
+ });
2589
+ const condition = recipe.maxRestartCondition || recipe.metadata?.maxRestartCondition;
2590
+ if (condition && condition.entity) {
2591
+ const currentAmount = initialInventory[condition.entity] || 0;
2592
+ if (currentAmount < condition.maxValue) {
2593
+ console.log(
2594
+ `[Venus Simulation Mock] Auto-starting ${recipeId} at initialization`,
2595
+ {
2596
+ currentAmount,
2597
+ maxValue: condition.maxValue,
2598
+ entity: condition.entity
2599
+ }
2600
+ );
2601
+ setTimeout(() => {
2602
+ this.executeRecipe(appIdentifier, recipeId, {});
2603
+ }, 1e3);
2604
+ }
2605
+ } else {
2606
+ console.log(
2607
+ `[Venus Simulation Mock] Auto-starting ${recipeId} at initialization (no condition)`
2608
+ );
2609
+ setTimeout(() => {
2610
+ this.executeRecipe(appIdentifier, recipeId, {});
2611
+ }, 1e3);
2612
+ }
2613
+ }
2614
+ });
2615
+ }
2616
+ return state;
2617
+ }
2618
+ generateRunId() {
2619
+ return "run_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
2620
+ }
2621
+ completeRun(appIdentifier, runId) {
2622
+ this.log(`Completing run ${runId} for ${appIdentifier}`);
2623
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2624
+ const mockSimulationStates = this.mockSimulationStates;
2625
+ const config = mockSimulationConfigs.get(appIdentifier);
2626
+ const state = mockSimulationStates.get(appIdentifier);
2627
+ if (!config || !state) return;
2628
+ const runIndex = state.activeRuns.findIndex((r) => r.id === runId);
2629
+ if (runIndex === -1) return;
2630
+ const run = state.activeRuns[runIndex];
2631
+ const recipe = config.recipes?.[run.recipeId];
2632
+ if (!recipe) return;
2633
+ const outputs = {};
2634
+ const rng = this.createSeededRandom(runId);
2635
+ if (recipe.outputs) {
2636
+ for (const [entityId, value] of Object.entries(recipe.outputs)) {
2637
+ if (typeof value === "number") {
2638
+ outputs[entityId] = value;
2639
+ } else if (typeof value === "object" && value != null && "min" in value && "max" in value && typeof value.min == "number" && typeof value.max === "number") {
2640
+ outputs[entityId] = Math.floor(rng() * (value.max - value.min + 1)) + value.min;
2641
+ }
2642
+ }
2643
+ }
2644
+ for (const [entityId, amount] of Object.entries(outputs)) {
2645
+ state.inventory[entityId] = (state.inventory[entityId] || 0) + amount;
2646
+ }
2647
+ if (recipe.endEffects) {
2648
+ this.applyEffects(state, recipe.endEffects);
2649
+ }
2650
+ run.status = "completed";
2651
+ run.outputs = outputs;
2652
+ state.activeRuns.splice(runIndex, 1);
2653
+ const isAutoRestart = recipe.autoRestart || recipe.metadata?.autoRestart;
2654
+ if (isAutoRestart) {
2655
+ console.log(
2656
+ `[Venus Simulation Mock] Checking auto-restart for ${run.recipeId}`,
2657
+ {
2658
+ topLevelAutoRestart: recipe.autoRestart,
2659
+ metadataAutoRestart: recipe.metadata?.autoRestart,
2660
+ hasCondition: !!(recipe.maxRestartCondition || recipe.metadata?.maxRestartCondition)
2661
+ }
2662
+ );
2663
+ const condition = recipe.maxRestartCondition || recipe.metadata?.maxRestartCondition;
2664
+ if (condition) {
2665
+ const currentAmount = state.inventory[condition.entity] || 0;
2666
+ if (currentAmount < condition.maxValue) {
2667
+ console.log(
2668
+ `[Venus Simulation Mock] Auto-restarting ${run.recipeId}`,
2669
+ {
2670
+ currentAmount,
2671
+ maxValue: condition.maxValue,
2672
+ entity: condition.entity
2673
+ }
2674
+ );
2675
+ setTimeout(() => {
2676
+ this.executeRecipe(appIdentifier, run.recipeId, recipe.inputs || {});
2677
+ }, 1e3);
2678
+ }
2679
+ } else {
2680
+ console.log(
2681
+ `[Venus Simulation Mock] Auto-restarting ${run.recipeId} (no condition)`
2682
+ );
2683
+ setTimeout(() => {
2684
+ this.executeRecipe(appIdentifier, run.recipeId, recipe.inputs || {});
2685
+ }, 1e3);
2686
+ }
2687
+ }
2688
+ console.log(
2689
+ `[Venus Simulation Mock] Completed run ${runId}, outputs:`,
2690
+ outputs
2691
+ );
2692
+ }
2693
+ createSeededRandom(seed) {
2694
+ let hash = 0;
2695
+ for (let i = 0; i < seed.length; i++) {
2696
+ const char = seed.charCodeAt(i);
2697
+ hash = (hash << 5) - hash + char;
2698
+ hash = hash & hash;
2699
+ }
2700
+ return () => {
2701
+ hash = (hash * 9301 + 49297) % 233280;
2702
+ return hash / 233280;
2703
+ };
2704
+ }
2705
+ applyEffects(state, effects) {
2706
+ if (!effects || !Array.isArray(effects)) return;
2707
+ for (const effect of effects) {
2708
+ switch (effect.type) {
2709
+ case "set":
2710
+ state.inventory[effect.target] = effect.value;
2711
+ console.log(
2712
+ `[Venus Simulation Mock] Effect: Set ${effect.target} = ${effect.value}`
2713
+ );
2714
+ break;
2715
+ case "add":
2716
+ state.inventory[effect.target] = (state.inventory[effect.target] || 0) + effect.value;
2717
+ console.log(
2718
+ `[Venus Simulation Mock] Effect: Add ${effect.value} to ${effect.target} (new value: ${state.inventory[effect.target]})`
2719
+ );
2720
+ break;
2721
+ case "multiply":
2722
+ state.inventory[effect.target] = (state.inventory[effect.target] || 0) * effect.value;
2723
+ console.log(
2724
+ `[Venus Simulation Mock] Effect: Multiply ${effect.target} by ${effect.value} (new value: ${state.inventory[effect.target]})`
2725
+ );
2726
+ break;
2727
+ case "min":
2728
+ state.inventory[effect.target] = Math.max(
2729
+ state.inventory[effect.target] || 0,
2730
+ effect.value
2731
+ );
2732
+ console.log(
2733
+ `[Venus Simulation Mock] Effect: Set ${effect.target} min ${effect.value} (new value: ${state.inventory[effect.target]})`
2734
+ );
2735
+ break;
2736
+ case "max":
2737
+ state.inventory[effect.target] = Math.min(
2738
+ state.inventory[effect.target] || 0,
2739
+ effect.value
2740
+ );
2741
+ console.log(
2742
+ `[Venus Simulation Mock] Effect: Set ${effect.target} max ${effect.value} (new value: ${state.inventory[effect.target]})`
2743
+ );
2744
+ break;
2745
+ case "enable_recipe":
2746
+ if (state.disabledRecipes?.includes(effect.target)) {
2747
+ state.disabledRecipes = state.disabledRecipes.filter(
2748
+ (r) => r !== effect.target
2749
+ );
2750
+ console.log(
2751
+ `[Venus Simulation Mock] Effect: Enabled recipe ${effect.target}`
2752
+ );
2753
+ }
2754
+ break;
2755
+ case "disable_recipe":
2756
+ if (!state.disabledRecipes) state.disabledRecipes = [];
2757
+ if (!state.disabledRecipes.includes(effect.target)) {
2758
+ state.disabledRecipes.push(effect.target);
2759
+ console.log(
2760
+ `[Venus Simulation Mock] Effect: Disabled recipe ${effect.target}`
2761
+ );
2762
+ }
2763
+ break;
2764
+ case "trigger_recipe":
2765
+ console.log(
2766
+ `[Venus Simulation Mock] Effect: Trigger recipe ${effect.target} (not implemented)`
2767
+ );
2768
+ break;
2769
+ default:
2770
+ console.warn(
2771
+ `[Venus Simulation Mock] Unknown effect type: ${effect.type}`
2772
+ );
2773
+ }
2774
+ }
2775
+ }
2776
+ async getConfigAsync() {
2777
+ console.log("[Venus Simulation Mock] getConfigAsync called");
2778
+ const appIdentifier = this.appId;
2779
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2780
+ const config = mockSimulationConfigs.get(appIdentifier) || {
2781
+ version: "1.0",
2782
+ entities: {},
2783
+ recipes: {}
2784
+ };
2785
+ return config;
2786
+ }
2787
+ async getStateAsync(roomId) {
2788
+ this.log("getStateAsync called:", roomId);
2789
+ const appIdentifier = this.appId;
2790
+ const mockSimulationStates = this.mockSimulationStates;
2791
+ let state = mockSimulationStates.get(appIdentifier);
2792
+ if (!state) {
2793
+ state = await this.initializeSimulationState(appIdentifier);
2794
+ }
2795
+ const mockSimulationConfigs = this.mockSimulationConfigs;
2796
+ return {
2797
+ ...state,
2798
+ roomId,
2799
+ configuration: mockSimulationConfigs.get(appIdentifier)
2800
+ };
2801
+ }
2802
+ async assignItemToSlotAsync(containerId, slotId, itemId) {
2803
+ this.log("assignItemToSlotAsync called:", {
2804
+ containerId,
2805
+ slotId,
2806
+ itemId
2807
+ });
2808
+ return { success: true, message: "Mock assignment successful" };
2809
+ }
2810
+ async removeItemFromSlotAsync(containerId, slotId) {
2811
+ this.log("removeItemFromSlotAsync called:", {
2812
+ containerId,
2813
+ slotId
2814
+ });
2815
+ return { success: true, message: "Mock removal successful" };
2816
+ }
2817
+ };
2818
+
2819
+ // src/simulation/index.ts
2820
+ function initializeSimulation(venusApi, host) {
2821
+ console.log("[Venus SDK] Initializing new Simulation Api");
2822
+ venusApi.simulation = {
2823
+ isEnabled: () => true
2824
+ };
2825
+ venusApi.simulation.getConfigAsync = () => {
2826
+ return host.simulation.getConfigAsync();
2827
+ };
2828
+ venusApi.simulation.getStateAsync = (options) => {
2829
+ return host.simulation.getStateAsync(options?.roomId);
2830
+ };
2831
+ venusApi.simulation.executeRecipeAsync = (recipeId, inputs, options) => {
2832
+ return host.simulation.executeRecipeAsync(recipeId, inputs, options);
2833
+ };
2834
+ venusApi.simulation.getActiveRunsAsync = () => {
2835
+ return host.simulation.getActiveRunsAsync();
2836
+ };
2837
+ venusApi.simulation.collectRecipeAsync = (runId) => {
2838
+ return host.simulation.collectRecipeAsync(runId);
2839
+ };
2840
+ venusApi.simulation.executeScopedRecipeAsync = (recipeId, entity, inputs, roomId, options) => {
2841
+ return host.simulation.executeScopedRecipeAsync(recipeId, entity, inputs, {
2842
+ roomId,
2843
+ ...options
2844
+ });
2845
+ };
2846
+ venusApi.simulation.triggerRecipeChainAsync = (recipeId, context, roomId) => {
2847
+ return host.simulation.triggerRecipeChainAsync(recipeId, {
2848
+ context,
2849
+ roomId
2850
+ });
2851
+ };
2852
+ venusApi.simulation.getAvailableRecipesAsync = async (roomId, includeActorRecipes) => {
2853
+ const result = await host.simulation.getAvailableRecipesAsync({
2854
+ roomId,
2855
+ includeActorRecipes
2856
+ });
2857
+ return result.recipes;
2858
+ };
2859
+ venusApi.simulation.getRecipeRequirementsAsync = (recipeId, entity, amount) => {
2860
+ return host.simulation.getRecipeRequirementsAsync({
2861
+ recipeId,
2862
+ entity,
2863
+ batchAmount: amount
2864
+ });
2865
+ };
2866
+ venusApi.simulation.getBatchRecipeRequirementsAsync = (recipes) => {
2867
+ return host.simulation.getBatchRecipeRequirementsAsync(recipes);
2868
+ };
2869
+ venusApi.simulation.resolveFieldValueAsync = (entityId, fieldPath, entity) => {
2870
+ return host.simulation.resolveFieldValueAsync(entityId, fieldPath, entity);
2871
+ };
2872
+ venusApi.simulation.getEntityMetadataAsync = (entityId) => {
2873
+ return host.simulation.getEntityMetadataAsync(entityId);
2874
+ };
2875
+ venusApi.simulation.getSlotAssignmentsAsync = (containerId) => {
2876
+ return host.simulation.getSlotAssignmentsAsync(containerId);
2877
+ };
2878
+ venusApi.simulation.getSlotContainersAsync = () => {
2879
+ return host.simulation.getSlotContainersAsync();
2880
+ };
2881
+ venusApi.simulation.assignItemToSlotAsync = (containerId, slotId, itemId) => {
2882
+ return host.simulation.assignItemToSlotAsync(containerId, slotId, itemId);
2883
+ };
2884
+ venusApi.simulation.removeItemFromSlotAsync = (containerId, slotId) => {
2885
+ return host.simulation.removeItemFromSlotAsync(containerId, slotId);
2886
+ };
2887
+ venusApi.simulation.getAvailableItemsAsync = (containerId, slotId) => {
2888
+ return host.simulation.getAvailableItemsAsync(containerId, slotId);
2889
+ };
2890
+ venusApi.simulation.calculatePowerPreviewAsync = (containerId, slotId, candidateItemId) => {
2891
+ return host.simulation.calculatePowerPreviewAsync(
2892
+ containerId,
2893
+ slotId,
2894
+ candidateItemId
2895
+ );
2896
+ };
2897
+ venusApi.simulation.executeBatchOperationsAsync = (operations, validateOnly) => {
2898
+ return host.simulation.executeBatchOperationsAsync(operations, validateOnly);
2899
+ };
2900
+ venusApi.simulation.validateSlotAssignmentAsync = (containerId, slotId, itemId) => {
2901
+ return host.simulation.validateSlotAssignmentAsync(
2902
+ containerId,
2903
+ slotId,
2904
+ itemId
2905
+ );
2906
+ };
2907
+ venusApi.simulation.sumContributions = (contributions) => {
2908
+ return host.simulation.sumContributions(contributions);
2909
+ };
2910
+ }
2911
+
2912
+ // src/time/utils.ts
2913
+ function isPacificDaylightTime(date) {
2914
+ const year = date.getFullYear();
2915
+ const marchStart = new Date(year, 2, 8);
2916
+ const daysUntilSundayInMarch = (7 - marchStart.getDay()) % 7;
2917
+ const dstStart = new Date(year, 2, 8 + daysUntilSundayInMarch);
2918
+ dstStart.setHours(2, 0, 0, 0);
2919
+ const novemberStart = new Date(year, 10, 1);
2920
+ const daysUntilSundayInNov = (7 - novemberStart.getDay()) % 7;
2921
+ const dstEnd = new Date(year, 10, 1 + daysUntilSundayInNov);
2922
+ dstEnd.setHours(2, 0, 0, 0);
2923
+ return date >= dstStart && date < dstEnd;
2924
+ }
2925
+
2926
+ // src/time/HostTimeApi.ts
2927
+ var HostTimeApi = class {
2928
+ constructor(rpcClient) {
2929
+ __publicField(this, "rpcClient");
2930
+ this.rpcClient = rpcClient;
2931
+ }
2932
+ async requestTimeAsync() {
2933
+ const response = await this.rpcClient.call(
2934
+ "H5_REQUEST_SERVER_TIME" /* REQUEST_SERVER_TIME */,
2935
+ {}
2936
+ );
2937
+ return response;
2938
+ }
2939
+ formatTime(timestamp, options) {
2940
+ let locale = "en-US";
2941
+ const windowVenus = window.venus;
2942
+ if (windowVenus._config.locale) {
2943
+ locale = windowVenus._config.locale;
2944
+ } else if (windowVenus._config.environment && windowVenus._config.environment.browserInfo && windowVenus._config.environment.browserInfo.language) {
2945
+ locale = windowVenus._config.environment.browserInfo.language;
2946
+ }
2947
+ const date = new Date(timestamp);
2948
+ const dateTimeOptions = {
2949
+ dateStyle: options.dateStyle || "medium",
2950
+ timeStyle: options.timeStyle || "medium",
2951
+ hour12: options.hour12 !== void 0 ? options.hour12 : true,
2952
+ ...options
2953
+ };
2954
+ return date.toLocaleString(locale, dateTimeOptions);
2955
+ }
2956
+ formatNumber(value, options) {
2957
+ try {
2958
+ let locale = "en-US";
2959
+ const windowVenus = window.venus;
2960
+ if (windowVenus._config.locale) {
2961
+ locale = windowVenus._config.locale;
2962
+ } else if (windowVenus._config.environment && windowVenus._config.environment.browserInfo && windowVenus._config.environment.browserInfo.language) {
2963
+ locale = windowVenus._config.environment.browserInfo.language;
2964
+ }
2965
+ const numberOptions = {
2966
+ style: options?.style || "decimal",
2967
+ minimumFractionDigits: options?.minimumFractionDigits || 0,
2968
+ maximumFractionDigits: options?.maximumFractionDigits || 2,
2969
+ ...options
2970
+ };
2971
+ return value.toLocaleString(locale, numberOptions);
2972
+ } catch (error) {
2973
+ console.error("[Venus] Error formatting number:", error);
2974
+ return String(value);
2975
+ }
2976
+ }
2977
+ async getFutureTimeAsync(options) {
2978
+ const timeInfo = await this.requestTimeAsync();
2979
+ const serverTime = new Date(timeInfo.serverTime);
2980
+ const result = new Date(serverTime);
2981
+ if (options?.days) {
2982
+ result.setDate(result.getDate() + options.days);
2983
+ }
2984
+ if (options?.hours) {
2985
+ result.setHours(result.getHours() + options.hours);
2986
+ }
2987
+ if (options?.minutes) {
2988
+ result.setMinutes(result.getMinutes() + options.minutes);
2989
+ }
2990
+ if (options?.timeOfDay) {
2991
+ const { hour = 0, minute = 0, second = 0 } = options.timeOfDay;
2992
+ timeInfo.timezoneOffset || (/* @__PURE__ */ new Date()).getTimezoneOffset();
2993
+ const localHour = hour;
2994
+ result.setHours(localHour, minute, second, 0);
2995
+ }
2996
+ if (options?.timezone) {
2997
+ switch (options.timezone.toUpperCase()) {
2998
+ case "PT":
2999
+ case "PST":
3000
+ case "PDT": {
3001
+ const isPDT = isPacificDaylightTime(result);
3002
+ const ptOffset = isPDT ? -7 : -8;
3003
+ result.setUTCHours(0, 0, 0, 0);
3004
+ const { hour = 0, minute = 0, second = 0 } = options.timeOfDay || {};
3005
+ const utcHour = (hour - ptOffset) % 24;
3006
+ result.setUTCHours(utcHour, minute, second, 0);
3007
+ break;
3008
+ }
3009
+ // Add other timezone cases as needed
3010
+ default:
3011
+ console.warn(
3012
+ "[Venus] Timezone " + options.timezone + " not supported, using local time"
3013
+ );
3014
+ }
3015
+ }
3016
+ return result.getTime();
3017
+ }
3018
+ };
3019
+
3020
+ // src/time/MockTimeApi.ts
3021
+ var MockTimeApi = class {
3022
+ constructor(venusApi) {
3023
+ __publicField(this, "venusApi");
3024
+ this.venusApi = venusApi;
3025
+ }
3026
+ formatNumber(value, options) {
3027
+ const locale = this.getLocale();
3028
+ const numberOptions = {
3029
+ style: options?.style || "decimal",
3030
+ minimumFractionDigits: options?.minimumFractionDigits || 0,
3031
+ maximumFractionDigits: options?.maximumFractionDigits || 2,
3032
+ ...options
3033
+ };
3034
+ console.log(`[Venus Mock] Formatting number ${value} with locale ${locale}`);
3035
+ return value.toLocaleString(locale, numberOptions);
3036
+ }
3037
+ formatTime(timestamp, options) {
3038
+ const locale = this.getLocale();
3039
+ const date = new Date(timestamp);
3040
+ const dateTimeOptions = {
3041
+ dateStyle: options.dateStyle || "medium",
3042
+ timeStyle: options.timeStyle || "medium",
3043
+ hour12: options.hour12 !== void 0 ? options.hour12 : true,
3044
+ ...options
3045
+ };
3046
+ console.log(
3047
+ `[Venus Mock] Formatting time ${timestamp} with locale ${locale}`
3048
+ );
3049
+ return date.toLocaleString(locale, dateTimeOptions);
3050
+ }
3051
+ async getFutureTimeAsync(options) {
3052
+ console.log("[Venus Mock] Getting future time with options:", options);
3053
+ const timeInfo = await this.requestTimeAsync();
3054
+ const serverTime = new Date(timeInfo.serverTime);
3055
+ const result = new Date(serverTime);
3056
+ if (options?.days) {
3057
+ result.setDate(result.getDate() + options.days);
3058
+ }
3059
+ if (options?.hours) {
3060
+ result.setHours(result.getHours() + options.hours);
3061
+ }
3062
+ if (options?.minutes) {
3063
+ result.setMinutes(result.getMinutes() + options.minutes);
3064
+ }
3065
+ if (options?.timeOfDay) {
3066
+ const { hour = 0, minute = 0, second = 0 } = options.timeOfDay;
3067
+ timeInfo.timezoneOffset || (/* @__PURE__ */ new Date()).getTimezoneOffset();
3068
+ const localHour = hour;
3069
+ result.setHours(localHour, minute, second, 0);
3070
+ }
3071
+ if (options?.timezone) {
3072
+ switch (options?.timezone.toUpperCase()) {
3073
+ case "PT":
3074
+ case "PST":
3075
+ case "PDT": {
3076
+ const isPDT = isPacificDaylightTime(result);
3077
+ const ptOffset = isPDT ? -7 : -8;
3078
+ result.getUTCDate();
3079
+ result.getUTCMonth();
3080
+ result.getUTCFullYear();
3081
+ result.setUTCHours(0, 0, 0, 0);
3082
+ const { hour = 0, minute = 0, second = 0 } = options.timeOfDay || {};
3083
+ const utcHour = (hour - ptOffset) % 24;
3084
+ result.setUTCHours(utcHour, minute, second, 0);
3085
+ break;
3086
+ }
3087
+ // Add other timezone cases as needed
3088
+ default:
3089
+ console.warn(
3090
+ `[Venus Mock] Timezone ${options.timezone} not supported, using local time`
3091
+ );
3092
+ }
3093
+ }
3094
+ return result.getTime();
3095
+ }
3096
+ async requestTimeAsync() {
3097
+ console.log("[Venus Mock] Requesting time");
3098
+ await createMockDelay(MOCK_DELAYS.short);
3099
+ const venusApi = this.venusApi;
3100
+ const mockOffset = venusApi._mock.serverTimeOffset || 2500;
3101
+ const mockServerTime = Date.now() + mockOffset;
3102
+ const timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
3103
+ const localTime = mockServerTime - timezoneOffset * 6e4;
3104
+ const timeInfo = {
3105
+ serverTime: mockServerTime,
3106
+ localTime,
3107
+ timezoneOffset,
3108
+ formattedTime: new Date(localTime).toISOString(),
3109
+ locale: venusApi._mock.user?.locale || "en-US"
3110
+ };
3111
+ console.log("[Venus Mock] Time response:", {
3112
+ serverTime: new Date(timeInfo.serverTime).toISOString(),
3113
+ localTime: new Date(timeInfo.localTime).toISOString(),
3114
+ timezoneOffset: timeInfo.timezoneOffset
3115
+ });
3116
+ return timeInfo;
3117
+ }
3118
+ getLocale() {
3119
+ const venusApi = this.venusApi;
3120
+ let locale = "en-US";
3121
+ if (venusApi._mock.user && venusApi._mock.user.locale) {
3122
+ locale = venusApi._mock.user.locale;
3123
+ } else if (venusApi._mock.environment && venusApi._mock.environment.browserInfo.language) {
3124
+ locale = venusApi._mock.environment.browserInfo.language;
3125
+ }
3126
+ return locale;
3127
+ }
3128
+ };
3129
+
3130
+ // src/time/index.ts
3131
+ function initializeTime(venusApi, host) {
3132
+ venusApi.requestTimeAsync = () => {
3133
+ return host.time.requestTimeAsync();
3134
+ };
3135
+ venusApi.getFutureTimeAsync = (options) => {
3136
+ return host.time.getFutureTimeAsync(options);
3137
+ };
3138
+ venusApi.formatTime = (timestamp, options) => {
3139
+ return host.time.formatTime(timestamp, options);
3140
+ };
3141
+ venusApi.formatNumber = (value, options) => {
3142
+ return host.time.formatNumber(value, options);
3143
+ };
3144
+ }
3145
+
3146
+ // src/version.ts
3147
+ var SDK_VERSION = "2.2.0";
3148
+
3149
+ exports.HapticFeedbackStyle = HapticFeedbackStyle;
3150
+ exports.HostCdnApi = HostCdnApi;
3151
+ exports.HostProfileApi = HostProfileApi;
3152
+ exports.HostTimeApi = HostTimeApi;
3153
+ exports.MockAdsApi = MockAdsApi;
3154
+ exports.MockAiApi = MockAiApi;
3155
+ exports.MockAnalyticsApi = MockAnalyticsApi;
3156
+ exports.MockAvatarApi = MockAvatarApi;
3157
+ exports.MockCdnApi = MockCdnApi;
3158
+ exports.MockFeaturesApi = MockFeaturesApi;
3159
+ exports.MockHapticsApi = MockHapticsApi;
3160
+ exports.MockIapApi = MockIapApi;
3161
+ exports.MockLifecycleApi = MockLifecycleApi;
3162
+ exports.MockLoggingApi = MockLoggingApi;
3163
+ exports.MockNavigationApi = MockNavigationApi;
3164
+ exports.MockNotificationsApi = MockNotificationsApi;
3165
+ exports.MockPopupsApi = MockPopupsApi;
3166
+ exports.MockProfileApi = MockProfileApi;
3167
+ exports.MockSimulationApi = MockSimulationApi;
3168
+ exports.MockStorageApi = MockStorageApi;
3169
+ exports.MockTimeApi = MockTimeApi;
3170
+ exports.RpcAdsApi = RpcAdsApi;
3171
+ exports.RpcAiApi = RpcAiApi;
3172
+ exports.RpcAnalyticsApi = RpcAnalyticsApi;
3173
+ exports.RpcAvatarApi = RpcAvatarApi;
3174
+ exports.RpcClient = RpcClient;
3175
+ exports.RpcFeaturesApi = RpcFeaturesApi;
3176
+ exports.RpcHapticsApi = RpcHapticsApi;
3177
+ exports.RpcIapApi = RpcIapApi;
3178
+ exports.RpcLifecycleApi = RpcLifecycleApi;
3179
+ exports.RpcLoggingApi = RpcLoggingApi;
3180
+ exports.RpcNavigationApi = RpcNavigationApi;
3181
+ exports.RpcPopupsApi = RpcPopupsApi;
3182
+ exports.RpcSimulationApi = RpcSimulationApi;
3183
+ exports.RpcStorageApi = RpcStorageApi;
3184
+ exports.SDK_VERSION = SDK_VERSION;
3185
+ exports.createMockStorageApi = createMockStorageApi;
3186
+ exports.initializeAds = initializeAds;
3187
+ exports.initializeAi = initializeAi;
3188
+ exports.initializeAnalytics = initializeAnalytics;
3189
+ exports.initializeAvatar3d = initializeAvatar3d;
3190
+ exports.initializeCdn = initializeCdn;
3191
+ exports.initializeFeaturesApi = initializeFeaturesApi;
3192
+ exports.initializeHaptics = initializeHaptics;
3193
+ exports.initializeIap = initializeIap;
3194
+ exports.initializeLifecycleApi = initializeLifecycleApi;
3195
+ exports.initializeLocalNotifications = initializeLocalNotifications;
3196
+ exports.initializeLoggingApi = initializeLoggingApi;
3197
+ exports.initializePopups = initializePopups;
3198
+ exports.initializeProfile = initializeProfile;
3199
+ exports.initializeSimulation = initializeSimulation;
3200
+ exports.initializeStackNavigation = initializeStackNavigation;
3201
+ exports.initializeStorage = initializeStorage;
3202
+ exports.initializeTime = initializeTime;
3203
+ exports.isPacificDaylightTime = isPacificDaylightTime;
3204
+ //# sourceMappingURL=index.cjs.map
3205
+ //# sourceMappingURL=index.cjs.map