@explorins/pers-sdk 1.3.5 → 1.3.7

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/README.md CHANGED
@@ -1,15 +1,13 @@
1
- # PERS SDK
1
+ # @explorins/pers-sdk
2
2
 
3
- Platform-agnostic TypeScript SDK for the PERS (Phygital Experience Rewards System) API.
3
+ [![npm version](https://badge.fury.io/js/%40explorins%2Fpers-sdk.svg)](https://badge.fury.io/js/%40explorins%2Fpers-sdk)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
5
 
5
- ## Features
6
+ **Platform-agnostic TypeScript SDK for PERS (Phygital Experience Rewards System)** - Core SDK providing domain-driven business logic and API integration for tourism loyalty applications.
6
7
 
7
- - **Platform Agnostic**: Works across web, mobile, and server environments
8
- - **Automatic Authentication**: Intelligent token management with proactive refresh
9
- - **Background Refresh**: Non-blocking token refresh for optimal performance
10
- - **TypeScript Support**: Full type safety with comprehensive interfaces
11
- - **Error Handling**: Robust error handling with retry mechanisms
12
- - **Production Ready**: Optimized defaults for production environments
8
+ ## PERS Ecosystem
9
+
10
+ PERS is a comprehensive tourism loyalty platform bridging physical and digital experiences through loyalty programs, campaign management, payments, blockchain integration, business management, and analytics.
13
11
 
14
12
  ## Installation
15
13
 
@@ -17,399 +15,169 @@ Platform-agnostic TypeScript SDK for the PERS (Phygital Experience Rewards Syste
17
15
  npm install @explorins/pers-sdk
18
16
  ```
19
17
 
18
+ ## Platform Integration
19
+
20
+ - **[@explorins/pers-sdk-angular](https://www.npmjs.com/package/@explorins/pers-sdk-angular)** - Angular dependency injection wrapper
21
+ - **[@explorins/pers-sdk-react-native](https://www.npmjs.com/package/@explorins/pers-sdk-react-native)** - React Native providers and hooks
22
+ - **Direct Integration** - Node.js, Vanilla JS, or custom frameworks
23
+
20
24
  ## Quick Start
21
25
 
22
26
  ### Basic Setup
23
27
 
24
28
  ```typescript
25
- import { createPersSDK, createAuthProvider } from '@explorins/pers-sdk/core';
26
- import { BrowserHttpClient } from '@explorins/pers-sdk/browser'; // or your HTTP client
27
-
28
- // Create auth provider
29
- const authProvider = createAuthProvider({
30
- authType: 'user',
31
- tokenProvider: () => getFirebaseToken(), // Your token provider
32
- projectKey: 'your-project-key'
33
- });
29
+ import { PersApiClient } from '@explorins/pers-sdk/core';
30
+
31
+ // Custom HTTP client (platform-specific)
32
+ const httpClient = {
33
+ get: async (url: string) => fetch(url).then(r => r.json()),
34
+ post: async (url: string, data: any) =>
35
+ fetch(url, { method: 'POST', body: JSON.stringify(data) }).then(r => r.json()),
36
+ put: async (url: string, data: any) =>
37
+ fetch(url, { method: 'PUT', body: JSON.stringify(data) }).then(r => r.json()),
38
+ delete: async (url: string) =>
39
+ fetch(url, { method: 'DELETE' }).then(r => r.json())
40
+ };
34
41
 
35
- // Create SDK instance
36
- const sdk = createPersSDK(new BrowserHttpClient(), {
42
+ // Create API client
43
+ const apiClient = new PersApiClient(httpClient, {
37
44
  environment: 'production',
38
- apiProjectKey: 'your-project-key',
39
- authProvider
45
+ apiVersion: 'v2',
46
+ apiProjectKey: 'your-project-key'
40
47
  });
41
48
 
42
- // Use the API client
43
- const apiClient = sdk.api();
49
+ // Login with external JWT (Firebase, Auth0, etc.)
50
+ const result = await apiClient.loginUser(firebaseJWT);
44
51
  ```
45
52
 
46
- ### Authentication
47
-
48
- #### User Authentication
53
+ ### Platform Examples
49
54
 
50
- ```typescript
51
- // Login user with external JWT (Firebase, Auth0, etc.)
52
- const firebaseToken = await getIdToken();
53
- const session = await apiClient.loginUser(firebaseToken);
54
-
55
- console.log('User authenticated:', session.user.email);
56
- ```
57
-
58
- #### Admin Authentication
55
+ #### Angular
59
56
 
60
57
  ```typescript
61
- // Login admin with external JWT
62
- const adminToken = await getAdminToken();
63
- const session = await apiClient.loginAdmin(adminToken);
58
+ import { PERS_ANGULAR_SDK_SERVICE } from '@explorins/pers-sdk-angular';
64
59
 
65
- console.log('Admin authenticated:', session.user.email);
66
- ```
67
-
68
- ### Making API Calls
60
+ @Injectable()
61
+ export class AuthService {
62
+ private persSDK = inject(PERS_ANGULAR_SDK_SERVICE);
69
63
 
70
- #### GET Requests
71
-
72
- ```typescript
73
- // Fetch user data
74
- const user = await apiClient.get<User>('/users/me');
75
-
76
- // Download file
77
- const csvData = await apiClient.get('/export/data.csv', 'blob');
78
- ```
79
-
80
- #### POST Requests
81
-
82
- ```typescript
83
- // Create resource
84
- const newUser = await apiClient.post<User>('/users', {
85
- name: 'John Doe',
86
- email: 'john@example.com'
87
- });
88
-
89
- // Public endpoint (bypass auth)
90
- const contact = await apiClient.post('/public/contact', formData, {
91
- bypassAuth: true
92
- });
64
+ async login(firebaseToken: string) {
65
+ return this.persSDK.api().loginUser(firebaseToken);
66
+ }
67
+ }
93
68
  ```
94
69
 
95
- #### PUT/DELETE Requests
96
-
97
- ```typescript
98
- // Update resource
99
- const updatedUser = await apiClient.put<User>('/users/123', userData);
70
+ #### React Native
100
71
 
101
- // Delete resource
102
- await apiClient.delete('/users/123');
103
- ```
104
-
105
- ## Configuration
72
+ ```tsx
73
+ import { usePersSDK } from '@explorins/pers-sdk-react-native';
106
74
 
107
- ### Basic Configuration
108
-
109
- ```typescript
110
- const config = {
111
- environment: 'production', // 'development' | 'staging' | 'production'
112
- apiProjectKey: 'your-project-key', // Required for API access
113
- apiVersion: 'v2', // 'v1' | 'v1.8' | 'v1.9' | 'v2'
114
- timeout: 30000, // Request timeout (ms)
115
- retries: 3, // Retry attempts
116
- authProvider // Authentication provider
117
- };
118
- ```
119
-
120
- ### Advanced Configuration
121
-
122
- ```typescript
123
- const config = {
124
- // ... basic config
75
+ function LoginScreen() {
76
+ const { login } = usePersSDK();
125
77
 
126
- // Token refresh settings
127
- tokenRefreshMargin: 120, // Refresh tokens 2 minutes before expiry
128
- backgroundRefreshThreshold: 30, // Use background refresh if >30s remaining
129
- };
130
- ```
131
-
132
- ## Authentication Providers
133
-
134
- ### Simple Token Provider
135
-
136
- ```typescript
137
- const authProvider = createAuthProvider({
138
- authType: 'user',
139
- token: 'static-token', // Static token
140
- projectKey: 'your-project-key'
141
- });
78
+ const handleLogin = async () => {
79
+ await login(firebaseToken);
80
+ };
81
+ }
142
82
  ```
143
83
 
144
- ### Dynamic Token Provider
84
+ ## Domain Architecture
145
85
 
146
86
  ```typescript
147
- const authProvider = createAuthProvider({
148
- authType: 'user',
149
- tokenProvider: async () => {
150
- // Fetch fresh token from your auth system
151
- return await getFirebaseToken();
152
- },
153
- projectKey: 'your-project-key',
154
-
155
- // Optional: Handle token refresh
156
- onTokenExpired: async () => {
157
- console.log('Token expired - refreshing...');
158
- },
159
-
160
- // Optional: React to token refresh
161
- onTokenRefreshed: (newToken) => {
162
- console.log('New token received');
163
- }
164
- });
87
+ // Domain-specific imports (recommended)
88
+ import { PersApiClient } from '@explorins/pers-sdk/core';
89
+ import { TokenSDK } from '@explorins/pers-sdk/token';
90
+ import { createBusinessSDK } from '@explorins/pers-sdk/business';
91
+ import { createCampaignSDK } from '@explorins/pers-sdk/campaign';
165
92
  ```
166
93
 
167
- ### Custom Storage
94
+ ## Core Authentication
168
95
 
169
96
  ```typescript
170
- const authProvider = createAuthProvider({
171
- authType: 'user',
172
- tokenProvider: () => getToken(),
173
- projectKey: 'your-project-key',
174
- tokenStorage: 'localStorage', // 'localStorage' | 'memory' | 'sessionStorage'
175
-
176
- // Or custom storage
177
- customTokenStorage: {
178
- setItem: async (key, value) => await customStorage.set(key, value),
179
- getItem: async (key) => await customStorage.get(key),
180
- removeItem: async (key) => await customStorage.remove(key)
181
- }
182
- });
183
- ```
184
-
185
- ## Token Management
186
-
187
- ### Token Lifecycle
188
-
189
- The SDK automatically handles token lifecycle:
190
-
191
- 1. **Proactive Refresh**: Tokens are refreshed before expiry
192
- 2. **Background Refresh**: Non-blocking refresh for optimal performance
193
- 3. **Fallback Refresh**: Reactive refresh if proactive refresh fails
194
- 4. **Provider Token**: Automatic fallback to provider token if refresh tokens expire
195
-
196
- ### Manual Token Checks
97
+ // Login with external JWT
98
+ const authResult = await apiClient.loginUser(externalJWT);
197
99
 
198
- ```typescript
199
- // Check if user is authenticated
100
+ // Check authentication status
200
101
  if (apiClient.hasValidAuth()) {
201
102
  console.log('User is authenticated');
202
103
  }
203
104
 
204
- // Check token expiry
205
- if (await apiClient.isTokenExpired(120)) {
206
- console.log('Token expires within 2 minutes');
207
- }
208
-
209
- // Check if full re-authentication is needed
210
- if (await apiClient.areAllTokensExpired()) {
211
- console.log('Full re-authentication required');
212
- redirectToLogin();
213
- }
214
- ```
215
-
216
- ## Error Handling
217
-
218
- ### API Errors
219
-
220
- ```typescript
221
- import { PersApiError } from '@explorins/pers-sdk/core';
222
-
223
- try {
224
- const data = await apiClient.get('/protected-endpoint');
225
- } catch (error) {
226
- if (error instanceof PersApiError) {
227
- console.error('API Error:', error.message);
228
- console.error('Status:', error.status);
229
- console.error('Endpoint:', error.endpoint);
230
- console.error('Retryable:', error.retryable);
231
- }
232
- }
233
- ```
234
-
235
- ### Authentication Errors
236
-
237
- Authentication failures are handled automatically, but you can listen for events:
238
-
239
- ```typescript
240
- // The SDK will automatically attempt refresh and fallback strategies
241
- // If all authentication methods fail, API calls will throw appropriate errors
242
- ```
243
-
244
- ## TypeScript Support
245
-
246
- ### Type Definitions
105
+ // Automatic token refresh handled internally
106
+ await apiClient.refreshToken();
247
107
 
248
- ```typescript
249
- import {
250
- PersApiClient,
251
- PersConfig,
252
- PersAuthProvider,
253
- PersEnvironment,
254
- PersApiVersion
255
- } from '@explorins/pers-sdk/core';
256
-
257
- // Custom interfaces
258
- interface User {
259
- id: string;
260
- email: string;
261
- name: string;
262
- }
263
-
264
- // Typed API calls
265
- const user = await apiClient.get<User>('/users/me');
266
- const users = await apiClient.get<User[]>('/users');
108
+ // Clear authentication
109
+ await apiClient.clearAuth();
267
110
  ```
268
111
 
269
- ### Custom Auth Provider
112
+ ## Business Domain Examples
270
113
 
114
+ ### Token Management
271
115
  ```typescript
272
- import { PersAuthProvider, AuthType } from '@explorins/pers-sdk/core';
116
+ import { TokenSDK } from '@explorins/pers-sdk/token';
273
117
 
274
- class CustomAuthProvider implements PersAuthProvider {
275
- authType: AuthType = 'user';
276
-
277
- async getToken(): Promise<string | null> {
278
- // Your implementation
279
- return await this.tokenManager.getAccessToken();
280
- }
281
-
282
- async getProjectKey(): Promise<string | null> {
283
- return 'your-project-key';
284
- }
285
-
286
- // Implement other required methods...
287
- }
118
+ const tokenSDK = new TokenSDK(apiClient);
119
+ const balances = await tokenSDK.getBalances(userId);
288
120
  ```
289
121
 
290
- ## Platform Integration
291
-
292
- ### Browser (React, Vue, etc.)
293
-
122
+ ### Business Operations
294
123
  ```typescript
295
- import { BrowserHttpClient } from '@explorins/pers-sdk/browser';
124
+ import { createBusinessSDK } from '@explorins/pers-sdk/business';
296
125
 
297
- const sdk = createPersSDK(new BrowserHttpClient(), config);
126
+ const businessSDK = createBusinessSDK(apiClient);
127
+ const businesses = await businessSDK.listBusinesses();
298
128
  ```
299
129
 
300
- ### Node.js
301
-
130
+ ### Campaign Management
302
131
  ```typescript
303
- import { NodeHttpClient } from '@explorins/pers-sdk/node';
132
+ import { createCampaignSDK } from '@explorins/pers-sdk/campaign';
304
133
 
305
- const sdk = createPersSDK(new NodeHttpClient(), config);
134
+ const campaignSDK = createCampaignSDK(apiClient);
135
+ const campaigns = await campaignSDK.getActiveCampaigns();
306
136
  ```
307
137
 
308
- ### React Native
309
-
310
- ```typescript
311
- import { ReactNativeHttpClient } from '@explorins/pers-sdk/react-native';
312
-
313
- const sdk = createPersSDK(new ReactNativeHttpClient(), config);
314
- ```
138
+ ## Available Domains
315
139
 
316
- ## Best Practices
140
+ - `/core` - Core API client and authentication
141
+ - `/token` - Token balances and transfers
142
+ - `/business` - Business operations and management
143
+ - `/campaign` - Marketing campaigns and challenges
144
+ - `/transaction` - Payment and transaction history
145
+ - `/redemption` - Reward redemption system
146
+ - `/payment` - Payment processing
147
+ - `/user` - User profile management
148
+ - `/web3` - Blockchain and wallet integration
149
+ - `/analytics` - Reporting and analytics
150
+ - `/tenant` - Multi-tenant management
317
151
 
318
- ### 1. Environment Configuration
152
+ ## Configuration
319
153
 
320
154
  ```typescript
321
- // Use environment variables
322
155
  const config = {
323
- environment: process.env.NODE_ENV === 'production' ? 'production' : 'development',
324
- apiProjectKey: process.env.PERS_PROJECT_KEY,
156
+ environment: 'production', // 'development' | 'staging' | 'production'
157
+ apiVersion: 'v2', // 'v1' | 'v1.8' | 'v1.9' | 'v2'
158
+ apiProjectKey: 'your-key', // Required: Your PERS project key
159
+ timeout: 30000, // Request timeout (default: 30s)
160
+ retries: 3 // Retry attempts (default: 3)
325
161
  };
326
162
  ```
327
163
 
328
- ### 2. Error Boundaries
329
-
330
- ```typescript
331
- // Wrap API calls in try-catch blocks
332
- const fetchUserData = async () => {
333
- try {
334
- return await apiClient.get<User>('/users/me');
335
- } catch (error) {
336
- // Handle error appropriately
337
- logError(error);
338
- showErrorToast('Failed to load user data');
339
- return null;
340
- }
341
- };
342
- ```
343
-
344
- ### 3. Token Provider Caching
345
-
346
- ```typescript
347
- let cachedToken: string | null = null;
348
-
349
- const authProvider = createAuthProvider({
350
- tokenProvider: async () => {
351
- if (!cachedToken) {
352
- cachedToken = await getFirebaseToken();
353
- }
354
- return cachedToken;
355
- },
356
- onTokenRefreshed: (newToken) => {
357
- cachedToken = newToken; // Update cache
358
- }
359
- });
360
- ```
361
-
362
- ## Migration Guide
363
-
364
- ### From v1.x to v2.x
365
-
366
- The v2 SDK introduces a cleaner, more maintainable architecture:
367
-
368
- ```typescript
369
- // v1.x (Legacy)
370
- import { PersSDK } from '@explorins/pers-sdk';
371
- const sdk = new PersSDK(config);
372
-
373
- // v2.x (Current)
374
- import { createPersSDK, createAuthProvider } from '@explorins/pers-sdk/core';
375
- import { BrowserHttpClient } from '@explorins/pers-sdk/browser';
376
-
377
- const authProvider = createAuthProvider(authConfig);
378
- const sdk = createPersSDK(new BrowserHttpClient(), {
379
- ...config,
380
- authProvider
381
- });
382
- ```
383
-
384
- ## API Reference
385
-
386
- ### Core Classes
387
-
388
- - **`PersApiClient`** - Main API client for authenticated requests
389
- - **`PersSDK`** - SDK wrapper providing access to API client
390
- - **`createAuthProvider()`** - Factory for creating authentication providers
391
- - **`createPersSDK()`** - Factory for creating SDK instances
392
-
393
- ### Interfaces
394
-
395
- - **`PersConfig`** - SDK configuration options
396
- - **`PersAuthProvider`** - Authentication provider interface
397
- - **`AuthTokens`** - Token structure definition
398
- - **`SimpleAuthConfig`** - Simple auth provider configuration
164
+ ## Dependencies
399
165
 
400
- ### Types
166
+ - **`@explorins/web3-ts`** (^0.3.75) - Web3 blockchain integration
167
+ - **`jwt-decode`** (^4.0.0) - JWT token parsing
168
+ - **`@explorins/pers-shared`** (*) - Shared types (peer dependency)
169
+ - **`ethers`** (^6.15.0) - Ethereum integration (peer dependency)
401
170
 
402
- - **`PersEnvironment`** - API environment options
403
- - **`PersApiVersion`** - Supported API versions
404
- - **`AuthType`** - Authentication types ('user' | 'admin')
171
+ ## Related Packages
405
172
 
406
- ## Support
173
+ - [@explorins/pers-sdk-angular](https://www.npmjs.com/package/@explorins/pers-sdk-angular) - Angular integration
174
+ - [@explorins/pers-sdk-react-native](https://www.npmjs.com/package/@explorins/pers-sdk-react-native) - React Native integration
175
+ - [@explorins/pers-shared](https://www.npmjs.com/package/@explorins/pers-shared) - Shared types and DTOs
176
+ - [@explorins/web3-ts](https://www.npmjs.com/package/@explorins/web3-ts) - Web3 utilities
407
177
 
408
- For issues, feature requests, or questions:
178
+ ## Documentation
409
179
 
410
- 1. Check the [documentation](https://docs.pers.ninja)
411
- 2. Search [existing issues](https://github.com/explorins/pers-sdk/issues)
412
- 3. Create a [new issue](https://github.com/explorins/pers-sdk/issues/new)
180
+ For comprehensive API documentation, usage guides, and examples, visit the [PERS SDK Documentation](https://docs.pers.ninja).
413
181
 
414
182
  ## License
415
183