@explorins/pers-sdk-react-native 2.1.1 → 2.1.2

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
@@ -207,7 +207,7 @@ export { PersSDKProvider, usePersSDK, type PersConfig, type PersSDKContext } fro
207
207
  * ```
208
208
  */
209
209
  export { useAuth, useTokens, useTokenBalances, useTransactions, useTransactionSigner, SigningStatus, useBusiness, useCampaigns, useRedemptions, useWeb3, usePurchases, useTenants, useUsers, useUserStatus, useFiles, useAnalytics, useDonations, useEvents } from './hooks';
210
- export type { OnStatusUpdateFn, StatusUpdateData, SigningStatusType } from './hooks';
210
+ export type { OnStatusUpdateFn, StatusUpdateData, SigningStatusType, TransactionSigningResult, SubmissionResult, AuthenticatedUser } from './hooks';
211
211
  export type { EventsHook, PersEvent, EventHandler, EventFilter, Unsubscribe } from './hooks';
212
212
  export type { TokenBalanceWithToken, UseTokenBalancesOptions, UseTokenBalancesResult } from './hooks';
213
213
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAGH,OAAO,aAAa,CAAC;AAMrB;;;;;;;;GAQG;AACH,OAAO,EACL,6BAA6B,EAC7B,KAAK,qBAAqB,EAC3B,MAAM,wCAAwC,CAAC;AAMhD;;;;;;;;;;GAUG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAEvE;;;;;;;;GAQG;AACH,OAAO,EACL,wBAAwB,GACzB,MAAM,uCAAuC,CAAC;AAM/C;;;GAGG;AACH,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAMvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EACL,eAAe,EACf,UAAU,EACV,KAAK,UAAU,EACf,KAAK,cAAc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AoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,EACrB,8BAA8B,EAC9B,2BAA2B,EAC5B,MAAM,iCAAiC,CAAC;AAEzC,YAAY,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAMzG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuFG;AACH,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,UAAU,EACX,MAAM,0BAA0B,CAAC"}
package/dist/index.js CHANGED
@@ -6828,7 +6828,8 @@ const DEFAULT_PERS_CONFIG = {
6828
6828
  timeout: 30000,
6829
6829
  retries: 3,
6830
6830
  tokenRefreshMargin: 60, // Refresh tokens 60 seconds before expiry
6831
- backgroundRefreshThreshold: 30 // Use background refresh if >30s remaining
6831
+ backgroundRefreshThreshold: 30, // Use background refresh if >30s remaining
6832
+ autoRestoreSession: true // Automatically restore session on initialization
6832
6833
  };
6833
6834
  /**
6834
6835
  * Internal function to construct API root from environment
@@ -6955,6 +6956,10 @@ var AuthStatus;
6955
6956
  AuthStatus["REFRESHING"] = "refreshing";
6956
6957
  /** No authentication present */
6957
6958
  AuthStatus["UNAUTHENTICATED"] = "unauthenticated";
6959
+ /** Session restoration completed (fired once on SDK initialization) */
6960
+ AuthStatus["SESSION_RESTORED"] = "session_restored";
6961
+ /** Session restoration determined no valid session exists */
6962
+ AuthStatus["SESSION_RESTORATION_FAILED"] = "session_restoration_failed";
6958
6963
  })(AuthStatus || (AuthStatus = {}));
6959
6964
 
6960
6965
  /**
@@ -7618,7 +7623,7 @@ class DefaultAuthProvider {
7618
7623
  /** SDK package name */
7619
7624
  const SDK_NAME = '@explorins/pers-sdk';
7620
7625
  /** SDK version - TODO: Load dynamically from package.json */
7621
- const SDK_VERSION = '2.1.0';
7626
+ const SDK_VERSION = '2.1.1';
7622
7627
  /** Full SDK identifier for headers */
7623
7628
  const SDK_USER_AGENT = `${SDK_NAME}/${SDK_VERSION}`;
7624
7629
 
@@ -13361,6 +13366,64 @@ class PersSDK {
13361
13366
  this._apiKeys = new ApiKeyManager(this.apiClient);
13362
13367
  this._analytics = new AnalyticsManager(this.apiClient);
13363
13368
  this._donations = new DonationManager(this.apiClient);
13369
+ // Automatically restore session if enabled and tokens exist
13370
+ if (config.autoRestoreSession !== false) {
13371
+ this.restoreSessionIfTokensExist().catch(err => {
13372
+ console.warn('[PersSDK] Failed to restore session on initialization:', err);
13373
+ });
13374
+ }
13375
+ }
13376
+ /**
13377
+ * Restore user session if valid tokens exist in storage
13378
+ *
13379
+ * This method is called automatically during SDK initialization when
13380
+ * `autoRestoreSession` is enabled (default). It checks for stored tokens
13381
+ * and fetches user data to restore the authentication state.
13382
+ *
13383
+ * Emits auth domain success event when session is restored.
13384
+ *
13385
+ * @internal
13386
+ * @returns Promise that resolves when session is restored or determined to be invalid
13387
+ */
13388
+ async restoreSessionIfTokensExist() {
13389
+ try {
13390
+ const hasToken = await this._auth.hasValidAuth();
13391
+ if (hasToken) {
13392
+ console.log('[PersSDK] Valid tokens found, restoring session...');
13393
+ try {
13394
+ // Fetch user data to validate tokens and restore session
13395
+ const userData = await this._auth.getCurrentUser();
13396
+ console.log('[PersSDK] Session restored successfully');
13397
+ // Emit event through proper event emitter
13398
+ // Send minimal data (just userId) - consumers can fetch full user if needed
13399
+ this._events.emitSuccess({
13400
+ type: 'session_restored',
13401
+ domain: 'authentication',
13402
+ userMessage: 'Session restored successfully',
13403
+ details: { userId: userData.id }
13404
+ });
13405
+ }
13406
+ catch (error) {
13407
+ // Tokens exist but are invalid (expired, revoked, etc.)
13408
+ console.warn('[PersSDK] Failed to restore session, tokens may be invalid:', error);
13409
+ await this._auth.clearAuth();
13410
+ // Emit restoration failed event
13411
+ this._events.emitError({
13412
+ type: 'session_restoration_failed',
13413
+ domain: 'authentication',
13414
+ userMessage: 'Session restoration failed',
13415
+ code: 'SESSION_INVALID',
13416
+ details: { error }
13417
+ });
13418
+ }
13419
+ }
13420
+ else {
13421
+ console.log('[PersSDK] No valid tokens found');
13422
+ }
13423
+ }
13424
+ catch (error) {
13425
+ console.warn('[PersSDK] Error during session restoration:', error);
13426
+ }
13364
13427
  }
13365
13428
  /**
13366
13429
  * Event emitter - Subscribe to SDK-wide events
@@ -14583,30 +14646,11 @@ const PersSDKProvider = ({ children, config }) => {
14583
14646
  // Auto-initialize if config is provided
14584
14647
  react.useEffect(() => {
14585
14648
  if (config && !isInitialized && !initializingRef.current) {
14586
- initialize(config).then(async () => {
14587
- // Validate stored tokens on startup
14588
- // SDK's initialize() already calls ensureValidToken() which handles expired tokens
14589
- // This provides an additional safety layer for missing/corrupted tokens
14590
- if (authProvider && sdk) {
14591
- try {
14592
- const hasToken = await sdk.auth.hasValidAuth();
14593
- if (!hasToken) {
14594
- console.log('[PersSDK] No tokens found on startup, ensuring clean state');
14595
- await authProvider.clearTokens();
14596
- setAuthenticationState(null, false);
14597
- }
14598
- // Note: Token expiration validation happens automatically in SDK's initialize()
14599
- // which calls ensureValidToken() → checks expiration → triggers AUTH_FAILED if needed
14600
- }
14601
- catch (error) {
14602
- console.warn('[PersSDK] Token validation on startup failed:', error);
14603
- }
14604
- }
14605
- }).catch(err => {
14649
+ initialize(config).catch(err => {
14606
14650
  console.error('Auto-initialization failed:', err);
14607
14651
  });
14608
14652
  }
14609
- }, [config, isInitialized, initialize, authProvider, sdk, setAuthenticationState]);
14653
+ }, [config, isInitialized, initialize]);
14610
14654
  const refreshUserData = react.useCallback(async () => {
14611
14655
  if (!sdk || !isAuthenticated || !isInitialized) {
14612
14656
  throw new Error('SDK not initialized or not authenticated. Cannot refresh user data.');
@@ -14620,52 +14664,36 @@ const PersSDKProvider = ({ children, config }) => {
14620
14664
  throw error;
14621
14665
  }
14622
14666
  }, [sdk, isAuthenticated, isInitialized]);
14623
- // Listen for authentication status changes and refresh user data when tokens are renewed
14667
+ // Listen for authentication events from core SDK
14668
+ // Set up immediately when SDK is created (don't wait for isInitialized)
14669
+ // to catch session_restored events that fire during SDK initialization
14624
14670
  react.useEffect(() => {
14625
- if (!authProvider || !isInitialized)
14626
- return;
14627
- // Access the config object with proper type safety
14628
- const providerConfig = authProvider.config;
14629
- if (!providerConfig)
14671
+ if (!sdk)
14630
14672
  return;
14631
- // Set up auth status change handler
14632
- const originalHandler = providerConfig.onAuthStatusChange;
14633
- const authStatusHandler = async (status) => {
14634
- console.log('[PersSDK] Auth status changed:', status);
14635
- // Call original handler first if it exists
14636
- if (originalHandler) {
14637
- await originalHandler(status);
14638
- }
14639
- // If token was refreshed successfully and user is authenticated, reload user data
14640
- if (status === 'authenticated' && isAuthenticated && sdk) {
14641
- try {
14642
- console.log('[PersSDK] Token refreshed, reloading user data...');
14643
- await refreshUserData();
14644
- }
14645
- catch (error) {
14646
- console.error('[PersSDK] Failed to refresh user data after token renewal:', error);
14647
- }
14673
+ const unsubscribe = sdk.events.subscribe((event) => {
14674
+ if (event.domain !== 'authentication')
14675
+ return;
14676
+ // Session restored successfully - sync React state
14677
+ if (event.type === 'session_restored') {
14678
+ console.log('[PersSDK] Session restoration event received, syncing state...');
14679
+ sdk.users.getCurrentUser()
14680
+ .then(userData => {
14681
+ setAuthenticationState(userData, true);
14682
+ })
14683
+ .catch(error => {
14684
+ console.error('[PersSDK] Failed to sync restored session:', error);
14685
+ });
14648
14686
  }
14649
- // If authentication failed, clear state
14650
- // Frontend app can observe isAuthenticated state change to show custom UI
14651
- if (status === 'auth_failed') {
14652
- console.log('[PersSDK] Authentication failed - session expired');
14653
- // Note: Token clearing already handled by SDK's handleAuthFailure()
14654
- // which calls authProvider.clearTokens() with robust retry logic
14655
- // Clear React state to sync with SDK
14656
- // This triggers re-render, allowing app to show login screen
14687
+ // Session restoration failed or auth error - clear React state
14688
+ if (event.type === 'session_restoration_failed' || event.code === 'AUTH_FAILED') {
14689
+ console.log('[PersSDK] Authentication failed - clearing session');
14657
14690
  setAuthenticationState(null, false);
14658
14691
  }
14659
- };
14660
- // Inject our handler into the auth provider config
14661
- providerConfig.onAuthStatusChange = authStatusHandler;
14662
- // Cleanup
14692
+ }, { domains: ['authentication'] });
14663
14693
  return () => {
14664
- if (originalHandler) {
14665
- providerConfig.onAuthStatusChange = originalHandler;
14666
- }
14694
+ unsubscribe();
14667
14695
  };
14668
- }, [authProvider, isInitialized, isAuthenticated, sdk, refreshUserData, setAuthenticationState]);
14696
+ }, [sdk, setAuthenticationState]);
14669
14697
  // iOS/Android: Monitor app state and validate tokens when app becomes active
14670
14698
  react.useEffect(() => {
14671
14699
  if (!sdk || reactNative.Platform.OS === 'web') {