squarefi-bff-api-module 1.32.1 → 1.32.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 (125) hide show
  1. package/dist/api/auth.d.ts +29 -0
  2. package/dist/api/auth.js +59 -0
  3. package/dist/api/bank-data.d.ts +4 -0
  4. package/dist/api/bank-data.js +6 -0
  5. package/dist/api/counterparties.d.ts +14 -0
  6. package/dist/api/counterparties.js +16 -0
  7. package/dist/api/developer.d.ts +12 -0
  8. package/dist/api/developer.js +12 -0
  9. package/dist/api/exchange.d.ts +14 -0
  10. package/dist/api/exchange.js +20 -0
  11. package/dist/api/frontend.d.ts +11 -0
  12. package/dist/api/frontend.js +11 -0
  13. package/dist/api/index.d.ts +38 -0
  14. package/dist/api/index.js +36 -0
  15. package/dist/api/issuing.d.ts +64 -0
  16. package/dist/api/issuing.js +140 -0
  17. package/dist/api/kyc.d.ts +21 -0
  18. package/dist/api/kyc.js +21 -0
  19. package/dist/api/list.d.ts +16 -0
  20. package/dist/api/list.js +16 -0
  21. package/dist/api/orders.d.ts +49 -0
  22. package/dist/api/orders.js +84 -0
  23. package/dist/api/persona.d.ts +7 -0
  24. package/dist/api/persona.js +7 -0
  25. package/dist/api/storage.d.ts +8 -0
  26. package/dist/api/storage.js +16 -0
  27. package/dist/api/tenants.d.ts +6 -0
  28. package/dist/api/tenants.js +6 -0
  29. package/dist/api/totp.d.ts +17 -0
  30. package/dist/api/totp.js +45 -0
  31. package/{src/api/types/autogen/apiV2.types.ts → dist/api/types/autogen/apiV2.types.d.ts} +0 -1
  32. package/dist/api/types/autogen/apiV2.types.js +5 -0
  33. package/dist/api/types/types.d.ts +2258 -0
  34. package/dist/api/types/types.js +1 -0
  35. package/dist/api/user.d.ts +18 -0
  36. package/dist/api/user.js +18 -0
  37. package/dist/api/virtual-accounts.d.ts +9 -0
  38. package/dist/api/virtual-accounts.js +9 -0
  39. package/dist/api/wallets.d.ts +24 -0
  40. package/dist/api/wallets.js +30 -0
  41. package/dist/constants.d.ts +303 -0
  42. package/dist/constants.js +332 -0
  43. package/dist/hooks/index.js +3 -0
  44. package/dist/hooks/useCalc.d.ts +25 -0
  45. package/dist/hooks/useCalc.js +115 -0
  46. package/dist/hooks/useFileUpload.d.ts +49 -0
  47. package/dist/hooks/useFileUpload.js +100 -0
  48. package/dist/hooks/useSupabaseSubscription/config.d.ts +2 -0
  49. package/dist/hooks/useSupabaseSubscription/config.js +5 -0
  50. package/dist/hooks/useSupabaseSubscription/index.js +2 -0
  51. package/dist/hooks/useSupabaseSubscription/specialized.d.ts +5 -0
  52. package/{src/hooks/useSupabaseSubscription/specialized.ts → dist/hooks/useSupabaseSubscription/specialized.js} +2 -5
  53. package/dist/hooks/useSupabaseSubscription/types.d.ts +16 -0
  54. package/dist/hooks/useSupabaseSubscription/types.js +1 -0
  55. package/dist/hooks/useSupabaseSubscription/useSupabaseSubscription.d.ts +5 -0
  56. package/dist/hooks/useSupabaseSubscription/useSupabaseSubscription.js +37 -0
  57. package/dist/index.d.ts +7 -0
  58. package/dist/utils/apiClientFactory.d.ts +31 -0
  59. package/dist/utils/apiClientFactory.js +138 -0
  60. package/dist/utils/converters.d.ts +1 -0
  61. package/dist/utils/converters.js +1 -0
  62. package/dist/utils/encrypt.d.ts +10 -0
  63. package/dist/utils/encrypt.js +77 -0
  64. package/dist/utils/fileStorage.d.ts +120 -0
  65. package/dist/utils/fileStorage.js +292 -0
  66. package/dist/utils/storage.d.ts +3 -0
  67. package/dist/utils/storage.js +24 -0
  68. package/dist/utils/supabase.d.ts +1 -0
  69. package/dist/utils/supabase.js +12 -0
  70. package/dist/utils/tokensFactory.d.ts +12 -0
  71. package/dist/utils/tokensFactory.js +42 -0
  72. package/package.json +4 -1
  73. package/.env.example +0 -1
  74. package/.husky/pre-commit +0 -2
  75. package/.prettierignore +0 -6
  76. package/.prettierrc +0 -7
  77. package/CHANGELOG.md +0 -1415
  78. package/FIXED_RLS_ERROR.md +0 -146
  79. package/QUICK_TEST.md +0 -127
  80. package/STORAGE_MODULE_SUMMARY.md +0 -228
  81. package/TEST_INSTRUCTIONS.md +0 -122
  82. package/docs/AUTH_TOKEN_USAGE.md +0 -290
  83. package/docs/BACKEND_SERVICE_URL.md +0 -334
  84. package/docs/FRONTEND_STORAGE_GUIDE.md +0 -529
  85. package/docs/STORAGE_MODULE.md +0 -490
  86. package/docs/STORAGE_QUICK_START.md +0 -76
  87. package/scripts/generate-openapi-types.ts +0 -41
  88. package/scripts/supabase-storage-setup.sql +0 -223
  89. package/src/api/auth.ts +0 -78
  90. package/src/api/bank-data.ts +0 -11
  91. package/src/api/counterparties.ts +0 -73
  92. package/src/api/developer.ts +0 -20
  93. package/src/api/exchange.ts +0 -44
  94. package/src/api/frontend.ts +0 -20
  95. package/src/api/index.ts +0 -57
  96. package/src/api/issuing.ts +0 -214
  97. package/src/api/kyc.ts +0 -41
  98. package/src/api/list.ts +0 -26
  99. package/src/api/orders.ts +0 -255
  100. package/src/api/persona.ts +0 -16
  101. package/src/api/storage.ts +0 -24
  102. package/src/api/tenants.ts +0 -8
  103. package/src/api/totp.ts +0 -51
  104. package/src/api/types/types.ts +0 -2820
  105. package/src/api/user.ts +0 -27
  106. package/src/api/virtual-accounts.ts +0 -15
  107. package/src/api/wallets.ts +0 -65
  108. package/src/constants.ts +0 -343
  109. package/src/hooks/useCalc.ts +0 -181
  110. package/src/hooks/useFileUpload.ts +0 -129
  111. package/src/hooks/useSupabaseSubscription/config.ts +0 -7
  112. package/src/hooks/useSupabaseSubscription/types.ts +0 -18
  113. package/src/hooks/useSupabaseSubscription/useSupabaseSubscription.ts +0 -53
  114. package/src/utils/apiClientFactory.ts +0 -194
  115. package/src/utils/converters.ts +0 -1
  116. package/src/utils/encrypt.ts +0 -96
  117. package/src/utils/fileStorage.ts +0 -353
  118. package/src/utils/storage.ts +0 -29
  119. package/src/utils/supabase.ts +0 -16
  120. package/src/utils/tokensFactory.ts +0 -59
  121. package/tsconfig.json +0 -15
  122. package/types.d.ts +0 -11
  123. /package/{src/hooks/index.ts → dist/hooks/index.d.ts} +0 -0
  124. /package/{src/hooks/useSupabaseSubscription/index.ts → dist/hooks/useSupabaseSubscription/index.d.ts} +0 -0
  125. /package/{src/index.ts → dist/index.js} +0 -0
@@ -0,0 +1,292 @@
1
+ import { supabaseClient } from './supabase';
2
+ /**
3
+ * Названия бакетов по умолчанию
4
+ */
5
+ export const ORDER_DOCS_BUCKET = 'order_docs';
6
+ /**
7
+ * Загружает файл в Supabase Storage
8
+ * Файл сохраняется по пути: {folder}/{fileName} или {fileName}
9
+ *
10
+ * Папки создаются автоматически при загрузке файла, если их не существует.
11
+ * Можно указывать вложенные папки через слэш: 'images/avatars/2024'
12
+ *
13
+ * @param options - параметры загрузки файла
14
+ * @param options.folder - опциональная папка внутри бакета (например, 'documents', 'images/avatars')
15
+ * @returns результат загрузки с ссылкой на файл
16
+ */
17
+ export const uploadFile = async (options) => {
18
+ const { file, fileName, bucket, folder, contentType, cacheControl = '3600', upsert = false, authToken } = options;
19
+ if (!supabaseClient) {
20
+ return {
21
+ success: false,
22
+ error: 'Supabase client is not initialized',
23
+ };
24
+ }
25
+ try {
26
+ // Если передан authToken, создаем клиент с токеном
27
+ let client = supabaseClient;
28
+ if (authToken) {
29
+ const { createClient } = await import('@supabase/supabase-js');
30
+ client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLIC_KEY, {
31
+ global: {
32
+ headers: {
33
+ Authorization: `Bearer ${authToken}`,
34
+ },
35
+ },
36
+ });
37
+ }
38
+ // Формируем путь к файлу: folder/fileName или fileName
39
+ const filePath = folder ? `${folder}/${fileName}` : fileName;
40
+ const { data, error } = await client.storage.from(bucket).upload(filePath, file, {
41
+ contentType,
42
+ cacheControl,
43
+ upsert,
44
+ });
45
+ if (error) {
46
+ console.error('Error uploading file:', error);
47
+ return {
48
+ success: false,
49
+ error: error.message,
50
+ };
51
+ }
52
+ // Получаем публичный URL
53
+ const { data: urlData } = client.storage.from(bucket).getPublicUrl(data.path);
54
+ // Получаем подписанный URL (действителен 1 час по умолчанию)
55
+ const { data: signedUrlData, error: signedUrlError } = await client.storage
56
+ .from(bucket)
57
+ .createSignedUrl(data.path, 3600);
58
+ return {
59
+ success: true,
60
+ publicUrl: urlData.publicUrl,
61
+ signedUrl: signedUrlError ? undefined : signedUrlData.signedUrl,
62
+ path: data.path,
63
+ };
64
+ }
65
+ catch (error) {
66
+ console.error('Unexpected error uploading file:', error);
67
+ return {
68
+ success: false,
69
+ error: error instanceof Error ? error.message : 'Unknown error',
70
+ };
71
+ }
72
+ };
73
+ /**
74
+ * Получает подписанный URL для доступа к файлу
75
+ *
76
+ * @param options - параметры получения URL
77
+ * @returns подписанный URL или null при ошибке
78
+ */
79
+ export const getSignedUrl = async (options) => {
80
+ const { path, bucket, expiresIn = 3600, authToken } = options;
81
+ if (!supabaseClient) {
82
+ console.error('Supabase client is not initialized');
83
+ return null;
84
+ }
85
+ try {
86
+ // Если передан authToken, создаем клиент с токеном
87
+ let client = supabaseClient;
88
+ if (authToken) {
89
+ const { createClient } = await import('@supabase/supabase-js');
90
+ client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLIC_KEY, {
91
+ global: {
92
+ headers: {
93
+ Authorization: `Bearer ${authToken}`,
94
+ },
95
+ },
96
+ });
97
+ }
98
+ const { data, error } = await client.storage.from(bucket).createSignedUrl(path, expiresIn);
99
+ if (error) {
100
+ console.error('Error creating signed URL:', error);
101
+ return null;
102
+ }
103
+ return data.signedUrl;
104
+ }
105
+ catch (error) {
106
+ console.error('Unexpected error creating signed URL:', error);
107
+ return null;
108
+ }
109
+ };
110
+ /**
111
+ * Получает публичный URL для файла
112
+ *
113
+ * Для ПРИВАТНЫХ бакетов:
114
+ * - URL постоянный (не истекает)
115
+ * - Требует Authorization header с service role key для доступа
116
+ * - Используется на backend для суперадмина
117
+ *
118
+ * Для ПУБЛИЧНЫХ бакетов:
119
+ * - URL доступен всем без аутентификации
120
+ *
121
+ * @example Backend usage for private buckets:
122
+ * ```typescript
123
+ * const url = getPublicUrl(filePath, bucket);
124
+ *
125
+ * // Access with service role key:
126
+ * fetch(url, {
127
+ * headers: {
128
+ * 'Authorization': `Bearer ${SUPABASE_SERVICE_ROLE_KEY}`
129
+ * }
130
+ * })
131
+ * ```
132
+ *
133
+ * @param path - путь к файлу
134
+ * @param bucket - название бакета
135
+ * @returns постоянный URL
136
+ */
137
+ export const getPublicUrl = (path, bucket) => {
138
+ if (!supabaseClient) {
139
+ console.error('Supabase client is not initialized');
140
+ return null;
141
+ }
142
+ const { data } = supabaseClient.storage.from(bucket).getPublicUrl(path);
143
+ return data.publicUrl;
144
+ };
145
+ /**
146
+ * Удаляет файл из хранилища
147
+ *
148
+ * @param path - путь к файлу
149
+ * @param bucket - название бакета
150
+ * @param authToken - JWT token для авторизации
151
+ * @returns true при успешном удалении
152
+ */
153
+ export const deleteFile = async (path, bucket, authToken) => {
154
+ if (!supabaseClient) {
155
+ console.error('Supabase client is not initialized');
156
+ return false;
157
+ }
158
+ try {
159
+ let client = supabaseClient;
160
+ if (authToken) {
161
+ const { createClient } = await import('@supabase/supabase-js');
162
+ client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLIC_KEY, {
163
+ global: {
164
+ headers: {
165
+ Authorization: `Bearer ${authToken}`,
166
+ },
167
+ },
168
+ });
169
+ }
170
+ const { error } = await client.storage.from(bucket).remove([path]);
171
+ if (error) {
172
+ console.error('Error deleting file:', error);
173
+ return false;
174
+ }
175
+ return true;
176
+ }
177
+ catch (error) {
178
+ console.error('Unexpected error deleting file:', error);
179
+ return false;
180
+ }
181
+ };
182
+ /**
183
+ * Удаляет несколько файлов из хранилища
184
+ *
185
+ * @param paths - массив путей к файлам
186
+ * @param bucket - название бакета
187
+ * @param authToken - JWT token для авторизации
188
+ * @returns true при успешном удалении всех файлов
189
+ */
190
+ export const deleteFiles = async (paths, bucket, authToken) => {
191
+ if (!supabaseClient) {
192
+ console.error('Supabase client is not initialized');
193
+ return false;
194
+ }
195
+ try {
196
+ let client = supabaseClient;
197
+ if (authToken) {
198
+ const { createClient } = await import('@supabase/supabase-js');
199
+ client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLIC_KEY, {
200
+ global: {
201
+ headers: {
202
+ Authorization: `Bearer ${authToken}`,
203
+ },
204
+ },
205
+ });
206
+ }
207
+ const { error } = await client.storage.from(bucket).remove(paths);
208
+ if (error) {
209
+ console.error('Error deleting files:', error);
210
+ return false;
211
+ }
212
+ return true;
213
+ }
214
+ catch (error) {
215
+ console.error('Unexpected error deleting files:', error);
216
+ return false;
217
+ }
218
+ };
219
+ /**
220
+ * Получает список файлов пользователя
221
+ *
222
+ * @param userId - ID пользователя
223
+ * @param bucket - название бакета
224
+ * @param authToken - JWT token для авторизации
225
+ * @returns список файлов или пустой массив при ошибке
226
+ */
227
+ export const listUserFiles = async (userId, bucket, authToken) => {
228
+ if (!supabaseClient) {
229
+ console.error('Supabase client is not initialized');
230
+ return [];
231
+ }
232
+ try {
233
+ let client = supabaseClient;
234
+ if (authToken) {
235
+ const { createClient } = await import('@supabase/supabase-js');
236
+ client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLIC_KEY, {
237
+ global: {
238
+ headers: {
239
+ Authorization: `Bearer ${authToken}`,
240
+ },
241
+ },
242
+ });
243
+ }
244
+ const { data, error } = await client.storage.from(bucket).list(userId);
245
+ if (error) {
246
+ console.error('Error listing files:', error);
247
+ return [];
248
+ }
249
+ return data || [];
250
+ }
251
+ catch (error) {
252
+ console.error('Unexpected error listing files:', error);
253
+ return [];
254
+ }
255
+ };
256
+ /**
257
+ * Скачивает файл из хранилища
258
+ *
259
+ * @param path - путь к файлу
260
+ * @param bucket - название бакета
261
+ * @param authToken - JWT token для авторизации
262
+ * @returns Blob файла или null при ошибке
263
+ */
264
+ export const downloadFile = async (path, bucket, authToken) => {
265
+ if (!supabaseClient) {
266
+ console.error('Supabase client is not initialized');
267
+ return null;
268
+ }
269
+ try {
270
+ let client = supabaseClient;
271
+ if (authToken) {
272
+ const { createClient } = await import('@supabase/supabase-js');
273
+ client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLIC_KEY, {
274
+ global: {
275
+ headers: {
276
+ Authorization: `Bearer ${authToken}`,
277
+ },
278
+ },
279
+ });
280
+ }
281
+ const { data, error } = await client.storage.from(bucket).download(path);
282
+ if (error) {
283
+ console.error('Error downloading file:', error);
284
+ return null;
285
+ }
286
+ return data;
287
+ }
288
+ catch (error) {
289
+ console.error('Unexpected error downloading file:', error);
290
+ return null;
291
+ }
292
+ };
@@ -0,0 +1,3 @@
1
+ export declare const getFromLocalStorage: (key: string) => string | null;
2
+ export declare const setToLocalStorage: (key: string, value: string) => void;
3
+ export declare const deleteFromLocalStorage: (key: string) => void;
@@ -0,0 +1,24 @@
1
+ export const getFromLocalStorage = (key) => {
2
+ if (typeof window === 'undefined') {
3
+ // eslint-disable-next-line no-console
4
+ // console.error('call getFromLocalStorage in server side');
5
+ return null;
6
+ }
7
+ return localStorage.getItem(key);
8
+ };
9
+ export const setToLocalStorage = (key, value) => {
10
+ if (typeof window === 'undefined') {
11
+ // eslint-disable-next-line no-console
12
+ console.error('call setToLocalStorage in server side');
13
+ return;
14
+ }
15
+ localStorage.setItem(key, value);
16
+ };
17
+ export const deleteFromLocalStorage = (key) => {
18
+ if (typeof window === 'undefined') {
19
+ // eslint-disable-next-line no-console
20
+ console.error('call deleteFromLocalStorage in server side');
21
+ return;
22
+ }
23
+ localStorage.removeItem(key);
24
+ };
@@ -0,0 +1 @@
1
+ export declare const supabaseClient: import("@supabase/supabase-js").SupabaseClient<any, "public", any> | null;
@@ -0,0 +1,12 @@
1
+ import { createClient } from '@supabase/supabase-js';
2
+ // Создаем клиент только если есть необходимые environment переменные
3
+ const createSupabaseClient = () => {
4
+ const supabaseUrl = process.env.SUPABASE_URL;
5
+ const supabasePublicKey = process.env.SUPABASE_PUBLIC_KEY;
6
+ if (!supabaseUrl || !supabasePublicKey) {
7
+ console.warn('Supabase environment variables are missing. Client will not be created.');
8
+ return null;
9
+ }
10
+ return createClient(supabaseUrl, supabasePublicKey);
11
+ };
12
+ export const supabaseClient = createSupabaseClient();
@@ -0,0 +1,12 @@
1
+ type ITokens = {
2
+ access_token: string;
3
+ refresh_token?: string | null;
4
+ };
5
+ export declare function setTokens({ access_token, refresh_token }: ITokens): void;
6
+ export declare function deleteTokens(): void;
7
+ export declare function refreshTokens(): Promise<ITokens>;
8
+ export declare function getTokens(): {
9
+ access_token: string | null;
10
+ refresh_token: string | null;
11
+ };
12
+ export {};
@@ -0,0 +1,42 @@
1
+ import { initData, isTMA } from '@telegram-apps/sdk-react';
2
+ import { deleteFromLocalStorage, getFromLocalStorage, setToLocalStorage } from './storage';
3
+ import { auth } from '../api/auth';
4
+ export function setTokens({ access_token, refresh_token }) {
5
+ access_token && setToLocalStorage('access_token', access_token);
6
+ refresh_token && setToLocalStorage('refresh_token', refresh_token);
7
+ }
8
+ export function deleteTokens() {
9
+ deleteFromLocalStorage('access_token');
10
+ deleteFromLocalStorage('refresh_token');
11
+ }
12
+ export async function refreshTokens() {
13
+ const refresh_token = getFromLocalStorage('refresh_token');
14
+ if (refresh_token) {
15
+ const refreshResponse = await auth.refresh.refresh_token({ refresh_token });
16
+ setTokens(refreshResponse);
17
+ return refreshResponse;
18
+ }
19
+ if (isTMA()) {
20
+ initData.restore();
21
+ const tg_id = initData.user()?.id;
22
+ const hash = initData.hash();
23
+ const init_data_raw = initData.raw();
24
+ if (!tg_id || !hash || !init_data_raw) {
25
+ return Promise.reject(new Error('No TG ID, hash or init data raw found in tokensFactory'));
26
+ }
27
+ const telegramSignInResponse = await auth.signin.telegram({
28
+ tg_id: tg_id.toString(),
29
+ hash,
30
+ init_data_raw,
31
+ });
32
+ setTokens(telegramSignInResponse);
33
+ return telegramSignInResponse;
34
+ }
35
+ return Promise.reject(new Error('No refresh token found'));
36
+ }
37
+ export function getTokens() {
38
+ return {
39
+ access_token: getFromLocalStorage('access_token'),
40
+ refresh_token: getFromLocalStorage('refresh_token'),
41
+ };
42
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squarefi-bff-api-module",
3
- "version": "1.32.1",
3
+ "version": "1.32.2",
4
4
  "description": "Squarefi BFF API client module",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -11,6 +11,9 @@
11
11
  "import": "./dist/index.js"
12
12
  }
13
13
  },
14
+ "files": [
15
+ "dist"
16
+ ],
14
17
  "repository": {
15
18
  "type": "git",
16
19
  "url": "git+https://github.com/squarefi-tech/bff-api-module-npm.git"
package/.env.example DELETED
@@ -1 +0,0 @@
1
- API_DOCS_URL=https://dev.api.sqfi.rest/docs-yaml
package/.husky/pre-commit DELETED
@@ -1,2 +0,0 @@
1
- npm run update:types
2
- npm run build
package/.prettierignore DELETED
@@ -1,6 +0,0 @@
1
- node_modules/
2
- dist/
3
- *.min.js
4
- *.min.css
5
- package-lock.json
6
-
package/.prettierrc DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "bracketSpacing": true,
3
- "printWidth": 120,
4
- "singleQuote": true,
5
- "tabWidth": 2,
6
- "trailingComma": "all"
7
- }