@dracoonghost/trndup-sdk 1.0.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/README.md ADDED
@@ -0,0 +1,224 @@
1
+ # TrndUp TypeScript SDK
2
+
3
+ Official TypeScript SDK for the TrndUp API with Firebase authentication support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # In your mobile app
9
+ npm install file:../trndup-service/src/sdk
10
+ # or when published
11
+ npm install @trndup/sdk
12
+ ```
13
+
14
+ ## Quick Start
15
+
16
+ ```typescript
17
+ import { TrndUpSDK } from '@trndup/sdk';
18
+ import auth from '@react-native-firebase/auth';
19
+
20
+ // Initialize SDK
21
+ const sdk = new TrndUpSDK({
22
+ baseUrl: 'https://api.trndup.app', // or 'http://localhost:3000' for dev
23
+ getToken: async () => {
24
+ const user = auth().currentUser;
25
+ return user ? await user.getIdToken() : null;
26
+ },
27
+ onAuthFailure: () => {
28
+ // Handle auth failure - navigate to login
29
+ console.log('Authentication failed - please log in again');
30
+ },
31
+ debug: __DEV__, // Enable debug logging in development
32
+ });
33
+
34
+ export default sdk;
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### Authentication
40
+
41
+ ```typescript
42
+ // Login with Firebase ID token
43
+ const result = await sdk.auth.login(firebaseIdToken);
44
+ console.log('User:', result.user);
45
+
46
+ // Get current user
47
+ const { user, socialAccounts } = await sdk.auth.getCurrentUser();
48
+
49
+ // Update profile
50
+ await sdk.auth.updateProfile({
51
+ username: 'New Name',
52
+ picture: 'https://...',
53
+ });
54
+
55
+ // Logout
56
+ await sdk.auth.logout();
57
+ ```
58
+
59
+ ### YouTube Analytics
60
+
61
+ ```typescript
62
+ // Check initialization status
63
+ const status = await sdk.youtube.getInitStatus();
64
+ console.log('Needs init:', status.needsInit);
65
+
66
+ // Initialize YouTube data
67
+ if (status.needsInit) {
68
+ await sdk.youtube.initialize();
69
+ }
70
+
71
+ // Get videos
72
+ const { videos, total } = await sdk.youtube.getVideos({
73
+ limit: 20,
74
+ sortBy: 'views',
75
+ });
76
+
77
+ // Get channel metrics
78
+ const metrics = await sdk.youtube.getChannelMetrics();
79
+ console.log('Subscribers:', metrics.subscriberCount);
80
+
81
+ // Get health score
82
+ const health = await sdk.youtube.getHealthScore({ range: '30d' });
83
+ console.log('Score:', health.score, 'Grade:', health.grade);
84
+ ```
85
+
86
+ ### Instagram Analytics
87
+
88
+ ```typescript
89
+ // Check initialization status
90
+ const status = await sdk.instagram.getInitStatus();
91
+
92
+ // Get posts
93
+ const { posts } = await sdk.instagram.getPosts({ limit: 20 });
94
+
95
+ // Get account metrics
96
+ const metrics = await sdk.instagram.getAccountMetrics();
97
+ console.log('Followers:', metrics.followersCount);
98
+ ```
99
+
100
+ ### Social Account Linking
101
+
102
+ ```typescript
103
+ // Link YouTube account
104
+ await sdk.social.linkYouTube({
105
+ accessToken: 'ya29.a0...',
106
+ refreshToken: '1//0g...',
107
+ });
108
+
109
+ // Link Instagram account
110
+ await sdk.social.linkInstagram({
111
+ accessToken: 'IGQVJ...',
112
+ });
113
+
114
+ // Get connected accounts
115
+ const accounts = await sdk.social.getConnectedAccounts();
116
+
117
+ // Unlink account
118
+ await sdk.social.unlinkAccount('youtube');
119
+ ```
120
+
121
+ ### Cross-Platform Insights
122
+
123
+ ```typescript
124
+ // Get overview
125
+ const overview = await sdk.insights.getOverview();
126
+ console.log('Total followers:', overview.totalFollowers);
127
+
128
+ // Get trending content
129
+ const trending = await sdk.insights.getTrending();
130
+ ```
131
+
132
+ ## Error Handling
133
+
134
+ ```typescript
135
+ import { TrndUpApiError, TrndUpNetworkError } from '@trndup/sdk';
136
+
137
+ try {
138
+ await sdk.youtube.getVideos();
139
+ } catch (error) {
140
+ if (error instanceof TrndUpApiError) {
141
+ console.error('API Error:', error.message);
142
+ console.error('Status:', error.status);
143
+ console.error('Code:', error.code);
144
+
145
+ if (error.isAuthError()) {
146
+ // Handle authentication error
147
+ console.log('Please log in again');
148
+ }
149
+
150
+ if (error.isRateLimitError()) {
151
+ // Handle rate limiting
152
+ console.log('Too many requests, please wait');
153
+ }
154
+ } else if (error instanceof TrndUpNetworkError) {
155
+ console.error('Network Error:', error.message);
156
+ } else {
157
+ console.error('Unknown error:', error);
158
+ }
159
+ }
160
+ ```
161
+
162
+ ## Configuration Options
163
+
164
+ ```typescript
165
+ interface TrndUpClientConfig {
166
+ /** Base URL for the API */
167
+ baseUrl: string;
168
+
169
+ /** Function to get the current Firebase ID token */
170
+ getToken: () => string | null | Promise<string | null>;
171
+
172
+ /** Called when auth completely fails */
173
+ onAuthFailure?: () => void | Promise<void>;
174
+
175
+ /** Called on any API error */
176
+ onError?: (error: ApiErrorResponse, endpoint: string) => void;
177
+
178
+ /** Custom headers to include in all requests */
179
+ defaultHeaders?: Record<string, string>;
180
+
181
+ /** Request timeout in milliseconds (default: 30000) */
182
+ timeout?: number;
183
+
184
+ /** Enable debug logging (default: false) */
185
+ debug?: boolean;
186
+ }
187
+ ```
188
+
189
+ ## Type Safety
190
+
191
+ The SDK is fully typed with TypeScript. All request/response types are available:
192
+
193
+ ```typescript
194
+ import type { Auth, YouTube, Instagram, Social, Insights } from '@trndup/sdk';
195
+
196
+ // Use types in your code
197
+ const user: Auth.User = await sdk.auth.getCurrentUser();
198
+ const videos: YouTube.Video[] = await sdk.youtube.getVideos();
199
+ ```
200
+
201
+ ## Development
202
+
203
+ ```bash
204
+ # Build SDK
205
+ cd src/sdk
206
+ npm install
207
+ npm run build
208
+
209
+ # Watch mode for development
210
+ npm run dev
211
+
212
+ # Type check
213
+ npm run type-check
214
+
215
+ # Link for local development
216
+ npm link
217
+
218
+ # In your mobile app
219
+ npm link @trndup/sdk
220
+ ```
221
+
222
+ ## License
223
+
224
+ MIT
@@ -0,0 +1,478 @@
1
+ interface ApiErrorResponse {
2
+ success: false;
3
+ error: string;
4
+ code?: string;
5
+ metadata?: Record<string, unknown>;
6
+ }
7
+ declare namespace Auth {
8
+ interface User {
9
+ id: string;
10
+ firebaseUid: string;
11
+ email: string;
12
+ username: string;
13
+ picture?: string;
14
+ emailVerified: boolean;
15
+ createdAt: string;
16
+ updatedAt: string;
17
+ }
18
+ interface SocialAccount {
19
+ provider: string;
20
+ accountName?: string;
21
+ username?: string;
22
+ profilePictureUrl?: string;
23
+ connectedAt: string;
24
+ }
25
+ interface LoginRequest {
26
+ idToken: string;
27
+ }
28
+ interface LoginResponse {
29
+ user: User;
30
+ idToken: string;
31
+ }
32
+ interface CurrentUserResponse {
33
+ user: User;
34
+ socialAccounts: SocialAccount[];
35
+ }
36
+ interface UpdateProfileRequest {
37
+ username?: string;
38
+ picture?: string;
39
+ }
40
+ interface UpdateProfileResponse {
41
+ user: User;
42
+ }
43
+ }
44
+ declare namespace Social {
45
+ interface LinkYouTubeRequest {
46
+ accessToken: string;
47
+ refreshToken?: string;
48
+ }
49
+ interface LinkInstagramRequest {
50
+ accessToken: string;
51
+ }
52
+ interface LinkAccountResponse {
53
+ message: string;
54
+ provider: string;
55
+ accountName?: string;
56
+ }
57
+ interface ConnectedAccount {
58
+ provider: string;
59
+ accountName?: string;
60
+ username?: string;
61
+ profilePictureUrl?: string;
62
+ connectedAt: string;
63
+ lastSyncAt?: string;
64
+ }
65
+ }
66
+ declare namespace YouTube {
67
+ interface InitStatusResponse {
68
+ needsInit: boolean;
69
+ message: string;
70
+ videoCount?: number;
71
+ channelId?: string;
72
+ channelTitle?: string;
73
+ }
74
+ interface Video {
75
+ id: string;
76
+ title: string;
77
+ description?: string;
78
+ thumbnailUrl?: string;
79
+ publishedAt: string;
80
+ duration?: string;
81
+ viewCount?: number;
82
+ likeCount?: number;
83
+ commentCount?: number;
84
+ engagementRate?: number;
85
+ }
86
+ interface GetVideosParams {
87
+ limit?: number;
88
+ offset?: number;
89
+ sortBy?: 'recent' | 'views' | 'engagement';
90
+ }
91
+ interface GetVideosResponse {
92
+ videos: Video[];
93
+ total: number;
94
+ hasMore: boolean;
95
+ }
96
+ interface ChannelMetrics {
97
+ subscriberCount: number;
98
+ totalViews: number;
99
+ totalVideos: number;
100
+ averageViews: number;
101
+ engagementRate: number;
102
+ }
103
+ interface HealthScore {
104
+ score: number;
105
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
106
+ metrics: {
107
+ consistency: number;
108
+ engagement: number;
109
+ growth: number;
110
+ quality: number;
111
+ };
112
+ }
113
+ interface GetHealthScoreParams {
114
+ range?: string;
115
+ }
116
+ }
117
+ declare namespace Instagram {
118
+ interface InitStatusResponse {
119
+ needsInit: boolean;
120
+ message: string;
121
+ postCount?: number;
122
+ accountId?: string;
123
+ username?: string;
124
+ }
125
+ interface Post {
126
+ id: string;
127
+ caption?: string;
128
+ mediaType: 'IMAGE' | 'VIDEO' | 'CAROUSEL_ALBUM';
129
+ mediaUrl: string;
130
+ permalink: string;
131
+ timestamp: string;
132
+ likeCount?: number;
133
+ commentsCount?: number;
134
+ engagementRate?: number;
135
+ }
136
+ interface GetPostsParams {
137
+ limit?: number;
138
+ offset?: number;
139
+ }
140
+ interface GetPostsResponse {
141
+ posts: Post[];
142
+ total: number;
143
+ hasMore: boolean;
144
+ }
145
+ interface AccountMetrics {
146
+ followersCount: number;
147
+ followsCount: number;
148
+ mediaCount: number;
149
+ averageLikes: number;
150
+ engagementRate: number;
151
+ }
152
+ }
153
+ declare namespace Insights {
154
+ interface CrossPlatformMetrics {
155
+ totalFollowers: number;
156
+ totalEngagement: number;
157
+ platforms: {
158
+ youtube?: {
159
+ subscribers: number;
160
+ views: number;
161
+ videos: number;
162
+ };
163
+ instagram?: {
164
+ followers: number;
165
+ posts: number;
166
+ avgEngagement: number;
167
+ };
168
+ };
169
+ }
170
+ interface TrendingContent {
171
+ youtube?: YouTube.Video[];
172
+ instagram?: Instagram.Post[];
173
+ }
174
+ }
175
+
176
+ /**
177
+ * TrndUp SDK - Base Client
178
+ *
179
+ * Core HTTP client with Firebase authentication support,
180
+ * error handling, and automatic retries.
181
+ */
182
+
183
+ interface TrndUpClientConfig {
184
+ /** Base URL for the API (e.g., 'https://api.trndup.app' or 'http://localhost:3000') */
185
+ baseUrl: string;
186
+ /** Function to get the current Firebase ID token */
187
+ getToken: () => string | null | Promise<string | null>;
188
+ /** Called when auth completely fails (user needs to re-login) */
189
+ onAuthFailure?: () => void | Promise<void>;
190
+ /** Called on any API error */
191
+ onError?: (error: ApiErrorResponse, endpoint: string) => void;
192
+ /** Custom headers to include in all requests */
193
+ defaultHeaders?: Record<string, string>;
194
+ /** Request timeout in milliseconds (default: 30000) */
195
+ timeout?: number;
196
+ /** Enable debug logging (default: false) */
197
+ debug?: boolean;
198
+ }
199
+ interface RequestOptions {
200
+ /** Skip authentication for this request */
201
+ skipAuth?: boolean;
202
+ /** Additional headers for this request */
203
+ headers?: Record<string, string>;
204
+ /** AbortController signal for cancellation */
205
+ signal?: AbortSignal;
206
+ /** Custom timeout for this request */
207
+ timeout?: number;
208
+ }
209
+ declare class TrndUpApiError extends Error {
210
+ readonly response: ApiErrorResponse;
211
+ readonly status: number;
212
+ readonly endpoint: string;
213
+ constructor(response: ApiErrorResponse, status: number, endpoint: string);
214
+ get code(): string | undefined;
215
+ get metadata(): Record<string, unknown> | undefined;
216
+ /** Check if error is due to authentication failure */
217
+ isAuthError(): boolean;
218
+ /** Check if error is due to rate limiting */
219
+ isRateLimitError(): boolean;
220
+ }
221
+ declare class TrndUpNetworkError extends Error {
222
+ readonly originalError: Error;
223
+ readonly endpoint: string;
224
+ constructor(originalError: Error, endpoint: string);
225
+ }
226
+ declare class TrndUpClient {
227
+ private config;
228
+ auth: any;
229
+ youtube: any;
230
+ instagram: any;
231
+ social: any;
232
+ insights: any;
233
+ constructor(config: TrndUpClientConfig);
234
+ get<T = unknown>(path: string, params?: Record<string, string | number | boolean | undefined>, options?: RequestOptions): Promise<T>;
235
+ post<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
236
+ put<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
237
+ patch<T = unknown>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
238
+ delete<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
239
+ private request;
240
+ private buildUrl;
241
+ private buildHeaders;
242
+ private handleResponse;
243
+ }
244
+
245
+ /**
246
+ * TrndUp SDK - Auth Module
247
+ *
248
+ * Firebase authentication methods
249
+ */
250
+
251
+ declare class AuthModule {
252
+ private client;
253
+ constructor(client: TrndUpClient);
254
+ /**
255
+ * Login with Firebase ID token
256
+ * POST /auth/login
257
+ */
258
+ login(idToken: string): Promise<Auth.LoginResponse>;
259
+ /**
260
+ * Get current authenticated user's profile
261
+ * GET /auth/me
262
+ */
263
+ getCurrentUser(): Promise<Auth.CurrentUserResponse>;
264
+ /**
265
+ * Update user profile
266
+ * PATCH /auth/me
267
+ */
268
+ updateProfile(data: Auth.UpdateProfileRequest): Promise<Auth.UpdateProfileResponse>;
269
+ /**
270
+ * Logout (acknowledge logout on backend)
271
+ * POST /auth/logout
272
+ */
273
+ logout(): Promise<{
274
+ message: string;
275
+ }>;
276
+ /**
277
+ * Check auth service status
278
+ * GET /auth/status
279
+ */
280
+ getStatus(): Promise<{
281
+ success: boolean;
282
+ message: string;
283
+ }>;
284
+ }
285
+
286
+ /**
287
+ * TrndUp SDK - YouTube Module
288
+ *
289
+ * YouTube analytics and data methods
290
+ */
291
+
292
+ declare class YouTubeModule {
293
+ private client;
294
+ constructor(client: TrndUpClient);
295
+ /**
296
+ * Get YouTube initialization status
297
+ * GET /v1/platforms/youtube/init/status
298
+ */
299
+ getInitStatus(): Promise<YouTube.InitStatusResponse>;
300
+ /**
301
+ * Initialize YouTube data sync
302
+ * POST /v1/platforms/youtube/init
303
+ */
304
+ initialize(): Promise<{
305
+ message: string;
306
+ jobId?: string;
307
+ }>;
308
+ /**
309
+ * Get YouTube videos
310
+ * GET /v1/platforms/youtube/videos
311
+ */
312
+ getVideos(params?: YouTube.GetVideosParams): Promise<YouTube.GetVideosResponse>;
313
+ /**
314
+ * Get specific video by ID
315
+ * GET /v1/platforms/youtube/videos/:videoId
316
+ */
317
+ getVideo(videoId: string): Promise<YouTube.Video>;
318
+ /**
319
+ * Get channel metrics
320
+ * GET /v1/platforms/youtube/channel/metrics
321
+ */
322
+ getChannelMetrics(): Promise<YouTube.ChannelMetrics>;
323
+ /**
324
+ * Get channel health score
325
+ * GET /v1/platforms/youtube/health
326
+ */
327
+ getHealthScore(params?: YouTube.GetHealthScoreParams): Promise<YouTube.HealthScore>;
328
+ /**
329
+ * Refresh YouTube data
330
+ * POST /v1/platforms/youtube/refresh
331
+ */
332
+ refresh(): Promise<{
333
+ message: string;
334
+ jobId?: string;
335
+ }>;
336
+ }
337
+
338
+ /**
339
+ * TrndUp SDK - Instagram Module
340
+ *
341
+ * Instagram analytics and data methods
342
+ */
343
+
344
+ declare class InstagramModule {
345
+ private client;
346
+ constructor(client: TrndUpClient);
347
+ /**
348
+ * Get Instagram initialization status
349
+ * GET /v1/platforms/instagram/init/status
350
+ */
351
+ getInitStatus(): Promise<Instagram.InitStatusResponse>;
352
+ /**
353
+ * Initialize Instagram data sync
354
+ * POST /v1/platforms/instagram/init
355
+ */
356
+ initialize(): Promise<{
357
+ message: string;
358
+ }>;
359
+ /**
360
+ * Get Instagram posts
361
+ * GET /v1/platforms/instagram/posts
362
+ */
363
+ getPosts(params?: Instagram.GetPostsParams): Promise<Instagram.GetPostsResponse>;
364
+ /**
365
+ * Get specific post by ID
366
+ * GET /v1/platforms/instagram/posts/:postId
367
+ */
368
+ getPost(postId: string): Promise<Instagram.Post>;
369
+ /**
370
+ * Get account metrics
371
+ * GET /v1/platforms/instagram/account/metrics
372
+ */
373
+ getAccountMetrics(): Promise<Instagram.AccountMetrics>;
374
+ /**
375
+ * Refresh Instagram data
376
+ * POST /v1/platforms/instagram/refresh
377
+ */
378
+ refresh(): Promise<{
379
+ message: string;
380
+ }>;
381
+ }
382
+
383
+ /**
384
+ * TrndUp SDK - Social Module
385
+ *
386
+ * Social account linking methods
387
+ */
388
+
389
+ declare class SocialModule {
390
+ private client;
391
+ constructor(client: TrndUpClient);
392
+ /**
393
+ * Link YouTube account
394
+ * POST /social/link/youtube
395
+ */
396
+ linkYouTube(data: Social.LinkYouTubeRequest): Promise<Social.LinkAccountResponse>;
397
+ /**
398
+ * Link Instagram account
399
+ * POST /social/link/instagram
400
+ */
401
+ linkInstagram(data: Social.LinkInstagramRequest): Promise<Social.LinkAccountResponse>;
402
+ /**
403
+ * Get all connected social accounts
404
+ * GET /social/accounts
405
+ */
406
+ getConnectedAccounts(): Promise<Social.ConnectedAccount[]>;
407
+ /**
408
+ * Unlink a social account
409
+ * DELETE /social/unlink/:provider
410
+ */
411
+ unlinkAccount(provider: string): Promise<{
412
+ message: string;
413
+ }>;
414
+ }
415
+
416
+ /**
417
+ * TrndUp SDK - Insights Module
418
+ *
419
+ * Cross-platform insights and analytics
420
+ */
421
+
422
+ declare class InsightsModule {
423
+ private client;
424
+ constructor(client: TrndUpClient);
425
+ /**
426
+ * Get cross-platform metrics
427
+ * GET /v1/insights/overview
428
+ */
429
+ getOverview(): Promise<Insights.CrossPlatformMetrics>;
430
+ /**
431
+ * Get trending content across all platforms
432
+ * GET /v1/insights/trending
433
+ */
434
+ getTrending(): Promise<Insights.TrendingContent>;
435
+ }
436
+
437
+ /**
438
+ * TrndUp API SDK
439
+ *
440
+ * Official TypeScript SDK for the TrndUp API.
441
+ * Provides type-safe methods for all API endpoints with Firebase authentication.
442
+ *
443
+ * @example
444
+ * ```typescript
445
+ * import { TrndUpSDK } from '@trndup/sdk';
446
+ * import auth from '@react-native-firebase/auth';
447
+ *
448
+ * const sdk = new TrndUpSDK({
449
+ * baseUrl: 'https://api.trndup.app',
450
+ * getToken: async () => {
451
+ * const user = auth().currentUser;
452
+ * return user ? await user.getIdToken() : null;
453
+ * },
454
+ * onAuthFailure: () => {
455
+ * // Handle auth failure - navigate to login
456
+ * navigation.navigate('Login');
457
+ * },
458
+ * });
459
+ *
460
+ * // Type-safe API calls
461
+ * const user = await sdk.auth.getCurrentUser();
462
+ * const videos = await sdk.youtube.getVideos({ limit: 10 });
463
+ * const healthScore = await sdk.youtube.getHealthScore({ range: '30d' });
464
+ * ```
465
+ */
466
+
467
+ declare class TrndUpSDK extends TrndUpClient {
468
+ auth: AuthModule;
469
+ youtube: YouTubeModule;
470
+ instagram: InstagramModule;
471
+ social: SocialModule;
472
+ insights: InsightsModule;
473
+ constructor(config: TrndUpClientConfig);
474
+ }
475
+
476
+ declare const SDK_VERSION = "1.0.0";
477
+
478
+ export { Auth, Insights, Instagram, type RequestOptions, SDK_VERSION, Social, TrndUpApiError, type TrndUpClientConfig, TrndUpNetworkError, TrndUpSDK, YouTube };