@hyve-sdk/js 1.5.0 → 2.1.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.d.ts CHANGED
@@ -65,24 +65,6 @@ interface Inventory {
65
65
  items: InventoryItem[];
66
66
  total_count: number;
67
67
  }
68
- /**
69
- * Ads configuration options
70
- * Ads are disabled by default and must be explicitly enabled
71
- */
72
- interface AdConfig$1 {
73
- /** Enable/disable ads (default: false) */
74
- enabled?: boolean;
75
- /** Sound setting for ads (default: 'on') */
76
- sound?: 'on' | 'off';
77
- /** Enable debug logging (default: false) */
78
- debug?: boolean;
79
- /** Callback before ad is shown */
80
- onBeforeAd?: (type: 'rewarded' | 'interstitial' | 'preroll') => void;
81
- /** Callback after ad is shown */
82
- onAfterAd?: (type: 'rewarded' | 'interstitial' | 'preroll') => void;
83
- /** Callback when user earns a reward (rewarded ads only) */
84
- onRewardEarned?: () => void;
85
- }
86
68
  /**
87
69
  * Persistent Game Data Types
88
70
  */
@@ -124,11 +106,10 @@ interface GameDataBatchItem {
124
106
  /**
125
107
  * Ads Service for Hyve SDK
126
108
  *
127
- * Simple wrapper around Google H5 Games Ads with configurable enable/disable.
128
- * Ads are OFF by default and must be explicitly enabled in SDK config.
109
+ * Wraps Google H5 Games Ads with auto-initialization and Playgama fallback.
110
+ * Ads are ON by default just call showAd() and it works.
129
111
  *
130
- * Prerequisites:
131
- * - Google H5 Games Ads SDK script must be loaded in HTML:
112
+ * Optional setup in HTML for Google H5 Games Ads:
132
113
  * <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
133
114
  * <script>
134
115
  * window.adBreak = window.adBreak || function(o) { (window.adsbygoogle = window.adsbygoogle || []).push(o); };
@@ -146,7 +127,6 @@ interface AdResult {
146
127
  completedAt: number;
147
128
  }
148
129
  interface AdConfig {
149
- enabled?: boolean;
150
130
  sound?: 'on' | 'off';
151
131
  debug?: boolean;
152
132
  onBeforeAd?: (type: AdType) => void;
@@ -175,37 +155,42 @@ declare global {
175
155
  }
176
156
  }
177
157
  /**
178
- * Simple Ads Manager
179
- * Ads are disabled by default
158
+ * Ads Manager — enabled by default, auto-initializes on first show() call.
180
159
  */
181
160
  declare class AdsService {
182
161
  private config;
183
- private initialized;
162
+ private initPromise;
184
163
  private ready;
185
164
  /**
186
- * Configure the ads service
187
- * Must set enabled: true to activate ads
165
+ * Optionally configure the ads service.
166
+ * Not required ads work without calling this.
188
167
  */
189
168
  configure(config: AdConfig): void;
190
169
  /**
191
- * Initialize the ads system
170
+ * Initialize the Google H5 Ads system.
171
+ * Returns a cached promise — safe to call multiple times.
192
172
  */
193
173
  private initialize;
194
174
  /**
195
- * Show an ad
196
- * Returns immediately if ads are disabled
175
+ * Show an ad. Auto-initializes on the first call.
176
+ * Returns immediately with success: false if ads are disabled or unavailable.
197
177
  */
198
178
  show(type: AdType): Promise<AdResult>;
199
179
  /**
200
- * Show an ad break
180
+ * Show an ad break via the Google H5 API.
201
181
  */
202
182
  private showAdBreak;
203
183
  /**
204
- * Check if ads are enabled
184
+ * Returns the configured ad lifecycle callbacks.
185
+ * Used by platform-specific providers (e.g. Playgama) to fire the same hooks.
205
186
  */
206
- isEnabled(): boolean;
187
+ getCallbacks(): {
188
+ onBeforeAd: (type: AdType) => void;
189
+ onAfterAd: (type: AdType) => void;
190
+ onRewardEarned: () => void;
191
+ };
207
192
  /**
208
- * Check if ads are ready to show
193
+ * Check if ads have successfully initialized and are ready to show.
209
194
  */
210
195
  isReady(): boolean;
211
196
  }
@@ -270,11 +255,12 @@ declare enum BillingPlatform {
270
255
  * - Web: Stripe Embedded Checkout (Stripe Elements)
271
256
  * - Native: In-App Purchases via NativeBridge
272
257
  *
258
+ * Auto-initializes on first getProducts() or purchase() call — no manual initialize() needed.
259
+ *
273
260
  * @example
274
261
  * ```typescript
275
262
  * import { BillingService } from '@hyve-sdk/js';
276
263
  *
277
- * // Initialize billing
278
264
  * const billing = new BillingService({
279
265
  * stripePublishableKey: 'pk_test_...',
280
266
  * checkoutUrl: 'https://your-api.com',
@@ -282,24 +268,10 @@ declare enum BillingPlatform {
282
268
  * userId: 'user_456'
283
269
  * });
284
270
  *
285
- * await billing.initialize();
286
- *
287
271
  * // Check which platform we're on
288
272
  * const platform = billing.getPlatform();
289
- * console.log('Running on:', platform);
290
- *
291
- * // Get available products
292
- * const products = await billing.getProducts();
293
- *
294
- * // For web: Ensure you have a container element in your HTML
295
- * // <div id="stripe-checkout-element"></div>
296
273
  *
297
- * // Purchase a product (web will mount Stripe checkout form)
298
- * const result = await billing.purchase('price_1234', {
299
- * elementId: 'stripe-checkout-element' // optional, defaults to 'stripe-checkout-element'
300
- * });
301
- *
302
- * // Set up callbacks for purchase events
274
+ * // Set up callbacks
303
275
  * billing.onPurchaseComplete((result) => {
304
276
  * console.log('Purchase successful!', result);
305
277
  * });
@@ -308,6 +280,10 @@ declare enum BillingPlatform {
308
280
  * console.error('Purchase failed:', result.error);
309
281
  * });
310
282
  *
283
+ * // Auto-inits on first call:
284
+ * const products = await billing.getProducts();
285
+ * const result = await billing.purchase('price_1234');
286
+ *
311
287
  * // Clean up when done
312
288
  * billing.dispose();
313
289
  * ```
@@ -315,24 +291,17 @@ declare enum BillingPlatform {
315
291
  declare class BillingService {
316
292
  private config;
317
293
  private platform;
318
- private isInitialized;
294
+ private initPromise;
319
295
  private nativeAvailable;
320
- private products;
321
296
  private stripe;
322
297
  private checkoutElement;
323
298
  private onPurchaseCompleteCallback?;
324
299
  private onPurchaseErrorCallback?;
325
- private onLogCallback?;
326
300
  constructor(config: BillingConfig);
327
301
  /**
328
- * Register a callback to receive all internal logs
329
- * Useful for displaying logs in a UI
330
- */
331
- onLog(callback: (level: "info" | "warn" | "error", message: string, data?: any) => void): void;
332
- /**
333
- * Internal logging method that calls both logger and custom callback
302
+ * Update billing configuration. Resets initialization so next call re-inits with new config.
334
303
  */
335
- private log;
304
+ configure(config: Partial<BillingConfig>): void;
336
305
  /**
337
306
  * Detects if running on web or native platform
338
307
  */
@@ -342,10 +311,10 @@ declare class BillingService {
342
311
  */
343
312
  getPlatform(): BillingPlatform;
344
313
  /**
345
- * Initialize the billing service
346
- * Must be called before using any other methods
314
+ * Initialize the billing service. Idempotent — returns cached promise on subsequent calls.
315
+ * Called automatically by getProducts() and purchase().
347
316
  */
348
- initialize(): Promise<boolean>;
317
+ private initialize;
349
318
  /**
350
319
  * Initialize native billing
351
320
  */
@@ -359,11 +328,11 @@ declare class BillingService {
359
328
  */
360
329
  private loadStripeScript;
361
330
  /**
362
- * Check if billing is available
331
+ * Check if billing is available based on current config and platform state
363
332
  */
364
333
  isAvailable(): boolean;
365
334
  /**
366
- * Get available products
335
+ * Get available products. Auto-initializes on first call.
367
336
  */
368
337
  getProducts(): Promise<BillingProduct[]>;
369
338
  /**
@@ -375,7 +344,7 @@ declare class BillingService {
375
344
  */
376
345
  private getProductsWeb;
377
346
  /**
378
- * Purchase a product
347
+ * Purchase a product. Auto-initializes on first call.
379
348
  * @param productId - The product ID (priceId for web/Stripe, productId for native)
380
349
  * @param options - Optional purchase options
381
350
  * @param options.elementId - For web: DOM element ID to mount Stripe checkout (default: 'stripe-checkout-element')
@@ -425,8 +394,8 @@ declare class BillingService {
425
394
  * HyveClient configuration options
426
395
  */
427
396
  interface HyveClientConfig extends TelemetryConfig {
428
- /** Ads configuration (disabled by default) */
429
- ads?: AdConfig$1;
397
+ /** Optional ads configuration (sound, debug, lifecycle callbacks) */
398
+ ads?: AdConfig;
430
399
  /** Billing configuration (disabled by default) */
431
400
  billing?: BillingConfig;
432
401
  /** Storage mode for persistent game data - 'cloud' (default) or 'local' */
@@ -444,9 +413,10 @@ declare class HyveClient {
444
413
  private gameId;
445
414
  private adsService;
446
415
  private playgamaService;
416
+ private playgamaInitPromise;
417
+ private crazyGamesService;
418
+ private crazyGamesInitPromise;
447
419
  private billingService;
448
- private billingConfig;
449
- private billingCallbacks;
450
420
  private storageMode;
451
421
  private cloudStorageAdapter;
452
422
  private localStorageAdapter;
@@ -456,11 +426,10 @@ declare class HyveClient {
456
426
  */
457
427
  constructor(config?: HyveClientConfig);
458
428
  /**
459
- * Authenticates a user from URL parameters
460
- * @param urlParams URL parameters or search string
461
- * @returns Promise resolving to boolean indicating success
429
+ * Parses JWT and game ID from the current window URL and stores them on the client.
430
+ * Called automatically during construction.
462
431
  */
463
- authenticateFromUrl(urlParams?: URLSearchParams | string): Promise<boolean>;
432
+ private _parseUrlAuth;
464
433
  /**
465
434
  * Sends a user-level telemetry event using JWT authentication
466
435
  * Requires JWT token, authenticated user, and game ID from URL parameters
@@ -545,6 +514,10 @@ declare class HyveClient {
545
514
  * @param mode Storage mode override (cloud or local)
546
515
  */
547
516
  private getStorageAdapter;
517
+ /**
518
+ * Returns the current game ID or throws if not available.
519
+ */
520
+ private requireGameId;
548
521
  /**
549
522
  * Save persistent game data
550
523
  * @param key Data key
@@ -602,7 +575,7 @@ declare class HyveClient {
602
575
  * Configure ads service
603
576
  * @param config Ads configuration
604
577
  */
605
- configureAds(config: AdConfig$1): void;
578
+ configureAds(config: AdConfig): void;
606
579
  /**
607
580
  * Show an ad
608
581
  * @param type Type of ad to show ('rewarded', 'interstitial', or 'preroll')
@@ -610,26 +583,25 @@ declare class HyveClient {
610
583
  */
611
584
  showAd(type: AdType): Promise<AdResult>;
612
585
  /**
613
- * Check if ads are enabled
614
- * @returns Boolean indicating if ads are enabled
586
+ * Notifies CrazyGames that gameplay has started.
587
+ * No-op on other platforms.
615
588
  */
616
- areAdsEnabled(): boolean;
589
+ gameplayStart(): Promise<void>;
617
590
  /**
618
- * Check if ads are ready to show
619
- * @returns Boolean indicating if ads are ready
591
+ * Notifies CrazyGames that gameplay has stopped.
592
+ * No-op on other platforms.
620
593
  */
621
- areAdsReady(): boolean;
594
+ gameplayStop(): Promise<void>;
622
595
  /**
623
- * Configure billing service
624
- * @param config Billing configuration
596
+ * Triggers a celebration effect on the CrazyGames website for significant achievements.
597
+ * No-op on other platforms.
625
598
  */
626
- configureBilling(config: BillingConfig): void;
599
+ happytime(): Promise<void>;
627
600
  /**
628
- * Initialize billing service
629
- * Must be called before using billing features
630
- * @returns Promise resolving to boolean indicating success
601
+ * Check if ads are ready to show
602
+ * @returns Boolean indicating if ads have initialized successfully
631
603
  */
632
- initializeBilling(): Promise<boolean>;
604
+ areAdsReady(): boolean;
633
605
  /**
634
606
  * Get the billing platform
635
607
  * @returns Current billing platform
@@ -668,11 +640,6 @@ declare class HyveClient {
668
640
  * Unmount Stripe checkout element
669
641
  */
670
642
  unmountBillingCheckout(): void;
671
- /**
672
- * Register a callback to receive billing logs
673
- * @param callback Function to call with log messages
674
- */
675
- onBillingLog(callback: (level: "info" | "warn" | "error", message: string, data?: any) => void): void;
676
643
  }
677
644
 
678
645
  /**
@@ -688,6 +655,8 @@ declare class HyveClient {
688
655
  */
689
656
 
690
657
  interface PlaygamaBridgeAdvertisement {
658
+ isInterstitialSupported: boolean;
659
+ isRewardedSupported: boolean;
691
660
  interstitialState: string;
692
661
  rewardedState: string;
693
662
  showInterstitial(placement?: string): void;
@@ -698,6 +667,11 @@ interface PlaygamaBridgeAdvertisement {
698
667
  interface PlaygamaBridge {
699
668
  initialize(): Promise<void>;
700
669
  advertisement: PlaygamaBridgeAdvertisement;
670
+ EVENT_NAME: {
671
+ INTERSTITIAL_STATE_CHANGED: string;
672
+ REWARDED_STATE_CHANGED: string;
673
+ [key: string]: string;
674
+ };
701
675
  }
702
676
  declare global {
703
677
  interface Window {
@@ -718,8 +692,101 @@ declare class PlaygamaService {
718
692
  */
719
693
  initialize(): Promise<boolean>;
720
694
  isInitialized(): boolean;
721
- showInterstitial(): Promise<AdResult>;
722
- showRewarded(): Promise<AdResult>;
695
+ showInterstitial(callbacks?: {
696
+ onBeforeAd?: () => void;
697
+ onAfterAd?: () => void;
698
+ }): Promise<AdResult>;
699
+ showRewarded(callbacks?: {
700
+ onBeforeAd?: () => void;
701
+ onAfterAd?: () => void;
702
+ onRewardEarned?: () => void;
703
+ }): Promise<AdResult>;
704
+ private loadScript;
705
+ }
706
+
707
+ /**
708
+ * CrazyGames SDK integration service
709
+ *
710
+ * Loads and initializes the CrazyGames SDK v2 when running on the CrazyGames platform.
711
+ * The SDK is loaded from CDN and exposes a global `window.CrazyGames.SDK` object.
712
+ *
713
+ * Detection: CrazyGames games run in an iframe on crazygames.com, so detection
714
+ * uses document.referrer and parent frame location checks.
715
+ *
716
+ * @packageDocumentation
717
+ */
718
+
719
+ type CrazyGamesEnvironment = 'local' | 'crazygames' | 'disabled';
720
+ interface CrazyGamesAdCallbacks {
721
+ adStarted?: () => void;
722
+ adFinished?: () => void;
723
+ adError?: (error: string, errorData?: unknown) => void;
724
+ }
725
+ interface CrazyGamesAdModule {
726
+ requestAd(type: 'midgame' | 'rewarded', callbacks: CrazyGamesAdCallbacks): void;
727
+ }
728
+ interface CrazyGamesGameModule {
729
+ gameplayStart(): void;
730
+ gameplayStop(): void;
731
+ happytime(): void;
732
+ }
733
+ interface CrazyGamesSDK {
734
+ ad: CrazyGamesAdModule;
735
+ game: CrazyGamesGameModule;
736
+ getEnvironment(): Promise<CrazyGamesEnvironment>;
737
+ }
738
+ declare global {
739
+ interface Window {
740
+ CrazyGames?: {
741
+ SDK: CrazyGamesSDK;
742
+ };
743
+ }
744
+ }
745
+ declare class CrazyGamesService {
746
+ private initialized;
747
+ /**
748
+ * Detects if the game is running on the CrazyGames platform.
749
+ * Games on CrazyGames run inside an iframe, so we check document.referrer
750
+ * and attempt to read the parent frame location.
751
+ */
752
+ static isCrazyGamesDomain(): boolean;
753
+ /**
754
+ * Loads the CrazyGames SDK from CDN and confirms the environment is 'crazygames'.
755
+ * Safe to call multiple times — resolves immediately if already initialized.
756
+ */
757
+ initialize(): Promise<boolean>;
758
+ isInitialized(): boolean;
759
+ /**
760
+ * Shows a midgame (interstitial) ad via the CrazyGames SDK.
761
+ */
762
+ showInterstitial(callbacks?: {
763
+ onBeforeAd?: () => void;
764
+ onAfterAd?: () => void;
765
+ }): Promise<AdResult>;
766
+ /**
767
+ * Shows a rewarded ad via the CrazyGames SDK.
768
+ * Resolves with success: true only when adFinished fires (ad was fully watched).
769
+ */
770
+ showRewarded(callbacks?: {
771
+ onBeforeAd?: () => void;
772
+ onAfterAd?: () => void;
773
+ onRewardEarned?: () => void;
774
+ }): Promise<AdResult>;
775
+ /**
776
+ * Notifies CrazyGames that gameplay has started.
777
+ * Call when the player actively begins or resumes playing.
778
+ */
779
+ gameplayStart(): void;
780
+ /**
781
+ * Notifies CrazyGames that gameplay has stopped.
782
+ * Call during menu access, level completion, or pausing.
783
+ */
784
+ gameplayStop(): void;
785
+ /**
786
+ * Triggers a celebration effect on the CrazyGames website.
787
+ * Use sparingly for significant achievements (boss defeat, personal record, etc.)
788
+ */
789
+ happytime(): void;
723
790
  private loadScript;
724
791
  }
725
792
 
@@ -817,51 +884,11 @@ declare const logger: Logger;
817
884
  * @returns Object containing parsed parameters with default values
818
885
  */
819
886
  declare function parseUrlParams(searchParams: URLSearchParams | string): {
820
- signature: string;
821
- message: string;
822
887
  gameStartTab: string;
823
- hyveToken: string;
824
888
  platform: string;
825
889
  hyveAccess: string;
826
890
  gameId: string;
827
891
  };
828
- /**
829
- * Validates an EVM signature against a message and user ID
830
- * @param signature The signature to validate
831
- * @param message The original message that was signed
832
- * @returns Promise resolving to boolean indicating if signature is valid
833
- */
834
- declare function validateSignature(signature: string, message: string): boolean;
835
- /**
836
- * Verifies a signed message containing metadata with expiration and address (LEGACY)
837
- * @param signature The signature to verify
838
- * @param message The encoded message containing metadata (JSON)
839
- * @returns The address that signed the message if valid, false otherwise
840
- */
841
- declare function handleVerifyMessage(signature: string, message: string): string | false;
842
- /**
843
- * Verifies a modern hyve-token
844
- * @param hyveToken The modern token in format: signature.address.randomBase64.timestamp
845
- * @param maxAgeSec Maximum age in seconds (default: 600 = 10 minutes)
846
- * @returns The verified address if valid, false otherwise
847
- */
848
- declare function verifyHyveToken(hyveToken: string, maxAgeSec?: number): string | false;
849
- /**
850
- * Unified authentication verification - tries modern token first, then falls back to legacy
851
- * @param params Object containing hyveToken, signature, message from URL params
852
- * @param maxAgeSec Maximum age for modern tokens in seconds (default: 600)
853
- * @returns Object with verification result and method used
854
- */
855
- declare function verifyAuthentication(params: {
856
- hyveToken?: string;
857
- signature?: string;
858
- message?: string;
859
- }, maxAgeSec?: number): {
860
- isValid: boolean;
861
- address: string | null;
862
- method: "modern" | "legacy" | "none";
863
- error?: string;
864
- };
865
892
  /**
866
893
  * Checks if the current domain is in the list of allowed domains
867
894
  * @param allowedDomains Array of allowed domains or a single domain string
@@ -1037,4 +1064,4 @@ declare class NativeBridge {
1037
1064
  */
1038
1065
  declare function generateUUID(): string;
1039
1066
 
1040
- export { type AdConfig$1 as AdConfig, type AdResult, type AdType, AdsService, type BillingConfig, BillingPlatform, type BillingProduct, BillingService, CloudStorageAdapter, type DeleteGameDataResponse, type GameDataBatchItem, type GameDataItem, type GameDataValue, type GetGameDataBatchResponse, type GetGameDataResponse, HyveClient, type HyveClientConfig, type Inventory, type InventoryItem, LocalStorageAdapter, Logger, NativeBridge, type NativeMessage, type NativeMessageHandler, NativeMessageType, PlaygamaService, type PurchaseResult, type SaveGameDataResponse, type StorageAdapter, type TelemetryAdditionalData, type TelemetryConfig, type TelemetryEvent, generateUUID, handleVerifyMessage, isDomainAllowed, logger, parseUrlParams, validateSignature, verifyAuthentication, verifyHyveToken };
1067
+ export { type AdConfig, type AdResult, type AdType, AdsService, type BillingConfig, BillingPlatform, type BillingProduct, BillingService, CloudStorageAdapter, CrazyGamesService, type DeleteGameDataResponse, type GameDataBatchItem, type GameDataItem, type GameDataValue, type GetGameDataBatchResponse, type GetGameDataResponse, HyveClient, type HyveClientConfig, type Inventory, type InventoryItem, LocalStorageAdapter, Logger, NativeBridge, type NativeMessage, type NativeMessageHandler, NativeMessageType, PlaygamaService, type PurchaseResult, type SaveGameDataResponse, type StorageAdapter, type TelemetryAdditionalData, type TelemetryConfig, type TelemetryEvent, generateUUID, isDomainAllowed, logger, parseUrlParams };