@oxyhq/core 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.
Files changed (277) hide show
  1. package/README.md +50 -0
  2. package/dist/cjs/AuthManager.js +361 -0
  3. package/dist/cjs/CrossDomainAuth.js +258 -0
  4. package/dist/cjs/HttpService.js +618 -0
  5. package/dist/cjs/OxyServices.base.js +263 -0
  6. package/dist/cjs/OxyServices.errors.js +22 -0
  7. package/dist/cjs/OxyServices.js +63 -0
  8. package/dist/cjs/constants/version.js +16 -0
  9. package/dist/cjs/crypto/index.js +20 -0
  10. package/dist/cjs/crypto/keyManager.js +887 -0
  11. package/dist/cjs/crypto/polyfill.js +64 -0
  12. package/dist/cjs/crypto/recoveryPhrase.js +169 -0
  13. package/dist/cjs/crypto/signatureService.js +296 -0
  14. package/dist/cjs/i18n/index.js +73 -0
  15. package/dist/cjs/i18n/locales/ar-SA.json +120 -0
  16. package/dist/cjs/i18n/locales/ca-ES.json +120 -0
  17. package/dist/cjs/i18n/locales/de-DE.json +120 -0
  18. package/dist/cjs/i18n/locales/en-US.json +956 -0
  19. package/dist/cjs/i18n/locales/es-ES.json +944 -0
  20. package/dist/cjs/i18n/locales/fr-FR.json +120 -0
  21. package/dist/cjs/i18n/locales/it-IT.json +120 -0
  22. package/dist/cjs/i18n/locales/ja-JP.json +119 -0
  23. package/dist/cjs/i18n/locales/ko-KR.json +120 -0
  24. package/dist/cjs/i18n/locales/locales/ar-SA.json +120 -0
  25. package/dist/cjs/i18n/locales/locales/ca-ES.json +120 -0
  26. package/dist/cjs/i18n/locales/locales/de-DE.json +120 -0
  27. package/dist/cjs/i18n/locales/locales/en-US.json +956 -0
  28. package/dist/cjs/i18n/locales/locales/es-ES.json +944 -0
  29. package/dist/cjs/i18n/locales/locales/fr-FR.json +120 -0
  30. package/dist/cjs/i18n/locales/locales/it-IT.json +120 -0
  31. package/dist/cjs/i18n/locales/locales/ja-JP.json +119 -0
  32. package/dist/cjs/i18n/locales/locales/ko-KR.json +120 -0
  33. package/dist/cjs/i18n/locales/locales/pt-PT.json +120 -0
  34. package/dist/cjs/i18n/locales/locales/zh-CN.json +120 -0
  35. package/dist/cjs/i18n/locales/pt-PT.json +120 -0
  36. package/dist/cjs/i18n/locales/zh-CN.json +120 -0
  37. package/dist/cjs/index.js +153 -0
  38. package/dist/cjs/mixins/OxyServices.analytics.js +49 -0
  39. package/dist/cjs/mixins/OxyServices.assets.js +380 -0
  40. package/dist/cjs/mixins/OxyServices.auth.js +259 -0
  41. package/dist/cjs/mixins/OxyServices.developer.js +97 -0
  42. package/dist/cjs/mixins/OxyServices.devices.js +116 -0
  43. package/dist/cjs/mixins/OxyServices.features.js +309 -0
  44. package/dist/cjs/mixins/OxyServices.fedcm.js +435 -0
  45. package/dist/cjs/mixins/OxyServices.karma.js +108 -0
  46. package/dist/cjs/mixins/OxyServices.language.js +154 -0
  47. package/dist/cjs/mixins/OxyServices.location.js +43 -0
  48. package/dist/cjs/mixins/OxyServices.payment.js +158 -0
  49. package/dist/cjs/mixins/OxyServices.popup.js +371 -0
  50. package/dist/cjs/mixins/OxyServices.privacy.js +162 -0
  51. package/dist/cjs/mixins/OxyServices.redirect.js +345 -0
  52. package/dist/cjs/mixins/OxyServices.security.js +81 -0
  53. package/dist/cjs/mixins/OxyServices.user.js +355 -0
  54. package/dist/cjs/mixins/OxyServices.utility.js +156 -0
  55. package/dist/cjs/mixins/index.js +79 -0
  56. package/dist/cjs/mixins/mixinHelpers.js +53 -0
  57. package/dist/cjs/models/interfaces.js +20 -0
  58. package/dist/cjs/models/session.js +2 -0
  59. package/dist/cjs/shared/index.js +70 -0
  60. package/dist/cjs/shared/utils/colorUtils.js +153 -0
  61. package/dist/cjs/shared/utils/debugUtils.js +73 -0
  62. package/dist/cjs/shared/utils/errorUtils.js +183 -0
  63. package/dist/cjs/shared/utils/index.js +49 -0
  64. package/dist/cjs/shared/utils/networkUtils.js +183 -0
  65. package/dist/cjs/shared/utils/themeUtils.js +106 -0
  66. package/dist/cjs/utils/apiUtils.js +61 -0
  67. package/dist/cjs/utils/asyncUtils.js +194 -0
  68. package/dist/cjs/utils/cache.js +226 -0
  69. package/dist/cjs/utils/deviceManager.js +205 -0
  70. package/dist/cjs/utils/errorUtils.js +154 -0
  71. package/dist/cjs/utils/index.js +26 -0
  72. package/dist/cjs/utils/languageUtils.js +165 -0
  73. package/dist/cjs/utils/loggerUtils.js +126 -0
  74. package/dist/cjs/utils/platform.js +144 -0
  75. package/dist/cjs/utils/requestUtils.js +209 -0
  76. package/dist/cjs/utils/sessionUtils.js +181 -0
  77. package/dist/cjs/utils/validationUtils.js +173 -0
  78. package/dist/esm/AuthManager.js +356 -0
  79. package/dist/esm/CrossDomainAuth.js +253 -0
  80. package/dist/esm/HttpService.js +614 -0
  81. package/dist/esm/OxyServices.base.js +259 -0
  82. package/dist/esm/OxyServices.errors.js +17 -0
  83. package/dist/esm/OxyServices.js +59 -0
  84. package/dist/esm/constants/version.js +13 -0
  85. package/dist/esm/crypto/index.js +13 -0
  86. package/dist/esm/crypto/keyManager.js +850 -0
  87. package/dist/esm/crypto/polyfill.js +61 -0
  88. package/dist/esm/crypto/recoveryPhrase.js +132 -0
  89. package/dist/esm/crypto/signatureService.js +259 -0
  90. package/dist/esm/i18n/index.js +69 -0
  91. package/dist/esm/i18n/locales/ar-SA.json +120 -0
  92. package/dist/esm/i18n/locales/ca-ES.json +120 -0
  93. package/dist/esm/i18n/locales/de-DE.json +120 -0
  94. package/dist/esm/i18n/locales/en-US.json +956 -0
  95. package/dist/esm/i18n/locales/es-ES.json +944 -0
  96. package/dist/esm/i18n/locales/fr-FR.json +120 -0
  97. package/dist/esm/i18n/locales/it-IT.json +120 -0
  98. package/dist/esm/i18n/locales/ja-JP.json +119 -0
  99. package/dist/esm/i18n/locales/ko-KR.json +120 -0
  100. package/dist/esm/i18n/locales/locales/ar-SA.json +120 -0
  101. package/dist/esm/i18n/locales/locales/ca-ES.json +120 -0
  102. package/dist/esm/i18n/locales/locales/de-DE.json +120 -0
  103. package/dist/esm/i18n/locales/locales/en-US.json +956 -0
  104. package/dist/esm/i18n/locales/locales/es-ES.json +944 -0
  105. package/dist/esm/i18n/locales/locales/fr-FR.json +120 -0
  106. package/dist/esm/i18n/locales/locales/it-IT.json +120 -0
  107. package/dist/esm/i18n/locales/locales/ja-JP.json +119 -0
  108. package/dist/esm/i18n/locales/locales/ko-KR.json +120 -0
  109. package/dist/esm/i18n/locales/locales/pt-PT.json +120 -0
  110. package/dist/esm/i18n/locales/locales/zh-CN.json +120 -0
  111. package/dist/esm/i18n/locales/pt-PT.json +120 -0
  112. package/dist/esm/i18n/locales/zh-CN.json +120 -0
  113. package/dist/esm/index.js +55 -0
  114. package/dist/esm/mixins/OxyServices.analytics.js +46 -0
  115. package/dist/esm/mixins/OxyServices.assets.js +377 -0
  116. package/dist/esm/mixins/OxyServices.auth.js +256 -0
  117. package/dist/esm/mixins/OxyServices.developer.js +94 -0
  118. package/dist/esm/mixins/OxyServices.devices.js +113 -0
  119. package/dist/esm/mixins/OxyServices.features.js +306 -0
  120. package/dist/esm/mixins/OxyServices.fedcm.js +433 -0
  121. package/dist/esm/mixins/OxyServices.karma.js +105 -0
  122. package/dist/esm/mixins/OxyServices.language.js +118 -0
  123. package/dist/esm/mixins/OxyServices.location.js +40 -0
  124. package/dist/esm/mixins/OxyServices.payment.js +155 -0
  125. package/dist/esm/mixins/OxyServices.popup.js +369 -0
  126. package/dist/esm/mixins/OxyServices.privacy.js +159 -0
  127. package/dist/esm/mixins/OxyServices.redirect.js +343 -0
  128. package/dist/esm/mixins/OxyServices.security.js +78 -0
  129. package/dist/esm/mixins/OxyServices.user.js +352 -0
  130. package/dist/esm/mixins/OxyServices.utility.js +153 -0
  131. package/dist/esm/mixins/index.js +76 -0
  132. package/dist/esm/mixins/mixinHelpers.js +48 -0
  133. package/dist/esm/models/interfaces.js +17 -0
  134. package/dist/esm/models/session.js +1 -0
  135. package/dist/esm/shared/index.js +31 -0
  136. package/dist/esm/shared/utils/colorUtils.js +143 -0
  137. package/dist/esm/shared/utils/debugUtils.js +65 -0
  138. package/dist/esm/shared/utils/errorUtils.js +170 -0
  139. package/dist/esm/shared/utils/index.js +15 -0
  140. package/dist/esm/shared/utils/networkUtils.js +173 -0
  141. package/dist/esm/shared/utils/themeUtils.js +98 -0
  142. package/dist/esm/utils/apiUtils.js +55 -0
  143. package/dist/esm/utils/asyncUtils.js +179 -0
  144. package/dist/esm/utils/cache.js +218 -0
  145. package/dist/esm/utils/deviceManager.js +168 -0
  146. package/dist/esm/utils/errorUtils.js +146 -0
  147. package/dist/esm/utils/index.js +7 -0
  148. package/dist/esm/utils/languageUtils.js +158 -0
  149. package/dist/esm/utils/loggerUtils.js +115 -0
  150. package/dist/esm/utils/platform.js +102 -0
  151. package/dist/esm/utils/requestUtils.js +203 -0
  152. package/dist/esm/utils/sessionUtils.js +171 -0
  153. package/dist/esm/utils/validationUtils.js +153 -0
  154. package/dist/types/AuthManager.d.ts +143 -0
  155. package/dist/types/CrossDomainAuth.d.ts +160 -0
  156. package/dist/types/HttpService.d.ts +163 -0
  157. package/dist/types/OxyServices.base.d.ts +126 -0
  158. package/dist/types/OxyServices.d.ts +81 -0
  159. package/dist/types/OxyServices.errors.d.ts +11 -0
  160. package/dist/types/constants/version.d.ts +13 -0
  161. package/dist/types/crypto/index.d.ts +11 -0
  162. package/dist/types/crypto/keyManager.d.ts +189 -0
  163. package/dist/types/crypto/polyfill.d.ts +11 -0
  164. package/dist/types/crypto/recoveryPhrase.d.ts +58 -0
  165. package/dist/types/crypto/signatureService.d.ts +86 -0
  166. package/dist/types/i18n/index.d.ts +3 -0
  167. package/dist/types/index.d.ts +50 -0
  168. package/dist/types/mixins/OxyServices.analytics.d.ts +66 -0
  169. package/dist/types/mixins/OxyServices.assets.d.ts +135 -0
  170. package/dist/types/mixins/OxyServices.auth.d.ts +186 -0
  171. package/dist/types/mixins/OxyServices.developer.d.ts +99 -0
  172. package/dist/types/mixins/OxyServices.devices.d.ts +96 -0
  173. package/dist/types/mixins/OxyServices.features.d.ts +228 -0
  174. package/dist/types/mixins/OxyServices.fedcm.d.ts +200 -0
  175. package/dist/types/mixins/OxyServices.karma.d.ts +85 -0
  176. package/dist/types/mixins/OxyServices.language.d.ts +81 -0
  177. package/dist/types/mixins/OxyServices.location.d.ts +64 -0
  178. package/dist/types/mixins/OxyServices.payment.d.ts +111 -0
  179. package/dist/types/mixins/OxyServices.popup.d.ts +205 -0
  180. package/dist/types/mixins/OxyServices.privacy.d.ts +122 -0
  181. package/dist/types/mixins/OxyServices.redirect.d.ts +245 -0
  182. package/dist/types/mixins/OxyServices.security.d.ts +78 -0
  183. package/dist/types/mixins/OxyServices.user.d.ts +182 -0
  184. package/dist/types/mixins/OxyServices.utility.d.ts +93 -0
  185. package/dist/types/mixins/index.d.ts +30 -0
  186. package/dist/types/mixins/mixinHelpers.d.ts +31 -0
  187. package/dist/types/models/interfaces.d.ts +415 -0
  188. package/dist/types/models/session.d.ts +27 -0
  189. package/dist/types/shared/index.d.ts +28 -0
  190. package/dist/types/shared/utils/colorUtils.d.ts +104 -0
  191. package/dist/types/shared/utils/debugUtils.d.ts +48 -0
  192. package/dist/types/shared/utils/errorUtils.d.ts +97 -0
  193. package/dist/types/shared/utils/index.d.ts +13 -0
  194. package/dist/types/shared/utils/networkUtils.d.ts +139 -0
  195. package/dist/types/shared/utils/themeUtils.d.ts +90 -0
  196. package/dist/types/utils/apiUtils.d.ts +53 -0
  197. package/dist/types/utils/asyncUtils.d.ts +58 -0
  198. package/dist/types/utils/cache.d.ts +127 -0
  199. package/dist/types/utils/deviceManager.d.ts +65 -0
  200. package/dist/types/utils/errorUtils.d.ts +46 -0
  201. package/dist/types/utils/index.d.ts +6 -0
  202. package/dist/types/utils/languageUtils.d.ts +37 -0
  203. package/dist/types/utils/loggerUtils.d.ts +48 -0
  204. package/dist/types/utils/platform.d.ts +40 -0
  205. package/dist/types/utils/requestUtils.d.ts +123 -0
  206. package/dist/types/utils/sessionUtils.d.ts +54 -0
  207. package/dist/types/utils/validationUtils.d.ts +85 -0
  208. package/package.json +84 -0
  209. package/src/AuthManager.ts +436 -0
  210. package/src/CrossDomainAuth.ts +307 -0
  211. package/src/HttpService.ts +752 -0
  212. package/src/OxyServices.base.ts +334 -0
  213. package/src/OxyServices.errors.ts +26 -0
  214. package/src/OxyServices.ts +129 -0
  215. package/src/constants/version.ts +15 -0
  216. package/src/crypto/index.ts +25 -0
  217. package/src/crypto/keyManager.ts +962 -0
  218. package/src/crypto/polyfill.ts +70 -0
  219. package/src/crypto/recoveryPhrase.ts +166 -0
  220. package/src/crypto/signatureService.ts +323 -0
  221. package/src/i18n/index.ts +75 -0
  222. package/src/i18n/locales/ar-SA.json +120 -0
  223. package/src/i18n/locales/ca-ES.json +120 -0
  224. package/src/i18n/locales/de-DE.json +120 -0
  225. package/src/i18n/locales/en-US.json +956 -0
  226. package/src/i18n/locales/es-ES.json +944 -0
  227. package/src/i18n/locales/fr-FR.json +120 -0
  228. package/src/i18n/locales/it-IT.json +120 -0
  229. package/src/i18n/locales/ja-JP.json +119 -0
  230. package/src/i18n/locales/ko-KR.json +120 -0
  231. package/src/i18n/locales/pt-PT.json +120 -0
  232. package/src/i18n/locales/zh-CN.json +120 -0
  233. package/src/index.ts +153 -0
  234. package/src/mixins/OxyServices.analytics.ts +53 -0
  235. package/src/mixins/OxyServices.assets.ts +412 -0
  236. package/src/mixins/OxyServices.auth.ts +358 -0
  237. package/src/mixins/OxyServices.developer.ts +114 -0
  238. package/src/mixins/OxyServices.devices.ts +119 -0
  239. package/src/mixins/OxyServices.features.ts +428 -0
  240. package/src/mixins/OxyServices.fedcm.ts +494 -0
  241. package/src/mixins/OxyServices.karma.ts +111 -0
  242. package/src/mixins/OxyServices.language.ts +127 -0
  243. package/src/mixins/OxyServices.location.ts +46 -0
  244. package/src/mixins/OxyServices.payment.ts +163 -0
  245. package/src/mixins/OxyServices.popup.ts +443 -0
  246. package/src/mixins/OxyServices.privacy.ts +182 -0
  247. package/src/mixins/OxyServices.redirect.ts +397 -0
  248. package/src/mixins/OxyServices.security.ts +103 -0
  249. package/src/mixins/OxyServices.user.ts +392 -0
  250. package/src/mixins/OxyServices.utility.ts +191 -0
  251. package/src/mixins/index.ts +91 -0
  252. package/src/mixins/mixinHelpers.ts +69 -0
  253. package/src/models/interfaces.ts +511 -0
  254. package/src/models/session.ts +30 -0
  255. package/src/shared/index.ts +82 -0
  256. package/src/shared/utils/colorUtils.ts +155 -0
  257. package/src/shared/utils/debugUtils.ts +73 -0
  258. package/src/shared/utils/errorUtils.ts +181 -0
  259. package/src/shared/utils/index.ts +59 -0
  260. package/src/shared/utils/networkUtils.ts +248 -0
  261. package/src/shared/utils/themeUtils.ts +115 -0
  262. package/src/types/bip39.d.ts +32 -0
  263. package/src/types/buffer.d.ts +97 -0
  264. package/src/types/color.d.ts +20 -0
  265. package/src/types/elliptic.d.ts +62 -0
  266. package/src/utils/apiUtils.ts +88 -0
  267. package/src/utils/asyncUtils.ts +252 -0
  268. package/src/utils/cache.ts +264 -0
  269. package/src/utils/deviceManager.ts +198 -0
  270. package/src/utils/errorUtils.ts +216 -0
  271. package/src/utils/index.ts +21 -0
  272. package/src/utils/languageUtils.ts +174 -0
  273. package/src/utils/loggerUtils.ts +153 -0
  274. package/src/utils/platform.ts +117 -0
  275. package/src/utils/requestUtils.ts +237 -0
  276. package/src/utils/sessionUtils.ts +206 -0
  277. package/src/utils/validationUtils.ts +174 -0
@@ -0,0 +1,334 @@
1
+ /**
2
+ * OxyServices Base Class
3
+ *
4
+ * Contains core infrastructure, HTTP client, request management, and error handling
5
+ */
6
+ import { jwtDecode } from 'jwt-decode';
7
+ import type { OxyConfig as OxyConfigBase, ApiError, User } from './models/interfaces';
8
+ import { handleHttpError } from './utils/errorUtils';
9
+ import { HttpService, type RequestOptions } from './HttpService';
10
+ import { OxyAuthenticationError, OxyAuthenticationTimeoutError } from './OxyServices.errors';
11
+
12
+ export interface OxyConfig extends OxyConfigBase {
13
+ cloudURL?: string;
14
+ }
15
+
16
+ interface JwtPayload {
17
+ exp?: number;
18
+ userId?: string;
19
+ id?: string;
20
+ sessionId?: string;
21
+ [key: string]: any;
22
+ }
23
+
24
+ /**
25
+ * Base class for OxyServices with core infrastructure
26
+ */
27
+ export class OxyServicesBase {
28
+ public httpService: HttpService;
29
+ public cloudURL: string;
30
+ public config: OxyConfig;
31
+
32
+ constructor(...args: any[]) {
33
+ const config = args[0] as OxyConfig;
34
+ if (!config || typeof config !== 'object') {
35
+ throw new Error('OxyConfig is required');
36
+ }
37
+ this.config = config;
38
+ this.cloudURL = config.cloudURL || 'https://cloud.oxy.so';
39
+
40
+ // Initialize unified HTTP service (handles auth, caching, deduplication, queuing, retry)
41
+ this.httpService = new HttpService(config);
42
+ }
43
+
44
+ // Test-only utility to reset global tokens between jest tests
45
+ static __resetTokensForTests(): void {
46
+ HttpService.__resetTokensForTests();
47
+ }
48
+
49
+ /**
50
+ * Make a request with all performance optimizations
51
+ * This is the main method for all API calls - ensures authentication and performance features
52
+ */
53
+ public async makeRequest<T>(
54
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
55
+ url: string,
56
+ data?: any,
57
+ options: RequestOptions = {}
58
+ ): Promise<T> {
59
+ return this.httpService.request<T>({
60
+ method,
61
+ url,
62
+ data: method !== 'GET' ? data : undefined,
63
+ params: method === 'GET' ? data : undefined,
64
+ ...options,
65
+ });
66
+ }
67
+
68
+ // ============================================================================
69
+ // CORE METHODS (HTTP Client, Token Management, Error Handling)
70
+ // ============================================================================
71
+
72
+ /**
73
+ * Get the configured Oxy API base URL
74
+ */
75
+ public getBaseURL(): string {
76
+ return this.httpService.getBaseURL();
77
+ }
78
+
79
+ /**
80
+ * Get the HTTP service instance
81
+ * Useful for advanced use cases where direct access to the HTTP service is needed
82
+ */
83
+ public getClient(): HttpService {
84
+ return this.httpService;
85
+ }
86
+
87
+ /**
88
+ * Get performance metrics
89
+ */
90
+ public getMetrics() {
91
+ return this.httpService.getMetrics();
92
+ }
93
+
94
+ /**
95
+ * Clear request cache
96
+ */
97
+ public clearCache(): void {
98
+ this.httpService.clearCache();
99
+ }
100
+
101
+ /**
102
+ * Clear specific cache entry
103
+ */
104
+ public clearCacheEntry(key: string): void {
105
+ this.httpService.clearCacheEntry(key);
106
+ }
107
+
108
+ /**
109
+ * Get cache statistics
110
+ */
111
+ public getCacheStats() {
112
+ return this.httpService.getCacheStats();
113
+ }
114
+
115
+ /**
116
+ * Get the configured Oxy Cloud (file storage/CDN) URL
117
+ */
118
+ public getCloudURL(): string {
119
+ return this.cloudURL;
120
+ }
121
+
122
+ /**
123
+ * Set authentication tokens
124
+ */
125
+ public setTokens(accessToken: string, refreshToken = ''): void {
126
+ this.httpService.setTokens(accessToken, refreshToken);
127
+ }
128
+
129
+ /**
130
+ * Clear stored authentication tokens
131
+ */
132
+ public clearTokens(): void {
133
+ this.httpService.clearTokens();
134
+ }
135
+
136
+ /**
137
+ * Get the current user ID from the access token
138
+ */
139
+ public getCurrentUserId(): string | null {
140
+ const accessToken = this.httpService.getAccessToken();
141
+ if (!accessToken) {
142
+ return null;
143
+ }
144
+
145
+ try {
146
+ const decoded = jwtDecode<JwtPayload>(accessToken);
147
+ return decoded.userId || decoded.id || null;
148
+ } catch (error) {
149
+ return null;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Check if the client has a valid access token (public method)
155
+ */
156
+ public hasValidToken(): boolean {
157
+ return this.httpService.hasAccessToken();
158
+ }
159
+
160
+ /**
161
+ * Get the raw access token (for constructing anchor URLs when needed)
162
+ */
163
+ public getAccessToken(): string | null {
164
+ return this.httpService.getAccessToken();
165
+ }
166
+
167
+ /**
168
+ * Wait for authentication to be ready
169
+ *
170
+ * Optimized for high-scale usage with immediate synchronous check and adaptive polling.
171
+ * Returns immediately if token is already available (0ms delay), otherwise uses
172
+ * adaptive polling that starts fast (50ms) and gradually increases to reduce CPU usage.
173
+ *
174
+ * @param timeoutMs Maximum time to wait in milliseconds (default: 5000ms)
175
+ * @returns Promise that resolves to true if authentication is ready, false if timeout
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * const isReady = await oxyServices.waitForAuth(3000);
180
+ * if (isReady) {
181
+ * // Proceed with authenticated operations
182
+ * }
183
+ * ```
184
+ */
185
+ public async waitForAuth(timeoutMs = 5000): Promise<boolean> {
186
+ // Immediate synchronous check - no delay if token is ready
187
+ if (this.httpService.hasAccessToken()) {
188
+ return true;
189
+ }
190
+
191
+ const startTime = performance.now();
192
+ const maxTime = startTime + timeoutMs;
193
+
194
+ // Adaptive polling: start fast, then slow down to reduce CPU usage
195
+ let pollInterval = 50; // Start with 50ms
196
+
197
+ while (performance.now() < maxTime) {
198
+ await new Promise(resolve => setTimeout(resolve, pollInterval));
199
+
200
+ if (this.httpService.hasAccessToken()) {
201
+ return true;
202
+ }
203
+
204
+ // Increase interval after first few checks (adaptive polling)
205
+ // This reduces CPU usage for long waits while maintaining responsiveness
206
+ if (pollInterval < 200) {
207
+ pollInterval = Math.min(pollInterval * 1.5, 200);
208
+ }
209
+ }
210
+
211
+ return false;
212
+ }
213
+
214
+ /**
215
+ * Execute a function with automatic authentication retry logic
216
+ * This handles the common case where API calls are made before authentication completes
217
+ */
218
+ public async withAuthRetry<T>(
219
+ operation: () => Promise<T>,
220
+ operationName: string,
221
+ options: {
222
+ maxRetries?: number;
223
+ retryDelay?: number;
224
+ authTimeoutMs?: number;
225
+ } = {}
226
+ ): Promise<T> {
227
+ const {
228
+ maxRetries = 2,
229
+ retryDelay = 1000,
230
+ authTimeoutMs = 5000
231
+ } = options;
232
+
233
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
234
+ try {
235
+ // First attempt: check if we have a token
236
+ if (!this.httpService.hasAccessToken()) {
237
+ if (attempt === 0) {
238
+ // On first attempt, wait briefly for authentication to complete
239
+ const authReady = await this.waitForAuth(authTimeoutMs);
240
+
241
+ if (!authReady) {
242
+ throw new OxyAuthenticationTimeoutError(operationName, authTimeoutMs);
243
+ }
244
+ } else {
245
+ // On retry attempts, fail immediately if no token
246
+ throw new OxyAuthenticationError(
247
+ `Authentication required: ${operationName} requires a valid access token.`,
248
+ 'AUTH_REQUIRED'
249
+ );
250
+ }
251
+ }
252
+
253
+ // Execute the operation
254
+ return await operation();
255
+
256
+ } catch (error: unknown) {
257
+ const isLastAttempt = attempt === maxRetries;
258
+ const errorObj = error && typeof error === 'object' ? error as { response?: { status?: number }; code?: string; message?: string } : null;
259
+ const isAuthError = errorObj?.response?.status === 401 ||
260
+ errorObj?.code === 'MISSING_TOKEN' ||
261
+ errorObj?.message?.includes('Authentication') ||
262
+ error instanceof OxyAuthenticationError;
263
+
264
+ if (isAuthError && !isLastAttempt && !(error instanceof OxyAuthenticationTimeoutError)) {
265
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
266
+ continue;
267
+ }
268
+
269
+ // If it's not an auth error, or it's the last attempt, throw the error
270
+ if (error instanceof OxyAuthenticationError) {
271
+ throw error;
272
+ }
273
+ throw this.handleError(error);
274
+ }
275
+ }
276
+
277
+ // This should never be reached, but TypeScript requires it
278
+ throw new OxyAuthenticationError(`${operationName} failed after ${maxRetries + 1} attempts`);
279
+ }
280
+
281
+ /**
282
+ * Validate the current access token with the server
283
+ */
284
+ async validate(): Promise<boolean> {
285
+ if (!this.hasValidToken()) {
286
+ return false;
287
+ }
288
+
289
+ try {
290
+ const res = await this.makeRequest<{ valid: boolean }>('GET', '/api/auth/validate', undefined, {
291
+ cache: false,
292
+ retry: false,
293
+ });
294
+ return res.valid === true;
295
+ } catch (error) {
296
+ return false;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Centralized error handling
302
+ */
303
+ public handleError(error: unknown): Error {
304
+ const api = handleHttpError(error);
305
+ // Ensure we always have a non-empty message
306
+ const message = api.message?.trim() || 'An unexpected error occurred';
307
+ const err = new Error(message) as Error & { code?: string; status?: number; details?: Record<string, unknown> };
308
+ err.code = api.code;
309
+ err.status = api.status;
310
+ err.details = api.details;
311
+ return err;
312
+ }
313
+
314
+ /**
315
+ * Health check endpoint
316
+ */
317
+ async healthCheck(): Promise<{
318
+ status: string;
319
+ users?: number;
320
+ timestamp?: string;
321
+ [key: string]: any
322
+ }> {
323
+ try {
324
+ return await this.makeRequest('GET', '/health', undefined, {
325
+ cache: false,
326
+ retry: false,
327
+ timeout: 5000
328
+ });
329
+ } catch (error) {
330
+ throw this.handleError(error);
331
+ }
332
+ }
333
+ }
334
+
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Custom error types for better error handling
3
+ */
4
+ export class OxyAuthenticationError extends Error {
5
+ public readonly code: string;
6
+ public readonly status: number;
7
+
8
+ constructor(message: string, code = 'AUTH_ERROR', status = 401) {
9
+ super(message);
10
+ this.name = 'OxyAuthenticationError';
11
+ this.code = code;
12
+ this.status = status;
13
+ }
14
+ }
15
+
16
+ export class OxyAuthenticationTimeoutError extends OxyAuthenticationError {
17
+ constructor(operationName: string, timeoutMs: number) {
18
+ super(
19
+ `Authentication timeout (${timeoutMs}ms): ${operationName} requires user authentication. Please ensure the user is logged in before calling this method.`,
20
+ 'AUTH_TIMEOUT',
21
+ 408
22
+ );
23
+ this.name = 'OxyAuthenticationTimeoutError';
24
+ }
25
+ }
26
+
@@ -0,0 +1,129 @@
1
+ /**
2
+ * OxyServices - Unified client for Oxy API and Oxy Cloud
3
+ *
4
+ * # Usage Examples
5
+ *
6
+ * ## Browser (ESM/TypeScript)
7
+ *
8
+ * ```typescript
9
+ * import { OxyServices } from './core/OxyServices';
10
+ *
11
+ * const oxy = new OxyServices({
12
+ * baseURL: 'https://api.oxy.so',
13
+ * cloudURL: 'https://cloud.oxy.so',
14
+ * });
15
+ *
16
+ * // Authenticate and fetch user
17
+ * await oxy.setTokens('ACCESS_TOKEN');
18
+ * const user = await oxy.getCurrentUser();
19
+ *
20
+ * // Upload a file (browser File API)
21
+ * const fileInput = document.querySelector('input[type=file]');
22
+ * const file = fileInput.files[0];
23
+ * await oxy.uploadRawFile(file);
24
+ *
25
+ * // Get a file download URL for <img src>
26
+ * const url = oxy.getFileDownloadUrl('fileId', 'thumb');
27
+ * ```
28
+ *
29
+ * ## Node.js (CommonJS/TypeScript)
30
+ *
31
+ * ```typescript
32
+ * import { OxyServices } from './core/OxyServices';
33
+ * import fs from 'fs';
34
+ *
35
+ * const oxy = new OxyServices({
36
+ * baseURL: 'https://api.oxy.so',
37
+ * cloudURL: 'https://cloud.oxy.so',
38
+ * });
39
+ *
40
+ * // Authenticate and fetch user
41
+ * await oxy.setTokens('ACCESS_TOKEN');
42
+ * const user = await oxy.getCurrentUser();
43
+ *
44
+ * // Upload a file (Node.js Buffer)
45
+ * const buffer = fs.readFileSync('myfile.png');
46
+ * const blob = new Blob([buffer]);
47
+ * await oxy.uploadRawFile(blob, { filename: 'myfile.png' });
48
+ *
49
+ * // Get a file download URL
50
+ * const url = oxy.getFileDownloadUrl('fileId');
51
+ * ```
52
+ *
53
+ * ## Configuration
54
+ * - `baseURL`: Oxy API endpoint (e.g., https://api.oxy.so)
55
+ * - `cloudURL`: Oxy Cloud/CDN endpoint (e.g., https://cloud.oxy.so)
56
+ *
57
+ * See method JSDoc for more details and options.
58
+ */
59
+ import { OxyServicesBase, type OxyConfig } from './OxyServices.base';
60
+ import { OxyAuthenticationError, OxyAuthenticationTimeoutError } from './OxyServices.errors';
61
+
62
+ // Import mixin composition helper
63
+ import { composeOxyServices } from './mixins';
64
+
65
+ /**
66
+ * OxyServices - Unified client library for interacting with the Oxy API
67
+ *
68
+ * This class provides all API functionality in one simple, easy-to-use interface.
69
+ *
70
+ * ## Architecture
71
+ * - **HttpService**: Unified HTTP service handling authentication, caching, deduplication, queuing, and retry
72
+ * - **OxyServices**: Provides high-level API methods
73
+ *
74
+ * ## Mixin Composition
75
+ * The class is composed using TypeScript mixins for better code organization:
76
+ * - **Base**: Core infrastructure (HTTP client, request management, error handling)
77
+ * - **Auth**: Authentication and session management
78
+ * - **User**: User profiles, follow, notifications
79
+ * - **Privacy**: Blocked and restricted users
80
+ * - **Language**: Language detection and metadata
81
+ * - **Payment**: Payment processing
82
+ * - **Karma**: Karma system
83
+ * - **Assets**: File upload and asset management
84
+ * - **Developer**: Developer API management
85
+ * - **Location**: Location-based features
86
+ * - **Analytics**: Analytics tracking
87
+ * - **Devices**: Device management
88
+ * - **Utility**: Utility methods and Express middleware
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const oxy = new OxyServices({
93
+ * baseURL: 'https://api.oxy.so',
94
+ * cloudURL: 'https://cloud.oxy.so'
95
+ * });
96
+ * ```
97
+ */
98
+ // Compose all mixins into the final OxyServices class
99
+ const OxyServicesComposed = composeOxyServices();
100
+
101
+ // Export as a named class to avoid TypeScript issues with anonymous class types
102
+ export class OxyServices extends (OxyServicesComposed as any) {
103
+ constructor(config: OxyConfig) {
104
+ super(config);
105
+ }
106
+ }
107
+
108
+ // Type augmentation to expose mixin methods to TypeScript
109
+ // This allows proper type checking while avoiding complex mixin type inference
110
+ export interface OxyServices extends InstanceType<ReturnType<typeof composeOxyServices>> {}
111
+
112
+ // Re-export error classes for convenience
113
+ export { OxyAuthenticationError, OxyAuthenticationTimeoutError };
114
+
115
+ /**
116
+ * Export the default Oxy Cloud URL (for backward compatibility)
117
+ */
118
+ export const OXY_CLOUD_URL = 'https://cloud.oxy.so';
119
+
120
+ /**
121
+ * Export the default Oxy API URL (for documentation)
122
+ */
123
+ export const OXY_API_URL = (typeof process !== 'undefined' && process.env && process.env.OXY_API_URL) || 'https://api.oxy.so';
124
+
125
+ /**
126
+ * Pre-configured client instance for easy import
127
+ * Uses OXY_API_URL as baseURL and OXY_CLOUD_URL as cloudURL
128
+ */
129
+ export const oxyClient = new OxyServices({ baseURL: OXY_API_URL, cloudURL: OXY_CLOUD_URL });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Package version and metadata constants
3
+ * This file is auto-generated to avoid runtime dependency on package.json
4
+ */
5
+
6
+ export const packageInfo = {
7
+ name: "@oxyhq/services",
8
+ version: "5.2.1",
9
+ description: "Reusable OxyHQ module to handle authentication, user management, karma system and more 🚀",
10
+ main: "lib/commonjs/node/index.js",
11
+ module: "lib/module/node/index.js",
12
+ types: "lib/typescript/node/index.d.ts"
13
+ } as const;
14
+
15
+ export const { name, version, description } = packageInfo;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Oxy Crypto Module
3
+ *
4
+ * Provides cryptographic identity management for the Oxy ecosystem.
5
+ * Handles key generation, secure storage, digital signatures, and recovery phrases.
6
+ */
7
+
8
+ // Import polyfills first - this ensures Buffer is available for bip39 and other libraries
9
+ import './polyfill';
10
+
11
+ export { KeyManager, type KeyPair } from './keyManager';
12
+ export {
13
+ SignatureService,
14
+ type SignedMessage,
15
+ type AuthChallenge
16
+ } from './signatureService';
17
+ export {
18
+ RecoveryPhraseService,
19
+ type RecoveryPhraseResult
20
+ } from './recoveryPhrase';
21
+
22
+ // Re-export for convenience
23
+ export { KeyManager as default } from './keyManager';
24
+
25
+