@onairosofficial/onairos-capacitor 0.1.3 → 0.1.5

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 (95) hide show
  1. package/OnairosofficialOnairosCapacitor.podspec +1 -1
  2. package/README.md +1 -1
  3. package/dist/onairos.capacitor.esm.js +509 -1
  4. package/dist/onairos.capacitor.esm.turbopack.js +509 -1
  5. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +187 -945
  6. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosRNScrapers.swift +1800 -0
  7. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +180 -629
  8. package/onairos.d.ts +24 -0
  9. package/package.json +5 -2
  10. package/src/assets/connectors/Linkedinicon.png +0 -0
  11. package/src/assets/connectors/Redditicon.png +0 -0
  12. package/src/assets/connectors/YouTubeicon2.png +0 -0
  13. package/src/assets/connectors/chatgpt.png +0 -0
  14. package/src/assets/connectors/claude.png +0 -0
  15. package/src/assets/connectors/instagram.png +0 -0
  16. package/src/assets/connectors/netflix.png +0 -0
  17. package/src/assets/connectors/pinterest.png +0 -0
  18. package/src/assets/connectors/sephora.png +0 -0
  19. package/src/assets/connectors/spotify.png +0 -0
  20. package/src/assets/connectors/tiktok.png +0 -0
  21. package/src/assets/permissions/onairos.png +0 -0
  22. package/src/assets/permissions/personalization.png +0 -0
  23. package/src/assets/permissions/public-profile-person.png +0 -0
  24. package/src/assets/permissions/raw-memories.png +0 -0
  25. package/src/capacitorConnectorCatalog.js +2 -6
  26. package/src/components/DataRequest.jsx +96 -532
  27. package/src/components/EmailAuth.jsx +4 -116
  28. package/src/components/PinSetup.jsx +39 -226
  29. package/src/components/SDKDesignPreview.jsx +33 -0
  30. package/src/components/SessionUserBar.jsx +2 -1
  31. package/src/components/TrainingScreen.jsx +18 -12
  32. package/src/components/UniversalOnboarding.jsx +191 -424
  33. package/src/components/WelcomeScreen.jsx +19 -12
  34. package/src/components/parity/NativeConnections.jsx +136 -0
  35. package/src/components/parity/NativeScreens.jsx +48 -0
  36. package/src/components/ui/PageLayout.jsx +7 -3
  37. package/src/nativeImport/ConnectorLoading.jsx +13 -0
  38. package/src/nativeImport/CustomImportSession.js +115 -0
  39. package/src/nativeImport/ImportIcon.jsx +29 -0
  40. package/src/nativeImport/ImportProgress.jsx +24 -0
  41. package/src/nativeImport/ImportStatus.jsx +9 -0
  42. package/src/nativeImport/NativeChatImport.jsx +28 -0
  43. package/src/nativeImport/NativeImportSession.js +123 -0
  44. package/src/nativeImport/NativeScraperImport.jsx +57 -0
  45. package/src/nativeImport/SmartFilter.jsx +28 -0
  46. package/src/nativeImport/customPayload.js +37 -0
  47. package/src/nativeImport/netflixExport.js +30 -0
  48. package/src/nativeImport/netflixHistory.js +28 -0
  49. package/src/nativeImport/netflixSession.js +59 -0
  50. package/src/nativeImport/rawHandoff.js +7 -0
  51. package/src/nativeImport/rn/config/api.js +5 -0
  52. package/src/nativeImport/rn/services/apiKeyService.js +2 -0
  53. package/src/nativeImport/rn/services/hingePayload.js +37 -0
  54. package/src/nativeImport/rn/services/nativeConversationImport.js +138 -0
  55. package/src/nativeImport/rn/services/nativeFileTransfer.js +127 -0
  56. package/src/nativeImport/rn/services/nativeRawRedaction.js +136 -0
  57. package/src/nativeImport/rn/services/netflixPayload.js +70 -0
  58. package/src/nativeImport/rn/services/rawMemoryPolicy.js +38 -0
  59. package/src/nativeImport/rn/services/sephoraPayload.js +166 -0
  60. package/src/nativeImport/rn/services/spotifyPayload.js +99 -0
  61. package/src/nativeImport/rn/source-manifest.json +45 -0
  62. package/src/nativeImport/rn/utils/importedFiles.js +74 -0
  63. package/src/nativeImport/rn/utils/nativeImportDates.js +45 -0
  64. package/src/nativeImport/rn/utils/nativeImportFileReceiver.js +51 -0
  65. package/src/nativeImport/rn/utils/nativeImportMetadata.js +74 -0
  66. package/src/nativeImport/rn/utils/nativeImportTopics.js +56 -0
  67. package/src/nativeImport/rn/utils/rawExportDelivery.js +12 -0
  68. package/src/nativeImport/rn/utils/webviewScripts/chatgptDiscovery.js +99 -0
  69. package/src/nativeImport/rn/utils/webviewScripts/claude.js +349 -0
  70. package/src/nativeImport/rn/utils/webviewScripts/gemini.js +356 -0
  71. package/src/nativeImport/rn/utils/webviewScripts/hinge.js +375 -0
  72. package/src/nativeImport/rn/utils/webviewScripts/instagram.js +152 -0
  73. package/src/nativeImport/rn/utils/webviewScripts/linkedin.js +825 -0
  74. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTImport.js +202 -0
  75. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTSession.js +63 -0
  76. package/src/nativeImport/rn/utils/webviewScripts/nativeImportFiles.js +132 -0
  77. package/src/nativeImport/rn/utils/webviewScripts/nativeImportProviders.js +80 -0
  78. package/src/nativeImport/rn/utils/webviewScripts/nativeLoginViewport.js +28 -0
  79. package/src/nativeImport/rn/utils/webviewScripts/netflix.js +257 -0
  80. package/src/nativeImport/rn/utils/webviewScripts/sephora.js +862 -0
  81. package/src/nativeImport/rn/utils/webviewScripts/sephoraSession.js +160 -0
  82. package/src/nativeImport/rn/utils/webviewScripts/spotify.js +1868 -0
  83. package/src/nativeImport/rn/utils/webviewScripts/telegram.js +630 -0
  84. package/src/nativeImport/rn/utils/webviewScripts/tiktok.js +2920 -0
  85. package/src/onairos.capacitor.jsx +14 -2
  86. package/src/onairos.core.jsx +3 -0
  87. package/src/onairosButton.jsx +23 -17
  88. package/src/styles/onairos-fonts.css +20 -0
  89. package/src/styles/onairos-native.css +709 -0
  90. package/src/styles/onairos-rn-parity.css +175 -0
  91. package/src/styles/sdkCssRegistry.js +83 -1
  92. package/src/styles/tailwind.capacitor.css +6 -0
  93. package/src/utils/capacitorPlugins.js +20 -12
  94. package/src/utils/nativeConnectorSession.js +18 -0
  95. package/src/utils/parityPolicy.js +41 -0
@@ -0,0 +1,375 @@
1
+ // Synced from RN utils/webviewScripts/hinge.ts by scripts/sync-rn-connectors.cjs.
2
+ const HINGE_CONSENT_POPUP_SCRIPT = `
3
+ (function() {
4
+ try {
5
+ const existing = document.getElementById('onairos-consent-overlay');
6
+ if (existing) existing.remove();
7
+
8
+ const overlay = document.createElement('div');
9
+ overlay.id = 'onairos-consent-overlay';
10
+ overlay.style.cssText = \`
11
+ position: fixed;
12
+ top: 0;
13
+ left: 0;
14
+ width: 100%;
15
+ height: 100%;
16
+ background: rgba(0, 0, 0, 0.7);
17
+ z-index: 999999;
18
+ display: flex;
19
+ align-items: center;
20
+ justify-content: center;
21
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
22
+ \`;
23
+
24
+ const popup = document.createElement('div');
25
+ popup.style.cssText = \`
26
+ background: white;
27
+ border-radius: 16px;
28
+ padding: 32px;
29
+ max-width: 400px;
30
+ width: 90%;
31
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
32
+ \`;
33
+
34
+ popup.innerHTML = \`
35
+ <div style="text-align: center;">
36
+ <div style="font-size: 48px; margin-bottom: 16px;">\u{1F49C}</div>
37
+ <h2 style="margin: 0 0 12px 0; font-size: 24px; color: #1a1a1a;">
38
+ Export Hinge Data?
39
+ </h2>
40
+ <p style="margin: 0 0 24px 0; color: #666; font-size: 16px; line-height: 1.5;">
41
+ Allow Onairos to export your Hinge matches and conversations for analysis?
42
+ </p>
43
+ <div style="display: flex; gap: 12px; justify-content: center;">
44
+ <button id="onairos-deny" style="
45
+ flex: 1;
46
+ padding: 14px 24px;
47
+ border: 2px solid #e0e0e0;
48
+ background: white;
49
+ color: #666;
50
+ border-radius: 8px;
51
+ font-size: 16px;
52
+ font-weight: 600;
53
+ cursor: pointer;
54
+ ">Deny</button>
55
+ <button id="onairos-allow" style="
56
+ flex: 1;
57
+ padding: 14px 24px;
58
+ border: none;
59
+ background: linear-gradient(135deg, #7C3AED 0%, #5B21B6 100%);
60
+ color: white;
61
+ border-radius: 8px;
62
+ font-size: 16px;
63
+ font-weight: 600;
64
+ cursor: pointer;
65
+ ">Allow</button>
66
+ </div>
67
+ </div>
68
+ \`;
69
+
70
+ overlay.appendChild(popup);
71
+ document.body.appendChild(overlay);
72
+
73
+ document.getElementById('onairos-deny').onclick = () => {
74
+ overlay.remove();
75
+ window.ReactNativeWebView.postMessage(JSON.stringify({
76
+ type: 'HINGE_CONSENT',
77
+ status: 'denied'
78
+ }));
79
+ };
80
+
81
+ document.getElementById('onairos-allow').onclick = () => {
82
+ document.getElementById('onairos-allow').innerHTML = '\u23F3 Starting...';
83
+ document.getElementById('onairos-allow').disabled = true;
84
+
85
+ window.ReactNativeWebView.postMessage(JSON.stringify({
86
+ type: 'HINGE_CONSENT',
87
+ status: 'allowed'
88
+ }));
89
+
90
+ setTimeout(() => overlay.remove(), 500);
91
+ };
92
+ } catch (error) {
93
+ window.ReactNativeWebView.postMessage(JSON.stringify({
94
+ type: 'HINGE_CONSENT',
95
+ status: 'error',
96
+ message: error.message
97
+ }));
98
+ }
99
+ })();
100
+ true;
101
+ `;
102
+ const HINGE_EXPORT_SCRIPT = `
103
+ (function() {
104
+ try {
105
+ console.log('\u{1F504} [HINGE] Script version: SDK_V1');
106
+ window.ReactNativeWebView.postMessage(JSON.stringify({
107
+ type: 'DEBUG_LOG',
108
+ message: 'Hinge Script version: SDK_V1 loaded'
109
+ }));
110
+
111
+ if (!document.body) {
112
+ window.ReactNativeWebView.postMessage(JSON.stringify({
113
+ type: 'HINGE_EXPORT_ERROR',
114
+ message: 'Page not ready'
115
+ }));
116
+ return;
117
+ }
118
+
119
+ // ============================================================
120
+ // PLACEHOLDER API CONFIGURATION - REPLACE WITH ACTUAL ENDPOINTS
121
+ // ============================================================
122
+ const HINGE_CONFIG = {
123
+ // Base URL for Hinge API
124
+ baseUrl: 'https://api.hinge.co', // PLACEHOLDER
125
+
126
+ // API Endpoints - PLACEHOLDERS
127
+ endpoints: {
128
+ // Get user profile/session
129
+ session: '/api/v1/session', // PLACEHOLDER
130
+ // Get matches list
131
+ matches: '/api/v1/matches', // PLACEHOLDER
132
+ // Get chats for a match (append match ID)
133
+ chats: '/api/v1/matches/{matchId}/messages', // PLACEHOLDER
134
+ // Get user preferences/likes
135
+ likes: '/api/v1/likes', // PLACEHOLDER
136
+ },
137
+
138
+ // How to extract auth token - PLACEHOLDER
139
+ getAuthToken: () => {
140
+ // Try multiple locations where token might be stored
141
+ // Option 1: Cookie
142
+ const cookieMatch = document.cookie.match(/auth_token=([^;]+)/);
143
+ if (cookieMatch) return cookieMatch[1];
144
+
145
+ // Option 2: localStorage
146
+ const localToken = localStorage.getItem('hinge_auth_token');
147
+ if (localToken) return localToken;
148
+
149
+ // Option 3: sessionStorage
150
+ const sessionToken = sessionStorage.getItem('hinge_auth_token');
151
+ if (sessionToken) return sessionToken;
152
+
153
+ // Option 4: Check for token in window object (some apps expose it)
154
+ if (window.__HINGE_TOKEN__) return window.__HINGE_TOKEN__;
155
+
156
+ return null;
157
+ },
158
+
159
+ // Request headers template - PLACEHOLDER
160
+ getHeaders: (token) => ({
161
+ 'Accept': 'application/json',
162
+ 'Content-Type': 'application/json',
163
+ 'Authorization': token ? 'Bearer ' + token : undefined,
164
+ 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)',
165
+ // Add any Hinge-specific headers here
166
+ // 'X-Hinge-App-Version': '9.0.0', // PLACEHOLDER
167
+ })
168
+ };
169
+ // ============================================================
170
+
171
+ console.log('\u{1F680} [HINGE] Starting extraction...');
172
+
173
+ (async () => {
174
+ try {
175
+ // STEP 1: Get authentication token
176
+ window.ReactNativeWebView.postMessage(JSON.stringify({
177
+ type: 'HINGE_EXPORT_PROGRESS',
178
+ stage: 'fetching_token',
179
+ progress: 2,
180
+ message: 'Getting authentication...'
181
+ }));
182
+
183
+ console.log('[HINGE] Getting auth token...');
184
+ const authToken = HINGE_CONFIG.getAuthToken();
185
+
186
+ if (!authToken) {
187
+ console.warn('[HINGE] No auth token found - user may not be logged in');
188
+ // Continue anyway - some APIs might work without explicit token
189
+ }
190
+
191
+ const headers = HINGE_CONFIG.getHeaders(authToken);
192
+ console.log('[HINGE] Auth token:', authToken ? 'Found' : 'Not found');
193
+
194
+ // STEP 2: Fetch matches list
195
+ window.ReactNativeWebView.postMessage(JSON.stringify({
196
+ type: 'HINGE_EXPORT_PROGRESS',
197
+ stage: 'fetching_matches',
198
+ progress: 10,
199
+ message: 'Fetching matches...'
200
+ }));
201
+
202
+ console.log('[HINGE] Fetching matches...');
203
+
204
+ let matches = [];
205
+ try {
206
+ const matchesResponse = await fetch(HINGE_CONFIG.baseUrl + HINGE_CONFIG.endpoints.matches, {
207
+ method: 'GET',
208
+ credentials: 'include',
209
+ headers: headers
210
+ });
211
+
212
+ console.log('[HINGE] Matches response:', matchesResponse.status);
213
+
214
+ if (matchesResponse.ok) {
215
+ const matchesData = await matchesResponse.json();
216
+ // PLACEHOLDER: Adjust based on actual API response structure
217
+ matches = matchesData.matches || matchesData.data || matchesData || [];
218
+ console.log('[HINGE] Found', matches.length, 'matches');
219
+ } else {
220
+ console.warn('[HINGE] Failed to fetch matches:', matchesResponse.status);
221
+ }
222
+ } catch (matchesError) {
223
+ console.warn('[HINGE] Matches fetch error:', matchesError.message);
224
+ }
225
+
226
+ if (matches.length === 0) {
227
+ window.ReactNativeWebView.postMessage(JSON.stringify({
228
+ type: 'HINGE_EXPORT_COMPLETE',
229
+ status: 'success',
230
+ data: {
231
+ matches: [],
232
+ chats: [],
233
+ total_matches: 0,
234
+ total_messages: 0
235
+ },
236
+ success: true,
237
+ message: 'Connected! No matches found.'
238
+ }));
239
+ return;
240
+ }
241
+
242
+ // STEP 3: Fetch chats for each match (limit to 20 most recent)
243
+ const limitedMatches = matches.slice(0, 20);
244
+ const chatData = [];
245
+ let totalMessages = 0;
246
+
247
+ for (let i = 0; i < limitedMatches.length; i++) {
248
+ const match = limitedMatches[i];
249
+ // PLACEHOLDER: Adjust match ID field based on actual API
250
+ const matchId = match.id || match.match_id || match.userId;
251
+ const matchName = match.name || match.firstName || match.displayName || 'Match';
252
+
253
+ const progressPercent = 20 + ((i / limitedMatches.length) * 60);
254
+
255
+ window.ReactNativeWebView.postMessage(JSON.stringify({
256
+ type: 'HINGE_EXPORT_PROGRESS',
257
+ stage: 'fetching_chats',
258
+ current: i + 1,
259
+ total: limitedMatches.length,
260
+ progress: Math.round(progressPercent),
261
+ message: 'Fetching chats ' + (i + 1) + '/' + limitedMatches.length
262
+ }));
263
+
264
+ try {
265
+ if (i > 0) {
266
+ await new Promise(resolve => setTimeout(resolve, 300));
267
+ }
268
+
269
+ const chatEndpoint = HINGE_CONFIG.endpoints.chats.replace('{matchId}', matchId);
270
+ const chatResponse = await fetch(HINGE_CONFIG.baseUrl + chatEndpoint, {
271
+ method: 'GET',
272
+ credentials: 'include',
273
+ headers: headers
274
+ });
275
+
276
+ if (chatResponse.ok) {
277
+ const chatRaw = await chatResponse.json();
278
+ // PLACEHOLDER: Adjust based on actual API response structure
279
+ const messages = chatRaw.messages || chatRaw.data || chatRaw || [];
280
+
281
+ // Extract user messages only
282
+ const userMessages = [];
283
+ for (const msg of messages) {
284
+ // PLACEHOLDER: Adjust sender field based on actual API
285
+ const isUserMessage = msg.is_sender || msg.fromSelf || msg.sender === 'self';
286
+ if (isUserMessage) {
287
+ const content = msg.text || msg.content || msg.body || '';
288
+ if (content.trim()) {
289
+ userMessages.push({
290
+ content: content.trim(),
291
+ timestamp: msg.timestamp || msg.created_at || msg.sent_at
292
+ });
293
+ }
294
+ }
295
+ }
296
+
297
+ if (userMessages.length > 0) {
298
+ chatData.push({
299
+ match_id: matchId,
300
+ match_name: matchName,
301
+ user_messages: userMessages,
302
+ total_messages: messages.length
303
+ });
304
+ totalMessages += userMessages.length;
305
+ console.log('[HINGE] \u2705 Chat', (i + 1), ':', matchName, '(' + userMessages.length + ' user msgs)');
306
+ }
307
+ } else {
308
+ console.warn('[HINGE] \u26A0\uFE0F Chat fetch failed for', matchId, ':', chatResponse.status);
309
+ }
310
+ } catch (chatError) {
311
+ console.warn('[HINGE] \u26A0\uFE0F Chat error for', matchId, ':', chatError.message);
312
+ }
313
+ }
314
+
315
+ // STEP 4: Compile and send results
316
+ console.log('\u2705 [HINGE] Extraction complete:', totalMessages, 'messages from', chatData.length, 'chats');
317
+
318
+ window.ReactNativeWebView.postMessage(JSON.stringify({
319
+ type: 'HINGE_EXPORT_COMPLETE',
320
+ status: 'success',
321
+ data: {
322
+ matches: limitedMatches.map(m => ({
323
+ id: m.id || m.match_id,
324
+ name: m.name || m.firstName || 'Match',
325
+ // PLACEHOLDER: Add more match fields as needed
326
+ })),
327
+ chats: chatData,
328
+ total_matches: limitedMatches.length,
329
+ total_chats: chatData.length,
330
+ total_messages: totalMessages
331
+ },
332
+ success: true
333
+ }));
334
+
335
+ } catch (error) {
336
+ console.error('\u274C [HINGE] Export failed:', error.message);
337
+ window.ReactNativeWebView.postMessage(JSON.stringify({
338
+ type: 'HINGE_EXPORT_ERROR',
339
+ status: 'error',
340
+ message: 'Fetch failed: ' + error.message,
341
+ success: false
342
+ }));
343
+ }
344
+ })();
345
+
346
+ } catch (error) {
347
+ console.error('\u274C [HINGE] Init error:', error.message);
348
+ window.ReactNativeWebView.postMessage(JSON.stringify({
349
+ type: 'HINGE_EXPORT_ERROR',
350
+ status: 'error',
351
+ message: 'Script error: ' + error.message,
352
+ success: false
353
+ }));
354
+ }
355
+ })();
356
+ true;
357
+ `;
358
+ const HINGE_SUCCESS_SCRIPT = `
359
+ (function() {
360
+ console.log('\u2705 Hinge export successful!');
361
+ })();
362
+ true;
363
+ `;
364
+ const HINGE_ERROR_SCRIPT = `
365
+ (function() {
366
+ console.log('\u274C Hinge export failed!');
367
+ })();
368
+ true;
369
+ `;
370
+ export {
371
+ HINGE_CONSENT_POPUP_SCRIPT,
372
+ HINGE_ERROR_SCRIPT,
373
+ HINGE_EXPORT_SCRIPT,
374
+ HINGE_SUCCESS_SCRIPT
375
+ };
@@ -0,0 +1,152 @@
1
+ // Synced from RN utils/webviewScripts/instagram.ts by scripts/sync-rn-connectors.cjs.
2
+ const INSTAGRAM_RUNTIME = String.raw`
3
+ (function () {
4
+ if (location.hostname !== 'www.instagram.com' && location.hostname !== 'instagram.com') return;
5
+ if (window.__onairosInstagram) return;
6
+ const send = (type, payload) => window.ReactNativeWebView.postMessage(JSON.stringify({type, ...payload}));
7
+ const blocked = () => /\/(accounts\/(login|signup|onetap)|challenge|checkpoint)\b/.test(location.pathname) ||
8
+ !!document.querySelector('input[type="password"], input[autocomplete="one-time-code"]');
9
+ const headers = () => ({
10
+ 'X-IG-App-ID': '936619743392459',
11
+ 'X-CSRFToken': (document.cookie.match(/(?:^|;\s*)csrftoken=([^;]+)/) || [])[1] || '',
12
+ 'X-Requested-With': 'XMLHttpRequest',
13
+ 'X-ASBD-ID': '129477',
14
+ });
15
+ // current_user is unavailable to some signed-in web sessions (HTTP 400).
16
+ // Use only Instagram's own account cookie as a fallback, never a viewed profile.
17
+ const sessionUserId = () => (document.cookie.match(/(?:^|;\s*)ds_user_id=(\d+)(?:;|$)/) || [])[1] || null;
18
+ // Bound both response headers and body reads, not just fetch().
19
+ const request = async (url, extra = {}) => {
20
+ const controller = new AbortController();
21
+ const timer = setTimeout(() => controller.abort(), 12000);
22
+ try {
23
+ const response = await fetch(url, {credentials: 'include', cache: 'no-store',
24
+ headers: {...headers(), ...extra}, signal: controller.signal});
25
+ const payload = await response.json().catch(() => null);
26
+ const data = response.ok ? payload : null;
27
+ const reason = payload && typeof payload.message === 'string' ? payload.message.toLowerCase() : '';
28
+ const failure = response.status === 429 ? 'RATE_LIMITED' :
29
+ /login_required|challenge_required|checkpoint_required/.test(reason) ? 'AUTH_REQUIRED' :
30
+ !response.ok || !data ? 'REQUEST_FAILED' : null;
31
+ const endpoint = url.includes('current_user') ? 'session' : url.includes('/liked/') ? 'likes' :
32
+ url.includes('/saved/posts/') ? 'savedPosts' : url.includes('/saved/') ? 'saved' : 'following';
33
+ send('INSTAGRAM_REQUEST_STATUS', {endpoint, status: response.status,
34
+ hasUser: !!(data && data.user), hasItems: !!(data && Array.isArray(data.items)),
35
+ hasUsers: !!(data && Array.isArray(data.users)), hasSessionUserId: !!sessionUserId(),
36
+ userAgentRejected: /user.?agent/.test(reason)});
37
+ return {data, failure, claim: response.headers.get('x-ig-set-www-claim')};
38
+ } finally { clearTimeout(timer); }
39
+ };
40
+ const authenticated = async () => {
41
+ if (blocked()) return false;
42
+ if (document.querySelector('a[href="/direct/inbox/"], [aria-label="New post"], a[href="/explore/"], svg[aria-label="Home"]')) return true;
43
+ try {
44
+ const {data} = await request('/api/v1/accounts/current_user/');
45
+ return !blocked() && !!(data && data.user && (data.user.pk || data.user.pk_id || data.user.username));
46
+ } catch { return false; }
47
+ };
48
+ let checking = false;
49
+ const check = async () => {
50
+ if (checking) return;
51
+ checking = true;
52
+ try { send('INSTAGRAM_AUTH_STATE', {authenticated: await authenticated()}); }
53
+ finally { checking = false; }
54
+ };
55
+ let exporting = false;
56
+ const extract = async () => {
57
+ if (exporting) return;
58
+ exporting = true;
59
+ const progress = (value, message) => send('INSTAGRAM_EXPORT_PROGRESS', {progress: value, message});
60
+ try {
61
+ if (!await authenticated()) {
62
+ send('INSTAGRAM_EXPORT_ERROR', {code: 'AUTH_REQUIRED'});
63
+ return;
64
+ }
65
+ const limit = 48; // Hosted social import default (bounded at 100 upstream).
66
+ const out = {likes: [], savedPosts: [], following: []};
67
+ const failures = [];
68
+ const read = {likes: false, savedPosts: false, following: false};
69
+ const categoryRequest = async (url, markers, key, category) => {
70
+ try {
71
+ const result = await request(url, markers);
72
+ if (result.failure) failures.push({category, code: result.failure});
73
+ else if (!Array.isArray(result.data && result.data[key])) failures.push({category, code: 'REQUEST_FAILED'});
74
+ else read[category] = true;
75
+ return result;
76
+ } catch { failures.push({category, code: 'REQUEST_FAILED'}); return {data: null}; }
77
+ };
78
+ const mapPost = m => m ? ({
79
+ id: String(m.id || m.pk || ''), caption: (m.caption && m.caption.text) || '',
80
+ owner: (m.user && m.user.username) || '',
81
+ mediaType: m.media_type === 2 ? 'video' : m.media_type === 8 ? 'carousel' : 'image',
82
+ url: m.code ? 'https://www.instagram.com/p/' + m.code + '/' : null,
83
+ likedAt: m.taken_at ? new Date(m.taken_at * 1000).toISOString() : null,
84
+ }) : null;
85
+ let claim = '0', uid = sessionUserId();
86
+ progress(5, 'Connecting your Instagram activity…');
87
+ try {
88
+ const result = await request('/api/v1/accounts/current_user/', {'X-IG-WWW-Claim': claim});
89
+ if (result.claim) claim = result.claim;
90
+ const user = result.data && result.data.user;
91
+ uid = (user && (user.pk || user.pk_id || user.id)) || uid;
92
+ } catch {}
93
+ const markers = {'X-IG-WWW-Claim': claim};
94
+ progress(20, 'Reading liked posts…');
95
+ try {
96
+ const {data} = await categoryRequest('/api/v1/feed/liked/?count=' + limit, markers, 'items', 'likes');
97
+ (data && Array.isArray(data.items) ? data.items : []).slice(0, limit).forEach(m => {
98
+ const post = mapPost(m); if (post && post.id) out.likes.push(post);
99
+ });
100
+ } catch {}
101
+ progress(45, 'Reading saved posts…');
102
+ for (const path of ['/api/v1/feed/saved/posts/', '/api/v1/feed/saved/']) {
103
+ if (out.savedPosts.length) break;
104
+ try {
105
+ const {data} = await categoryRequest(path + '?count=' + limit, markers, 'items', 'savedPosts');
106
+ (data && Array.isArray(data.items) ? data.items : []).slice(0, limit).forEach(item => {
107
+ const post = mapPost(item.media || item); if (post && post.id) out.savedPosts.push(post);
108
+ });
109
+ } catch {}
110
+ }
111
+ progress(70, 'Reading followed accounts…');
112
+ if (uid) {
113
+ try {
114
+ const {data} = await categoryRequest('/api/v1/friendships/' + encodeURIComponent(uid) + '/following/?count=' + limit, markers, 'users', 'following');
115
+ (data && Array.isArray(data.users) ? data.users : []).slice(0, limit).forEach(user => {
116
+ out.following.push({username: user.username, fullName: user.full_name || '', id: String(user.pk || '')});
117
+ });
118
+ } catch {}
119
+ } else { failures.push({category: 'following', code: 'REQUEST_FAILED'}); }
120
+ if (blocked()) { send('INSTAGRAM_EXPORT_ERROR', {code: 'AUTH_REQUIRED'}); return; }
121
+ if (!out.likes.length && !out.savedPosts.length && !out.following.length) {
122
+ // One working saved-post path is enough; a failed alternate is not a failed category.
123
+ const unresolved = failures.filter(failure => !read[failure.category]).map(failure => failure.code);
124
+ const code = unresolved.includes('AUTH_REQUIRED') ? 'AUTH_REQUIRED' :
125
+ unresolved.includes('RATE_LIMITED') ? 'RATE_LIMITED' : unresolved.length ? 'REQUEST_FAILED' : 'NO_DATA';
126
+ send('INSTAGRAM_EXPORT_ERROR', {code}); return;
127
+ }
128
+ progress(85, 'Preparing your Instagram activity…');
129
+ send('INSTAGRAM_EXPORT_COMPLETE', {data: out});
130
+ } catch { send('INSTAGRAM_EXPORT_ERROR', {code: 'EXTRACTION_FAILED'}); }
131
+ finally { exporting = false; }
132
+ };
133
+ window.__onairosInstagram = {check, extract};
134
+ setInterval(check, 2500);
135
+ })();
136
+ `;
137
+ const INSTAGRAM_SESSION_SCRIPT = INSTAGRAM_RUNTIME + `
138
+ window.__onairosInstagram?.check(); true;
139
+ `;
140
+ const INSTAGRAM_EXPORT_SCRIPT = INSTAGRAM_RUNTIME + `
141
+ window.__onairosInstagram?.extract(); true;
142
+ `;
143
+ const INSTAGRAM_CONSENT_POPUP_SCRIPT = INSTAGRAM_SESSION_SCRIPT;
144
+ const INSTAGRAM_SUCCESS_SCRIPT = "true;";
145
+ const INSTAGRAM_ERROR_SCRIPT = "true;";
146
+ export {
147
+ INSTAGRAM_CONSENT_POPUP_SCRIPT,
148
+ INSTAGRAM_ERROR_SCRIPT,
149
+ INSTAGRAM_EXPORT_SCRIPT,
150
+ INSTAGRAM_SESSION_SCRIPT,
151
+ INSTAGRAM_SUCCESS_SCRIPT
152
+ };