@explorins/pers-sdk-react-native 1.3.2 → 1.5.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.
Files changed (94) hide show
  1. package/README.md +276 -123
  2. package/dist/hooks/index.d.ts +10 -0
  3. package/dist/hooks/index.d.ts.map +1 -1
  4. package/dist/hooks/index.js +8 -0
  5. package/dist/hooks/useAnalytics.d.ts +96 -0
  6. package/dist/hooks/useAnalytics.d.ts.map +1 -0
  7. package/dist/hooks/useAnalytics.js +73 -0
  8. package/dist/hooks/useAuth.d.ts +52 -7
  9. package/dist/hooks/useAuth.d.ts.map +1 -1
  10. package/dist/hooks/useAuth.js +250 -3
  11. package/dist/hooks/useBusiness.d.ts +45 -3
  12. package/dist/hooks/useBusiness.d.ts.map +1 -1
  13. package/dist/hooks/useBusiness.js +182 -28
  14. package/dist/hooks/useCampaigns.d.ts +11 -4
  15. package/dist/hooks/useCampaigns.d.ts.map +1 -1
  16. package/dist/hooks/useCampaigns.js +101 -39
  17. package/dist/hooks/useDonations.d.ts +33 -0
  18. package/dist/hooks/useDonations.d.ts.map +1 -0
  19. package/dist/hooks/useDonations.js +62 -0
  20. package/dist/hooks/useFiles.d.ts +50 -0
  21. package/dist/hooks/useFiles.d.ts.map +1 -0
  22. package/dist/hooks/useFiles.js +140 -0
  23. package/dist/hooks/usePurchases.d.ts +9 -0
  24. package/dist/hooks/usePurchases.d.ts.map +1 -0
  25. package/dist/hooks/usePurchases.js +56 -0
  26. package/dist/hooks/useRedemptions.d.ts +10 -5
  27. package/dist/hooks/useRedemptions.d.ts.map +1 -1
  28. package/dist/hooks/useRedemptions.js +118 -66
  29. package/dist/hooks/useTenants.d.ts +10 -0
  30. package/dist/hooks/useTenants.d.ts.map +1 -0
  31. package/dist/hooks/useTenants.js +68 -0
  32. package/dist/hooks/useTokens.d.ts +36 -2
  33. package/dist/hooks/useTokens.d.ts.map +1 -1
  34. package/dist/hooks/useTokens.js +180 -19
  35. package/dist/hooks/useTransactionSigner.d.ts +73 -0
  36. package/dist/hooks/useTransactionSigner.d.ts.map +1 -0
  37. package/dist/hooks/useTransactionSigner.js +216 -0
  38. package/dist/hooks/useTransactions.d.ts +45 -3
  39. package/dist/hooks/useTransactions.d.ts.map +1 -1
  40. package/dist/hooks/useTransactions.js +149 -39
  41. package/dist/hooks/useUserStatus.d.ts +9 -0
  42. package/dist/hooks/useUserStatus.d.ts.map +1 -0
  43. package/dist/hooks/useUserStatus.js +57 -0
  44. package/dist/hooks/useUsers.d.ts +17 -0
  45. package/dist/hooks/useUsers.d.ts.map +1 -0
  46. package/dist/hooks/useUsers.js +120 -0
  47. package/dist/hooks/useWeb3.d.ts +69 -6
  48. package/dist/hooks/useWeb3.d.ts.map +1 -1
  49. package/dist/hooks/useWeb3.js +177 -17
  50. package/dist/index.d.ts +6 -4
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +31540 -794
  53. package/dist/index.js.map +1 -1
  54. package/dist/polyfills/index.d.ts +1 -1
  55. package/dist/polyfills/index.d.ts.map +1 -1
  56. package/dist/polyfills/index.js +155 -9
  57. package/dist/polyfills/web3-polyfills.d.ts +7 -0
  58. package/dist/polyfills/web3-polyfills.d.ts.map +1 -0
  59. package/dist/polyfills/web3-polyfills.js +85 -0
  60. package/dist/providers/PersSDKProvider.d.ts +28 -18
  61. package/dist/providers/PersSDKProvider.d.ts.map +1 -1
  62. package/dist/providers/PersSDKProvider.js +63 -129
  63. package/dist/providers/react-native-auth-provider.d.ts +19 -64
  64. package/dist/providers/react-native-auth-provider.d.ts.map +1 -1
  65. package/dist/providers/react-native-auth-provider.js +57 -175
  66. package/package.json +177 -157
  67. package/src/hooks/index.ts +13 -1
  68. package/src/hooks/useAnalytics.ts +150 -0
  69. package/src/hooks/useAuth.ts +286 -27
  70. package/src/hooks/useBusiness.ts +193 -30
  71. package/src/hooks/useCampaigns.ts +121 -43
  72. package/src/hooks/useDonations.ts +68 -0
  73. package/src/hooks/useFiles.ts +160 -0
  74. package/src/hooks/usePurchases.ts +69 -0
  75. package/src/hooks/useRedemptions.ts +135 -68
  76. package/src/hooks/useTenants.ts +77 -0
  77. package/src/hooks/useTokens.ts +189 -21
  78. package/src/hooks/useTransactionSigner.ts +287 -0
  79. package/src/hooks/useTransactions.ts +163 -41
  80. package/src/hooks/useUserStatus.ts +65 -0
  81. package/src/hooks/useUsers.ts +133 -0
  82. package/src/hooks/useWeb3.ts +201 -21
  83. package/src/index.ts +22 -17
  84. package/src/polyfills/index.ts +163 -10
  85. package/src/polyfills/web3-polyfills.ts +98 -0
  86. package/src/providers/PersSDKProvider.tsx +114 -178
  87. package/src/providers/react-native-auth-provider.ts +65 -208
  88. package/dist/index.esm.js +0 -1057
  89. package/dist/index.esm.js.map +0 -1
  90. package/dist/polyfills/index.simple.d.ts +0 -2
  91. package/dist/polyfills/index.simple.d.ts.map +0 -1
  92. package/dist/polyfills/index.simple.js +0 -17
  93. package/src/polyfills/index.simple.ts +0 -22
  94. package/src/types/external-modules.d.ts +0 -13
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Web3 specific polyfills for React Native
3
+ * Addresses instanceof and constructor issues in React Native environments
4
+ */
5
+
6
+ export const setupWeb3InstanceofPolyfill = () => {
7
+ try {
8
+ // Store the original instanceof behavior
9
+ const originalInstanceof = Function.prototype[Symbol.hasInstance];
10
+
11
+ // Override Symbol.hasInstance for better Web3 detection in React Native
12
+ if (typeof global !== 'undefined' && global.Symbol && global.Symbol.hasInstance) {
13
+ // Create a safer instanceof check for Web3
14
+ const createSafeInstanceofCheck = (constructor: any) => {
15
+ return function(instance: any) {
16
+ // Try the original check first
17
+ try {
18
+ if (originalInstanceof) {
19
+ return originalInstanceof.call(constructor, instance);
20
+ }
21
+ return instance instanceof constructor;
22
+ } catch (error) {
23
+ // Fallback to constructor and duck-typing checks
24
+ if (!instance || typeof instance !== 'object') {
25
+ return false;
26
+ }
27
+
28
+ // Check constructor name
29
+ if (instance.constructor && instance.constructor.name === constructor.name) {
30
+ return true;
31
+ }
32
+
33
+ // Check constructor reference
34
+ if (instance.constructor === constructor) {
35
+ return true;
36
+ }
37
+
38
+ // For Web3 specifically, check characteristic properties
39
+ if (constructor.name === 'Web3' &&
40
+ 'currentProvider' in instance &&
41
+ 'eth' in instance &&
42
+ 'utils' in instance) {
43
+ return true;
44
+ }
45
+
46
+ return false;
47
+ }
48
+ };
49
+ };
50
+
51
+ // Apply the polyfill to global scope for dynamic loading
52
+ (global as any).__PERS_SDK_SAFE_INSTANCEOF__ = createSafeInstanceofCheck;
53
+
54
+ }
55
+
56
+ return true;
57
+ } catch (error) {
58
+ console.warn('[PERS SDK] Web3 instanceof polyfill setup failed:', error);
59
+ return false;
60
+ }
61
+ };
62
+
63
+ export const createSafeWeb3Check = (provider: unknown): boolean => {
64
+ if (!provider || typeof provider !== 'object') {
65
+ return false;
66
+ }
67
+
68
+ try {
69
+ // Method 1: Check if it's already a Web3 instance using multiple approaches
70
+ const providerObj = provider as any;
71
+
72
+ // Constructor name check
73
+ if (providerObj.constructor?.name === 'Web3') {
74
+ return true;
75
+ }
76
+
77
+ // Duck typing for Web3 properties
78
+ if ('currentProvider' in providerObj &&
79
+ 'eth' in providerObj &&
80
+ 'utils' in providerObj &&
81
+ typeof providerObj.eth === 'object') {
82
+ return true;
83
+ }
84
+
85
+ // Check for Web3 version property
86
+ if ('version' in providerObj && typeof providerObj.version === 'string') {
87
+ return true;
88
+ }
89
+
90
+ return false;
91
+ } catch (error) {
92
+ console.warn('Safe Web3 check failed:', error);
93
+ return false;
94
+ }
95
+ };
96
+
97
+ // Auto-initialize
98
+ setupWeb3InstanceofPolyfill();
@@ -1,71 +1,83 @@
1
- import React, { createContext, useContext, useEffect, useState, ReactNode, useCallback, useRef } from 'react';
2
- import { PersApiClient } from '@explorins/pers-sdk/core';
3
- import { TokenSDK } from '@explorins/pers-sdk/token';
4
- import { createTransactionSDK } from '@explorins/pers-sdk/transaction';
5
- import { createBusinessSDK } from '@explorins/pers-sdk/business';
6
- import { createCampaignSDK } from '@explorins/pers-sdk/campaign';
7
- import { createRedemptionSDK } from '@explorins/pers-sdk/redemption';
8
- import { createWeb3SDK } from '@explorins/pers-sdk/web3';
1
+ import React, { createContext, useContext, useState, ReactNode, useCallback, useRef } from 'react';
2
+ import { PersSDK, PersConfig, createAuthProvider } from '@explorins/pers-sdk/core';
9
3
  import { ReactNativeHttpClient } from './react-native-http-client';
10
- import { BaseReactNativeAuthProvider } from './react-native-auth-provider';
11
-
12
- // Types for the SDK context
13
- export interface PersSDKConfig {
14
- apiProjectKey: string;
15
- environment?: 'development' | 'staging' | 'production';
16
- timeout?: number;
17
- }
4
+ import { ReactNativeAuthProvider } from './react-native-auth-provider';
5
+ import { UserDTO, AdminDTO } from '@explorins/pers-shared';
6
+
7
+ // Import manager types for TypeScript
8
+ import type {
9
+ AuthManager,
10
+ UserManager,
11
+ TokenManager,
12
+ BusinessManager,
13
+ CampaignManager,
14
+ RedemptionManager,
15
+ TransactionManager,
16
+ PurchaseManager,
17
+ TenantManager,
18
+ AnalyticsManager,
19
+ DonationManager
20
+ } from '@explorins/pers-sdk/core';
21
+
22
+ // Re-export PersConfig for external use
23
+ export type { PersConfig } from '@explorins/pers-sdk/core';
18
24
 
19
25
  export interface PersSDKContext {
20
- // SDK instances
21
- tokens: any | null;
22
- transactions: any | null;
23
- business: any | null;
24
- campaigns: any | null;
25
- redemptions: any | null;
26
- web3: any | null;
27
- apiClient: PersApiClient | null;
26
+ // Main SDK instance
27
+ sdk: PersSDK | null;
28
+
29
+ // Manager shortcuts for convenience
30
+ auth: AuthManager | null;
31
+ users: UserManager | null;
32
+ tokens: TokenManager | null;
33
+ businesses: BusinessManager | null;
34
+ campaigns: CampaignManager | null;
35
+ redemptions: RedemptionManager | null;
36
+ transactions: TransactionManager | null;
37
+ purchases: PurchaseManager | null;
38
+ tenants: TenantManager | null;
39
+ analytics: AnalyticsManager | null;
40
+ donations: DonationManager | null;
41
+
42
+ // Legacy support (deprecated but kept for backward compatibility)
43
+ business: BusinessManager | null;
44
+
45
+ // Platform-specific providers
46
+ authProvider: ReactNativeSDKAuthProvider | null;
28
47
 
29
48
  // State
30
49
  isInitialized: boolean;
31
50
  isAuthenticated: boolean;
32
- user: any | null;
51
+ user: UserDTO | AdminDTO | null;
33
52
  accountAddress: string | null;
34
53
 
35
54
  // Methods
36
- initialize: (config: PersSDKConfig) => Promise<void>;
37
- login: (jwtToken: string, userType?: 'user' | 'admin') => Promise<any>;
38
- loginWithRawData: (rawUserData: any) => Promise<any>;
39
- logout: () => Promise<void>;
55
+ initialize: (config: PersConfig) => Promise<void>;
56
+ setAuthenticationState: (user: UserDTO | AdminDTO | null, accountAddress: string | null, isAuthenticated: boolean) => void;
57
+ refreshUserData: () => Promise<void>;
40
58
  }
41
59
 
42
60
  // Create the context
43
61
  const SDKContext = createContext<PersSDKContext | null>(null);
44
62
 
45
- // Custom auth provider for React Native
46
- class ReactNativeSDKAuthProvider extends BaseReactNativeAuthProvider {
47
- public authType: 'admin' | 'user' = 'user';
48
- private _token: string | null = null;
49
-
50
- constructor(private projectKey: string) {
51
- super(projectKey);
52
- }
53
-
54
- async getToken(): Promise<string | null> {
55
- return this._token;
63
+ // Simple wrapper for SDK integration
64
+ class ReactNativeSDKAuthProvider extends ReactNativeAuthProvider {
65
+ constructor(projectKey: string) {
66
+ super(projectKey, { debug: true });
56
67
  }
57
68
 
69
+ // Override setAccessToken to provide backward compatibility
58
70
  async setToken(token: string | null): Promise<void> {
59
- this._token = token;
60
- }
61
-
62
- async getProjectKey(): Promise<string | null> {
63
- return this.projectKey;
71
+ if (token) {
72
+ await this.setAccessToken(token);
73
+ } else {
74
+ await this.clearTokens();
75
+ }
64
76
  }
65
77
 
66
- async onTokenExpired(): Promise<void> {
67
- console.log('Token expired - clearing token');
68
- this._token = null;
78
+ // Override getToken for backward compatibility
79
+ async getToken(): Promise<string | null> {
80
+ return await super.getToken();
69
81
  }
70
82
  }
71
83
 
@@ -74,73 +86,47 @@ export const PersSDKProvider: React.FC<{
74
86
  children: ReactNode;
75
87
  }> = ({ children }) => {
76
88
  const initializingRef = useRef(false);
77
- const [apiClient, setApiClient] = useState<PersApiClient | null>(null);
89
+ const [sdk, setSdk] = useState<PersSDK | null>(null);
78
90
  const [authProvider, setAuthProvider] = useState<ReactNativeSDKAuthProvider | null>(null);
79
- const [sdks, setSdks] = useState<{
80
- tokens: any | null;
81
- transactions: any | null;
82
- business: any | null;
83
- campaigns: any | null;
84
- redemptions: any | null;
85
- web3: any | null;
86
- }>({
87
- tokens: null,
88
- transactions: null,
89
- business: null,
90
- campaigns: null,
91
- redemptions: null,
92
- web3: null,
93
- });
94
91
 
95
92
  const [isInitialized, setIsInitialized] = useState(false);
96
93
  const [isAuthenticated, setIsAuthenticated] = useState(false);
97
- const [user, setUser] = useState<any>(null);
94
+ const [user, setUser] = useState<UserDTO | AdminDTO | null>(null);
98
95
  const [accountAddress, setAccountAddress] = useState<string | null>(null);
99
96
 
100
- const initialize = useCallback(async (config: PersSDKConfig) => {
97
+ const initialize = useCallback(async (config: PersConfig) => {
101
98
  // Prevent multiple initializations
102
99
  if (isInitialized || initializingRef.current) {
103
- console.log('⚠️ SDK already initialized or initializing, skipping...');
100
+ console.log('SDK already initialized or initializing, skipping...');
104
101
  return;
105
102
  }
106
103
 
107
104
  initializingRef.current = true;
108
105
 
109
106
  try {
110
- console.log('🚀 Initializing PERS SDK with config:', config);
107
+ console.log('Initializing PERS SDK with config:', config);
111
108
 
112
- // Create auth provider
113
- const auth = new ReactNativeSDKAuthProvider(config.apiProjectKey);
109
+ // Create React Native auth provider
110
+ const auth = new ReactNativeSDKAuthProvider(config.apiProjectKey || 'default-project');
114
111
  setAuthProvider(auth);
115
112
 
116
113
  // Create HTTP client
117
114
  const httpClient = new ReactNativeHttpClient();
118
115
 
119
- // Create API client
120
- const client = new PersApiClient(httpClient, {
121
- apiProjectKey: config.apiProjectKey,
122
- authProvider: auth,
123
- environment: config.environment || 'development',
124
- });
125
-
126
- setApiClient(client);
127
-
128
- // Initialize domain SDKs
129
- const domainSDKs = {
130
- tokens: new TokenSDK(client),
131
- transactions: createTransactionSDK(client),
132
- business: createBusinessSDK(client),
133
- campaigns: createCampaignSDK(client),
134
- redemptions: createRedemptionSDK(client),
135
- web3: createWeb3SDK(client),
116
+ // Create config with auth provider - use the ReactNative auth provider directly
117
+ const sdkConfig: PersConfig = {
118
+ ...config,
119
+ authProvider: auth
136
120
  };
137
121
 
138
- setSdks(domainSDKs);
122
+ // Initialize PersSDK with manager pattern
123
+ const sdkInstance = new PersSDK(httpClient, sdkConfig);
124
+ setSdk(sdkInstance);
139
125
  setIsInitialized(true);
140
126
 
141
- console.log('PERS SDK initialized successfully');
127
+ console.log('PERS SDK initialized successfully');
142
128
  } catch (error) {
143
- console.error('Failed to initialize PERS SDK:', error);
129
+ console.error('Failed to initialize PERS SDK:', error);
144
130
  initializingRef.current = false;
145
131
  throw error;
146
132
  } finally {
@@ -148,99 +134,50 @@ export const PersSDKProvider: React.FC<{
148
134
  }
149
135
  }, []);
150
136
 
151
- const login = useCallback(async (jwtToken: string, userType: 'user' | 'admin' = 'user') => {
152
- if (!apiClient || !authProvider) {
153
- throw new Error('SDK not initialized. Call initialize() first.');
154
- }
155
-
156
- try {
157
- console.log(`🔐 Logging in as ${userType}...`);
158
-
159
- // Set token in auth provider
160
- await authProvider.setToken(jwtToken);
161
-
162
- // Perform login with API client
163
- const result = userType === 'admin'
164
- ? await apiClient.loginAdmin(jwtToken)
165
- : await apiClient.loginUser(jwtToken);
166
-
167
- const userData = result.user || result.admin;
168
- const userAccountAddress = (userData as any)?.accountAddress ||
169
- (userData as any)?.wallets?.[0]?.address ||
170
- null;
171
-
172
- setUser(userData);
173
- setAccountAddress(userAccountAddress);
174
- setIsAuthenticated(true);
175
-
176
- console.log('✅ Login successful');
177
- return result;
178
- } catch (error) {
179
- console.error('❌ Login failed:', error);
180
- throw error;
181
- }
182
- }, [apiClient, authProvider]);
183
-
184
- const loginWithRawData = useCallback(async (rawUserData: any) => {
185
- if (!apiClient || !authProvider) {
186
- throw new Error('SDK not initialized. Call initialize() first.');
187
- }
137
+ const setAuthenticationState = useCallback((user: UserDTO | AdminDTO | null, accountAddress: string | null, isAuthenticated: boolean) => {
138
+ setUser(user);
139
+ setAccountAddress(accountAddress);
140
+ setIsAuthenticated(isAuthenticated);
141
+ }, []);
188
142
 
189
- try {
190
- console.log('🔐 Logging in with raw user data...');
191
-
192
- const result = await apiClient.loginUserWithRawData(rawUserData);
193
-
194
- // Set token from result
195
- if (result.accessToken) {
196
- await authProvider.setToken(result.accessToken);
197
- }
198
-
199
- const userData = result.user;
200
- const userAccountAddress = (userData as any)?.accountAddress ||
201
- (userData as any)?.wallets?.[0]?.address ||
202
- null;
203
-
204
- setUser(userData);
205
- setAccountAddress(userAccountAddress);
206
- setIsAuthenticated(true);
207
-
208
- console.log('✅ Raw data login successful');
209
- return result;
210
- } catch (error) {
211
- console.error('❌ Raw data login failed:', error);
212
- throw error;
143
+ const refreshUserData = useCallback(async (): Promise<void> => {
144
+ if (!sdk || !isAuthenticated || !isInitialized) {
145
+ throw new Error('SDK not initialized or not authenticated. Cannot refresh user data.');
213
146
  }
214
- }, [apiClient, authProvider]);
215
-
216
- const logout = useCallback(async () => {
147
+
217
148
  try {
218
- console.log('🔓 Logging out...');
219
-
220
- if (authProvider) {
221
- await authProvider.setToken(null);
222
- }
223
-
224
- setUser(null);
225
- setAccountAddress(null);
226
- setIsAuthenticated(false);
227
-
228
- console.log('✅ Logout successful');
149
+ console.log('Refreshing user data from remote server...');
150
+ const freshUserData = await sdk.users.getCurrentUser();
151
+ setUser(freshUserData);
152
+ console.log('User data refreshed successfully:', freshUserData);
229
153
  } catch (error) {
230
- console.error(' Logout failed:', error);
154
+ console.error('Failed to refresh user data:', error);
231
155
  throw error;
232
156
  }
233
- }, [authProvider]);
157
+ }, [sdk, isAuthenticated, isInitialized]);
234
158
 
235
159
  const contextValue: PersSDKContext = {
236
- // SDK instances
237
- tokens: sdks.tokens,
238
- transactions: sdks.transactions,
239
- business: sdks.business,
240
- campaigns: sdks.campaigns,
241
- redemptions: sdks.redemptions,
242
- web3: sdks.web3,
243
- apiClient,
160
+ // Main SDK instance
161
+ sdk,
162
+
163
+ // Manager shortcuts for convenience
164
+ auth: sdk?.auth || null,
165
+ users: sdk?.users || null,
166
+ tokens: sdk?.tokens || null,
167
+ businesses: sdk?.businesses || null,
168
+ campaigns: sdk?.campaigns || null,
169
+ redemptions: sdk?.redemptions || null,
170
+ transactions: sdk?.transactions || null,
171
+ purchases: sdk?.purchases || null,
172
+ tenants: sdk?.tenants || null,
173
+ analytics: sdk?.analytics || null,
174
+ donations: sdk?.donations || null,
175
+
176
+ // Legacy support (deprecated but kept for backward compatibility)
177
+ business: sdk?.businesses || null,
178
+
179
+ // Platform-specific providers
180
+ authProvider,
244
181
 
245
182
  // State
246
183
  isInitialized,
@@ -250,9 +187,8 @@ export const PersSDKProvider: React.FC<{
250
187
 
251
188
  // Methods
252
189
  initialize,
253
- login,
254
- loginWithRawData,
255
- logout,
190
+ setAuthenticationState,
191
+ refreshUserData,
256
192
  };
257
193
 
258
194
  return (