@onairosofficial/onairos-capacitor 0.1.4 → 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 (88) 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/PinSetup.jsx +39 -226
  28. package/src/components/SDKDesignPreview.jsx +33 -0
  29. package/src/components/SessionUserBar.jsx +2 -1
  30. package/src/components/UniversalOnboarding.jsx +190 -423
  31. package/src/components/WelcomeScreen.jsx +7 -0
  32. package/src/components/parity/NativeConnections.jsx +136 -0
  33. package/src/components/parity/NativeScreens.jsx +48 -0
  34. package/src/components/ui/PageLayout.jsx +7 -3
  35. package/src/nativeImport/ConnectorLoading.jsx +13 -0
  36. package/src/nativeImport/CustomImportSession.js +115 -0
  37. package/src/nativeImport/ImportIcon.jsx +29 -0
  38. package/src/nativeImport/ImportProgress.jsx +24 -0
  39. package/src/nativeImport/ImportStatus.jsx +9 -0
  40. package/src/nativeImport/NativeChatImport.jsx +28 -0
  41. package/src/nativeImport/NativeImportSession.js +123 -0
  42. package/src/nativeImport/NativeScraperImport.jsx +57 -0
  43. package/src/nativeImport/SmartFilter.jsx +28 -0
  44. package/src/nativeImport/customPayload.js +37 -0
  45. package/src/nativeImport/netflixExport.js +30 -0
  46. package/src/nativeImport/netflixHistory.js +28 -0
  47. package/src/nativeImport/netflixSession.js +59 -0
  48. package/src/nativeImport/rawHandoff.js +7 -0
  49. package/src/nativeImport/rn/config/api.js +5 -0
  50. package/src/nativeImport/rn/services/apiKeyService.js +2 -0
  51. package/src/nativeImport/rn/services/hingePayload.js +37 -0
  52. package/src/nativeImport/rn/services/nativeConversationImport.js +138 -0
  53. package/src/nativeImport/rn/services/nativeFileTransfer.js +127 -0
  54. package/src/nativeImport/rn/services/nativeRawRedaction.js +136 -0
  55. package/src/nativeImport/rn/services/netflixPayload.js +70 -0
  56. package/src/nativeImport/rn/services/rawMemoryPolicy.js +38 -0
  57. package/src/nativeImport/rn/services/sephoraPayload.js +166 -0
  58. package/src/nativeImport/rn/services/spotifyPayload.js +99 -0
  59. package/src/nativeImport/rn/source-manifest.json +45 -0
  60. package/src/nativeImport/rn/utils/importedFiles.js +74 -0
  61. package/src/nativeImport/rn/utils/nativeImportDates.js +45 -0
  62. package/src/nativeImport/rn/utils/nativeImportFileReceiver.js +51 -0
  63. package/src/nativeImport/rn/utils/nativeImportMetadata.js +74 -0
  64. package/src/nativeImport/rn/utils/nativeImportTopics.js +56 -0
  65. package/src/nativeImport/rn/utils/rawExportDelivery.js +12 -0
  66. package/src/nativeImport/rn/utils/webviewScripts/chatgptDiscovery.js +99 -0
  67. package/src/nativeImport/rn/utils/webviewScripts/claude.js +349 -0
  68. package/src/nativeImport/rn/utils/webviewScripts/gemini.js +356 -0
  69. package/src/nativeImport/rn/utils/webviewScripts/hinge.js +375 -0
  70. package/src/nativeImport/rn/utils/webviewScripts/instagram.js +152 -0
  71. package/src/nativeImport/rn/utils/webviewScripts/linkedin.js +825 -0
  72. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTImport.js +202 -0
  73. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTSession.js +63 -0
  74. package/src/nativeImport/rn/utils/webviewScripts/nativeImportFiles.js +132 -0
  75. package/src/nativeImport/rn/utils/webviewScripts/nativeImportProviders.js +80 -0
  76. package/src/nativeImport/rn/utils/webviewScripts/nativeLoginViewport.js +28 -0
  77. package/src/nativeImport/rn/utils/webviewScripts/netflix.js +257 -0
  78. package/src/nativeImport/rn/utils/webviewScripts/sephora.js +862 -0
  79. package/src/nativeImport/rn/utils/webviewScripts/sephoraSession.js +160 -0
  80. package/src/nativeImport/rn/utils/webviewScripts/spotify.js +1868 -0
  81. package/src/nativeImport/rn/utils/webviewScripts/telegram.js +630 -0
  82. package/src/nativeImport/rn/utils/webviewScripts/tiktok.js +2920 -0
  83. package/src/onairos.core.jsx +3 -0
  84. package/src/onairosButton.jsx +23 -17
  85. package/src/styles/onairos-rn-parity.css +175 -0
  86. package/src/styles/tailwind.capacitor.css +4 -0
  87. package/src/utils/nativeConnectorSession.js +18 -0
  88. package/src/utils/parityPolicy.js +41 -0
@@ -0,0 +1,123 @@
1
+ import {createNativeSessionScript,parseNativeSessionMessage} from './rn/utils/webviewScripts/nativeChatGPTSession.js';
2
+ import {createNativeImportScript,parseNativeImportMessage,CANCEL_NATIVE_IMPORT} from './rn/utils/webviewScripts/nativeChatGPTImport.js';
3
+ import {createNativeSignOutScript,NATIVE_IMPORT_PROVIDERS} from './rn/utils/webviewScripts/nativeImportProviders.js';
4
+ import {NATIVE_LOGIN_VIEWPORT_SCRIPT} from './rn/utils/webviewScripts/nativeLoginViewport.js';
5
+ import {requireNativeConversationAccess,storeNativeConversations} from './rn/services/nativeConversationImport.js';
6
+ import {protectNativeRawExport} from './rn/services/nativeRawRedaction.js';
7
+ import {createNativeFileTransfer} from './rn/services/nativeFileTransfer.js';
8
+ import {attachRawExportDelivery} from './rn/utils/rawExportDelivery.js';
9
+
10
+ const defaults={requireAccess:requireNativeConversationAccess,store:storeNativeConversations,protect:protectNativeRawExport,createFiles:createNativeFileTransfer};
11
+ /** Titles only before review; content is bounded to the user's confirmed ID set. */
12
+ export class NativeImportSession {
13
+ constructor({plugin,platform='chatgpt',rawOnly=false,onState=()=>{},onComplete=()=>{},onCancel=()=>{},services={}}){
14
+ Object.assign(this,{plugin,platform,rawOnly,onState,onComplete,onCancel});this.services={...defaults,...services};
15
+ this.sessionId=globalThis.crypto?.randomUUID?.()||`import-${Date.now()}-${Math.random().toString(36).slice(2)}`;
16
+ this.control=new AbortController();this.active=true;this.stage='login';this.listeners=[];this.request='';this.serial=0;this.items=[];this.approved=new Set();this.chats=new Map();this.bytes=0;this.fileSequence=0;
17
+ }
18
+ state(stage,extra={}){if(!this.active)return;this.stage=stage;this.onState({stage,...extra});}
19
+ assertActive(){if(!this.active||this.control.signal.aborted)throw new Error('Import cancelled.');}
20
+ async listen(name,handler){const handle=await this.plugin.addListener(name,handler);if(!this.active)await handle.remove();else this.listeners.push(handle);}
21
+ async start(){
22
+ try{
23
+ if(!this.plugin?.startNativeImport)throw new Error('Update and sync the native Capacitor package to use Smart Filter.');
24
+ this.state('login',{message:'Checking import access…'});
25
+ const headers=await this.services.requireAccess(this.control.signal,this.platform);this.assertActive();this.authorization=headers.Authorization;
26
+ await this.listen('nativeImportMessage',event=>{void this.receive(event).catch(error=>this.fail(error));});
27
+ await this.listen('nativeImportLifecycle',event=>{if(event.sessionId!==this.sessionId)return;if(event.status==='cancelled')void this.cancel(true);else if(event.status==='error')void this.fail(new Error(event.message||'The provider browser ended.'));});
28
+ this.assertActive();
29
+ await this.plugin.startNativeImport({platform:this.platform,sessionId:this.sessionId,useHostIntro:true,sessionScript:NATIVE_LOGIN_VIEWPORT_SCRIPT+createNativeSessionScript(this.sessionId,this.platform)});
30
+ if(!this.active){try{await this.plugin.finishNativeImport({sessionId:this.sessionId});}catch{}return;}
31
+ if(this.stage==='login')this.onState({stage:'login',message:`Sign in to ${NATIVE_IMPORT_PROVIDERS[this.platform].name}`});
32
+ }catch(error){await this.fail(error);}
33
+ }
34
+ run(script){return this.plugin.runNativeImportScript({sessionId:this.sessionId,script});}
35
+ async begin(selection,options={}){
36
+ if(!this.active||this.stage!==(selection?'topics':'login'))return;
37
+ if(selection&&(!selection.length||selection.some(item=>!this.items.some(known=>known.id===item.id))))throw new Error('Invalid import selection.');
38
+ const ids=new Set(selection?.map(item=>item.id)||[]);
39
+ if(selection&&ids.size!==selection.length)throw new Error('Invalid import selection.');
40
+ // Only canonical titles from discovery are passed back to the provider.
41
+ const chosen=selection?this.items.filter(item=>ids.has(item.id)):undefined;
42
+ this.request=String(++this.serial);this.approved=ids;this.chats.clear();this.bytes=0;
43
+ this.filesApproved=this.rawOnly&&!!chosen&&options.includeFiles===true;
44
+ this.state(selection?'importing':'scanning',{items:chosen||[],completed:0,total:chosen?.length||0,message:selection?'Importing selected chats…':'Finding chat titles…'});
45
+ await this.plugin.setNativeImportVisible({sessionId:this.sessionId,visible:false});this.assertActive();
46
+ const headers=await this.services.requireAccess(this.control.signal,this.platform);this.assertActive();
47
+ if(headers.Authorization!==this.authorization)throw new Error('Your Onairos account changed. Sign in again.');
48
+ if(this.filesApproved)this.fileTransfer=await this.services.createFiles(this.platform,[...ids],this.control.signal);
49
+ this.assertActive();
50
+ await this.run(createNativeImportScript(this.request,chosen,{platform:this.platform,includeFiles:this.filesApproved,fileDelivery:'temporary'}));
51
+ clearTimeout(this.watchdog);this.watchdog=setTimeout(()=>void this.fail(new Error('The import took too long. Please retry.')),selection?(this.filesApproved?905000:Math.min(905000,Math.max(125000,chosen.length*22000+5000))):30000);
52
+ }
53
+ async receive(event){
54
+ if(!this.active||event.sessionId!==this.sessionId)return;
55
+ const session=parseNativeSessionMessage(event.raw,event.origin,this.sessionId,this.platform);
56
+ if(session){if(session==='authenticated'&&this.stage==='login')await this.begin();return;}
57
+ const message=parseNativeImportMessage(event.raw,event.origin,this.request,this.platform);if(!message)return;
58
+ if(message.type==='error')throw new Error({sign_in:'Finish provider sign-in and retry.',timeout:'The provider took too long. Please retry.',network:'The provider connection was interrupted.',rate_limited:'The provider is limiting requests. Wait and try fewer chats.',conversation_unavailable:'A selected chat is no longer available. Try another selection.'}[message.code]||'The provider could not complete this import. Please retry.');
59
+ if(message.type==='titles'&&this.stage==='scanning'){
60
+ clearTimeout(this.watchdog);this.request='';if(!message.items.length)throw new Error('There are no conversations in this account yet.');
61
+ this.items=message.items;await this.plugin.setNativeImportVisible({sessionId:this.sessionId,visible:false});this.assertActive();this.state('topics',{items:this.items});return;
62
+ }
63
+ if(this.stage!=='importing')return;
64
+ if('sequence' in message){await this.receiveFile(message);return;}
65
+ if(message.type==='conversation'&&this.approved.has(message.conversation.conversationId)){
66
+ this.bytes+=event.raw.length*2;if(this.bytes>20_000_000)throw new Error('This selection is too large. Select fewer chats.');
67
+ this.chats.set(message.conversation.conversationId,message.conversation);
68
+ }else if(message.type==='item'&&this.approved.has(message.id))this.onState({item:message});
69
+ else if(message.type==='progress')this.onState({completed:message.completed,total:message.total,message:'Reading selected chats…'});
70
+ else if(message.type==='cooldown')this.onState({message:'Waiting for the provider’s rate limit…'});
71
+ else if(message.type==='complete')await this.complete();
72
+ }
73
+ async receiveFile(message){
74
+ if(!this.filesApproved||!this.fileTransfer||!this.approved.has(message.conversationId)||this.fileBusy||message.sequence!==this.fileSequence+1)throw new Error('Invalid file transfer sequence.');
75
+ this.fileBusy=true;
76
+ try{
77
+ const chat=this.chats.get(message.conversationId);if(!chat)throw new Error('Missing selected conversation.');
78
+ if(message.type==='file_start'){
79
+ if(this.activeFile)throw new Error('File transfer already active.');
80
+ this.activeFile={id:await this.fileTransfer.begin({...message.file,conversationId:chat.conversationId,conversationTitle:chat.title}),conversationId:chat.conversationId};
81
+ }else{
82
+ if(!this.activeFile||this.activeFile.conversationId!==message.conversationId)throw new Error('Invalid file transfer order.');
83
+ if(message.type==='file_chunk')await this.fileTransfer.chunk(this.activeFile.id,message.index,message.data);
84
+ else{const file=await this.fileTransfer.finish(this.activeFile.id);chat.files=[...(chat.files||[]),file];this.activeFile=null;}
85
+ }
86
+ this.assertActive();this.fileSequence=message.sequence;
87
+ await this.run(`window.__onairosFileAck && window.__onairosFileAck(${JSON.stringify(this.request)},${message.sequence},true);true;`);
88
+ }finally{this.fileBusy=false;}
89
+ }
90
+ async complete(){
91
+ if(this.stage!=='importing')return;
92
+ if(this.activeFile||this.fileBusy)throw new Error('A file did not finish transferring.');
93
+ this.request='';clearTimeout(this.watchdog);
94
+ const conversations=[...this.approved].flatMap(id=>{const chat=this.chats.get(id);return chat&&(chat.messages.length||chat.files?.length)?[chat]:[];});
95
+ if(!conversations.length)throw new Error('No readable chats were imported. Choose another selection.');
96
+ this.state('saving',{message:this.rawOnly?'Privacy-checking your chats…':'Saving selected chats…',completed:0,total:conversations.length});
97
+ const fileDelivery=this.fileTransfer?await this.fileTransfer.complete():undefined;this.assertActive();
98
+ let payload;
99
+ if(this.rawOnly){
100
+ const protectedPayload=await this.services.protect({platform:this.platform,ephemeral:true,persisted:false,conversations:conversations.map(({files,...chat})=>chat)},this.control.signal,this.authorization);
101
+ this.assertActive();payload=attachRawExportDelivery(protectedPayload,fileDelivery);
102
+ }else await this.services.store(conversations,this.control.signal,(completed,total,id)=>this.onState({completed,total,item:id?{id,status:'done'}:undefined}),id=>this.onState({item:{id,status:'importing'}}),this.platform,this.authorization);
103
+ this.assertActive();
104
+ try{await this.run(createNativeSignOutScript(this.platform,this.sessionId));}catch{}
105
+ this.assertActive();this.chats.clear();await this.plugin.finishNativeImport({sessionId:this.sessionId});
106
+ this.assertActive();this.state('complete',{message:'Import complete',completed:conversations.length,total:conversations.length});await this.onComplete(payload);await this.dispose();
107
+ }
108
+ async fail(error){
109
+ if(!this.active)return;
110
+ this.control.abort();clearTimeout(this.watchdog);this.request='';this.chats.clear();
111
+ try{await this.fileTransfer?.cancel();}catch{}
112
+ try{await this.plugin.finishNativeImport({sessionId:this.sessionId});}catch{}
113
+ this.state('error',{error:error?.message||'Import failed. Please retry.',code:error?.code});await this.dispose();
114
+ }
115
+ async dispose(){this.active=false;clearTimeout(this.watchdog);this.control.abort();this.chats.clear();const handles=this.listeners.splice(0);await Promise.all(handles.map(handle=>Promise.resolve(handle.remove()).catch(()=>{})));}
116
+ async cancel(notify=false){
117
+ if(!this.active)return;this.active=false;this.control.abort();clearTimeout(this.watchdog);this.request='';this.chats.clear();
118
+ try{await this.run(CANCEL_NATIVE_IMPORT);}catch{}
119
+ try{await this.fileTransfer?.cancel();}catch{}
120
+ try{await this.plugin.finishNativeImport({sessionId:this.sessionId});}catch{}
121
+ await this.dispose();if(notify)this.onCancel();
122
+ }
123
+ }
@@ -0,0 +1,57 @@
1
+ import React,{useEffect,useRef,useState} from 'react';
2
+ import {OnairosSpotifyNative,OnairosChatGPTNative} from '../nativeConnectors.js';
3
+ import {getRequiredUserAuthHeaders,getApiKey} from '../utils/authHeaders.js';
4
+ import {API_CONFIG} from './rn/config/api.js';
5
+ import ImportProgress,{IMPORT_SUCCESS_HOLD_MS} from './ImportProgress.jsx';
6
+ import ConnectorLoading from './ConnectorLoading.jsx';
7
+ import {NativeAction} from '../components/parity/NativeScreens.jsx';
8
+ import {storeCustomPayload} from './customPayload.js';
9
+ import {CustomImportSession} from './CustomImportSession.js';
10
+
11
+ export default function NativeScraperImport({platform,onClose,onConnected}){
12
+ const name={spotify:'Spotify',netflix:'Netflix',sephora:'Sephora','instagram-data':'Instagram',hinge:'Hinge'}[platform];
13
+ const [view,setView]=useState({stage:'login',completed:0,total:100}),[attempt,setAttempt]=useState(0);
14
+ const callbacks=useRef({onClose,onConnected});callbacks.current={onClose,onConnected};
15
+ const cancel=useRef(()=>{});
16
+ useEffect(()=>{
17
+ let active=true,listener,timer,flow,stop=()=>{};const control=new AbortController();
18
+ const sessionId=globalThis.crypto?.randomUUID?.()||`spotify-${Date.now()}-${Math.random().toString(36).slice(2)}`;
19
+ const state=patch=>{if(active)setView(old=>({...old,...patch}));};
20
+ const done=()=>{state({stage:'complete',completed:100});timer=setTimeout(()=>{if(active)callbacks.current.onConnected();},IMPORT_SUCCESS_HOLD_MS);};
21
+ if(platform!=='spotify'){
22
+ flow=new CustomImportSession({plugin:OnairosChatGPTNative,platform,onState:state,onComplete:done,onCancel:()=>callbacks.current.onClose()});
23
+ stop=()=>flow.cancel();cancel.current=stop;void flow.start();
24
+ }else{
25
+ stop=()=>OnairosSpotifyNative.closeSpotifyConnector({sessionId}).catch(()=>{});cancel.current=stop;
26
+ void(async()=>{
27
+ try{
28
+ const headers=getRequiredUserAuthHeaders({requireToken:true});
29
+ listener=await OnairosSpotifyNative.addListener('onairosNativeConnectorEvent',event=>{
30
+ if(!active||event.platform!=='spotify'||event.sessionId!==sessionId)return;
31
+ const progress=event.status==='extracting'&&typeof event.progress==='number'?Math.max(5,Math.min(89,event.progress)):{authenticated:18,authenticating:30,extracting:64,uploading:90}[event.status];
32
+ if(progress!==undefined)state({stage:'importing',completed:progress});
33
+ if(event.status==='waiting_for_login')state({stage:'login'});
34
+ });
35
+ if(!active){await listener.remove();return;}
36
+ const result=await OnairosSpotifyNative.connectSpotifyNative({sessionId,jwtToken:headers.Authorization.replace(/^Bearer /,''),apiKey:getApiKey(),baseUrl:API_CONFIG.getBaseUrl(),useHostImportUI:true});
37
+ if(!active){await stop();return;}
38
+ if(result?.extracted!==true)throw new Error('Spotify did not confirm extraction.');
39
+ state({stage:'saving',completed:90});
40
+ const saveTimeout=setTimeout(()=>control.abort(),45000);
41
+ let saved;try{saved=await storeCustomPayload('spotify',result.data,{signal:control.signal,authorization:headers.Authorization});}finally{clearTimeout(saveTimeout);}
42
+ if(!active)return;
43
+ if(getRequiredUserAuthHeaders({requireToken:true}).Authorization!==headers.Authorization)throw new Error('Your Onairos account changed. Please retry.');
44
+ state({count:saved.count});done();
45
+ }catch(error){if(active)state({stage:'error',error:error?.message||'Could not connect Spotify. Please retry.'});}
46
+ })();
47
+ }
48
+ return()=>{active=false;control.abort();clearTimeout(timer);void listener?.remove();void stop();};
49
+ },[platform,attempt]);
50
+ const close=()=>{void cancel.current();callbacks.current.onClose();};
51
+ const noun=platform==='spotify'?'song':platform==='netflix'?'title':'item';
52
+ const label=view.stage==='complete'?(view.count?`${view.count} ${view.count===1?`${noun} has`:`${noun}s have`} been successfully connected`:`${name} connected`):view.completed>=90?`Privacy-checking your ${platform==='spotify'?'listening':platform==='netflix'?'viewing':'activity'} history…`:'Preparing your memories';
53
+ return <div className="rn-import-overlay" role="dialog" aria-modal="true" aria-label={`${name} import`}>
54
+ <header className="rn-import-header"><button aria-label={`Close ${name}`} onClick={close}>×</button><strong>Onairos</strong><span/></header>
55
+ {view.stage==='error'?<section className="rn-import-progress"><h1>Let’s try that again</h1><p role="alert">{view.error}</p><NativeAction onClick={()=>{setView({stage:'login',completed:0,total:100});setAttempt(v=>v+1);}}>Try again</NativeAction></section>:view.stage==='login'?<ConnectorLoading provider={name}/>:<ImportProgress provider={name} completed={view.completed} total={100} label={label} success={view.stage==='complete'}/>}
56
+ </div>;
57
+ }
@@ -0,0 +1,28 @@
1
+ import React,{useMemo,useState} from 'react';
2
+ import {clusterImportTitles,filterImportTitleExclusions,importTopicDateRange} from './rn/utils/nativeImportTopics.js';
3
+ import logo from '../assets/permissions/onairos.png';
4
+ import ImportIcon,{NativeImportCategoryIcon} from './ImportIcon.jsx';
5
+ import claude from '../assets/connectors/claude.png';
6
+ import chatgpt from '../assets/connectors/chatgpt.png';
7
+ import {NativeAction,NativeInfoIcon} from '../components/parity/NativeScreens.jsx';
8
+
9
+ export default function SmartFilter({items,provider='ChatGPT',onImport,onClose,filesAvailable=false,defaultSelected}){
10
+ const topics=useMemo(()=>clusterImportTitles(items),[items]);
11
+ const [selected,setSelected]=useState(()=>new Set(defaultSelected||topics.filter(t=>!t.sensitive).flatMap(t=>t.conversationIds)));
12
+ const [expanded,setExpanded]=useState(new Set()),[exclusions,setExclusions]=useState(''),[showExclusions,setShowExclusions]=useState(false),[files,setFiles]=useState(false);
13
+ const chosen=filterImportTitleExclusions(items.filter(item=>selected.has(item.id)),exclusions),chosenIds=new Set(chosen.map(item=>item.id));
14
+ const toggle=ids=>setSelected(previous=>{const next=new Set(previous),all=ids.every(id=>next.has(id));ids.forEach(id=>all?next.delete(id):next.add(id));return next;});
15
+ return <section className="rn-screen rn-smart-filter" aria-label="Smart Filter">
16
+ <header className="rn-import-header"><button aria-label={`Close ${provider}`} onClick={onClose}>×</button><strong>Onairos</strong><span/></header>
17
+ <div className="rn-import-heading"><div className="rn-import-brands"><span><img src={provider==='Claude'?claude:chatgpt} alt={provider}/></span><i className="rn-connection-line" aria-hidden="true">{['#FF765F','#FFC77F','#D7B3BD','#8AA4FF','#A594FC','#BD7BFF'].map((color,i)=><b key={color} style={{background:color,'--dash-index':i}}/>)}</i><span><img src={logo} alt="Onairos"/></span></div><h1>Choose what to import</h1><p>Pick the chats you want to share with Onairos</p></div>
18
+ <div className="rn-import-selection"><span aria-live="polite">{chosen.length} {chosen.length===1?'chat':'chats'} selected</span><button onClick={()=>toggle(items.map(x=>x.id))}>{items.every(x=>selected.has(x.id))?'Deselect all':'Select all'}</button></div>
19
+ <div className="rn-import-topics" tabIndex={0}>{topics.map(topic=>{
20
+ const chats=items.filter(x=>topic.conversationIds.includes(x.id)),count=chats.filter(x=>chosenIds.has(x.id)).length,open=expanded.has(topic.id),date=importTopicDateRange(chats);
21
+ return <section key={topic.id}><div className="rn-topic-heading"><button className="rn-topic-title" role="checkbox" aria-checked={count>0} aria-label={topic.label} onClick={()=>toggle(topic.conversationIds)}><span className="rn-topic-symbol" aria-hidden="true"><NativeImportCategoryIcon label={topic.label} size={19}/></span><span className="rn-topic-meta"><span className="rn-topic-label-row"><strong>{topic.label}</strong>{date&&<small>{date}</small>}</span><small>{count}/{chats.length}{topic.sensitive?' · Sensitive':''}</small></span></button><button aria-label={`${open?'Hide':'Show'} chats in ${topic.label}`} aria-expanded={open} onClick={()=>setExpanded(old=>{const next=new Set(old);open?next.delete(topic.id):next.add(topic.id);return next;})}><span className={`rn-topic-chevron ${open?'is-open':''}`}><ImportIcon name="chevron" size={12} color="#737B89"/></span></button><button role="checkbox" aria-checked={count>0} aria-label={`Select chats in ${topic.label}`} className={`rn-import-check ${count?'is-checked':''}`} onClick={()=>toggle(topic.conversationIds)}>{count?'✓':''}</button></div>
22
+ <div className={`rn-topic-disclosure ${open?'is-open':''}`} aria-hidden={!open} inert={!open?'':undefined}><div>{chats.map(chat=><button key={chat.id} className="rn-topic-chat" role="checkbox" aria-label={chat.title} aria-checked={chosenIds.has(chat.id)} onClick={()=>toggle([chat.id])}><span className={`rn-import-check ${chosenIds.has(chat.id)?'is-checked':''}`}>{chosenIds.has(chat.id)?'✓':''}</span><span>{chat.title}<small>{importTopicDateRange([chat])}</small></span></button>)}</div></div></section>;
23
+ })}</div>
24
+ {filesAvailable&&<label className="rn-import-files"><input type="checkbox" checked={files} onChange={e=>setFiles(e.target.checked)}/><span><strong>Files · Optional</strong><small>Attachments from selected chats are transferred to temporary storage for this app to download.</small><small>Up to 25 MiB each · 100 MiB per connector</small></span></label>}
25
+ <footer className="rn-import-footer"><button className="rn-exclude-toggle" aria-expanded={showExclusions} onClick={()=>setShowExclusions(v=>!v)}>Exclude specific things</button>{showExclusions&&<><textarea aria-label="Exclude title phrases" placeholder="e.g. therapy, my startup, medical" value={exclusions} onChange={e=>setExclusions(e.target.value)}/><p>Leave out titles containing these comma-separated phrases. Only selected conversation text is imported.</p></>}
26
+ {!!importTopicDateRange(items,true)&&<p>All chats shown: {importTopicDateRange(items,true)}</p>}<p className="rn-import-privacy"><ImportIcon name="lock" size={12} color="#9aa0ab"/><span>Sensitive topics are off by default and never shared unless you turn them on.</span> <a href="https://privacy.onairos.io" target="_blank" rel="noreferrer" aria-label="About Smart Filter privacy"><NativeInfoIcon/></a></p><NativeAction disabled={!chosen.length} onClick={()=>onImport(chosen,{includeFiles:files})}>Import selected</NativeAction></footer>
27
+ </section>;
28
+ }
@@ -0,0 +1,37 @@
1
+ import {buildPayload as spotifyPayload} from './rn/services/spotifyPayload.js';
2
+ import {buildPayload as netflixPayload} from './rn/services/netflixPayload.js';
3
+ import {buildPayload as sephoraPayload} from './rn/services/sephoraPayload.js';
4
+ import {buildPayload as hingePayload} from './rn/services/hingePayload.js';
5
+ import {getRequiredUserAuthHeaders,getApiKey} from '../utils/authHeaders.js';
6
+ import {API_CONFIG} from './rn/config/api.js';
7
+ const array=value=>Array.isArray(value)?value:[];
8
+ const pick=(value,keys)=>Object.fromEntries(keys.filter(key=>value?.[key]!==undefined).map(key=>[key,value[key]]));
9
+ export function buildCustomPayload(platform,data){
10
+ if(!data||typeof data!=='object'||Array.isArray(data))throw new Error('The provider returned invalid activity.');
11
+ if(platform==='spotify'){
12
+ const tracks=items=>array(items).filter(t=>t?.trackId&&t?.name).map(t=>pick(t,['trackId','name','artists','album','albumId','popularity','duration','playedAt','savedAt','imageUrl','previewUrl','explicit']));
13
+ const saved=tracks(data.savedTracks),recent=saved.length?[]:tracks(data.tracks);
14
+ return spotifyPayload({savedTracks:saved,recentlyPlayed:{items:recent},topItems:{tracks:[],artists:[],timeRange:'medium_term'},playlists:[],savedAlbums:[],profile:data.profile,userId:data.userId});
15
+ }
16
+ if(platform==='netflix')return netflixPayload({viewingHistory:{items:array(data.viewingHistory).filter(x=>x?.videoId&&x?.title)},myList:[],ratings:[],profile:data.profile});
17
+ if(platform==='sephora')return sephoraPayload({basket:data.basket,loves:array(data.loves),purchases:array(data.purchases),profile:data.profile,profileId:data.profileId});
18
+ if(platform==='hinge')return hingePayload({matches:array(data.matches),chats:array(data.chats).filter(x=>x?.match_id&&Array.isArray(x.user_messages))});
19
+ if(platform==='instagram-data')return {likes:array(data.likes).map(x=>pick(x,['id','caption','owner','mediaType','url','likedAt'])),savedPosts:array(data.savedPosts).map(x=>pick(x,['id','caption','owner','mediaType','url','likedAt'])),following:array(data.following).map(x=>pick(x,['id','username','fullName']))};
20
+ throw new Error('Unsupported native scraper.');
21
+ }
22
+ export function customPayloadCount(platform,body){
23
+ const d=body.data||body;
24
+ return platform==='spotify'?d.savedTracks.length+d.recentlyPlayed.length:platform==='netflix'?d.viewingHistory.length:platform==='sephora'?d.basket.items.length+d.loves.length+d.purchasedItems.length:platform==='hinge'?d.matches.length+d.chats.length:array(d.likes).length+array(d.savedPosts).length+array(d.following).length;
25
+ }
26
+ export async function storeCustomPayload(platform,data,{signal,authorization,fetchImpl=fetch}={}){
27
+ const body=buildCustomPayload(platform,data),count=customPayloadCount(platform,body);
28
+ if(!count)throw new Error(platform==='netflix'?'Netflix’s viewing history could not be read. Please retry.':'No activity was available to import. Check your account and try again.');
29
+ const headers=getRequiredUserAuthHeaders({requireToken:true});
30
+ if(authorization&&headers.Authorization!==authorization)throw new Error('Your Onairos account changed. Please retry.');
31
+ const key=getApiKey();if(key)headers['x-api-key']=key;
32
+ const response=await fetchImpl(`${API_CONFIG.getBaseUrl()}${platform==='instagram-data'?'/instagram-sync':'/platform-data/store'}`,{method:'POST',headers:{...headers,'Content-Type':'application/json'},body:JSON.stringify(body),signal});
33
+ const result=await response.json();
34
+ if(!response.ok||result?.success!==true)throw new Error('Your activity could not be saved. Please try again.');
35
+ if(signal?.aborted)throw new Error('Import cancelled.');
36
+ return {count};
37
+ }
@@ -0,0 +1,30 @@
1
+ import {readNetflixHistory} from './netflixHistory.js';
2
+
3
+ // Keep RN's two-page bound, result shape and bridge contract while reading the
4
+ // current Netflix history UI rather than its retired .retableRow markup.
5
+ export const NETFLIX_RENDERED_EXPORT_SCRIPT=`
6
+ (async function(){
7
+ var post=function(value){window.ReactNativeWebView.postMessage(JSON.stringify(value));};
8
+ var read=${readNetflixHistory.toString()};
9
+ try{
10
+ var origin=window.location.origin;
11
+ if(origin!=='https://www.netflix.com')return;
12
+ var items=read(document,origin),pages=1;
13
+ if(!items.length){post({type:'NETFLIX_EXPORT_ERROR',code:'HISTORY_UNREADABLE'});return;}
14
+ post({type:'NETFLIX_EXPORT_PROGRESS',stage:'history',progress:20});
15
+ var more=Array.from(document.querySelectorAll('button,a[role="button"]')).find(function(button){return /^show more$/i.test((button.textContent||'').trim())&&!button.disabled;});
16
+ if(more){
17
+ var initial=items.length;more.click();
18
+ for(var attempt=0;attempt<20;attempt++){
19
+ await new Promise(function(resolve){setTimeout(resolve,250);});
20
+ var next=read(document,origin);
21
+ if(next.length>initial){items=next;pages=2;break;}
22
+ }
23
+ }
24
+ var profileName='unknown';
25
+ try{var user=window.netflix.reactContext.models.memberContext.data.userInfo;profileName=user.profileName||user.name||user.accountOwnerName||'unknown';}catch(_){}
26
+ post({type:'NETFLIX_EXPORT_PROGRESS',stage:'complete',progress:95});
27
+ post({type:'NETFLIX_EXPORT_COMPLETE',success:true,status:'success',data:{viewingHistory:items,profile:{profileName:profileName},summary:{totalItems:items.length,totalPages:pages,profileName:profileName}}});
28
+ }catch(_){post({type:'NETFLIX_EXPORT_ERROR',code:'HISTORY_UNREADABLE'});}
29
+ })();true;
30
+ `;
@@ -0,0 +1,28 @@
1
+ // Self-contained so the same parser can run in the private provider browser.
2
+ export function readNetflixHistory(doc,origin){
3
+ var records=[],seen=new Set();
4
+ function videoId(link){
5
+ try{var url=new URL(link.getAttribute('href'),origin);return url.origin===origin&&url.pathname.match(/^\/(?:title|watch)\/(\d+)(?:\/|$)/)?.[1];}catch{return null;}
6
+ }
7
+ Array.from(doc.querySelectorAll('a[href]')).forEach(function(link){
8
+ var id=videoId(link),title=(link.textContent||'').trim();if(!id||!title)return;
9
+ var date='',container=link.parentElement;
10
+ for(var depth=0;container&&container!==doc.body&&depth<8;depth++,container=container.parentElement){
11
+ var links=Array.from(container.querySelectorAll('a[href]')).filter(videoId);
12
+ if(links.length>1)break;
13
+ var legacyDate=container.querySelector('.col.date');
14
+ if(legacyDate){date=(legacyDate.textContent||'').trim();break;}
15
+ var walker=doc.createTreeWalker(container,4),node;
16
+ while((node=walker.nextNode())){
17
+ if(link.contains(node))continue;
18
+ var match=(node.textContent||'').match(/\b(?:\d{1,2}\/\d{1,2}\/\d{2,4}|\d{4}-\d{2}-\d{2})\b/);
19
+ if(match){date=match[0];break;}
20
+ }
21
+ if(date)break;
22
+ }
23
+ if(!date)return;
24
+ var key=id+'|'+date+'|'+title;if(seen.has(key))return;seen.add(key);
25
+ records.push({videoId:id,title:title,date:date,type:title.includes(':')?'series':'movie'});
26
+ });
27
+ return records;
28
+ }
@@ -0,0 +1,59 @@
1
+ import {readNetflixHistory} from './netflixHistory.js';
2
+ // Mobile Netflix can finish sign-in on its app-promotion page instead of /browse.
3
+ // Observe authenticated controls and rendered history; extraction stays in its
4
+ // separate RN-compatible export adapter.
5
+ export const NETFLIX_SESSION_SCRIPT = String.raw`
6
+ (function () {
7
+ if (window.location.origin !== 'https://www.netflix.com') return;
8
+ if (window.__onairosNetflixSession) { window.__onairosNetflixSession(); return; }
9
+ var sentPath = null, historySent = false, navigating = false;
10
+ var readHistory = ${readNetflixHistory.toString()};
11
+ function check() {
12
+ if (!document.body) return;
13
+ var picker = document.querySelector('.profiles-gate-container, .profile-gate-label');
14
+ if (picker) {
15
+ var style = window.getComputedStyle(picker);
16
+ if (style.display !== 'none' && style.visibility !== 'hidden') return;
17
+ }
18
+ var path = window.location.pathname;
19
+ var historyPage = /^\/(viewingactivity|settings\/viewed)\/?$/i.test(path) || Array.from(document.querySelectorAll('h1,h2')).some(function(heading){return /^(watch history and ratings|viewing activity)$/i.test((heading.textContent||'').trim());});
20
+ if (historyPage) {
21
+ if (!historySent && readHistory(document,window.location.origin).length) {
22
+ historySent = true;
23
+ window.ReactNativeWebView.postMessage(JSON.stringify({type:'NETFLIX_AUTH_STATE',authenticated:true,path:path,historyReady:true}));
24
+ }
25
+ return;
26
+ }
27
+ if (window.__onairosNetflixPrepare && !navigating && !/^\/(login|signin|signup|logout|signout|loginhelp)(\/|$)/i.test(path)) {
28
+ navigating = true;
29
+ // The host hides this window before it acknowledges with navigation.
30
+ window.ReactNativeWebView.postMessage(JSON.stringify({type:'NETFLIX_AUTH_STATE',authenticated:true,path:path,profileReady:true}));
31
+ return;
32
+ }
33
+ var signOut = false, account = false;
34
+ document.querySelectorAll('a[href]').forEach(function (link) {
35
+ try {
36
+ var url = new URL(link.getAttribute('href'), window.location.origin);
37
+ if (url.origin !== window.location.origin) return;
38
+ if (/^\/(signout|logout)\/?$/i.test(url.pathname)) signOut = true;
39
+ if (/^\/(youraccount|account)(\/|$)/i.test(url.pathname)) account = true;
40
+ } catch (_) {}
41
+ });
42
+ if (signOut && account && sentPath !== path) {
43
+ sentPath = path;
44
+ window.ReactNativeWebView.postMessage(JSON.stringify({type:'NETFLIX_AUTH_STATE',authenticated:true,path:path}));
45
+ }
46
+ }
47
+ window.__onairosNetflixSession = check;
48
+ var observer = new MutationObserver(check);
49
+ var observationOptions = {childList:true,subtree:true,attributes:true,attributeFilter:['href','class','style']};
50
+ observer.observe(document, observationOptions);
51
+ window.addEventListener('DOMContentLoaded', check);
52
+ window.addEventListener('pageshow', function () { observer.observe(document, observationOptions); check(); });
53
+ window.addEventListener('pagehide', function () { observer.disconnect(); });
54
+ check();
55
+ })();
56
+ true;
57
+ `;
58
+
59
+ export const NETFLIX_PREPARE_SCRIPT = `window.__onairosNetflixPrepare=true;window.__onairosNetflixSession();true;`;
@@ -0,0 +1,7 @@
1
+ /** Only decorate the host callback result, after persistence/logging boundaries. */
2
+ export function attachNativeRawExports(result,records,authorization){
3
+ const approved=(result?.approved||[]).includes('rawMemories');
4
+ const authorized=result?.authorizedData?.rawMemories===true;
5
+ const payloads=approved&&authorized?records.filter(record=>record.authorization===authorization).map(record=>record.payload):[];
6
+ return payloads.length?{...result,ephemeralPayloads:payloads,...(payloads.length===1?{ephemeralPayload:payloads[0]}:{})}:result;
7
+ }
@@ -0,0 +1,5 @@
1
+ // Capacitor auth adapter for the synced RN import services.
2
+ import {API_CONFIG as config} from '../../../config/api-config.js';
3
+ import {getRequiredUserAuthHeaders} from '../../../utils/authHeaders.js';
4
+ export const API_CONFIG={getBaseUrl:()=>window.onairosBaseUrl||config.getBaseUrl()};
5
+ export async function getUserAuthHeaders(){return getRequiredUserAuthHeaders({requireToken:true});}
@@ -0,0 +1,2 @@
1
+ // Capacitor auth adapter; no credentials are copied into provider WebViews.
2
+ export {getApiKey} from '../../../utils/authHeaders.js';
@@ -0,0 +1,37 @@
1
+ // Generated pure mapping from RN services/hingeDataService.ts.
2
+ export function buildPayload(data){
3
+ const Platform={OS:"ios"};
4
+ const mobileMetadata = {
5
+ platform: Platform.OS,
6
+ appVersion: "1.0.0",
7
+ osVersion: Platform.OS === "ios" ? "17.0" : Platform.OS,
8
+ deviceModel: Platform.OS === "ios" ? "iPhone" : "Android",
9
+ isOfflineSync: false,
10
+ extractedAt: (/* @__PURE__ */new Date()).toISOString()
11
+ };
12
+ const requestBody = {
13
+ platform: "mobile-hinge",
14
+ dataType: "dating",
15
+ data: {
16
+ matches: data.matches,
17
+ chats: data.chats.map(chat => ({
18
+ matchId: chat.match_id,
19
+ matchName: chat.match_name,
20
+ messages: chat.user_messages.map((msg, idx) => ({
21
+ id: `${chat.match_id}-msg-${idx}`,
22
+ content: msg.content,
23
+ timestamp: msg.timestamp || (/* @__PURE__ */new Date()).toISOString(),
24
+ role: "user"
25
+ })),
26
+ totalMessages: chat.total_messages
27
+ }))
28
+ },
29
+ summary: {
30
+ matchCount: data.matches.length,
31
+ chatCount: data.chats.length,
32
+ totalUserMessages: data.chats.reduce((sum, c) => sum + c.user_messages.length, 0)
33
+ },
34
+ mobileMetadata
35
+ };
36
+ return requestBody;
37
+ }
@@ -0,0 +1,138 @@
1
+ // Synced from RN services/nativeConversationImport.ts by scripts/sync-rn-connectors.cjs.
2
+ import { API_CONFIG, getUserAuthHeaders } from "../config/api.js";
3
+ import { requireRawMemoryAccess } from "./rawMemoryPolicy.js";
4
+ import { sanitizeNativeMetadata } from "../utils/nativeImportMetadata.js";
5
+ function backendTimestamp(value) {
6
+ if (value === void 0 || value === null) return void 0;
7
+ const date = new Date(typeof value === "number" ? value < 1e12 ? value * 1e3 : value : String(value));
8
+ return Number.isFinite(date.getTime()) ? date.toISOString() : void 0;
9
+ }
10
+ function assertActive(signal) {
11
+ if (signal.aborted) throw new Error("Import cancelled.");
12
+ }
13
+ function sessionExpired() {
14
+ return Object.assign(new Error("Your Onairos login expired. Sign in to Onairos again before importing chats."), { code: "ONAIROS_SESSION_EXPIRED" });
15
+ }
16
+ async function requireNativeConversationAccess(signal, platform = "chatgpt") {
17
+ assertActive(signal);
18
+ await requireRawMemoryAccess(platform, signal);
19
+ assertActive(signal);
20
+ let headers;
21
+ try {
22
+ headers = await getUserAuthHeaders();
23
+ } catch {
24
+ throw sessionExpired();
25
+ }
26
+ assertActive(signal);
27
+ const check = new AbortController();
28
+ const abort = () => check.abort();
29
+ signal.addEventListener("abort", abort);
30
+ const timeout = setTimeout(abort, 15e3);
31
+ try {
32
+ const base = (API_CONFIG.getBaseUrl ? API_CONFIG.getBaseUrl() : API_CONFIG.BASE_URL).replace(/\/$/, "");
33
+ const response = await fetch(`${base}/llm-data/stats`, { headers, signal: check.signal });
34
+ assertActive(signal);
35
+ if (response.status === 401) throw sessionExpired();
36
+ const result = await response.json().catch(() => null);
37
+ if (!response.ok || result?.success !== true) {
38
+ throw Object.assign(new Error("Login verification is temporarily unavailable. Please try again."), { code: "ONAIROS_SESSION_CHECK_UNAVAILABLE", status: response.status });
39
+ }
40
+ } finally {
41
+ clearTimeout(timeout);
42
+ signal.removeEventListener("abort", abort);
43
+ }
44
+ return headers;
45
+ }
46
+ async function storeNativeConversations(conversations, signal, onProgress = () => {
47
+ }, onSaving = () => {
48
+ }, platform = "chatgpt", expectedAuthorization) {
49
+ const readable = conversations.filter((chat) => chat.messages.some((message) => message.content.trim()));
50
+ if (!readable.length) throw new Error("No readable conversations to save.");
51
+ if (conversations.some((chat) => chat.platform && chat.platform !== platform)) throw new Error("Conversation provider does not match this import.");
52
+ const headers = await requireNativeConversationAccess(signal, platform);
53
+ if (expectedAuthorization && headers.Authorization !== expectedAuthorization) throw sessionExpired();
54
+ const base = (API_CONFIG.getBaseUrl ? API_CONFIG.getBaseUrl() : API_CONFIG.BASE_URL).replace(/\/$/, "");
55
+ let completed = 0, cursor = 0;
56
+ const group = new AbortController();
57
+ const cancelGroup = () => group.abort();
58
+ signal.addEventListener("abort", cancelGroup);
59
+ if (signal.aborted) cancelGroup();
60
+ onProgress(0, readable.length);
61
+ const worker = async () => {
62
+ while (cursor < readable.length) {
63
+ assertActive(group.signal);
64
+ const chat = readable[cursor++];
65
+ const request = new AbortController();
66
+ const abort = () => request.abort();
67
+ group.signal.addEventListener("abort", abort);
68
+ const timeout = setTimeout(abort, 3e4);
69
+ try {
70
+ const currentHeaders = await getUserAuthHeaders().catch(() => {
71
+ throw sessionExpired();
72
+ });
73
+ assertActive(group.signal);
74
+ if (currentHeaders.Authorization !== headers.Authorization) throw sessionExpired();
75
+ onSaving(chat.conversationId);
76
+ const response = await fetch(`${base}/llm-data/store`, {
77
+ method: "POST",
78
+ signal: request.signal,
79
+ headers: { ...headers, "Content-Type": "application/json" },
80
+ body: JSON.stringify({
81
+ platform: `mobile-${platform}`,
82
+ memoryType: "conversation",
83
+ conversationData: {
84
+ conversationId: chat.conversationId,
85
+ messages: chat.messages.filter((message) => message.content.trim()).map((message) => ({
86
+ id: message.id,
87
+ role: message.role,
88
+ content: message.content,
89
+ timestamp: backendTimestamp(message.timestamp),
90
+ parent: message.prevMessageId,
91
+ updatedAt: backendTimestamp(message.updatedAt),
92
+ contentType: message.contentType,
93
+ channel: message.channel,
94
+ recipient: message.recipient,
95
+ status: message.status,
96
+ metadata: sanitizeNativeMetadata({ ...message.metadata, model_slug: message.modelSlug || message.metadata?.model_slug })
97
+ })),
98
+ context: {
99
+ title: chat.title,
100
+ create_time: chat.createdAt,
101
+ update_time: chat.updatedAt,
102
+ providerMetadata: sanitizeNativeMetadata({ ...chat.metadata, model_slug: chat.modelSlug || chat.metadata?.model_slug })
103
+ },
104
+ metadata: sanitizeNativeMetadata({ ...chat.metadata, model_slug: chat.modelSlug || chat.metadata?.model_slug })
105
+ }
106
+ })
107
+ });
108
+ assertActive(group.signal);
109
+ const result = await response.json().catch(() => null);
110
+ if (!response.ok || result?.success !== true) {
111
+ if (response.status === 401) throw sessionExpired();
112
+ throw new Error(response.status === 403 ? "This app cannot save these chats. Check its import access." : "Some chats could not be saved. Retry the import to finish connecting.");
113
+ }
114
+ const finalHeaders = await getUserAuthHeaders().catch(() => {
115
+ throw sessionExpired();
116
+ });
117
+ assertActive(group.signal);
118
+ if (finalHeaders.Authorization !== headers.Authorization) throw sessionExpired();
119
+ onProgress(++completed, readable.length, chat.conversationId);
120
+ } catch (error) {
121
+ group.abort();
122
+ throw error;
123
+ } finally {
124
+ clearTimeout(timeout);
125
+ group.signal.removeEventListener("abort", abort);
126
+ }
127
+ }
128
+ };
129
+ try {
130
+ await Promise.all(Array.from({ length: Math.min(3, readable.length) }, worker));
131
+ } finally {
132
+ signal.removeEventListener("abort", cancelGroup);
133
+ }
134
+ }
135
+ export {
136
+ requireNativeConversationAccess,
137
+ storeNativeConversations
138
+ };