@hyve-sdk/js 1.5.1 → 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,35 +155,34 @@ 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
184
  * Returns the configured ad lifecycle callbacks.
205
- * Used by platform-specific ad providers (e.g. Playgama) to fire the same
206
- * onBeforeAd / onAfterAd / onRewardEarned hooks that the Google H5 path uses.
185
+ * Used by platform-specific providers (e.g. Playgama) to fire the same hooks.
207
186
  */
208
187
  getCallbacks(): {
209
188
  onBeforeAd: (type: AdType) => void;
@@ -211,11 +190,7 @@ declare class AdsService {
211
190
  onRewardEarned: () => void;
212
191
  };
213
192
  /**
214
- * Check if ads are enabled
215
- */
216
- isEnabled(): boolean;
217
- /**
218
- * Check if ads are ready to show
193
+ * Check if ads have successfully initialized and are ready to show.
219
194
  */
220
195
  isReady(): boolean;
221
196
  }
@@ -280,11 +255,12 @@ declare enum BillingPlatform {
280
255
  * - Web: Stripe Embedded Checkout (Stripe Elements)
281
256
  * - Native: In-App Purchases via NativeBridge
282
257
  *
258
+ * Auto-initializes on first getProducts() or purchase() call — no manual initialize() needed.
259
+ *
283
260
  * @example
284
261
  * ```typescript
285
262
  * import { BillingService } from '@hyve-sdk/js';
286
263
  *
287
- * // Initialize billing
288
264
  * const billing = new BillingService({
289
265
  * stripePublishableKey: 'pk_test_...',
290
266
  * checkoutUrl: 'https://your-api.com',
@@ -292,24 +268,10 @@ declare enum BillingPlatform {
292
268
  * userId: 'user_456'
293
269
  * });
294
270
  *
295
- * await billing.initialize();
296
- *
297
271
  * // Check which platform we're on
298
272
  * const platform = billing.getPlatform();
299
- * console.log('Running on:', platform);
300
- *
301
- * // Get available products
302
- * const products = await billing.getProducts();
303
- *
304
- * // For web: Ensure you have a container element in your HTML
305
- * // <div id="stripe-checkout-element"></div>
306
273
  *
307
- * // Purchase a product (web will mount Stripe checkout form)
308
- * const result = await billing.purchase('price_1234', {
309
- * elementId: 'stripe-checkout-element' // optional, defaults to 'stripe-checkout-element'
310
- * });
311
- *
312
- * // Set up callbacks for purchase events
274
+ * // Set up callbacks
313
275
  * billing.onPurchaseComplete((result) => {
314
276
  * console.log('Purchase successful!', result);
315
277
  * });
@@ -318,6 +280,10 @@ declare enum BillingPlatform {
318
280
  * console.error('Purchase failed:', result.error);
319
281
  * });
320
282
  *
283
+ * // Auto-inits on first call:
284
+ * const products = await billing.getProducts();
285
+ * const result = await billing.purchase('price_1234');
286
+ *
321
287
  * // Clean up when done
322
288
  * billing.dispose();
323
289
  * ```
@@ -325,24 +291,17 @@ declare enum BillingPlatform {
325
291
  declare class BillingService {
326
292
  private config;
327
293
  private platform;
328
- private isInitialized;
294
+ private initPromise;
329
295
  private nativeAvailable;
330
- private products;
331
296
  private stripe;
332
297
  private checkoutElement;
333
298
  private onPurchaseCompleteCallback?;
334
299
  private onPurchaseErrorCallback?;
335
- private onLogCallback?;
336
300
  constructor(config: BillingConfig);
337
301
  /**
338
- * Register a callback to receive all internal logs
339
- * Useful for displaying logs in a UI
340
- */
341
- onLog(callback: (level: "info" | "warn" | "error", message: string, data?: any) => void): void;
342
- /**
343
- * Internal logging method that calls both logger and custom callback
302
+ * Update billing configuration. Resets initialization so next call re-inits with new config.
344
303
  */
345
- private log;
304
+ configure(config: Partial<BillingConfig>): void;
346
305
  /**
347
306
  * Detects if running on web or native platform
348
307
  */
@@ -352,10 +311,10 @@ declare class BillingService {
352
311
  */
353
312
  getPlatform(): BillingPlatform;
354
313
  /**
355
- * Initialize the billing service
356
- * 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().
357
316
  */
358
- initialize(): Promise<boolean>;
317
+ private initialize;
359
318
  /**
360
319
  * Initialize native billing
361
320
  */
@@ -369,11 +328,11 @@ declare class BillingService {
369
328
  */
370
329
  private loadStripeScript;
371
330
  /**
372
- * Check if billing is available
331
+ * Check if billing is available based on current config and platform state
373
332
  */
374
333
  isAvailable(): boolean;
375
334
  /**
376
- * Get available products
335
+ * Get available products. Auto-initializes on first call.
377
336
  */
378
337
  getProducts(): Promise<BillingProduct[]>;
379
338
  /**
@@ -385,7 +344,7 @@ declare class BillingService {
385
344
  */
386
345
  private getProductsWeb;
387
346
  /**
388
- * Purchase a product
347
+ * Purchase a product. Auto-initializes on first call.
389
348
  * @param productId - The product ID (priceId for web/Stripe, productId for native)
390
349
  * @param options - Optional purchase options
391
350
  * @param options.elementId - For web: DOM element ID to mount Stripe checkout (default: 'stripe-checkout-element')
@@ -435,8 +394,8 @@ declare class BillingService {
435
394
  * HyveClient configuration options
436
395
  */
437
396
  interface HyveClientConfig extends TelemetryConfig {
438
- /** Ads configuration (disabled by default) */
439
- ads?: AdConfig$1;
397
+ /** Optional ads configuration (sound, debug, lifecycle callbacks) */
398
+ ads?: AdConfig;
440
399
  /** Billing configuration (disabled by default) */
441
400
  billing?: BillingConfig;
442
401
  /** Storage mode for persistent game data - 'cloud' (default) or 'local' */
@@ -455,9 +414,9 @@ declare class HyveClient {
455
414
  private adsService;
456
415
  private playgamaService;
457
416
  private playgamaInitPromise;
417
+ private crazyGamesService;
418
+ private crazyGamesInitPromise;
458
419
  private billingService;
459
- private billingConfig;
460
- private billingCallbacks;
461
420
  private storageMode;
462
421
  private cloudStorageAdapter;
463
422
  private localStorageAdapter;
@@ -467,11 +426,10 @@ declare class HyveClient {
467
426
  */
468
427
  constructor(config?: HyveClientConfig);
469
428
  /**
470
- * Authenticates a user from URL parameters
471
- * @param urlParams URL parameters or search string
472
- * @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.
473
431
  */
474
- authenticateFromUrl(urlParams?: URLSearchParams | string): Promise<boolean>;
432
+ private _parseUrlAuth;
475
433
  /**
476
434
  * Sends a user-level telemetry event using JWT authentication
477
435
  * Requires JWT token, authenticated user, and game ID from URL parameters
@@ -556,6 +514,10 @@ declare class HyveClient {
556
514
  * @param mode Storage mode override (cloud or local)
557
515
  */
558
516
  private getStorageAdapter;
517
+ /**
518
+ * Returns the current game ID or throws if not available.
519
+ */
520
+ private requireGameId;
559
521
  /**
560
522
  * Save persistent game data
561
523
  * @param key Data key
@@ -613,7 +575,7 @@ declare class HyveClient {
613
575
  * Configure ads service
614
576
  * @param config Ads configuration
615
577
  */
616
- configureAds(config: AdConfig$1): void;
578
+ configureAds(config: AdConfig): void;
617
579
  /**
618
580
  * Show an ad
619
581
  * @param type Type of ad to show ('rewarded', 'interstitial', or 'preroll')
@@ -621,26 +583,25 @@ declare class HyveClient {
621
583
  */
622
584
  showAd(type: AdType): Promise<AdResult>;
623
585
  /**
624
- * Check if ads are enabled
625
- * @returns Boolean indicating if ads are enabled
586
+ * Notifies CrazyGames that gameplay has started.
587
+ * No-op on other platforms.
626
588
  */
627
- areAdsEnabled(): boolean;
589
+ gameplayStart(): Promise<void>;
628
590
  /**
629
- * Check if ads are ready to show
630
- * @returns Boolean indicating if ads are ready
591
+ * Notifies CrazyGames that gameplay has stopped.
592
+ * No-op on other platforms.
631
593
  */
632
- areAdsReady(): boolean;
594
+ gameplayStop(): Promise<void>;
633
595
  /**
634
- * Configure billing service
635
- * @param config Billing configuration
596
+ * Triggers a celebration effect on the CrazyGames website for significant achievements.
597
+ * No-op on other platforms.
636
598
  */
637
- configureBilling(config: BillingConfig): void;
599
+ happytime(): Promise<void>;
638
600
  /**
639
- * Initialize billing service
640
- * Must be called before using billing features
641
- * @returns Promise resolving to boolean indicating success
601
+ * Check if ads are ready to show
602
+ * @returns Boolean indicating if ads have initialized successfully
642
603
  */
643
- initializeBilling(): Promise<boolean>;
604
+ areAdsReady(): boolean;
644
605
  /**
645
606
  * Get the billing platform
646
607
  * @returns Current billing platform
@@ -679,11 +640,6 @@ declare class HyveClient {
679
640
  * Unmount Stripe checkout element
680
641
  */
681
642
  unmountBillingCheckout(): void;
682
- /**
683
- * Register a callback to receive billing logs
684
- * @param callback Function to call with log messages
685
- */
686
- onBillingLog(callback: (level: "info" | "warn" | "error", message: string, data?: any) => void): void;
687
643
  }
688
644
 
689
645
  /**
@@ -748,6 +704,92 @@ declare class PlaygamaService {
748
704
  private loadScript;
749
705
  }
750
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;
790
+ private loadScript;
791
+ }
792
+
751
793
  /**
752
794
  * Storage adapter interface - supports cloud and local implementations
753
795
  */
@@ -842,51 +884,11 @@ declare const logger: Logger;
842
884
  * @returns Object containing parsed parameters with default values
843
885
  */
844
886
  declare function parseUrlParams(searchParams: URLSearchParams | string): {
845
- signature: string;
846
- message: string;
847
887
  gameStartTab: string;
848
- hyveToken: string;
849
888
  platform: string;
850
889
  hyveAccess: string;
851
890
  gameId: string;
852
891
  };
853
- /**
854
- * Validates an EVM signature against a message and user ID
855
- * @param signature The signature to validate
856
- * @param message The original message that was signed
857
- * @returns Promise resolving to boolean indicating if signature is valid
858
- */
859
- declare function validateSignature(signature: string, message: string): boolean;
860
- /**
861
- * Verifies a signed message containing metadata with expiration and address (LEGACY)
862
- * @param signature The signature to verify
863
- * @param message The encoded message containing metadata (JSON)
864
- * @returns The address that signed the message if valid, false otherwise
865
- */
866
- declare function handleVerifyMessage(signature: string, message: string): string | false;
867
- /**
868
- * Verifies a modern hyve-token
869
- * @param hyveToken The modern token in format: signature.address.randomBase64.timestamp
870
- * @param maxAgeSec Maximum age in seconds (default: 600 = 10 minutes)
871
- * @returns The verified address if valid, false otherwise
872
- */
873
- declare function verifyHyveToken(hyveToken: string, maxAgeSec?: number): string | false;
874
- /**
875
- * Unified authentication verification - tries modern token first, then falls back to legacy
876
- * @param params Object containing hyveToken, signature, message from URL params
877
- * @param maxAgeSec Maximum age for modern tokens in seconds (default: 600)
878
- * @returns Object with verification result and method used
879
- */
880
- declare function verifyAuthentication(params: {
881
- hyveToken?: string;
882
- signature?: string;
883
- message?: string;
884
- }, maxAgeSec?: number): {
885
- isValid: boolean;
886
- address: string | null;
887
- method: "modern" | "legacy" | "none";
888
- error?: string;
889
- };
890
892
  /**
891
893
  * Checks if the current domain is in the list of allowed domains
892
894
  * @param allowedDomains Array of allowed domains or a single domain string
@@ -1062,4 +1064,4 @@ declare class NativeBridge {
1062
1064
  */
1063
1065
  declare function generateUUID(): string;
1064
1066
 
1065
- 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 };