// Polyfills - must be imported first for Hermes engine compatibility import 'react-native-url-polyfill/auto'; /** * @fileoverview PERS SDK for React Native - Tourism Loyalty System * * A comprehensive React Native SDK for integrating with the PERS (Phygital Experience Rewards System) * platform. Provides complete functionality for tourism loyalty applications including user management, * token operations, business integrations, campaign management, and blockchain transaction signing. * * **Key Features:** * - Secure authentication with React Native Keychain integration * - Token management (earn, redeem, transfer, balance checking) * - Business and campaign management * - Blockchain transaction signing with WebAuthn * - React Native optimized with automatic polyfills * - Type-safe interfaces with comprehensive TypeScript support * - Analytics and reporting capabilities * - Donation and charitable giving features * * @example * **Quick Start:** * ```typescript * import { PersSDKProvider, usePersSDK, useTransactionSigner } from '@explorins/pers-sdk-react-native'; * * // 1. Wrap your app with the provider * function App() { * return ( * * * * ); * } * * // 2. Use hooks in your components * function RewardScreen() { * const { user, isAuthenticated, earnTokens } = usePersSDK(); * const { signAndSubmitTransactionWithJWT } = useTransactionSigner(); * * // Your reward logic here... * } * ``` * * @version 1.5.19 * @author eXplorins * @license MIT */ // Initialize React Native polyfills automatically import './polyfills'; // ============================================================================== // AUTHENTICATION PROVIDERS // ============================================================================== /** * React Native-specific authentication provider with secure keychain integration * * Provides secure token storage using React Native Keychain, biometric authentication, * and automatic token refresh capabilities. * * @see {@link createReactNativeAuthProvider} - Factory function for auth provider * @see {@link ReactNativeAuthConfig} - Configuration interface */ export { createReactNativeAuthProvider, type ReactNativeAuthConfig } from './providers/react-native-auth-provider'; // ============================================================================== // SECURE STORAGE // ============================================================================== /** * Secure Token Storage with Keychain Integration * * Implements the TokenStorage interface using React Native Keychain for sensitive data * (Private Keys, Access Tokens) and AsyncStorage for configuration/public data. * * - Encryption: Hardware-backed keystore * - Persistence: Survives app uninstall (on iOS usually) or clears on uninstall (Android) if configured * * @see {@link ReactNativeSecureStorage} - The implementation class */ export { ReactNativeSecureStorage } from './storage/rn-secure-storage'; /** * Secure token storage using React Native AsyncStorage * * Provides encrypted token storage with automatic cleanup and secure key management. * Integrates with React Native Keychain for enhanced security on supported devices. * * @see {@link AsyncStorageTokenStorage} - Secure storage implementation * @deprecated Use ReactNativeSecureStorage for better security (Keychain integration) */ export { AsyncStorageTokenStorage, } from './storage/async-storage-token-storage'; // ============================================================================== // DPoP PROVIDER // ============================================================================== /** * React Native DPoP Crypto Provider * implements DPoPCryptoProvider using react-native-quick-crypto */ export { ReactNativeDPoPProvider } from './providers/rn-dpop-provider'; // ============================================================================== // CORE PROVIDER & CONTEXT // ============================================================================== /** * Main PERS SDK provider and context for React Native applications * * The PersSDKProvider should wrap your entire app to provide PERS functionality * throughout your component tree. Use usePersSDK hook to access SDK features. * * @example * ```typescript * import { PersSDKProvider, usePersSDK } from '@explorins/pers-sdk-react-native'; * * function App() { * return ( * * * * * * ); * } * * function YourComponent() { * const { user, isAuthenticated, earnTokens } = usePersSDK(); * // Use PERS functionality here... * } * ``` * * @see {@link PersSDKProvider} - Main provider component * @see {@link usePersSDK} - Hook to access SDK functionality * @see {@link PersConfig} - Provider configuration interface * @see {@link PersSDKContext} - Context type definition */ export { PersSDKProvider, usePersSDK, type PersConfig, type PersSDKContext } from './providers/PersSDKProvider'; // ============================================================================== // REACT HOOKS (Primary Interface) // ============================================================================== /** * Comprehensive React hooks for PERS platform integration * * These hooks provide the primary interface for interacting with the PERS platform * in React Native applications. Each hook is optimized for specific functionality * and includes automatic error handling, loading states, and real-time updates. * * **Authentication & User Management:** * - `useAuth` - User authentication, login, logout, registration * - `useUsers` - User profile management and data operations * - `useUserStatus` - Real-time user status and activity monitoring * * **Token & Financial Operations:** * - `useTokens` - Token balance, earning, and management * - `useTransactions` - Transaction history and monitoring * - `useTransactionSigner` - **⭐ Blockchain transaction signing** * - `usePurchases` - Purchase history and payment processing * - `useDonations` - Charitable giving and donation management * * **Business & Campaign Management:** * - `useBusiness` - Business profile and operations * - `useBookings` - Booking management with status validation * - `useCampaigns` - Marketing campaigns and promotions * - `useRedemptions` - Reward redemption and fulfillment * * **Platform & Analytics:** * - `useTenants` - Multi-tenant configuration and management * - `useAnalytics` - Usage analytics and reporting * - `useFiles` - File upload and management * - `useWeb3` - Blockchain integration and wallet operations * - `useEvents` - ** SDK event subscriptions for notifications** * * @example * **Token Operations:** * ```typescript * import { useTokens, useTransactionSigner } from '@explorins/pers-sdk-react-native'; * * function TokenScreen() { * const { balance, earnTokens, redeemTokens } = useTokens(); * const { signAndSubmitTransactionWithJWT } = useTransactionSigner(); * * const handleEarn = async (amount: number) => { * const result = await earnTokens({ amount, source: 'reward' }); * console.log('Earned tokens:', result); * }; * * const handleRedeem = async (amount: number) => { * const redemption = await redeemTokens({ amount }); * const txResult = await signAndSubmitTransactionWithJWT(redemption.jwtToken); * console.log('Redemption completed:', txResult.transactionHash); * }; * } * ``` * * @example * **Campaign Integration:** * ```typescript * import { useCampaigns, useAuth } from '@explorins/pers-sdk-react-native'; * * function CampaignScreen() { * const { activeCampaigns, participateInCampaign } = useCampaigns(); * const { user } = useAuth(); * * const handleParticipate = async (campaignId: string) => { * const result = await participateInCampaign(campaignId, { * userId: user?.id, * participationData: { source: 'mobile_app' } * }); * }; * } * ``` * * @example * **Event Subscriptions:** * ```typescript * import { useEvents, useEffect } from '@explorins/pers-sdk-react-native'; * * function NotificationHandler() { * const { subscribe, isAvailable } = useEvents(); * * useEffect(() => { * if (!isAvailable) return; * * const unsubscribe = subscribe((event) => { * showNotification(event.userMessage, event.level); * }); * * return () => unsubscribe(); * }, [subscribe, isAvailable]); * } * ``` */ export { useAuth, useTokens, useTokenBalances, useTransactions, useTransactionSigner, SigningStatus, useBusiness, useBookings, useCampaigns, useRedemptions, useWeb3, usePurchases, useTenants, useUsers, useUserStatus, useFiles, useAnalytics, useDonations, useEvents, useTriggerSources, // IPFS hooks - for resolving ipfs:// URLs and loading metadata useResolvedUrl, useMetadata, useIPFSUrl, // alias for useResolvedUrl useTransactionMetadata // convenience for transaction items } from './hooks'; // Re-export signing status types for convenience export type { TransactionSignerHook, OnStatusUpdateFn, StatusUpdateData, SigningStatusType, TransactionSigningResult, SubmissionResult, AuthenticatedUser } from './hooks'; // Re-export event types for convenience export type { EventsHook, PersEvent, EventHandler, EventFilter, Unsubscribe } from './hooks'; // Re-export token balance types for convenience export type { TokenBalanceWithToken, UseTokenBalancesOptions, UseTokenBalancesResult } from './hooks'; // Re-export campaign types for convenience export type { CampaignClaimFilters, CampaignFilterOptions, CampaignHook, GetCampaignsOptions } from './hooks'; // Re-export redemption types for convenience export type { RedemptionRedeemFilters, RedemptionFilterOptions, RedemptionHook, GetRedemptionsOptions } from './hooks'; // Re-export business types for convenience export type { BusinessFilterOptions, BusinessHook } from './hooks'; // Re-export transaction types for convenience export type { TransactionQueryOptions, TransactionHook } from './hooks'; // Re-export trigger source types for convenience export type { TriggerSourceQueryOptions, TriggerSourceHook } from './hooks'; // Re-export analytics types for convenience export type { AnalyticsHook } from './hooks'; // Re-export booking types for convenience export type { BookingHook, BookingQueryOptions, BookingValidationOptions } from './hooks'; // ============================================================================== // PLATFORM ADAPTERS // ============================================================================== /** * React Native-optimized HTTP client with automatic request/response handling * * Provides platform-specific networking with proper error handling, timeout management, * and React Native compatibility. Automatically handles headers, authentication tokens, * and response parsing. * * @see {@link ReactNativeHttpClient} - The HTTP client implementation * @see {@link HttpClient} - The HTTP client interface * @see {@link RequestOptions} - Request configuration options */ export { ReactNativeHttpClient, type HttpClient, type RequestOptions } from './providers/react-native-http-client'; // ============================================================================== // POLYFILLS & COMPATIBILITY // ============================================================================== /** * React Native polyfill utilities for web compatibility * * Automatically initializes required polyfills for crypto, URL, and other web APIs * that may not be available in React Native environments. These are typically * loaded automatically, but manual initialization is available for advanced use cases. * * @see {@link initializeReactNativePolyfills} - Manual polyfill initialization */ export { initializeReactNativePolyfills } from './polyfills'; // ============================================================================== // TYPE DEFINITIONS & SHARED UTILITIES // ============================================================================== /** * Re-export all types and utilities from the shared PERS library * * This includes all core types, DTOs, enums, and utility functions used across * the PERS platform. These types ensure consistency between different SDK versions * and platform implementations. * * **Included Types:** * - User and authentication types (UserDTO, AuthenticationResult, etc.) * - Token and transaction types (TokenDTO, TransactionDTO, etc.) * - Business and campaign types (BusinessDTO, CampaignDTO, etc.) * - API request/response types for all endpoints * - Error types and status enums * - Utility functions for pagination, token display, etc. * * @see {@link https://github.com/eXplorins/pers-shared} - Shared library documentation */ export * from '@explorins/pers-sdk'; /** * Token utilities re-exported from token module * * @see {@link getMetadataFromTokenUnitResponse} - Get full metadata object from token unit */ export { getMetadataFromTokenUnitResponse } from '@explorins/pers-sdk/token'; /** * Shared SDK utilities re-exported from base SDK * * Includes helper functions for: * - Pagination utilities (buildPaginationParams, extractData, etc.) */ export { // Pagination utilities buildPaginationParams, extractData, extractPagination, isPaginatedResponse, normalizeToPaginated, fetchAllPages, type PaginationOptions, type PaginationWithFilters, type ListResponse } from '@explorins/pers-sdk'; /** * Re-export Web3 and blockchain-related types from base SDK * * Provides TypeScript definitions for Web3 operations, token management, * and blockchain interactions. These types are used by the transaction * signing hooks and Web3 integration features. * * @see {@link TokenBalanceRequest} - Request structure for token balance queries * @see {@link TokenBalance} - Token balance response data * @see {@link TokenMetadata} - Token metadata and details * @see {@link TokenCollection} - Collection of tokens for batch operations */ export type { TokenBalanceRequest, TokenBalance, TokenMetadata, TokenCollection, TokenCollectionRequest } from '@explorins/pers-sdk/web3'; // ============================================================================== // TRANSACTION REQUEST FACTORY FUNCTIONS // ============================================================================== /** * Transaction Request Factory Functions * * Factory functions for creating properly structured transaction DTOs. * Prioritizes accountId/accountType over raw addresses for security and consistency. * * @example * ```typescript * import { * buildMintRequest, * buildTransferRequest, * buildBurnRequest, * useTransactions, * AccountOwnerType * } from '@explorins/pers-sdk-react-native'; * * function TokenOperations() { * const { createTransaction } = useTransactions(); * * const handleMint = async () => { * const request = buildMintRequest({ * amount: 100, * contractAddress: '0x...', * chainId: 137, * recipientAccountType: AccountOwnerType.USER, * recipientAccountId: 'user-123' * }); * await createTransaction(request); * }; * } * ``` * * @see {@link buildMintRequest} - Create mint transaction requests * @see {@link buildBurnRequest} - Create burn transaction requests * @see {@link buildTransferRequest} - Create transfer transaction requests * @see {@link buildPOSTransferRequest} - Create POS transfer requests (business submits on behalf of user) * @see {@link buildPOSBurnRequest} - Create POS burn requests (business submits burn on behalf of user) * @see {@link buildSubmissionRequest} - Create submission requests from QR/signature data */ export { buildMintRequest, buildBurnRequest, buildTransferRequest, buildPOSTransferRequest, buildPOSBurnRequest, buildSubmissionRequest, ClientTransactionType, extractDeadlineFromSigningData, buildPendingTransactionData, needsSubmission, needsExternalSigning, getSigningUrl } from '@explorins/pers-sdk/transaction'; export type { POSAuthorizationOptions, PendingTransactionParams } from '@explorins/pers-sdk/transaction'; // ============================================================================== // ERROR CLASSES (for instanceof checks) // ============================================================================== /** * Structured error handling for PERS SDK * * The SDK provides comprehensive error classes and utilities for consistent error handling * across all operations. Errors follow the StructuredError pattern from @explorins/pers-shared. * * **Error Classes:** * - `PersApiError` - API errors with structured backend details * - `AuthenticationError` - Authentication/authorization failures (401) * * **Error Utilities:** * - `ErrorUtils.getMessage(error)` - Extract user-friendly message * - `ErrorUtils.getStatus(error)` - Get HTTP status code * - `ErrorUtils.isRetryable(error)` - Check if operation should be retried * - `ErrorUtils.isTokenExpiredError(error)` - Detect token expiration * * @example * **Basic Error Handling:** * ```typescript * import { PersApiError, ErrorUtils } from '@explorins/pers-sdk-react-native'; * * try { * await sdk.campaigns.claimCampaign({ campaignId }); * } catch (error) { * if (error instanceof PersApiError) { * // Structured error with backend details * console.log('Error code:', error.code); // 'CAMPAIGN_BUSINESS_REQUIRED' * console.log('Status:', error.status); // 400 * console.log('Message:', error.message); // Backend error message * console.log('User message:', error.userMessage); // User-friendly message * console.log('Retryable:', error.retryable); // false * } else { * // Generic error fallback * const message = ErrorUtils.getMessage(error); * console.error('Operation failed:', message); * } * } * ``` * * @example * **Error Utilities:** * ```typescript * import { ErrorUtils } from '@explorins/pers-sdk-react-native'; * * try { * await someOperation(); * } catch (error) { * const status = ErrorUtils.getStatus(error); // Extract status code * const message = ErrorUtils.getMessage(error); // Extract message * const retryable = ErrorUtils.isRetryable(error); // Check if retryable * * if (ErrorUtils.isTokenExpiredError(error)) { * // Handle token expiration * await refreshToken(); * } else if (retryable) { * // Retry operation * await retry(someOperation); * } else { * // Show error to user * showError(message); * } * } * ``` * * @example * **React Native Error Display:** * ```typescript * import { PersApiError, ErrorUtils } from '@explorins/pers-sdk-react-native'; * import { Alert } from 'react-native'; * * const handleError = (error: unknown) => { * if (error instanceof PersApiError) { * // Show structured error * Alert.alert( * 'Error', * error.userMessage || error.message, * [ * { text: 'OK' }, * error.retryable && { text: 'Retry', onPress: retry } * ].filter(Boolean) * ); * } else { * // Show generic error * Alert.alert('Error', ErrorUtils.getMessage(error)); * } * }; * ``` */ export { PersApiError, AuthenticationError, ErrorUtils } from '@explorins/pers-sdk/core'; // ============================================================================== // DATA SOURCE TRACKING // ============================================================================== /** * Data source tracking utilities for attribution analytics * * Native apps MUST configure data source and platform info for proper attribution. * Web apps benefit from auto-detection, but can still set explicit values. * * @example * **React Native Setup:** * ```typescript * import { usePersSDK, detectReactNativePlatform } from '@explorins/pers-sdk-react-native'; * * const { sdk } = usePersSDK(); * * // Set platform info (call once on app start) * sdk.setPlatform(detectReactNativePlatform()); * * // Set data source (call once, update on deep links/push) * sdk.setDataSource({ * channel: 'mobile', * source: 'app_store', * }); * ``` * * @example * **Handle Deep Links:** * ```typescript * import { parseUtmParams } from '@explorins/pers-sdk-react-native'; * * function handleDeepLink(url: string) { * const utm = parseUtmParams(url); * sdk.updateDataSource({ * medium: utm.medium, * campaign: utm.campaign, * source: utm.source || 'deep_link', * }); * } * ``` * * @example * **Handle Push Notifications:** * ```typescript * function handlePushNotification(notification: PushNotification) { * sdk.updateDataSource({ * medium: 'push', * source: 'push_notification', * campaign: notification.campaignId, * }); * } * ``` */ export { // Types type Platform, type DataSource, type UtmParams, type WebDataSourceConfig, type NativeDataSourceConfig, // Utilities parseUtmParams, detectSourceFromReferrer, detectWebPlatform, } from '@explorins/pers-sdk/core'; // React Native specific platform detection export { detectReactNativePlatform } from './utils/platform-detection'; // ============================================================================== // FIELD VALIDATION UTILITIES // ============================================================================== /** * Field validation utilities for custom fields and forms * * These functions are re-exported from @explorins/pers-shared for convenience. * Use them for client-side validation before submitting data to the backend. * * @example * **Single Field Validation:** * ```typescript * import { validateFieldValue, FieldType, FieldValidationRules } from '@explorins/pers-sdk-react-native'; * * const rules: FieldValidationRules = { minLength: 3 }; * const error = validateFieldValue('ab', rules, 'text'); * // error: { message: 'Must be at least 3 characters' } * ``` * * @example * **Form Validation:** * ```typescript * import { validateAllFields, FieldDefinition } from '@explorins/pers-sdk-react-native'; * * const definitions: FieldDefinition[] = [ * { key: 'email', fieldType: 'email', label: 'Email', validation: { minLength: 1 } }, * { key: 'phone', fieldType: 'phone', label: 'Phone', validation: {} } * ]; * * const formData = { email: 'invalid', phone: '123' }; * const errors = validateAllFields(formData, definitions); * // errors: [{ field: 'email', message: 'Invalid email format' }] * ``` * * @see {@link validateFieldValue} - Validate a single field value * @see {@link validateAllFields} - Validate all fields against definitions * @see {@link FieldDefinition} - Field definition structure * @see {@link FieldValidationRules} - Available validation rules */ export { validateFieldValue, validateAllFields, validateFieldComparisons, compareValues, type FieldDefinition, type FieldValidationRules, type ValidationErrorDetail, type FieldType, type FieldComparison, type ComparisonOperator, } from '@explorins/pers-sdk'; // ============================================================================== // BOOKING STATUS VALIDATION // ============================================================================== /** * Booking status types and validation utilities for eligibility checks * * Use these to validate if a user's booking status meets requirements * for redemptions, campaigns, or other booking-dependent features. * * **BookingStatus:** 'past' | 'active' | 'future' * - `past`: User's stay has ended (checkOut ≤ now) * - `active`: User is currently staying (checkIn ≤ now < checkOut) * - `future`: Upcoming booking (checkIn > now) * * **BookingRequirementType:** 'active' | 'future' | 'past' | 'active_future' | 'any' * - `active`: Only active bookings allowed * - `future`: Only future bookings allowed * - `past`: Only past bookings allowed * - `active_future`: Active OR future bookings allowed * - `any`: Any booking status allowed * * @example * **Basic Validation:** * ```typescript * import { * isBookingStatusValid, * BookingStatus, * BookingRequirementType * } from '@explorins/pers-sdk-react-native'; * * const userBookingStatus: BookingStatus = booking.status; * const requirement: BookingRequirementType = redemption.bookingRequirement; * const canRedeem = isBookingStatusValid(userBookingStatus, requirement); * ``` * * @example * **Redemption Screen:** * ```typescript * function RedemptionCard({ redemption, userBooking }) { * const isEligible = redemption.bookingRequirement * ? isBookingStatusValid(userBooking?.status ?? 'past', redemption.bookingRequirement) * : true; * * return ( * * {redemption.name} * {!isEligible && ( * * Requires {redemption.bookingRequirement} booking * * )} * * ); * } * ``` * * @example * **Validation Results:** * ```typescript * isBookingStatusValid('active', 'active'); // true * isBookingStatusValid('future', 'active'); // false * isBookingStatusValid('active', 'active_future'); // true * isBookingStatusValid('future', 'active_future'); // true * isBookingStatusValid('past', 'active_future'); // false * isBookingStatusValid('past', 'any'); // true * ``` */ export { isBookingStatusValid, type BookingStatus, type BookingRequirementType } from '@explorins/pers-sdk';