@b3dotfun/sdk 0.0.47-test.5 → 0.0.48-alpha.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.
Files changed (63) hide show
  1. package/README.md +222 -3
  2. package/dist/cjs/anyspend/react/components/AnySpendCustom.js +5 -3
  3. package/dist/cjs/notifications/index.d.ts +3 -0
  4. package/dist/cjs/notifications/index.js +25 -0
  5. package/dist/cjs/notifications/react/hooks/index.d.ts +1 -0
  6. package/dist/cjs/notifications/react/hooks/index.js +17 -0
  7. package/dist/cjs/notifications/react/hooks/useNotifications.d.ts +42 -0
  8. package/dist/cjs/notifications/react/hooks/useNotifications.js +148 -0
  9. package/dist/cjs/notifications/react/index.d.ts +1 -0
  10. package/dist/cjs/notifications/react/index.js +17 -0
  11. package/dist/cjs/notifications/services/api.d.ts +67 -0
  12. package/dist/cjs/notifications/services/api.js +184 -0
  13. package/dist/cjs/notifications/services/index.d.ts +1 -0
  14. package/dist/cjs/notifications/services/index.js +17 -0
  15. package/dist/cjs/notifications/types/index.d.ts +51 -0
  16. package/dist/cjs/notifications/types/index.js +2 -0
  17. package/dist/cjs/shared/utils/auth-token.d.ts +7 -0
  18. package/dist/cjs/shared/utils/auth-token.js +17 -0
  19. package/dist/cjs/shared/utils/index.d.ts +1 -0
  20. package/dist/cjs/shared/utils/index.js +1 -0
  21. package/dist/esm/anyspend/react/components/AnySpendCustom.js +5 -3
  22. package/dist/esm/notifications/index.d.ts +3 -0
  23. package/dist/esm/notifications/index.js +7 -0
  24. package/dist/esm/notifications/react/hooks/index.d.ts +1 -0
  25. package/dist/esm/notifications/react/hooks/index.js +1 -0
  26. package/dist/esm/notifications/react/hooks/useNotifications.d.ts +42 -0
  27. package/dist/esm/notifications/react/hooks/useNotifications.js +145 -0
  28. package/dist/esm/notifications/react/index.d.ts +1 -0
  29. package/dist/esm/notifications/react/index.js +1 -0
  30. package/dist/esm/notifications/services/api.d.ts +67 -0
  31. package/dist/esm/notifications/services/api.js +179 -0
  32. package/dist/esm/notifications/services/index.d.ts +1 -0
  33. package/dist/esm/notifications/services/index.js +1 -0
  34. package/dist/esm/notifications/types/index.d.ts +51 -0
  35. package/dist/esm/shared/utils/auth-token.d.ts +7 -0
  36. package/dist/esm/shared/utils/auth-token.js +11 -0
  37. package/dist/esm/shared/utils/index.d.ts +1 -0
  38. package/dist/esm/shared/utils/index.js +1 -0
  39. package/dist/types/notifications/index.d.ts +3 -0
  40. package/dist/types/notifications/react/hooks/index.d.ts +1 -0
  41. package/dist/types/notifications/react/hooks/useNotifications.d.ts +42 -0
  42. package/dist/types/notifications/react/index.d.ts +1 -0
  43. package/dist/types/notifications/services/api.d.ts +67 -0
  44. package/dist/types/notifications/services/index.d.ts +1 -0
  45. package/dist/types/notifications/types/index.d.ts +51 -0
  46. package/dist/types/shared/utils/auth-token.d.ts +7 -0
  47. package/dist/types/shared/utils/index.d.ts +1 -0
  48. package/package.json +21 -1
  49. package/src/anyspend/react/components/AnySpendCustom.tsx +5 -3
  50. package/src/notifications/index.ts +9 -0
  51. package/src/notifications/react/hooks/index.ts +1 -0
  52. package/src/notifications/react/hooks/useNotifications.ts +153 -0
  53. package/src/notifications/react/index.ts +1 -0
  54. package/src/notifications/services/api.ts +217 -0
  55. package/src/notifications/services/index.ts +1 -0
  56. package/src/notifications/types/index.ts +58 -0
  57. package/src/shared/utils/auth-token.ts +13 -0
  58. package/src/shared/utils/index.ts +1 -0
  59. package/dist/cjs/shared/react/hooks/__tests__/useCurrencyConversion.test.js +0 -245
  60. package/dist/esm/shared/react/hooks/__tests__/useCurrencyConversion.test.d.ts +0 -1
  61. package/dist/esm/shared/react/hooks/__tests__/useCurrencyConversion.test.js +0 -243
  62. package/dist/types/shared/react/hooks/__tests__/useCurrencyConversion.test.d.ts +0 -1
  63. /package/dist/{cjs/shared/react/hooks/__tests__/useCurrencyConversion.test.d.ts → esm/notifications/types/index.js} +0 -0
@@ -0,0 +1,153 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { notificationsAPI } from "../../services/api";
3
+ import type { UserData } from "../../types";
4
+
5
+ /**
6
+ * React hook for managing B3 notifications
7
+ * Automatically uses the authenticated user's ID from JWT
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * import { useNotifications } from '@b3dotfun/sdk/notifications/react';
12
+ *
13
+ * function NotificationSettings() {
14
+ * const { user, loading, connectEmail, connectTelegram, isEmailConnected } = useNotifications();
15
+ *
16
+ * if (loading) return <div>Loading...</div>;
17
+ *
18
+ * return (
19
+ * <div>
20
+ * {!isEmailConnected && (
21
+ * <button onClick={() => connectEmail('user@example.com')}>
22
+ * Connect Email
23
+ * </button>
24
+ * )}
25
+ * <button onClick={connectTelegram}>Connect Telegram</button>
26
+ * </div>
27
+ * );
28
+ * }
29
+ * ```
30
+ */
31
+ export function useNotifications() {
32
+ const [user, setUser] = useState<UserData | null>(null);
33
+ const [loading, setLoading] = useState(true);
34
+ const [error, setError] = useState<Error | null>(null);
35
+
36
+ // Refs to track polling timers for cleanup
37
+ const telegramPollIntervalRef = useRef<NodeJS.Timeout | null>(null);
38
+ const telegramPollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
39
+
40
+ // Cleanup function for Telegram polling
41
+ const cleanupTelegramPolling = () => {
42
+ if (telegramPollIntervalRef.current) {
43
+ clearInterval(telegramPollIntervalRef.current);
44
+ telegramPollIntervalRef.current = null;
45
+ }
46
+ if (telegramPollTimeoutRef.current) {
47
+ clearTimeout(telegramPollTimeoutRef.current);
48
+ telegramPollTimeoutRef.current = null;
49
+ }
50
+ };
51
+
52
+ // Load user data on mount
53
+ useEffect(() => {
54
+ loadUser();
55
+ }, []);
56
+
57
+ // Cleanup polling on unmount
58
+ useEffect(() => {
59
+ return () => {
60
+ cleanupTelegramPolling();
61
+ };
62
+ }, []);
63
+
64
+ const loadUser = async () => {
65
+ try {
66
+ setLoading(true);
67
+ setError(null);
68
+ const userData = await notificationsAPI.getUser();
69
+ setUser(userData);
70
+ } catch (err) {
71
+ setError(err instanceof Error ? err : new Error("Failed to load user"));
72
+ console.error("Failed to load user:", err);
73
+ } finally {
74
+ setLoading(false);
75
+ }
76
+ };
77
+
78
+ const connectEmail = async (email: string) => {
79
+ try {
80
+ await notificationsAPI.connectEmail(email);
81
+ await loadUser(); // Refresh user data
82
+ } catch (err) {
83
+ console.error("Failed to connect email:", err);
84
+ throw err;
85
+ }
86
+ };
87
+
88
+ const connectTelegram = async () => {
89
+ try {
90
+ // Clear any existing polling before starting new one
91
+ cleanupTelegramPolling();
92
+
93
+ const { deepLink } = await notificationsAPI.getTelegramLink();
94
+ window.open(deepLink, "_blank");
95
+
96
+ // Poll for connection status
97
+ telegramPollIntervalRef.current = setInterval(async () => {
98
+ try {
99
+ const { connected } = await notificationsAPI.checkTelegramStatus();
100
+ if (connected) {
101
+ cleanupTelegramPolling();
102
+ await loadUser(); // Refresh user data
103
+ }
104
+ } catch (err) {
105
+ console.error("Failed to check Telegram status:", err);
106
+ }
107
+ }, 2000);
108
+
109
+ // Stop polling after 2 minutes
110
+ telegramPollTimeoutRef.current = setTimeout(() => {
111
+ cleanupTelegramPolling();
112
+ }, 120000);
113
+ } catch (err) {
114
+ console.error("Failed to connect Telegram:", err);
115
+ throw err;
116
+ }
117
+ };
118
+
119
+ const updateChannel = async (channelId: string, updates: { enabled?: boolean }) => {
120
+ try {
121
+ await notificationsAPI.updateChannel(channelId, updates);
122
+ await loadUser(); // Refresh user data
123
+ } catch (err) {
124
+ console.error("Failed to update channel:", err);
125
+ throw err;
126
+ }
127
+ };
128
+
129
+ const deleteChannel = async (channelId: string) => {
130
+ try {
131
+ await notificationsAPI.deleteChannel(channelId);
132
+ await loadUser(); // Refresh user data
133
+ } catch (err) {
134
+ console.error("Failed to delete channel:", err);
135
+ throw err;
136
+ }
137
+ };
138
+
139
+ return {
140
+ user,
141
+ loading,
142
+ error,
143
+ refresh: loadUser,
144
+ connectEmail,
145
+ connectTelegram,
146
+ updateChannel,
147
+ deleteChannel,
148
+ // Convenience helpers
149
+ isEmailConnected: user?.channels?.find(c => c.channel_type === "email")?.enabled === 1,
150
+ isTelegramConnected: user?.channels?.find(c => c.channel_type === "telegram")?.enabled === 1,
151
+ isDiscordConnected: user?.channels?.find(c => c.channel_type === "discord")?.enabled === 1,
152
+ };
153
+ }
@@ -0,0 +1 @@
1
+ export * from "./hooks";
@@ -0,0 +1,217 @@
1
+ import { getAuthToken } from "@b3dotfun/sdk/shared/utils/auth-token";
2
+ import type {
3
+ NotificationHistory,
4
+ NotificationPreferences,
5
+ SendNotificationRequest,
6
+ TelegramLinkResponse,
7
+ TelegramStatusResponse,
8
+ UserData,
9
+ } from "../types";
10
+
11
+ const DEFAULT_API_URL = "https://notifications.b3.fun";
12
+
13
+ let apiUrl: string = DEFAULT_API_URL;
14
+
15
+ export function setApiUrl(url: string) {
16
+ apiUrl = url;
17
+ }
18
+
19
+ export function getApiUrl(): string {
20
+ return apiUrl;
21
+ }
22
+
23
+ function getHeaders(includeAuth = false): HeadersInit {
24
+ const headers: HeadersInit = {
25
+ "Content-Type": "application/json",
26
+ };
27
+
28
+ if (includeAuth) {
29
+ const token = getAuthToken();
30
+ if (token) {
31
+ headers["Authorization"] = `Bearer ${token}`;
32
+ }
33
+ }
34
+
35
+ return headers;
36
+ }
37
+
38
+ export const notificationsAPI = {
39
+ // ===== USER MANAGEMENT =====
40
+
41
+ /**
42
+ * Register the current user (userId extracted from JWT)
43
+ */
44
+ async registerUser() {
45
+ const res = await fetch(`${apiUrl}/users`, {
46
+ method: "POST",
47
+ headers: getHeaders(true),
48
+ });
49
+ if (!res.ok) {
50
+ const errorBody = await res.text().catch(() => "Could not read error body");
51
+ throw new Error(`API Error: ${res.status} ${res.statusText} - ${errorBody}`);
52
+ }
53
+ return res.json();
54
+ },
55
+
56
+ /**
57
+ * Get current user's profile and preferences
58
+ */
59
+ async getUser(): Promise<UserData> {
60
+ const res = await fetch(`${apiUrl}/users/me`, {
61
+ headers: getHeaders(true),
62
+ });
63
+ return res.json();
64
+ },
65
+
66
+ /**
67
+ * Get current user's notification history
68
+ */
69
+ async getHistory(appId?: string, limit = 100): Promise<NotificationHistory[]> {
70
+ const params = new URLSearchParams();
71
+ if (appId) params.append("appId", appId);
72
+ params.append("limit", limit.toString());
73
+
74
+ const res = await fetch(`${apiUrl}/users/me/history?${params}`, {
75
+ headers: getHeaders(true),
76
+ });
77
+ return res.json();
78
+ },
79
+
80
+ // ===== CHANNELS =====
81
+
82
+ /**
83
+ * Add a notification channel for current user
84
+ */
85
+ async addChannel(channelType: string, channelIdentifier: string, metadata?: Record<string, any>) {
86
+ const res = await fetch(`${apiUrl}/users/me/channels`, {
87
+ method: "POST",
88
+ headers: getHeaders(true),
89
+ body: JSON.stringify({
90
+ channelType,
91
+ channelIdentifier,
92
+ enabled: true,
93
+ metadata,
94
+ }),
95
+ });
96
+ return res.json();
97
+ },
98
+
99
+ /**
100
+ * Connect email for current user
101
+ */
102
+ async connectEmail(email: string) {
103
+ return this.addChannel("email", email);
104
+ },
105
+
106
+ /**
107
+ * Update a notification channel
108
+ */
109
+ async updateChannel(
110
+ channelId: string,
111
+ updates: { enabled?: boolean; channelIdentifier?: string; metadata?: Record<string, any> },
112
+ ) {
113
+ const res = await fetch(`${apiUrl}/users/me/channels/${channelId}`, {
114
+ method: "PUT",
115
+ headers: getHeaders(true),
116
+ body: JSON.stringify(updates),
117
+ });
118
+ return res.json();
119
+ },
120
+
121
+ /**
122
+ * Delete a notification channel
123
+ */
124
+ async deleteChannel(channelId: string) {
125
+ const res = await fetch(`${apiUrl}/users/me/channels/${channelId}`, {
126
+ method: "DELETE",
127
+ headers: getHeaders(true),
128
+ });
129
+ return res.json();
130
+ },
131
+
132
+ // ===== TELEGRAM =====
133
+
134
+ /**
135
+ * Get Telegram deep link for current user
136
+ */
137
+ async getTelegramLink(): Promise<TelegramLinkResponse> {
138
+ const res = await fetch(`${apiUrl}/telegram/request-link`, {
139
+ method: "POST",
140
+ headers: getHeaders(true),
141
+ });
142
+ return res.json();
143
+ },
144
+
145
+ /**
146
+ * Check current user's Telegram connection status
147
+ */
148
+ async checkTelegramStatus(): Promise<TelegramStatusResponse> {
149
+ const res = await fetch(`${apiUrl}/telegram/status/me`, {
150
+ headers: getHeaders(true),
151
+ });
152
+ return res.json();
153
+ },
154
+
155
+ // ===== APP PREFERENCES =====
156
+
157
+ /**
158
+ * Save notification preferences for an app
159
+ * @param appId - The application ID
160
+ * @param settings - Notification preferences including channels, type, and enabled status (defaults to true)
161
+ */
162
+ async savePreferences(appId: string, settings: NotificationPreferences) {
163
+ const res = await fetch(`${apiUrl}/users/me/apps/${appId}/settings`, {
164
+ method: "POST",
165
+ headers: getHeaders(true),
166
+ body: JSON.stringify({ enabled: true, ...settings }),
167
+ });
168
+ return res.json();
169
+ },
170
+
171
+ /**
172
+ * Get notification settings for an app
173
+ */
174
+ async getAppSettings(appId: string) {
175
+ const res = await fetch(`${apiUrl}/users/me/apps/${appId}/settings`, {
176
+ headers: getHeaders(true),
177
+ });
178
+ return res.json();
179
+ },
180
+
181
+ // ===== IN-APP NOTIFICATIONS =====
182
+
183
+ /**
184
+ * Get current user's in-app notifications
185
+ */
186
+ async getInAppNotifications() {
187
+ const res = await fetch(`${apiUrl}/users/me/notifications`, {
188
+ headers: getHeaders(true),
189
+ });
190
+ return res.json();
191
+ },
192
+
193
+ /**
194
+ * Mark a notification as read
195
+ */
196
+ async markNotificationAsRead(notificationId: string) {
197
+ const res = await fetch(`${apiUrl}/users/me/notifications/${notificationId}/read`, {
198
+ method: "PUT",
199
+ headers: getHeaders(true),
200
+ });
201
+ return res.json();
202
+ },
203
+
204
+ // ===== SENDING NOTIFICATIONS =====
205
+
206
+ /**
207
+ * Send a notification (requires auth)
208
+ */
209
+ async sendNotification(data: SendNotificationRequest) {
210
+ const res = await fetch(`${apiUrl}/send`, {
211
+ method: "POST",
212
+ headers: getHeaders(true),
213
+ body: JSON.stringify(data),
214
+ });
215
+ return res.json();
216
+ },
217
+ };
@@ -0,0 +1 @@
1
+ export * from "./api";
@@ -0,0 +1,58 @@
1
+ export type ChannelType = "email" | "telegram" | "discord" | "sms" | "whatsapp" | "in_app";
2
+
3
+ export interface NotificationChannel {
4
+ id: number;
5
+ channel_type: ChannelType;
6
+ enabled: number;
7
+ channel_identifier: string;
8
+ }
9
+
10
+ export interface UserData {
11
+ user: {
12
+ id: number;
13
+ user_id: string;
14
+ };
15
+ channels: NotificationChannel[];
16
+ appSettings: Array<{
17
+ app_id: string;
18
+ notification_type: string;
19
+ enabled: number;
20
+ channels: string;
21
+ }>;
22
+ }
23
+
24
+ export interface NotificationHistory {
25
+ id: string;
26
+ app_id: string;
27
+ notification_type: string;
28
+ title: string;
29
+ message: string;
30
+ created_at: string;
31
+ read: boolean;
32
+ }
33
+
34
+ export interface TelegramLinkResponse {
35
+ deepLink: string;
36
+ verificationCode: string;
37
+ botUsername: string;
38
+ }
39
+
40
+ export interface TelegramStatusResponse {
41
+ connected: boolean;
42
+ chatId?: string;
43
+ }
44
+
45
+ export interface NotificationPreferences {
46
+ notificationType: string;
47
+ channels: string[];
48
+ enabled?: boolean;
49
+ }
50
+
51
+ export interface SendNotificationRequest {
52
+ userId: string;
53
+ appId: string;
54
+ notificationType: string;
55
+ message: string;
56
+ title?: string;
57
+ data?: Record<string, any>;
58
+ }
@@ -0,0 +1,13 @@
1
+ import Cookies from "js-cookie";
2
+
3
+ const B3_AUTH_COOKIE_NAME = "b3-auth";
4
+
5
+ /**
6
+ * Get the authentication token from the B3 auth cookie
7
+ * This token is managed by the B3 Global Account authentication system
8
+ *
9
+ * @returns The JWT token string or null if not found
10
+ */
11
+ export function getAuthToken(): string | null {
12
+ return Cookies.get(B3_AUTH_COOKIE_NAME) || null;
13
+ }
@@ -1,4 +1,5 @@
1
1
  // Export utility functions
2
+ export * from "./auth-token";
2
3
  export * from "./cn";
3
4
  export * from "./formatNumber";
4
5
  export * from "./formatUsername";