@onairosofficial/onairos-capacitor 0.1.0 → 0.1.1

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 (181) hide show
  1. package/LICENSE +194 -10
  2. package/README.md +182 -25
  3. package/dist/onairos.capacitor.esm.js +1 -0
  4. package/dist/onairos.capacitor.esm.turbopack.js +1 -0
  5. package/onairos.d.ts +656 -0
  6. package/package.json +186 -38
  7. package/src/OnairosReconnectButton.jsx +272 -0
  8. package/src/RSA.jsx +57 -0
  9. package/src/assets/NewLogo.png +0 -0
  10. package/src/assets/OnairosNewLogo.png +0 -0
  11. package/src/assets/chatgpt-icon.png +0 -0
  12. package/src/assets/fire-horse.png +0 -0
  13. package/src/assets/fire-horse.transparent.png +0 -0
  14. package/src/assets/latest-firehorse.png +0 -0
  15. package/src/assets/perplexity.png +0 -0
  16. package/src/assets/persona.png +0 -0
  17. package/src/assets/persona1.png +0 -0
  18. package/src/assets/persona2.png +0 -0
  19. package/src/assets/persona3.png +0 -0
  20. package/src/assets/persona4.png +0 -0
  21. package/src/assets/persona5.png +0 -0
  22. package/src/capacitorConnectorCatalog.js +38 -0
  23. package/src/capacitorOAuthConfig.js +52 -0
  24. package/src/chatgptHostedImport/index.js +303 -0
  25. package/src/components/AuthButtons.jsx +48 -0
  26. package/src/components/ConnectChatGPTModal.jsx +666 -0
  27. package/src/components/ConnectClaudeModal.jsx +610 -0
  28. package/src/components/ConnectGeminiModal.jsx +639 -0
  29. package/src/components/ConnectGrokModal.jsx +701 -0
  30. package/src/components/ConnectPerplexityModal.jsx +726 -0
  31. package/src/components/DataExplainerScreen.jsx +349 -0
  32. package/src/components/DataRequest.js +885 -0
  33. package/src/components/DataRequest.jsx +1055 -0
  34. package/src/components/EmailAuth.js +1871 -0
  35. package/src/components/EmailAuth.jsx +2062 -0
  36. package/src/components/ExtensionInstallPrompt.jsx +142 -0
  37. package/src/components/GoogleButton.js +133 -0
  38. package/src/components/LLMConnectorManager.jsx +201 -0
  39. package/src/components/LoadingPage.jsx +19 -0
  40. package/src/components/LoadingScreen.jsx +81 -0
  41. package/src/components/LunarBirthdate.jsx +96 -0
  42. package/src/components/LunarLoadingPage.jsx +251 -0
  43. package/src/components/Notification.jsx +21 -0
  44. package/src/components/OnairosAppButton.jsx +85 -0
  45. package/src/components/OnairosSSO.jsx +645 -0
  46. package/src/components/OnairosTrigger.jsx +61 -0
  47. package/src/components/PerplexityLogo.jsx +43 -0
  48. package/src/components/PinSetup.js +200 -0
  49. package/src/components/PinSetup.jsx +228 -0
  50. package/src/components/SDK_PIN_INTEGRATION_REQUIRED_CHANGES.md +526 -0
  51. package/src/components/SdkErrorBoundary.jsx +36 -0
  52. package/src/components/SecuritySetup.js +81 -0
  53. package/src/components/SessionUserBar.jsx +83 -0
  54. package/src/components/SignUp.js +123 -0
  55. package/src/components/TestTelegramButton.js +53 -0
  56. package/src/components/TrainingComponent.jsx +200 -0
  57. package/src/components/TrainingScreen.jsx +897 -0
  58. package/src/components/UniversalOnboarding.js +306 -0
  59. package/src/components/UniversalOnboarding.jsx +4837 -0
  60. package/src/components/ValentineLoadingPage.jsx +502 -0
  61. package/src/components/ValentineModeSelector.jsx +162 -0
  62. package/src/components/WelcomeScreen.jsx +435 -0
  63. package/src/components/WrappedLoadingPage.jsx +205 -0
  64. package/src/components/connectors/ChatGPTConnector.js +348 -0
  65. package/src/components/connectors/ChatGPTConnector.jsx +348 -0
  66. package/src/components/connectors/ClaudeConnector.js +44 -0
  67. package/src/components/connectors/ClaudeConnector.jsx +44 -0
  68. package/src/components/connectors/GeminiConnector.js +170 -0
  69. package/src/components/connectors/GeminiConnector.jsx +170 -0
  70. package/src/components/connectors/GmailConnector.js +148 -0
  71. package/src/components/connectors/GmailConnector.jsx +148 -0
  72. package/src/components/connectors/GrokConnector.js +16 -0
  73. package/src/components/connectors/GrokConnector.jsx +16 -0
  74. package/src/components/connectors/HingeConnector.js +419 -0
  75. package/src/components/connectors/HingeConnector.jsx +419 -0
  76. package/src/components/connectors/InstagramDataConnector.js +726 -0
  77. package/src/components/connectors/InstagramDataConnector.jsx +726 -0
  78. package/src/components/connectors/LinkedInConnector.js +4 -0
  79. package/src/components/connectors/LinkedInConnector.jsx +296 -0
  80. package/src/components/connectors/PerplexityConnector.jsx +16 -0
  81. package/src/components/connectors/PinterestConnector.js +208 -0
  82. package/src/components/connectors/PinterestConnector.jsx +208 -0
  83. package/src/components/connectors/README.md +292 -0
  84. package/src/components/connectors/RedditConnector.js +229 -0
  85. package/src/components/connectors/RedditConnector.jsx +229 -0
  86. package/src/components/connectors/SephoraConnector.js +482 -0
  87. package/src/components/connectors/SephoraConnector.jsx +482 -0
  88. package/src/components/connectors/TikTokConnector.jsx +430 -0
  89. package/src/components/connectors/YoutubeConnector.js +361 -0
  90. package/src/components/connectors/YoutubeConnector.jsx +361 -0
  91. package/src/components/connectors/index.js +50 -0
  92. package/src/components/icons.jsx +46 -0
  93. package/src/components/icons.tsx +21 -0
  94. package/src/components/ui/PageLayout.jsx +1255 -0
  95. package/src/components/ui/PrimaryButton.jsx +162 -0
  96. package/src/components/ui/button.jsx +49 -0
  97. package/src/components/ui/card.jsx +61 -0
  98. package/src/components/ui/checkbox.jsx +33 -0
  99. package/src/components/ui/label.jsx +29 -0
  100. package/src/components/utils/UpdateConnections.js +45 -0
  101. package/src/components/utils/oauthHelper.js +97 -0
  102. package/src/config/api-config.js +138 -0
  103. package/src/deepLink.jsx +38 -0
  104. package/src/getPin.js +26 -0
  105. package/src/icons/Avatar.png +0 -0
  106. package/src/icons/Sentiment.png +0 -0
  107. package/src/icons/Trait.png +0 -0
  108. package/src/iframe/DataRequestPage.jsx +285 -0
  109. package/src/iframe/OnairosButtonIntegration.md +148 -0
  110. package/src/iframe/components/Box.jsx +56 -0
  111. package/src/iframe/components/IndividualConnection.jsx +88 -0
  112. package/src/iframe/dataRequestHandler.js +714 -0
  113. package/src/iframe/data_request_iframe.html +27 -0
  114. package/src/iframe/data_request_page.js +47 -0
  115. package/src/iframe/icons/Avatar.png +1 -0
  116. package/src/iframe/icons/Avatar2.png +1 -0
  117. package/src/iframe/icons/Sentiment.png +1 -0
  118. package/src/iframe/icons/Trait.png +1 -0
  119. package/src/iframe/icons/onairos_logo.png +0 -0
  120. package/src/iframe/utils/api.js +57 -0
  121. package/src/index.js +274 -0
  122. package/src/laravel/OnairosVue.vue +410 -0
  123. package/src/laravel/blade-helpers.js +320 -0
  124. package/src/laravel/vite-plugin.js +179 -0
  125. package/src/mobile/MobileDataRequestPage.jsx +233 -0
  126. package/src/mobile/components/MobileBox.jsx +71 -0
  127. package/src/mobile/components/MobileIndividualConnection.jsx +51 -0
  128. package/src/mobile/shims/browser-apis.js +78 -0
  129. package/src/mobile/shims/lucide-shim.js +85 -0
  130. package/src/newUI/EMAIL_VERIFICATION_API_SCHEMA.md +268 -0
  131. package/src/newUI/PlatformConnectorsStep.tsx +435 -0
  132. package/src/newUI/PrimaryButton.tsx +213 -0
  133. package/src/newUI/SignInStep.tsx +194 -0
  134. package/src/newUI/VerificationStep.tsx +133 -0
  135. package/src/newUI/WelcomeScreen.tsx +311 -0
  136. package/src/newUI/services/connectedAccountsService.js +129 -0
  137. package/src/onairos.capacitor.jsx +16 -0
  138. package/src/onairos.core.jsx +133 -0
  139. package/src/onairos.jsx +14 -0
  140. package/src/onairos.native.jsx +15 -0
  141. package/src/onairosButton.jsx +9000 -0
  142. package/src/overlay/CheckBox.jsx +114 -0
  143. package/src/overlay/IndividualConnection copy.js +86 -0
  144. package/src/overlay/IndividualConnection.js +191 -0
  145. package/src/overlay/IndividualConnectionNew.jsx +157 -0
  146. package/src/overlay/box.js +84 -0
  147. package/src/overlay/overlay.js +437 -0
  148. package/src/styles/onairos-scoped-preflight.css +97 -0
  149. package/src/styles/sdkCssRegistry.js +20 -0
  150. package/src/styles/styleLoaderInsertShadow.js +69 -0
  151. package/src/styles/tailwind.capacitor.css +395 -0
  152. package/src/styles/tailwind.css +395 -0
  153. package/src/theme/colors.js +40 -0
  154. package/src/utils/apiKeyValidation.js +341 -0
  155. package/src/utils/apiResponseLogger.js +316 -0
  156. package/src/utils/authHeaders.js +275 -0
  157. package/src/utils/biometrics.js +26 -0
  158. package/src/utils/bookmarkletUtils.js +28 -0
  159. package/src/utils/capacitorDetection.js +278 -0
  160. package/src/utils/capacitorLLMHelper.js +352 -0
  161. package/src/utils/capacitorPlugins.js +366 -0
  162. package/src/utils/crossDomainSSO.js +587 -0
  163. package/src/utils/deepLinking.js +27 -0
  164. package/src/utils/devLogger.js +46 -0
  165. package/src/utils/extensionDetection.js +418 -0
  166. package/src/utils/extractMemory.js +277 -0
  167. package/src/utils/framerBrandingOverrides.js +40 -0
  168. package/src/utils/googleWebClientId.js +55 -0
  169. package/src/utils/overlayHandler.js +224 -0
  170. package/src/utils/platformDisconnect.js +309 -0
  171. package/src/utils/pollTrainingStatus.js +200 -0
  172. package/src/utils/rawMemoriesAccess.js +211 -0
  173. package/src/utils/resolveBackendAppId.js +47 -0
  174. package/src/utils/responseFormatter.js +140 -0
  175. package/src/utils/sdkDebugStorage.js +113 -0
  176. package/src/utils/sdkInitialization.js +645 -0
  177. package/src/utils/sessionManager.js +1258 -0
  178. package/src/utils/startBackgroundTraining.js +100 -0
  179. package/src/utils/userDataFormatter.js +222 -0
  180. package/index.d.ts +0 -1
  181. package/index.js +0 -1
@@ -0,0 +1,645 @@
1
+ /**
2
+ * Onairos SDK Initialization
3
+ * Implements standardized SDK initialization following SDK_API_KEY_VALIDATION.md
4
+ */
5
+
6
+ import { validateApiKey, detectEnvironment, getErrorInfo } from './apiKeyValidation.js';
7
+
8
+ // Global SDK state
9
+ let globalSDKState = {
10
+ isInitialized: false,
11
+ apiKey: null,
12
+ userToken: null,
13
+ onTokenExpired: null,
14
+ config: null,
15
+ validationResult: null,
16
+ googleClientIds: null,
17
+ importBridgeUrl: null
18
+ };
19
+
20
+ const getTelemetryBaseUrl = () => {
21
+ try {
22
+ const override = typeof window !== 'undefined' && typeof window.onairosBaseUrl === 'string'
23
+ ? window.onairosBaseUrl.trim().replace(/\/$/, '')
24
+ : '';
25
+ if (override) return override;
26
+ } catch (_) {}
27
+ return 'https://api2.onairos.uk';
28
+ };
29
+
30
+ const reportSdkError = (payload) => {
31
+ try {
32
+ const body = JSON.stringify({
33
+ platform: globalSDKState.config?.platform || payload.platform || 'web',
34
+ sdkVersion: globalSDKState.config?.sdkVersion || payload.sdkVersion || '3.4.0',
35
+ occurredAt: new Date().toISOString(),
36
+ ...payload,
37
+ });
38
+ const url = `${getTelemetryBaseUrl()}/sdk/track/error`;
39
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
40
+ navigator.sendBeacon(url, new Blob([body], { type: 'application/json' }));
41
+ return;
42
+ }
43
+ if (typeof fetch === 'function') {
44
+ fetch(url, {
45
+ method: 'POST',
46
+ headers: { 'Content-Type': 'application/json' },
47
+ body,
48
+ keepalive: true,
49
+ }).catch(() => {});
50
+ }
51
+ } catch (_) {
52
+ // Telemetry must never affect SDK callers.
53
+ }
54
+ };
55
+
56
+ // Internal Google Client IDs storage (also accessible via index.js exports)
57
+ let _googleClientIds = {
58
+ webClientId: null,
59
+ iosClientId: null,
60
+ androidClientId: null,
61
+ serverClientId: null
62
+ };
63
+
64
+ /**
65
+ * Set Google Client IDs globally (called during initialization)
66
+ * @param {object} clientIds - Google OAuth client IDs
67
+ */
68
+ const setGoogleClientIds = (clientIds) => {
69
+ if (!clientIds) return;
70
+
71
+ if (clientIds.webClientId) {
72
+ _googleClientIds.webClientId = clientIds.webClientId;
73
+ if (typeof window !== 'undefined') {
74
+ window.onairosGoogleClientId = clientIds.webClientId;
75
+ }
76
+ }
77
+ if (clientIds.iosClientId) {
78
+ _googleClientIds.iosClientId = clientIds.iosClientId;
79
+ if (typeof window !== 'undefined') {
80
+ window.onairosGoogleIosClientId = clientIds.iosClientId;
81
+ }
82
+ }
83
+ if (clientIds.androidClientId) {
84
+ _googleClientIds.androidClientId = clientIds.androidClientId;
85
+ if (typeof window !== 'undefined') {
86
+ window.onairosGoogleAndroidClientId = clientIds.androidClientId;
87
+ }
88
+ }
89
+ if (clientIds.serverClientId) {
90
+ _googleClientIds.serverClientId = clientIds.serverClientId;
91
+ if (typeof window !== 'undefined') {
92
+ window.onairosGoogleServerClientId = clientIds.serverClientId;
93
+ }
94
+ }
95
+
96
+ globalSDKState.googleClientIds = { ..._googleClientIds };
97
+ };
98
+
99
+ /**
100
+ * Set the shared import bridge URL globally.
101
+ * Accept either a base origin (https://onairos.uk) or a full /import URL.
102
+ * @param {string|null|undefined} bridgeUrl - Import bridge URL or base
103
+ * @returns {string|null} - Normalized bridge URL
104
+ */
105
+ const setImportBridgeUrl = (bridgeUrl) => {
106
+ const trimmed = typeof bridgeUrl === 'string' ? bridgeUrl.trim().replace(/\/+$/, '') : '';
107
+ if (!trimmed) return null;
108
+
109
+ let normalized = trimmed;
110
+ try {
111
+ const parsed = new URL(trimmed);
112
+ if (!parsed.pathname || parsed.pathname === '/') {
113
+ parsed.pathname = '/import';
114
+ normalized = parsed.toString().replace(/\/+$/, '');
115
+ }
116
+ } catch (_) {
117
+ // Keep the raw string when callers provide a relative/custom bridge path.
118
+ }
119
+
120
+ if (typeof window !== 'undefined') {
121
+ window.onairosImportBridgeUrl = normalized;
122
+ }
123
+
124
+ globalSDKState.importBridgeUrl = normalized;
125
+ return normalized;
126
+ };
127
+
128
+ /**
129
+ * Get configured Google Client IDs
130
+ * @returns {object} - Google client IDs
131
+ */
132
+ export const getGoogleClientIdsFromSDK = () => ({ ..._googleClientIds });
133
+
134
+ /**
135
+ * Initialize SDK with API key validation
136
+ * @param {object} config - Initialization configuration
137
+ * @returns {Promise<object>} - Initialization result
138
+ */
139
+ export const initializeApiKey = async (config) => {
140
+ const {
141
+ apiKey,
142
+ environment = detectEnvironment(),
143
+ enableLogging = false,
144
+ timeout = 30000,
145
+ retryAttempts = 3,
146
+ platform = 'web',
147
+ sdkVersion = '3.4.0',
148
+ // Google OAuth Client IDs (for Capacitor/native apps)
149
+ googleClientIds = null,
150
+ // Shared import bridge URL for provider import flows
151
+ importBridgeUrl = null
152
+ } = config;
153
+
154
+ const normalizedImportBridgeUrl = importBridgeUrl ? setImportBridgeUrl(importBridgeUrl) : null;
155
+
156
+ // Validate required parameters
157
+ if (!apiKey) {
158
+ const error = new Error('API key is required for SDK initialization');
159
+ error.code = 'MISSING_API_KEY';
160
+ reportSdkError({
161
+ phase: 'initializeApiKey',
162
+ message: error.message,
163
+ code: error.code,
164
+ severity: 'error',
165
+ platform,
166
+ sdkVersion,
167
+ });
168
+ throw error;
169
+ }
170
+
171
+ if (enableLogging) {
172
+ console.log('🔧 [Onairos SDK] Initializing with config:', {
173
+ environment,
174
+ platform,
175
+ sdkVersion,
176
+ timeout,
177
+ retryAttempts,
178
+ apiKeyPrefix: apiKey.substring(0, 8) + '...',
179
+ hasGoogleClientIds: !!googleClientIds,
180
+ hasImportBridgeUrl: !!normalizedImportBridgeUrl
181
+ });
182
+ }
183
+
184
+ // Set Google Client IDs if provided (for Capacitor/native apps)
185
+ if (googleClientIds) {
186
+ setGoogleClientIds(googleClientIds);
187
+ if (enableLogging) {
188
+ console.log('🔑 [Onairos SDK] Google OAuth client IDs configured:', {
189
+ hasWebClientId: !!googleClientIds.webClientId,
190
+ hasIosClientId: !!googleClientIds.iosClientId,
191
+ hasAndroidClientId: !!googleClientIds.androidClientId,
192
+ hasServerClientId: !!googleClientIds.serverClientId
193
+ });
194
+ }
195
+ }
196
+
197
+ if (enableLogging && normalizedImportBridgeUrl) {
198
+ console.log('🌉 [Onairos SDK] Import bridge configured:', normalizedImportBridgeUrl);
199
+ }
200
+
201
+ try {
202
+ // Validate API key with backend
203
+ const validationResult = await validateApiKey(apiKey, {
204
+ environment,
205
+ timeout,
206
+ retryAttempts,
207
+ platform,
208
+ sdkVersion
209
+ });
210
+
211
+ if (!validationResult.isValid) {
212
+ const errorInfo = getErrorInfo(validationResult.code, validationResult);
213
+ const error = new Error(validationResult.error || errorInfo.message);
214
+ error.code = validationResult.code;
215
+ error.details = validationResult.message;
216
+ error.suggestions = errorInfo.suggestions;
217
+ error.keyType = validationResult.keyType;
218
+
219
+ if (enableLogging) {
220
+ console.error('❌ [Onairos SDK] Initialization failed:', {
221
+ error: error.message,
222
+ code: error.code,
223
+ suggestions: error.suggestions
224
+ });
225
+ }
226
+
227
+ reportSdkError({
228
+ phase: 'initializeApiKey',
229
+ message: error.message,
230
+ code: error.code,
231
+ severity: 'error',
232
+ platform,
233
+ sdkVersion,
234
+ metadata: {
235
+ keyType: error.keyType,
236
+ environment,
237
+ },
238
+ });
239
+ error.__onairosReported = true;
240
+
241
+ throw error;
242
+ }
243
+
244
+ // Store global state
245
+ globalSDKState = {
246
+ isInitialized: true,
247
+ apiKey,
248
+ config: {
249
+ environment,
250
+ enableLogging,
251
+ timeout,
252
+ retryAttempts,
253
+ platform,
254
+ sdkVersion,
255
+ importBridgeUrl: normalizedImportBridgeUrl
256
+ },
257
+ validationResult,
258
+ googleClientIds: googleClientIds ? { ..._googleClientIds } : null,
259
+ importBridgeUrl: normalizedImportBridgeUrl
260
+ };
261
+
262
+ try {
263
+ if (typeof window !== 'undefined') window.onairosApiKey = apiKey;
264
+ } catch (_) {}
265
+ try {
266
+ if (typeof localStorage !== 'undefined') localStorage.setItem('onairos_api_key', apiKey);
267
+ } catch (_) {}
268
+
269
+ if (enableLogging) {
270
+ console.log('✅ [Onairos SDK] Initialized successfully:', {
271
+ keyType: validationResult.keyType,
272
+ permissions: validationResult.permissions?.length || 0,
273
+ rateLimits: validationResult.rateLimits,
274
+ developer: validationResult.developer?.name
275
+ });
276
+ }
277
+
278
+ return {
279
+ success: true,
280
+ message: 'SDK initialized successfully',
281
+ keyType: validationResult.keyType,
282
+ permissions: validationResult.permissions,
283
+ rateLimits: validationResult.rateLimits,
284
+ developer: validationResult.developer,
285
+ apiKey: validationResult.apiKey,
286
+ googleClientIds: googleClientIds ? { ..._googleClientIds } : null,
287
+ importBridgeUrl: normalizedImportBridgeUrl
288
+ };
289
+
290
+ } catch (error) {
291
+ // Reset global state on failure
292
+ globalSDKState = {
293
+ isInitialized: false,
294
+ apiKey: null,
295
+ userToken: null,
296
+ onTokenExpired: null,
297
+ config: null,
298
+ validationResult: null,
299
+ googleClientIds: null,
300
+ importBridgeUrl: null
301
+ };
302
+
303
+ if (enableLogging) {
304
+ console.error('❌ [Onairos SDK] Initialization error:', error);
305
+ }
306
+
307
+ if (!error.__onairosReported) {
308
+ reportSdkError({
309
+ phase: 'initializeApiKey',
310
+ message: error?.message || 'SDK initialization failed',
311
+ code: error?.code,
312
+ severity: 'error',
313
+ platform,
314
+ sdkVersion,
315
+ metadata: { environment },
316
+ });
317
+ }
318
+
319
+ throw error;
320
+ }
321
+ };
322
+
323
+ /**
324
+ * Check if SDK is initialized
325
+ * @returns {boolean}
326
+ */
327
+ export const isSDKInitialized = () => {
328
+ return globalSDKState.isInitialized;
329
+ };
330
+
331
+ /**
332
+ * Get current SDK state
333
+ * @returns {object}
334
+ */
335
+ export const getSDKState = () => {
336
+ return { ...globalSDKState };
337
+ };
338
+
339
+ /**
340
+ * Get API key from initialized SDK
341
+ * @returns {string|null}
342
+ */
343
+ export const getApiKey = () => {
344
+ return globalSDKState.apiKey;
345
+ };
346
+
347
+ /**
348
+ * Store user JWT token for authenticated API calls.
349
+ * @param {string} token
350
+ */
351
+ export const setToken = (token) => {
352
+ globalSDKState.userToken = token || null;
353
+ try {
354
+ if (typeof localStorage !== 'undefined') {
355
+ if (token) {
356
+ localStorage.setItem('onairos_user_token', token);
357
+ } else {
358
+ localStorage.removeItem('onairos_user_token');
359
+ }
360
+ }
361
+ } catch (_) {}
362
+ };
363
+
364
+ /**
365
+ * Get user JWT token from memory/storage.
366
+ * @returns {string|null}
367
+ */
368
+ export const getToken = () => {
369
+ if (globalSDKState.userToken) return globalSDKState.userToken;
370
+ try {
371
+ if (typeof localStorage !== 'undefined') {
372
+ return localStorage.getItem('onairos_user_token') || null;
373
+ }
374
+ } catch (_) {}
375
+ return null;
376
+ };
377
+
378
+ /**
379
+ * Register callback for auth expiry events (HTTP 401).
380
+ * @param {Function|null} callback
381
+ */
382
+ export const setOnTokenExpired = (callback) => {
383
+ globalSDKState.onTokenExpired = typeof callback === 'function' ? callback : null;
384
+ };
385
+
386
+ /**
387
+ * Get SDK configuration
388
+ * @returns {object|null}
389
+ */
390
+ export const getSDKConfig = () => {
391
+ return globalSDKState.config;
392
+ };
393
+
394
+ /**
395
+ * Get validation result
396
+ * @returns {object|null}
397
+ */
398
+ export const getValidationResult = () => {
399
+ return globalSDKState.validationResult;
400
+ };
401
+
402
+ /**
403
+ * Reset SDK state (for testing or re-initialization)
404
+ */
405
+ export const resetSDK = () => {
406
+ globalSDKState = {
407
+ isInitialized: false,
408
+ apiKey: null,
409
+ userToken: null,
410
+ onTokenExpired: null,
411
+ config: null,
412
+ validationResult: null,
413
+ googleClientIds: null,
414
+ importBridgeUrl: null
415
+ };
416
+
417
+ // Also reset Google client IDs
418
+ _googleClientIds = {
419
+ webClientId: null,
420
+ iosClientId: null,
421
+ androidClientId: null,
422
+ serverClientId: null
423
+ };
424
+
425
+ // Clear window globals
426
+ if (typeof window !== 'undefined') {
427
+ window.onairosGoogleClientId = undefined;
428
+ window.onairosGoogleIosClientId = undefined;
429
+ window.onairosGoogleAndroidClientId = undefined;
430
+ window.onairosGoogleServerClientId = undefined;
431
+ window.onairosImportBridgeUrl = undefined;
432
+ }
433
+ };
434
+
435
+ /**
436
+ * Ensure SDK is initialized before operations
437
+ * @param {string} operation - Operation name for error messages
438
+ * @throws {Error} - If SDK is not initialized
439
+ */
440
+ export const ensureSDKInitialized = (operation = 'operation') => {
441
+ if (!globalSDKState.isInitialized) {
442
+ const error = new Error(`SDK not initialized. Call initializeApiKey() before ${operation}.`);
443
+ error.code = 'SDK_NOT_INITIALIZED';
444
+ throw error;
445
+ }
446
+ };
447
+
448
+ /**
449
+ * Make authenticated API request using initialized SDK
450
+ * @param {string} endpoint - API endpoint
451
+ * @param {object} options - Request options
452
+ * @returns {Promise<object>} - Response data
453
+ */
454
+ export const makeAuthenticatedRequest = async (endpoint, options = {}) => {
455
+ ensureSDKInitialized('making API requests');
456
+
457
+ const {
458
+ method = 'GET',
459
+ body = null,
460
+ headers = {},
461
+ timeout = globalSDKState.config.timeout,
462
+ requiresUserToken = /\/(sendModel|updateAccountInfo|inferenceUsername)\b|\/api\/signed-url\b/.test(String(endpoint || ''))
463
+ } = options;
464
+
465
+ const baseUrl = (() => {
466
+ try {
467
+ const override = typeof window !== 'undefined' && typeof window.onairosBaseUrl === 'string'
468
+ ? window.onairosBaseUrl.trim().replace(/\/$/, '')
469
+ : '';
470
+ if (override) return override;
471
+ } catch (_) {}
472
+ return 'https://api2.onairos.uk';
473
+ })();
474
+
475
+ const url = `${baseUrl}${endpoint}`;
476
+
477
+ const currentUserToken = getToken();
478
+ if (requiresUserToken && !currentUserToken) {
479
+ const authError = new Error('Authentication required. Call setToken(userJwtToken) before this request.');
480
+ authError.code = 'AUTHENTICATION_REQUIRED';
481
+ reportSdkError({
482
+ phase: 'makeAuthenticatedRequest',
483
+ message: authError.message,
484
+ code: authError.code,
485
+ endpoint,
486
+ baseUrl,
487
+ severity: 'error',
488
+ });
489
+ throw authError;
490
+ }
491
+
492
+ const requestHeaders = {
493
+ 'Authorization': `Bearer ${(requiresUserToken ? currentUserToken : (currentUserToken || globalSDKState.apiKey))}`,
494
+ 'Content-Type': 'application/json',
495
+ ...(globalSDKState.apiKey ? { 'x-api-key': globalSDKState.apiKey } : {}),
496
+ 'X-SDK-Platform': globalSDKState.config.platform,
497
+ 'User-Agent': `OnairosSDK/${globalSDKState.config.sdkVersion}`,
498
+ ...headers
499
+ };
500
+
501
+ const requestOptions = {
502
+ method,
503
+ headers: requestHeaders
504
+ };
505
+
506
+ if (body && method !== 'GET') {
507
+ requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
508
+ }
509
+
510
+ // Add timeout
511
+ const controller = new AbortController();
512
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
513
+ requestOptions.signal = controller.signal;
514
+
515
+ try {
516
+ const response = await fetch(url, requestOptions);
517
+ clearTimeout(timeoutId);
518
+
519
+ if (response.status === 401) {
520
+ setToken(null);
521
+ try { globalSDKState.onTokenExpired?.(); } catch (_) {}
522
+ const unauthorizedError = new Error('Authentication required');
523
+ unauthorizedError.code = 'AUTHENTICATION_REQUIRED';
524
+ unauthorizedError.status = 401;
525
+ reportSdkError({
526
+ phase: 'makeAuthenticatedRequest',
527
+ message: unauthorizedError.message,
528
+ code: unauthorizedError.code,
529
+ status: response.status,
530
+ endpoint,
531
+ baseUrl,
532
+ severity: 'error',
533
+ });
534
+ unauthorizedError.__onairosReported = true;
535
+ throw unauthorizedError;
536
+ }
537
+
538
+ const data = await response.json();
539
+
540
+ if (!response.ok) {
541
+ const error = new Error(data.error || `HTTP ${response.status}`);
542
+ error.status = response.status;
543
+ error.code = data.code;
544
+ error.details = data.details;
545
+ reportSdkError({
546
+ phase: 'makeAuthenticatedRequest',
547
+ message: error.message,
548
+ code: error.code,
549
+ status: response.status,
550
+ endpoint,
551
+ baseUrl,
552
+ severity: 'error',
553
+ metadata: { details: error.details },
554
+ });
555
+ error.__onairosReported = true;
556
+ throw error;
557
+ }
558
+
559
+ if (globalSDKState.config.enableLogging) {
560
+ console.log(`📡 [Onairos SDK] ${method} ${endpoint}:`, {
561
+ status: response.status,
562
+ success: data.success !== false
563
+ });
564
+ }
565
+
566
+ return data;
567
+
568
+ } catch (error) {
569
+ clearTimeout(timeoutId);
570
+
571
+ if (error.name === 'AbortError') {
572
+ const timeoutError = new Error(`Request timeout after ${timeout}ms`);
573
+ timeoutError.code = 'REQUEST_TIMEOUT';
574
+ reportSdkError({
575
+ phase: 'makeAuthenticatedRequest',
576
+ message: timeoutError.message,
577
+ code: timeoutError.code,
578
+ endpoint,
579
+ baseUrl,
580
+ severity: 'error',
581
+ metadata: { timeout },
582
+ });
583
+ throw timeoutError;
584
+ }
585
+
586
+ if (globalSDKState.config.enableLogging) {
587
+ console.error(`❌ [Onairos SDK] ${method} ${endpoint} failed:`, error.message);
588
+ }
589
+
590
+ if (!error.__onairosReported) {
591
+ reportSdkError({
592
+ phase: 'makeAuthenticatedRequest',
593
+ message: error?.message || 'Authenticated request failed',
594
+ code: error?.code,
595
+ status: error?.status,
596
+ endpoint,
597
+ baseUrl,
598
+ severity: 'error',
599
+ });
600
+ }
601
+
602
+ throw error;
603
+ }
604
+ };
605
+
606
+ /**
607
+ * Configuration interface for TypeScript/JSDoc
608
+ * @typedef {Object} InitConfig
609
+ * @property {string} apiKey - Required: Developer API key
610
+ * @property {'production'|'development'} [environment='production'] - Environment
611
+ * @property {boolean} [enableLogging=false] - Enable debug logging
612
+ * @property {number} [timeout=30000] - Request timeout in milliseconds
613
+ * @property {number} [retryAttempts=3] - Number of retry attempts
614
+ * @property {string} [platform='web'] - Platform identifier
615
+ * @property {string} [sdkVersion='3.4.0'] - SDK version
616
+ */
617
+
618
+ /**
619
+ * Validation result interface
620
+ * @typedef {Object} ValidationResult
621
+ * @property {boolean} isValid - Whether the API key is valid
622
+ * @property {boolean} success - Whether the validation was successful
623
+ * @property {string[]} [permissions] - Array of permissions
624
+ * @property {Object} [rateLimits] - Rate limit information
625
+ * @property {number} rateLimits.remaining - Remaining requests
626
+ * @property {number} rateLimits.resetTime - Reset timestamp
627
+ * @property {'admin'|'developer'|'invalid'} keyType - Type of API key
628
+ * @property {string} [error] - Error message if validation failed
629
+ * @property {string} [code] - Error code if validation failed
630
+ */
631
+
632
+ export default {
633
+ initializeApiKey,
634
+ isSDKInitialized,
635
+ getSDKState,
636
+ getApiKey,
637
+ setToken,
638
+ getToken,
639
+ setOnTokenExpired,
640
+ getSDKConfig,
641
+ getValidationResult,
642
+ resetSDK,
643
+ ensureSDKInitialized,
644
+ makeAuthenticatedRequest
645
+ };