@onairosofficial/onairos-capacitor 0.1.0 → 0.1.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 (202) hide show
  1. package/CAPACITOR_QUICK_START.md +379 -0
  2. package/CONNECTORS.md +122 -0
  3. package/LICENSE +194 -10
  4. package/OnairosofficialOnairosCapacitor.podspec +13 -0
  5. package/Package.swift +26 -0
  6. package/README.md +176 -25
  7. package/dist/onairos.capacitor.esm.js +1 -0
  8. package/dist/onairos.capacitor.esm.turbopack.js +1 -0
  9. package/docs/CAPACITOR_INTEGRATION_GUIDE.md +159 -0
  10. package/docs/CAPACITOR_MOCK_APP_TESTING.md +213 -0
  11. package/docs/CAPACITOR_SDK_FIXES_SUMMARY.md +65 -0
  12. package/docs/CROSS_SDK_PARITY.md +239 -0
  13. package/docs/DATA_FREQUENCY.md +57 -0
  14. package/docs/DEVELOPER_SDK_CHANGES.md +532 -0
  15. package/docs/INCIDENT_ENABLETRAINING_PIN_WEB_8.1.9.md +82 -0
  16. package/docs/ONAIROS_BUTTON_PROPS.md +152 -0
  17. package/docs/PLATFORM_APIS.md +559 -0
  18. package/docs/RAW_MEMORIES_API.md +305 -0
  19. package/docs/RAW_MEMORIES_SDK_UPDATE.md +54 -0
  20. package/docs/SDK_PARITY_ROLLUP_2026_04_24_to_05_02.md +96 -0
  21. package/docs/oldFixes.md +216 -0
  22. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +993 -0
  23. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosNetflixNativePlugin.swift +33 -0
  24. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +1082 -0
  25. package/onairos.d.ts +656 -0
  26. package/package.json +188 -37
  27. package/src/OnairosReconnectButton.jsx +272 -0
  28. package/src/RSA.jsx +57 -0
  29. package/src/assets/NewLogo.png +0 -0
  30. package/src/assets/OnairosNewLogo.png +0 -0
  31. package/src/assets/chatgpt-icon.png +0 -0
  32. package/src/assets/fire-horse.png +0 -0
  33. package/src/assets/fire-horse.transparent.png +0 -0
  34. package/src/assets/latest-firehorse.png +0 -0
  35. package/src/assets/perplexity.png +0 -0
  36. package/src/assets/persona.png +0 -0
  37. package/src/assets/persona1.png +0 -0
  38. package/src/assets/persona2.png +0 -0
  39. package/src/assets/persona3.png +0 -0
  40. package/src/assets/persona4.png +0 -0
  41. package/src/assets/persona5.png +0 -0
  42. package/src/capacitorConnectorCatalog.js +38 -0
  43. package/src/capacitorOAuthConfig.js +52 -0
  44. package/src/chatgptHostedImport/index.js +303 -0
  45. package/src/components/AuthButtons.jsx +48 -0
  46. package/src/components/ConnectChatGPTModal.jsx +666 -0
  47. package/src/components/ConnectClaudeModal.jsx +610 -0
  48. package/src/components/ConnectGeminiModal.jsx +639 -0
  49. package/src/components/ConnectGrokModal.jsx +701 -0
  50. package/src/components/ConnectPerplexityModal.jsx +726 -0
  51. package/src/components/DataExplainerScreen.jsx +349 -0
  52. package/src/components/DataRequest.js +885 -0
  53. package/src/components/DataRequest.jsx +1055 -0
  54. package/src/components/EmailAuth.js +1871 -0
  55. package/src/components/EmailAuth.jsx +2062 -0
  56. package/src/components/ExtensionInstallPrompt.jsx +142 -0
  57. package/src/components/GoogleButton.js +133 -0
  58. package/src/components/LLMConnectorManager.jsx +201 -0
  59. package/src/components/LoadingPage.jsx +19 -0
  60. package/src/components/LoadingScreen.jsx +81 -0
  61. package/src/components/LunarBirthdate.jsx +96 -0
  62. package/src/components/LunarLoadingPage.jsx +251 -0
  63. package/src/components/Notification.jsx +21 -0
  64. package/src/components/OnairosAppButton.jsx +85 -0
  65. package/src/components/OnairosSSO.jsx +645 -0
  66. package/src/components/OnairosTrigger.jsx +61 -0
  67. package/src/components/PerplexityLogo.jsx +43 -0
  68. package/src/components/PinSetup.js +200 -0
  69. package/src/components/PinSetup.jsx +228 -0
  70. package/src/components/SDK_PIN_INTEGRATION_REQUIRED_CHANGES.md +526 -0
  71. package/src/components/SdkErrorBoundary.jsx +36 -0
  72. package/src/components/SecuritySetup.js +81 -0
  73. package/src/components/SessionUserBar.jsx +83 -0
  74. package/src/components/SignUp.js +123 -0
  75. package/src/components/TestTelegramButton.js +53 -0
  76. package/src/components/TrainingComponent.jsx +200 -0
  77. package/src/components/TrainingScreen.jsx +897 -0
  78. package/src/components/UniversalOnboarding.js +306 -0
  79. package/src/components/UniversalOnboarding.jsx +4837 -0
  80. package/src/components/ValentineLoadingPage.jsx +502 -0
  81. package/src/components/ValentineModeSelector.jsx +162 -0
  82. package/src/components/WelcomeScreen.jsx +435 -0
  83. package/src/components/WrappedLoadingPage.jsx +205 -0
  84. package/src/components/connectors/ChatGPTConnector.js +348 -0
  85. package/src/components/connectors/ChatGPTConnector.jsx +348 -0
  86. package/src/components/connectors/ClaudeConnector.js +44 -0
  87. package/src/components/connectors/ClaudeConnector.jsx +44 -0
  88. package/src/components/connectors/GeminiConnector.js +170 -0
  89. package/src/components/connectors/GeminiConnector.jsx +170 -0
  90. package/src/components/connectors/GmailConnector.js +148 -0
  91. package/src/components/connectors/GmailConnector.jsx +148 -0
  92. package/src/components/connectors/GrokConnector.js +16 -0
  93. package/src/components/connectors/GrokConnector.jsx +16 -0
  94. package/src/components/connectors/HingeConnector.js +419 -0
  95. package/src/components/connectors/HingeConnector.jsx +419 -0
  96. package/src/components/connectors/InstagramDataConnector.js +726 -0
  97. package/src/components/connectors/InstagramDataConnector.jsx +726 -0
  98. package/src/components/connectors/LinkedInConnector.js +4 -0
  99. package/src/components/connectors/LinkedInConnector.jsx +296 -0
  100. package/src/components/connectors/PerplexityConnector.jsx +16 -0
  101. package/src/components/connectors/PinterestConnector.js +208 -0
  102. package/src/components/connectors/PinterestConnector.jsx +208 -0
  103. package/src/components/connectors/README.md +292 -0
  104. package/src/components/connectors/RedditConnector.js +229 -0
  105. package/src/components/connectors/RedditConnector.jsx +229 -0
  106. package/src/components/connectors/SephoraConnector.js +482 -0
  107. package/src/components/connectors/SephoraConnector.jsx +482 -0
  108. package/src/components/connectors/TikTokConnector.jsx +430 -0
  109. package/src/components/connectors/YoutubeConnector.js +361 -0
  110. package/src/components/connectors/YoutubeConnector.jsx +361 -0
  111. package/src/components/connectors/index.js +50 -0
  112. package/src/components/icons.jsx +46 -0
  113. package/src/components/icons.tsx +21 -0
  114. package/src/components/ui/PageLayout.jsx +1255 -0
  115. package/src/components/ui/PrimaryButton.jsx +162 -0
  116. package/src/components/ui/button.jsx +49 -0
  117. package/src/components/ui/card.jsx +61 -0
  118. package/src/components/ui/checkbox.jsx +33 -0
  119. package/src/components/ui/label.jsx +29 -0
  120. package/src/components/utils/UpdateConnections.js +45 -0
  121. package/src/components/utils/oauthHelper.js +97 -0
  122. package/src/config/api-config.js +138 -0
  123. package/src/deepLink.jsx +38 -0
  124. package/src/getPin.js +26 -0
  125. package/src/icons/Avatar.png +0 -0
  126. package/src/icons/Sentiment.png +0 -0
  127. package/src/icons/Trait.png +0 -0
  128. package/src/iframe/DataRequestPage.jsx +285 -0
  129. package/src/iframe/OnairosButtonIntegration.md +148 -0
  130. package/src/iframe/components/Box.jsx +56 -0
  131. package/src/iframe/components/IndividualConnection.jsx +88 -0
  132. package/src/iframe/dataRequestHandler.js +714 -0
  133. package/src/iframe/data_request_iframe.html +27 -0
  134. package/src/iframe/data_request_page.js +47 -0
  135. package/src/iframe/icons/Avatar.png +1 -0
  136. package/src/iframe/icons/Avatar2.png +1 -0
  137. package/src/iframe/icons/Sentiment.png +1 -0
  138. package/src/iframe/icons/Trait.png +1 -0
  139. package/src/iframe/icons/onairos_logo.png +0 -0
  140. package/src/iframe/utils/api.js +57 -0
  141. package/src/index.js +274 -0
  142. package/src/laravel/OnairosVue.vue +410 -0
  143. package/src/laravel/blade-helpers.js +320 -0
  144. package/src/laravel/vite-plugin.js +179 -0
  145. package/src/mobile/MobileDataRequestPage.jsx +233 -0
  146. package/src/mobile/components/MobileBox.jsx +71 -0
  147. package/src/mobile/components/MobileIndividualConnection.jsx +51 -0
  148. package/src/mobile/shims/browser-apis.js +78 -0
  149. package/src/mobile/shims/lucide-shim.js +85 -0
  150. package/src/nativeConnectors.js +5 -0
  151. package/src/newUI/EMAIL_VERIFICATION_API_SCHEMA.md +268 -0
  152. package/src/newUI/PlatformConnectorsStep.tsx +435 -0
  153. package/src/newUI/PrimaryButton.tsx +213 -0
  154. package/src/newUI/SignInStep.tsx +194 -0
  155. package/src/newUI/VerificationStep.tsx +133 -0
  156. package/src/newUI/WelcomeScreen.tsx +311 -0
  157. package/src/newUI/services/connectedAccountsService.js +129 -0
  158. package/src/onairos.capacitor.jsx +15 -0
  159. package/src/onairos.core.jsx +133 -0
  160. package/src/onairos.jsx +14 -0
  161. package/src/onairos.native.jsx +15 -0
  162. package/src/onairosButton.jsx +9000 -0
  163. package/src/overlay/CheckBox.jsx +114 -0
  164. package/src/overlay/IndividualConnection copy.js +86 -0
  165. package/src/overlay/IndividualConnection.js +191 -0
  166. package/src/overlay/IndividualConnectionNew.jsx +157 -0
  167. package/src/overlay/box.js +84 -0
  168. package/src/overlay/overlay.js +437 -0
  169. package/src/styles/onairos-scoped-preflight.css +97 -0
  170. package/src/styles/sdkCssRegistry.js +20 -0
  171. package/src/styles/styleLoaderInsertShadow.js +69 -0
  172. package/src/styles/tailwind.capacitor.css +395 -0
  173. package/src/styles/tailwind.css +395 -0
  174. package/src/theme/colors.js +40 -0
  175. package/src/utils/apiKeyValidation.js +341 -0
  176. package/src/utils/apiResponseLogger.js +316 -0
  177. package/src/utils/authHeaders.js +275 -0
  178. package/src/utils/biometrics.js +26 -0
  179. package/src/utils/bookmarkletUtils.js +28 -0
  180. package/src/utils/capacitorDetection.js +278 -0
  181. package/src/utils/capacitorLLMHelper.js +352 -0
  182. package/src/utils/capacitorPlugins.js +366 -0
  183. package/src/utils/crossDomainSSO.js +587 -0
  184. package/src/utils/deepLinking.js +27 -0
  185. package/src/utils/devLogger.js +46 -0
  186. package/src/utils/extensionDetection.js +418 -0
  187. package/src/utils/extractMemory.js +277 -0
  188. package/src/utils/framerBrandingOverrides.js +40 -0
  189. package/src/utils/googleWebClientId.js +55 -0
  190. package/src/utils/overlayHandler.js +224 -0
  191. package/src/utils/platformDisconnect.js +309 -0
  192. package/src/utils/pollTrainingStatus.js +200 -0
  193. package/src/utils/rawMemoriesAccess.js +211 -0
  194. package/src/utils/resolveBackendAppId.js +47 -0
  195. package/src/utils/responseFormatter.js +140 -0
  196. package/src/utils/sdkDebugStorage.js +113 -0
  197. package/src/utils/sdkInitialization.js +645 -0
  198. package/src/utils/sessionManager.js +1258 -0
  199. package/src/utils/startBackgroundTraining.js +100 -0
  200. package/src/utils/userDataFormatter.js +222 -0
  201. package/index.d.ts +0 -1
  202. package/index.js +0 -1
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Capacitor LLM Data Collection Helper
3
+ *
4
+ * This utility provides native LLM data collection for Capacitor apps
5
+ * without requiring the browser extension. It uses direct API calls
6
+ * to store LLM conversation data.
7
+ *
8
+ * NOTE: These are placeholder functions for now. Implementation will be added
9
+ * when LLM connectors are ready on the backend.
10
+ *
11
+ * TO ENABLE LLM COLLECTION:
12
+ * 1. Implement LLM backend endpoints
13
+ * 2. Change LLM_COLLECTION_ENABLED to true
14
+ * 3. The Capacitor/mobile detection is already handled - just add your logic
15
+ */
16
+
17
+ import { isCapacitor, isMobileApp, getEnvironmentType } from './capacitorDetection.js';
18
+ import { getApiBaseUrl } from '../config/api-config.js';
19
+
20
+ // Feature flag - set to true when LLM backend is ready
21
+ // When enabled, mobile apps (Capacitor/React Native) will use these functions
22
+ // Capacitor detection is already built-in - you just need to implement the backend calls
23
+ const LLM_COLLECTION_ENABLED = false;
24
+
25
+ /**
26
+ * Store LLM conversation data directly to Onairos backend
27
+ * This is the "native method" for Capacitor/mobile apps - no browser extension needed
28
+ *
29
+ * @param {Object} conversationData - LLM conversation data
30
+ * @param {Array} conversationData.messages - Array of messages [{role: 'user', content: '...'}, {role: 'assistant', content: '...'}]
31
+ * @param {string} conversationData.platform - LLM platform ('chatgpt', 'claude', 'gemini', 'grok')
32
+ * @param {string} conversationData.timestamp - ISO timestamp of conversation
33
+ * @param {Object} userInfo - User authentication information
34
+ * @param {string} userInfo.username - User's username or email
35
+ * @param {string} userInfo.userId - User's unique ID
36
+ * @param {string} userInfo.sessionToken - JWT session token
37
+ * @param {string} platform - LLM platform name
38
+ * @returns {Promise<Object>} Response object with success status
39
+ */
40
+ export const storeCapacitorLLMData = async (conversationData, userInfo, platform) => {
41
+ // Check if we're in mobile app environment
42
+ if (!isMobileApp()) {
43
+ return {
44
+ success: false,
45
+ error: 'Not in mobile app environment',
46
+ note: 'Use browser extension for LLM data collection on web'
47
+ };
48
+ }
49
+
50
+ // Feature flag check - when LLM_COLLECTION_ENABLED is true, the actual implementation will run
51
+ if (!LLM_COLLECTION_ENABLED) {
52
+ return {
53
+ success: false,
54
+ error: 'LLM collection not yet implemented',
55
+ note: 'This is a placeholder. Implementation will be added when backend is ready.',
56
+ data: {
57
+ platform,
58
+ environment: getEnvironmentType(),
59
+ messageCount: conversationData?.messages?.length || 0
60
+ }
61
+ };
62
+ }
63
+
64
+ // TODO: Actual implementation will go here when LLM backend is ready
65
+ // The implementation logic can be added by the other dev without worrying about Capacitor detection
66
+ // as the detection is already handled above
67
+ try {
68
+ // Validate inputs
69
+ if (!conversationData || !conversationData.messages) {
70
+ throw new Error('conversationData.messages is required');
71
+ }
72
+
73
+ if (!userInfo || !userInfo.sessionToken) {
74
+ throw new Error('userInfo.sessionToken is required');
75
+ }
76
+
77
+ if (!platform) {
78
+ throw new Error('platform is required (chatgpt, claude, gemini, grok)');
79
+ }
80
+
81
+ // Generate hash for integrity check
82
+ const dataHash = await generateDataHash(conversationData);
83
+
84
+ // Determine source type based on environment
85
+ const sourceType = isCapacitor() ? 'capacitor_app' :
86
+ isMobileApp() ? 'react_native_app' :
87
+ 'mobile_app';
88
+
89
+ // Format data according to backend API schema
90
+ const payload = {
91
+ encryptedData: btoa(JSON.stringify(conversationData)),
92
+ encryptionMetadata: {
93
+ algorithm: "AES-GCM",
94
+ keyDerivation: "PBKDF2",
95
+ iterations: 100000
96
+ },
97
+ authentication: {
98
+ username: userInfo.username || userInfo.email,
99
+ timestamp: Date.now()
100
+ },
101
+ integrity: {
102
+ hash: dataHash,
103
+ algorithm: "SHA-256"
104
+ },
105
+ platform: platform,
106
+ source: sourceType,
107
+ metadata: {
108
+ environment: getEnvironmentType(),
109
+ isCapacitor: isCapacitor(),
110
+ isMobileApp: isMobileApp(),
111
+ timestamp: new Date().toISOString()
112
+ }
113
+ };
114
+
115
+ const response = await fetch(`${getApiBaseUrl()}/llm-data/store`, {
116
+ method: 'POST',
117
+ headers: {
118
+ 'Content-Type': 'application/json',
119
+ 'Authorization': `Bearer ${userInfo.sessionToken || userInfo.jwtToken}`,
120
+ 'X-Onairos-User': userInfo.userId || userInfo.username,
121
+ 'X-Onairos-Source': sourceType
122
+ },
123
+ body: JSON.stringify(payload)
124
+ });
125
+
126
+ const responseData = await response.json();
127
+
128
+ if (response.ok) {
129
+ return {
130
+ success: true,
131
+ data: responseData,
132
+ platform,
133
+ source: sourceType
134
+ };
135
+ } else {
136
+ console.error('Failed to store LLM data:', response.status, responseData);
137
+ return {
138
+ success: false,
139
+ error: responseData.error || 'Failed to store LLM data',
140
+ status: response.status,
141
+ details: responseData
142
+ };
143
+ }
144
+ } catch (error) {
145
+ console.error('Error storing conversation data:', error);
146
+ return {
147
+ success: false,
148
+ error: error.message,
149
+ stack: error.stack
150
+ };
151
+ }
152
+ };
153
+
154
+ /**
155
+ * Generate SHA-256 hash of data for integrity verification
156
+ * @param {Object} data - Data to hash
157
+ * @returns {Promise<string>} SHA-256 hash
158
+ */
159
+ async function generateDataHash(data) {
160
+ try {
161
+ const encoder = new TextEncoder();
162
+ const dataString = JSON.stringify(data);
163
+ const dataBuffer = encoder.encode(dataString);
164
+ const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
165
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
166
+ const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
167
+ return `sha256-${hashHex}`;
168
+ } catch (error) {
169
+ console.error('Error generating hash:', error);
170
+ return `sha256-${Date.now()}`; // Fallback
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Batch store multiple LLM conversations
176
+ * @param {Array} conversations - Array of conversation objects
177
+ * @param {Object} userInfo - User authentication info
178
+ * @returns {Promise<Object>} Summary of batch operation
179
+ */
180
+ export const storeBatchLLMData = async (conversations, userInfo) => {
181
+ if (!LLM_COLLECTION_ENABLED) {
182
+ return {
183
+ success: false,
184
+ error: 'LLM collection not yet implemented',
185
+ note: 'Placeholder function'
186
+ };
187
+ }
188
+
189
+ // TODO: Implementation will go here
190
+ const results = {
191
+ total: conversations.length,
192
+ successful: 0,
193
+ failed: 0,
194
+ errors: []
195
+ };
196
+
197
+ for (const conversation of conversations) {
198
+ const result = await storeCapacitorLLMData(
199
+ {
200
+ messages: conversation.messages,
201
+ timestamp: conversation.timestamp
202
+ },
203
+ userInfo,
204
+ conversation.platform
205
+ );
206
+
207
+ if (result.success) {
208
+ results.successful++;
209
+ } else {
210
+ results.failed++;
211
+ results.errors.push({
212
+ platform: conversation.platform,
213
+ error: result.error
214
+ });
215
+ }
216
+ }
217
+
218
+ return results;
219
+ };
220
+
221
+ /**
222
+ * Retrieve LLM conversation history
223
+ * @param {Object} userInfo - User authentication info
224
+ * @param {Object} options - Query options
225
+ * @param {string} options.platform - Filter by platform (optional)
226
+ * @param {number} options.limit - Maximum number of conversations to retrieve
227
+ * @param {number} options.offset - Offset for pagination
228
+ * @returns {Promise<Object>} Conversation history
229
+ */
230
+ export const getLLMHistory = async (userInfo, options = {}) => {
231
+ if (!LLM_COLLECTION_ENABLED) {
232
+ return {
233
+ success: false,
234
+ error: 'LLM collection not yet implemented',
235
+ note: 'Placeholder function'
236
+ };
237
+ }
238
+
239
+ // TODO: Implementation will go here
240
+ try {
241
+ const { platform, limit = 20, offset = 0 } = options;
242
+
243
+ const queryParams = new URLSearchParams({
244
+ limit: limit.toString(),
245
+ offset: offset.toString()
246
+ });
247
+
248
+ if (platform) {
249
+ queryParams.set('platform', platform);
250
+ }
251
+
252
+ const response = await fetch(`${getApiBaseUrl()}/llm-data/history?${queryParams}`, {
253
+ method: 'GET',
254
+ headers: {
255
+ 'Authorization': `Bearer ${userInfo.sessionToken || userInfo.jwtToken}`,
256
+ 'X-Onairos-User': userInfo.userId || userInfo.username
257
+ }
258
+ });
259
+
260
+ const data = await response.json();
261
+
262
+ if (response.ok) {
263
+ return {
264
+ success: true,
265
+ data: data
266
+ };
267
+ } else {
268
+ console.error('Failed to retrieve LLM history:', response.status);
269
+ return {
270
+ success: false,
271
+ error: data.error || 'Failed to retrieve history'
272
+ };
273
+ }
274
+ } catch (error) {
275
+ console.error('Error retrieving LLM history:', error);
276
+ return {
277
+ success: false,
278
+ error: error.message
279
+ };
280
+ }
281
+ };
282
+
283
+ /**
284
+ * Get LLM usage statistics
285
+ * @param {Object} userInfo - User authentication info
286
+ * @returns {Promise<Object>} Usage statistics
287
+ */
288
+ export const getLLMStats = async (userInfo) => {
289
+ if (!LLM_COLLECTION_ENABLED) {
290
+ return {
291
+ success: false,
292
+ error: 'LLM collection not yet implemented',
293
+ note: 'Placeholder function'
294
+ };
295
+ }
296
+
297
+ // TODO: Implementation will go here
298
+ try {
299
+ const response = await fetch(`${getApiBaseUrl()}/llm-data/stats`, {
300
+ method: 'GET',
301
+ headers: {
302
+ 'Authorization': `Bearer ${userInfo.sessionToken || userInfo.jwtToken}`,
303
+ 'X-Onairos-User': userInfo.userId || userInfo.username
304
+ }
305
+ });
306
+
307
+ const data = await response.json();
308
+
309
+ if (response.ok) {
310
+ return {
311
+ success: true,
312
+ stats: data
313
+ };
314
+ } else {
315
+ console.error('Failed to retrieve LLM stats:', response.status);
316
+ return {
317
+ success: false,
318
+ error: data.error || 'Failed to retrieve stats'
319
+ };
320
+ }
321
+ } catch (error) {
322
+ console.error('Error retrieving LLM stats:', error);
323
+ return {
324
+ success: false,
325
+ error: error.message
326
+ };
327
+ }
328
+ };
329
+
330
+ /**
331
+ * Helper to format conversation data from app
332
+ * @param {Array} messages - Array of message objects
333
+ * @param {string} platform - Platform name
334
+ * @returns {Object} Formatted conversation data
335
+ */
336
+ export const formatConversationData = (messages, platform) => {
337
+ return {
338
+ messages: messages.map(msg => ({
339
+ role: msg.role || 'user',
340
+ content: msg.content || msg.text || '',
341
+ timestamp: msg.timestamp || new Date().toISOString()
342
+ })),
343
+ platform: platform,
344
+ timestamp: new Date().toISOString(),
345
+ metadata: {
346
+ source: 'capacitor_app',
347
+ environment: getEnvironmentType(),
348
+ messageCount: messages.length
349
+ }
350
+ };
351
+ };
352
+
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Capacitor plugin accessors that avoid importing `@capacitor/*` packages.
3
+ *
4
+ * Why: static imports of `@capacitor/core` / `@capacitor/browser` / `@capacitor/app`
5
+ * can force those modules to be evaluated during `import('onairos')`, which has been
6
+ * observed to crash iOS WKWebView in some environments.
7
+ *
8
+ * These helpers only rely on the runtime global `window.Capacitor` when present.
9
+ */
10
+
11
+ export const getCapacitor = () => {
12
+ if (typeof window === 'undefined') return undefined;
13
+ return window.Capacitor;
14
+ };
15
+
16
+ export const isCapacitorNativePlatform = () => {
17
+ try {
18
+ const cap = getCapacitor();
19
+ const native = !!cap?.isNativePlatform?.();
20
+ // Extra guard: some environments may expose a Capacitor-like global on web.
21
+ // We only treat it as native when platform is not "web".
22
+ const platform = cap?.getPlatform?.() || null;
23
+ return !!(native && platform && platform !== 'web');
24
+ } catch {
25
+ return false;
26
+ }
27
+ };
28
+
29
+ export const getCapacitorPlatform = () => {
30
+ try {
31
+ return getCapacitor()?.getPlatform?.() || null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ };
36
+
37
+ export const getCapacitorBrowser = () => {
38
+ const cap = getCapacitor();
39
+ // Capacitor historically exposed plugins on `Capacitor.Plugins.*`.
40
+ // Some environments/plugins also expose a top-level property.
41
+ return (
42
+ cap?.Plugins?.Browser ||
43
+ cap?.Plugins?.CapacitorBrowser ||
44
+ cap?.Browser ||
45
+ undefined
46
+ );
47
+ };
48
+
49
+ export const getCapacitorApp = () => {
50
+ const cap = getCapacitor();
51
+ return (
52
+ cap?.Plugins?.App ||
53
+ cap?.App ||
54
+ cap?.CapacitorApp ||
55
+ (typeof window !== 'undefined' ? window.App : undefined)
56
+ );
57
+ };
58
+
59
+ /**
60
+ * Get a Capacitor plugin by trying multiple possible names.
61
+ * Useful when native side registers under `jsName` vs `identifier` or legacy naming.
62
+ */
63
+ export const getCapacitorPlugin = (...names) => {
64
+ const cap = getCapacitor();
65
+ for (const n of names.flat().filter(Boolean)) {
66
+ try {
67
+ if (cap?.Plugins?.[n]) return cap.Plugins[n];
68
+ if (cap?.[n]) return cap[n];
69
+ } catch (_) {}
70
+ }
71
+ return undefined;
72
+ };
73
+
74
+ export const isCapacitorPluginAvailable = (...names) => {
75
+ const cap = getCapacitor();
76
+ try {
77
+ if (cap?.isPluginAvailable) return names.flat().some((n) => !!n && cap.isPluginAvailable(String(n)));
78
+ } catch (_) {}
79
+ try {
80
+ return names.flat().some((n) => !!n && !!cap?.Plugins?.[n]);
81
+ } catch (_) {
82
+ return false;
83
+ }
84
+ };
85
+
86
+ export const tryCapacitorBrowserClose = () => {
87
+ try {
88
+ return Promise.resolve(getCapacitorBrowser()?.close?.()).catch(() => undefined);
89
+ } catch {
90
+ return Promise.resolve(undefined);
91
+ }
92
+ };
93
+
94
+ /**
95
+ * Get the Capacitor Google Auth plugin, if the host app installed one.
96
+ *
97
+ * Supported plugins (common options):
98
+ * - `GoogleAuth` (e.g. @codetrix-studio/capacitor-google-auth) -> initialize() + signIn()
99
+ * - `SocialLogin` (e.g. @capgo/capacitor-social-login) -> initialize() + login({ provider: 'google' })
100
+ *
101
+ * IMPORTANT:
102
+ * - This SDK never statically imports `@capacitor/*` packages (WKWebView crash avoidance).
103
+ * - The host Capacitor app must install/configure the plugin + its own Google OAuth client IDs.
104
+ */
105
+ export const getCapacitorGoogleAuth = () => {
106
+ return getCapacitorPlugin(
107
+ 'SocialLogin',
108
+ 'GoogleAuth',
109
+ 'CapacitorGoogleAuth',
110
+ 'GoogleSignIn',
111
+ 'GoogleSignin',
112
+ 'GoogleAuthentication',
113
+ 'GooglePlus'
114
+ );
115
+ };
116
+
117
+ /**
118
+ * Check if a native Google Auth plugin is available.
119
+ * If true, the SDK should prefer native sign-in over web-based @react-oauth/google.
120
+ */
121
+ export const isNativeGoogleAuthAvailable = () => {
122
+ return isCapacitorPluginAvailable(
123
+ 'SocialLogin',
124
+ 'GoogleAuth',
125
+ 'CapacitorGoogleAuth',
126
+ 'GoogleSignIn',
127
+ 'GoogleSignin',
128
+ 'GoogleAuthentication',
129
+ 'GooglePlus'
130
+ );
131
+ };
132
+
133
+ const pickFirstDefined = (...vals) => vals.find((v) => v !== undefined && v !== null);
134
+
135
+ const readWindowString = (key) => {
136
+ try {
137
+ if (typeof window === 'undefined') return null;
138
+ const v = window?.[key];
139
+ if (!v) return null;
140
+ const s = String(v).trim();
141
+ return s || null;
142
+ } catch {
143
+ return null;
144
+ }
145
+ };
146
+
147
+ /**
148
+ * Build a @capgo/capacitor-social-login Google config from SDK-provided globals.
149
+ *
150
+ * These globals are set via `updateGoogleClientIds()` in `src/index.js`.
151
+ */
152
+ const getCapgoGoogleConfigFromWindow = () => {
153
+ const webClientId =
154
+ readWindowString('onairosGoogleClientId') ||
155
+ readWindowString('onairosGoogleWebClientId') ||
156
+ null;
157
+ const iosClientId =
158
+ readWindowString('onairosGoogleIosClientId') ||
159
+ readWindowString('onairosGoogleIOSClientId') ||
160
+ null;
161
+ const androidClientId =
162
+ readWindowString('onairosGoogleAndroidClientId') ||
163
+ null;
164
+ const serverClientId =
165
+ readWindowString('onairosGoogleServerClientId') ||
166
+ webClientId ||
167
+ null;
168
+
169
+ return { webClientId, iosClientId, androidClientId, serverClientId };
170
+ };
171
+
172
+ /**
173
+ * Perform native Google Sign-In using whichever Capacitor Google Auth plugin is present.
174
+ *
175
+ * @returns {Promise<{success: boolean, user?: object, idToken?: string, accessToken?: string, serverAuthCode?: string, error?: string}>}
176
+ */
177
+ export const performNativeGoogleSignIn = async () => {
178
+ try {
179
+ const GoogleAuth = getCapacitorGoogleAuth();
180
+
181
+ if (!GoogleAuth) {
182
+ return {
183
+ success: false,
184
+ error:
185
+ 'Native Google Auth plugin not available. Please install/configure a Capacitor Google auth plugin (e.g. @codetrix-studio/capacitor-google-auth or @capgo/capacitor-social-login).',
186
+ };
187
+ }
188
+
189
+ const platform = getCapacitorPlatform();
190
+ const isCapgoSocialLogin =
191
+ typeof GoogleAuth?.login === 'function' && typeof GoogleAuth?.signIn !== 'function';
192
+
193
+ // Initialize if needed (some plugins require this).
194
+ if (typeof GoogleAuth.initialize === 'function') {
195
+ if (isCapgoSocialLogin) {
196
+ // @capgo/capacitor-social-login REQUIRES provider configuration in initialize() on iOS,
197
+ // otherwise login() throws "Missing provider or options".
198
+ const { webClientId, iosClientId, serverClientId } = getCapgoGoogleConfigFromWindow();
199
+
200
+ // iOS requires iOSClientId for @capgo/capacitor-social-login
201
+ if (platform === 'ios' && !iosClientId) {
202
+ return {
203
+ success: false,
204
+ error:
205
+ 'Missing iOS Google Client ID. Call updateGoogleClientIds({ iosClientId: "...", webClientId: "..." }) before rendering the login UI (required for @capgo/capacitor-social-login on iOS).',
206
+ };
207
+ }
208
+
209
+ // Basic (online) mode is what we want: it returns an idToken.
210
+ // Only attempt auto-initialize if we have enough info for this platform.
211
+ // (Host apps may already initialize SocialLogin themselves; we should not hard-fail.)
212
+ const googleCfg = { mode: 'online' };
213
+ let canAutoInit = false;
214
+ if (platform === 'ios') {
215
+ if (iosClientId) {
216
+ googleCfg.iOSClientId = iosClientId;
217
+ if (webClientId) googleCfg.webClientId = webClientId;
218
+ if (serverClientId) googleCfg.iOSServerClientId = serverClientId;
219
+ canAutoInit = true;
220
+ }
221
+ } else {
222
+ // Android/Web flows can often run with just a webClientId.
223
+ if (webClientId) {
224
+ googleCfg.webClientId = webClientId;
225
+ canAutoInit = true;
226
+ }
227
+ }
228
+
229
+ if (canAutoInit) {
230
+ try {
231
+ await GoogleAuth.initialize({ google: googleCfg });
232
+ } catch (_) {
233
+ // ignore; we'll attempt login and surface its error
234
+ }
235
+ }
236
+ } else {
237
+ // Other plugins may support initialize() with no args or different args.
238
+ try {
239
+ await GoogleAuth.initialize();
240
+ } catch (_) {
241
+ // ignore
242
+ }
243
+ }
244
+ }
245
+
246
+ // Perform sign-in. Different plugins expose different method names.
247
+ let result;
248
+ if (typeof GoogleAuth.signIn === 'function') {
249
+ result = await GoogleAuth.signIn();
250
+ } else if (typeof GoogleAuth.login === 'function') {
251
+ // @capgo/capacitor-social-login expects an `options` object (can be empty).
252
+ try {
253
+ // Best-effort to avoid silently reusing the previous account/session on iOS.
254
+ // This makes the account chooser appear even after a previous successful login.
255
+ try {
256
+ if (platform === 'ios' && typeof GoogleAuth.logout === 'function') {
257
+ await GoogleAuth.logout({ provider: 'google' });
258
+ }
259
+ } catch (_) {}
260
+
261
+ const googleLoginOptions = {};
262
+ if (platform === 'ios') {
263
+ // iOS-only: force the account selection prompt
264
+ googleLoginOptions.forcePrompt = true;
265
+ }
266
+
267
+ result = await GoogleAuth.login({ provider: 'google', options: googleLoginOptions });
268
+ } catch (e) {
269
+ const msg = (() => {
270
+ try {
271
+ return String(e?.message || e?.error || e || '');
272
+ } catch {
273
+ return '';
274
+ }
275
+ })();
276
+
277
+ if (isCapgoSocialLogin && msg.toLowerCase().includes('missing provider') ) {
278
+ return {
279
+ success: false,
280
+ error:
281
+ 'Google native sign-in is not configured. If you are using @capgo/capacitor-social-login on iOS, you must initialize it with iOSClientId (or call updateGoogleClientIds({ iosClientId: "...", webClientId: "..." })).',
282
+ };
283
+ }
284
+ throw e;
285
+ }
286
+ } else {
287
+ return {
288
+ success: false,
289
+ error: 'Native Google Auth plugin does not expose signIn() or login().',
290
+ };
291
+ }
292
+
293
+ const userLike = pickFirstDefined(result?.user, result?.profile, result);
294
+
295
+ const idToken = pickFirstDefined(
296
+ result?.idToken,
297
+ result?.authentication?.idToken,
298
+ result?.tokens?.idToken,
299
+ result?.tokens?.id_token,
300
+ result?.result?.idToken
301
+ );
302
+
303
+ const accessToken = pickFirstDefined(
304
+ result?.accessToken,
305
+ result?.authentication?.accessToken,
306
+ result?.tokens?.accessToken,
307
+ result?.tokens?.access_token,
308
+ result?.result?.accessToken
309
+ );
310
+
311
+ const serverAuthCode = pickFirstDefined(
312
+ result?.serverAuthCode,
313
+ result?.authentication?.serverAuthCode,
314
+ result?.result?.serverAuthCode
315
+ );
316
+
317
+ return {
318
+ success: true,
319
+ user: {
320
+ email: pickFirstDefined(userLike?.email, userLike?.mail, userLike?.user?.email),
321
+ name: pickFirstDefined(
322
+ userLike?.givenName,
323
+ userLike?.displayName,
324
+ userLike?.name,
325
+ userLike?.user?.name
326
+ ),
327
+ familyName: pickFirstDefined(userLike?.familyName, userLike?.user?.familyName),
328
+ id: pickFirstDefined(userLike?.id, userLike?.userId, userLike?.user?.id),
329
+ imageUrl: pickFirstDefined(userLike?.imageUrl, userLike?.photoUrl, userLike?.picture),
330
+ },
331
+ idToken,
332
+ accessToken,
333
+ serverAuthCode,
334
+ rawResponse: result,
335
+ };
336
+ } catch (error) {
337
+ console.error('[Capacitor GoogleAuth] Sign-in failed:', error);
338
+ return {
339
+ success: false,
340
+ error: error?.message || error?.error || 'Native Google Sign-In failed',
341
+ };
342
+ }
343
+ };
344
+
345
+ /**
346
+ * Sign out from native Google Auth (best-effort; plugins vary).
347
+ */
348
+ export const performNativeGoogleSignOut = async () => {
349
+ try {
350
+ const GoogleAuth = getCapacitorGoogleAuth();
351
+ if (!GoogleAuth) return { success: false, error: 'Plugin not available' };
352
+
353
+ if (typeof GoogleAuth.signOut === 'function') {
354
+ await GoogleAuth.signOut();
355
+ return { success: true };
356
+ }
357
+ if (typeof GoogleAuth.logout === 'function') {
358
+ await GoogleAuth.logout();
359
+ return { success: true };
360
+ }
361
+
362
+ return { success: false, error: 'Plugin does not expose signOut() or logout().' };
363
+ } catch (error) {
364
+ return { success: false, error: error?.message || 'Sign out failed' };
365
+ }
366
+ };