openrtc 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +92 -0
  2. package/README.md +51 -10
  3. package/dist/{DelegatingRuntimeAdapter-CjHzBEBA.d.ts → DelegatingRuntimeAdapter-BxOcVIx_.d.ts} +23 -2
  4. package/dist/{IpcRuntimeAdapter-CtckyMol.d.ts → IpcRuntimeAdapter-U5AEH0jn.d.ts} +6 -3
  5. package/dist/auth/index.js +1 -1
  6. package/dist/auth/internal.js +1 -1
  7. package/dist/chunk-7DN33VUQ.js +1 -0
  8. package/dist/chunk-BLOEZIFJ.js +1 -0
  9. package/dist/chunk-FQETZQPW.js +2 -0
  10. package/dist/chunk-IUHUYHNZ.js +1 -0
  11. package/dist/chunk-UBEE42VU.js +2 -0
  12. package/dist/chunk-UPO23UMZ.js +3 -0
  13. package/dist/chunk-WNJE3MJF.js +1 -0
  14. package/dist/{factories-CwZiIRg1.d.ts → framing-lxzHEuSr.d.ts} +71 -4
  15. package/dist/index.d.ts +109 -9
  16. package/dist/index.js +2 -2
  17. package/dist/openrtc_bg.wasm +0 -0
  18. package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
  19. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  20. package/dist/runtime/index.d.ts +14 -7
  21. package/dist/runtime/index.js +1 -1
  22. package/dist/runtime/tauri.d.ts +3 -3
  23. package/dist/runtime/tauri.js +1 -1
  24. package/dist/transport/index.d.ts +1 -1
  25. package/dist/transport/index.js +1 -1
  26. package/dist/{types-DyCGvj9l.d.ts → types-D0fRvUbN.d.ts} +31 -10
  27. package/env/index.d.ts +64 -0
  28. package/env/index.mjs +230 -0
  29. package/package.json +19 -10
  30. package/dist/chunk-3VTF5RKW.js +0 -1
  31. package/dist/chunk-JXGKO7SX.js +0 -1
  32. package/dist/chunk-MFT6SOZ6.js +0 -3
  33. package/dist/chunk-SGZWR63E.js +0 -1
  34. package/dist/chunk-VARALO7G.js +0 -1
  35. package/dist/chunk-WOHFM6DI.js +0 -2
  36. package/dist/chunk-YHJOXD46.js +0 -2
@@ -1 +0,0 @@
1
- import {b,c as c$1}from'./chunk-WOHFM6DI.js';function c(){return b()}var i=class extends c$1{constructor(r){super({...r,bridge:b(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
@@ -1 +0,0 @@
1
- import {y,x}from'./chunk-JXGKO7SX.js';var n=class extends y{constructor(e){super(new x(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
@@ -1,2 +0,0 @@
1
- import {q,y,x,u as u$1,t as t$1,j as j$1,d,w,i,l,c,m,n,o,p}from'./chunk-JXGKO7SX.js';import {t,r,a,A,C as C$1}from'./chunk-YHJOXD46.js';function _(h,e="native runtime"){if(!h||typeof h!="object")throw new Error(`[openrtc] ${e} requires a valid IPC bridge object.`);if(typeof h.invoke!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing invoke(command, args).`);if(typeof h.listen!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing listen(event, handler).`);return h}var C=null;async function K(){return C||(C=(async()=>{let h="openrtc-tauri",e="../../../tauri/src/runtime/ipc";try{return await import(h)}catch(t){try{return await import(e)}catch(i){let n=new Error("[openrtc] Native support now lives in the first-party `openrtc-tauri` package. Install `openrtc-tauri` (and `@tauri-apps/api`) or pass an explicit IPC bridge to OpenRTC.native(...).");throw n.cause={packageError:t,workspaceError:i},n}}})()),C}function j(){let h=null,e=async()=>(h||(h=K().then(t=>_(t.createTauriIpcBridge(),"openrtc-tauri"))),h);return {async invoke(t,i){return (await e()).invoke(t,i)},async listen(t,i){return (await e()).listen(t,i)},async isAvailable(){try{let t=await e();return typeof t.isAvailable=="function"?!!await t.isAvailable():!0}catch{return false}}}}var X="relay-only endpoint ticket unavailable",J=12e3,Z=250,ee=1500;function te(h){return String(h?.message??h??"").toLowerCase().includes(X)}async function E(h,e={}){let t$1=e.windowMs??J,i=e.minDelayMs??Z,n=e.maxDelayMs??ee,r$1=Date.now(),a=0,o=null;for(;e.isActive?.()??true;){a+=1;try{return await h()}catch(l){if(o=l,!te(l))throw l;let s=Date.now()-r$1;if(s>=t$1)throw l;let c=Math.min(t(a,i,n),Math.max(0,t$1-s));c>0&&await r(c);}}throw o||new Error("endpoint ticket minting stopped before a ticket was available")}var u=class u{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.lastNativeAuthSyncAtMs=0;this.hasLoggedMissingAuthForDevices=false;this.nativeRtdbPresenceScope=null;this.nativeRtdbTicketVersion=0;this.lastNativePresenceTicket=null;this.nativeRtdbPresenceDisabledForSession=false;this.fallback=new x(e),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=_(e.ipcBridge??j(),"NativeIpcBridge");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=u$1(t$1);return e.fallback.wasm=this.allowWasmFallback,e}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,n){return this.fallback.sendMessage(e,t,i,n)}pollMessages(e){return this.fallback.pollMessages(e)}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}openPeerBi(e,t){return this.fallback.openPeerBi(e,t)}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}getCurrentUserId(){return this.fallback.getCurrentUserIdForScope()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}matchesNativeStatusTag(e){let t=j$1(e);return this.matchesTag(t)}async buildNativeRtdbScope(e){return this.fallback.resolveRtdbScope(e??void 0)}async syncNativeRtdbPresenceTicket(e){if(this.nativeRtdbPresenceDisabledForSession)return;let t=await this.buildNativeRtdbScope(),i=await this.resolveLocalDeviceId();if(!(!t||!i))try{if(!this.fallback.rtdbPresence||!this.nativeRtdbPresenceScope){await this.fallback.registerRtdbPresence(t,i,this.nativeRtdbTicketVersion),this.nativeRtdbPresenceScope=t,this.lastNativePresenceTicket=e,d("[NativeIpcBridge][RTDB] registered native presence ticket state",{deviceId:i,ticketVersion:this.nativeRtdbTicketVersion,ticketFingerprint:w(e)});return}let r=this.lastNativePresenceTicket!==e;(this.nativeRtdbPresenceScope.kind!==t.kind||t.kind==="user-scoped"&&this.nativeRtdbPresenceScope.kind==="user-scoped"&&(this.nativeRtdbPresenceScope.appTag!==t.appTag||this.nativeRtdbPresenceScope.userId!==t.userId)||t.kind==="space"&&this.nativeRtdbPresenceScope.kind==="space"&&this.nativeRtdbPresenceScope.namespaceId!==t.namespaceId)&&(await this.fallback.registerRtdbPresence(t,i,this.nativeRtdbTicketVersion),this.nativeRtdbPresenceScope=t),r&&(this.nativeRtdbTicketVersion+=1,await this.fallback.rtdbPresence?.bumpTicketVersion(t,i,this.nativeRtdbTicketVersion),d("[NativeIpcBridge][RTDB] bumped native ticketVersion after managed ticket change",{deviceId:i,ticketVersion:this.nativeRtdbTicketVersion,ticketFingerprint:w(e)})),this.nativeRtdbPresenceScope=t,this.lastNativePresenceTicket=e;}catch(n){this.nativeRtdbPresenceDisabledForSession=true,this.nativeRtdbPresenceScope=null,this.lastNativePresenceTicket=null,console.warn("[NativeIpcBridge][RTDB] native RTDB presence mirror unavailable; continuing with Firestore/native presence.",n);}}async markNativeRtdbOffline(){if(!this.nativeRtdbPresenceScope)return;let e=await this.resolveLocalDeviceId();if(e)try{await this.fallback.rtdbPresence?.markOffline(this.nativeRtdbPresenceScope,e,this.nativeRtdbTicketVersion),d("[NativeIpcBridge][RTDB] marked native presence offline",{deviceId:e,ticketVersion:this.nativeRtdbTicketVersion});}catch(t){console.warn("[NativeIpcBridge][RTDB] failed to mark native presence offline:",t);}finally{this.nativeRtdbPresenceScope=null,this.nativeRtdbTicketVersion=0,this.lastNativePresenceTicket=null,this.nativeRtdbPresenceDisabledForSession=false;}}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t=null;if(!this.strictMode&&e?.iroh&&typeof e.iroh=="object"){let s=e.iroh;s.localDiscovery===true&&(t={enabled:true,advertise:s.localDiscoveryMode!=="passive"});}let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let s=e.webrtc===true?null:e.webrtc,c=Array.isArray(s?.iceServers)?s.iceServers.map(w=>this.normalizeNativeIceServer(w)).filter(w=>!!w):[],d=this.strictMode||s?.privacyMode===true;(this.strictMode||s?.privacyMode===true||s?.useTurn===true)&&(c=[...c,...await this.loadNativeTurnIceServers()]),d&&(c=this.filterNativeStunServers(c));let f=c.some(w=>this.nativeIceServerHasTurnUrl(w)),g=d&&f;d&&!f&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let I=s?.lanMode===true;(c.length>0||g||I)&&(i={iceServers:c.length>0?c:void 0,privacyMode:g,lanMode:I||void 0});}let n=null;if(e?.moq&&typeof e.moq=="object"){let s=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;s&&(n={relayUrl:s});}let r=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let s=e.ble===true?null:e.ble,c=Number(s?.connectTimeoutMs),d=Number(s?.retryAttempts),p=Number(s?.retryBackoffMs);r={enabled:s?.enabled!==false,connectTimeoutMs:Number.isFinite(c)&&c>0?Math.round(c):void 0,retryAttempts:Number.isFinite(d)&&d>=0?Math.round(d):void 0,retryBackoffMs:Number.isFinite(p)&&p>=0?Math.round(p):void 0};}let a=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,o=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,l=this.strictMode?o??"auto":o;return !a&&!l&&!i&&!n&&!t&&!r?null:{irohRelayOnly:a||void 0,irohRelayTransportPolicy:l,irohLan:t,webrtc:i,moq:n,ble:r}}isTauriEnv(){return a()}nextConnectionEventRetryDelayMs(e){return t(e,u.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,u.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,d(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async canUseTauriIpc(){return this.ipcBridge?typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true:typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<u.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0;try{return await this.invokeIpc("rtc_native_status"),d("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(d("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let n=this.ipcBridge.invoke(e,t),r=i?.timeoutMs??u.MANAGED_SESSION_IPC_TIMEOUT_MS;return r===null||r<=0?n:A(n,r,()=>new Error(`${e} timeout after ${r}ms`))}isRetryableManagedSessionStartError(e){let t=(e instanceof Error?e.message:String(e??"")).toLowerCase();return !t||t.includes("start_rtc_managed_session")&&t.includes("timeout after")?false:!!(t.includes("callback")&&t.includes("id")||t.includes("channel closed")||t.includes("ipc channel closed"))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await C$1().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){if(await this.fallback.setAuthContext(e),!e?.token)await this.markNativeRtdbOffline(),await this.clearNativeAuthRelay("setAuthContext");else if(!await this.ensureNativeAuth("setAuthContext",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for setAuthContext")}async signOut(){await this.fallback.signOut(),await this.markNativeRtdbOffline(),await this.clearNativeAuthRelay("signOut");}async stopAuthScopedActivity(e){let t=this.resolveNativeAuthScopedUserId(e?.userId??null),i$1=await this.shouldUseTauriSignaling();if(i("NativeIpcBridge.stopAuthScopedActivity",{userId:t,useTauri:i$1}),i$1)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect"),t?this.invokeIpc("set_rtc_offline",{userId:t}):Promise.resolve()]);}catch(n){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",n);}await this.markNativeRtdbOffline(),await this.fallback.stopAuthScopedActivity({userId:t});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return d(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let n=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,r=this.currentUser?.getToken?await this.currentUser.getToken(n):null,o=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;if(!r)return d(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t;if(r===this.lastSyncedAuthToken)return !0;let l=await Promise.allSettled([this.invokeIpc("desktop_set_pluto_auth_token",{authToken:r,refreshToken:o})]);return l[0]?.status==="rejected"?(console.warn(`[NativeIpcBridge] desktop auth relay failed (${e}):`,l[0].reason),!1):(this.lastSyncedAuthToken=r,this.lastNativeAuthSyncAtMs=Date.now(),d(`[NativeIpcBridge] auth token relayed to native runtime (${e}) user_id=${this.currentUser?.id}`),!0)}catch(n){return console.error("[NativeIpcBridge] auth sync failed:",n),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,n=t?.maxWaitMs??(i?u.AUTH_REQUIRED_WAIT_MS:0),r$1=t?.pollMs??250,a=Date.now()+Math.max(0,n);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=a)return false;await r(r$1);}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),i=typeof t?.device_id=="string"?t.device_id:"",n=typeof t?.device_name=="string"?t.device_name.trim():"";if(i)return this.cachedLocalDeviceId=i,n&&(this.cachedLocalDeviceName=n),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=typeof e?.device_name=="string"?e.device_name.trim():"";if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("searchDevices",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for searchDevices");let i=await this.invokeIpc("search_rtc_devices",{userId:this.currentUser?.id});if(Array.isArray(i?.devices)){let n=i.devices.map(r=>this.normalizeDevice(r));return e&&(n=n.filter(r=>r.ticket!==e&&r.deviceId!==e&&r.nodeId!==e)),n}throw typeof i?.message=="string"?new Error(String(i.message)):new Error("Unexpected response for search_rtc_devices")}return this.fallback.searchDevices(e)}async listDevicesWithStatus(){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("listDevicesWithStatus",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for listDevicesWithStatus");let t=await this.invokeIpc("search_rtc_devices_with_status",{userId:this.currentUser?.id});if(Array.isArray(t?.devices)){let i=t.devices,n=i.filter(o=>this.matchesNativeStatusTag(o)).map(o=>l(o)),r=await this.resolveLocalDeviceId().catch(()=>null),a=!!r&&n.some(o=>o.deviceId===r);return c("[NativeIpcBridge] listDevicesWithStatus result",{rawCount:i.length,count:n.length,localDeviceId:r,selfIncluded:a,devices:n.map(o=>({deviceId:o.deviceId,deviceName:o.deviceName,online:!!o.online,connectionStatus:o.connectionStatus,settledReady:!!o.settledReady,peerHealth:o.peerHealth,scopes:o.scopes,connectionId:o.connectionId??null,deviceIdHint:o.deviceIdHint??null,nodeId:o.nodeId??null,activeTransport:o.activeTransport??null,parallelTransport:o.parallelTransport??null}))}),r&&!a&&c("[NativeIpcBridge] native status snapshot excludes local device by design",{localDeviceId:r,count:n.length}),n}throw typeof t?.message=="string"?new Error(String(t.message)):new Error("Unexpected response for search_rtc_devices_with_status")}return this.fallback.listDevicesWithStatus()}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:m(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>m(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(u.MANAGED_SESSION_IPC_TIMEOUT_MS,t+1e3):u.MANAGED_SESSION_IPC_TIMEOUT_MS,n=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !n||typeof n!="object"?null:m(n)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>n(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return o(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("setOffline",{requireToken:!0,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for setOffline");let i=this.getCurrentUserId();await this.invokeIpc("set_rtc_offline",{userId:i}),await this.markNativeRtdbOffline();return}catch(t){console.warn("[NativeIpcBridge] set_rtc_offline failed:",t);}return this.fallback.setOffline(e)}async updateDevice(e,t){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("updateDevice",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for updateDevice");let r=this.getCurrentUserId();if(!r)throw new Error("updateDevice requires authenticated user scope");try{await this.invokeIpc("update_rtc_device",{userId:r,deviceId:e,deviceName:t.deviceName??null,capabilities:t.capabilities??null,metadata:t.metadata??null});return}catch(a){throw console.warn("[NativeIpcBridge] update_rtc_device failed:",a),a instanceof Error?a:new Error(String(a))}}return this.fallback.updateDevice(e,t)}async deleteDevice(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("deleteDevice",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for deleteDevice");let n=this.getCurrentUserId();if(!n)throw new Error("deleteDevice requires authenticated user scope");try{await this.invokeIpc("delete_rtc_device",{userId:n,deviceId:e});return}catch(r){throw console.warn("[NativeIpcBridge] delete_rtc_device failed:",r),r instanceof Error?r:new Error(String(r))}}return this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=typeof e?.device_id=="string"?e.device_id.trim():"";return t?{deviceId:t,deviceName:this.normalizeNativeDeviceName(typeof e?.device_name=="string"?e.device_name:""),platformType:typeof e?.platform_type=="string"?e.platform_type:this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=typeof t?.device_id=="string"?t.device_id.trim():"";return i?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:i,deviceName:this.cachedLocalDeviceName,platformType:typeof t?.platform_type=="string"?t.platform_type:this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeAuthScopedUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let n=await this.buildNativeTransportConfigPayload(),r$1={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...n?{transports:n}:{},autoConnect:e.autoConnect!==false,presence:e.presence!==false,apiKey:this.options.apiKey??null},a=null,o=null;for(let p=1;p<=u.MANAGED_SESSION_IPC_MAX_ATTEMPTS;p+=1)try{a=await this.invokeIpc("start_rtc_managed_session",r$1,{timeoutMs:u.MANAGED_SESSION_IPC_TIMEOUT_MS}),o=null;break}catch(f){o=f;let g=this.isRetryableManagedSessionStartError(f),I=u.MANAGED_SESSION_IPC_MAX_ATTEMPTS-p;if(console.warn("[NativeIpcBridge][managed-session][ipc-attempt-failed]",{attempt:p,retryable:g,remaining:I,message:f instanceof Error?f.message:String(f)}),!g||I<=0)throw f;await this.ensureNativeAuth("startManagedSessionNative-retry",{requireToken:true,maxWaitMs:5e3}),await r(250*p);}if(!a&&o)throw o instanceof Error?o:new Error(String(o));let l=typeof a?.ticket=="string"&&a.ticket.trim().length>0?a.ticket.trim():null;l&&e.presence!==false&&await this.syncNativeRtdbPresenceTicket(l);let s=a?.localDevice&&typeof a.localDevice=="object"?a.localDevice:a?.local_device&&typeof a.local_device=="object"?a.local_device:null,c=s?{deviceId:typeof s.deviceId=="string"?s.deviceId:typeof s.device_id=="string"?s.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof s.deviceName=="string"?s.deviceName:typeof s.device_name=="string"?s.device_name:""),platformType:typeof s.platformType=="string"?s.platformType:typeof s.platform_type=="string"?s.platform_type:"desktop",capabilities:s.capabilities??void 0,lastSeenAt:typeof s.lastSeenAt=="string"?s.lastSeenAt:typeof s.last_seen_at=="string"?s.last_seen_at:void 0}:null,d={localNodeId:typeof a?.localNodeId=="string"?a.localNodeId:typeof a?.local_node_id=="string"?a.local_node_id:null,ticket:l,ticketScope:typeof a?.ticketScope=="string"?a.ticketScope:typeof a?.ticket_scope=="string"?a.ticket_scope:null,presenceStarted:typeof a?.presenceStarted=="boolean"?a.presenceStarted:!!a?.presence_started,autoConnectStarted:typeof a?.autoConnectStarted=="boolean"?a.autoConnectStarted:!!a?.auto_connect_started,localDevice:c?.deviceId?c:null};return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:d.localNodeId,ticketScope:d.ticketScope,presenceStarted:d.presenceStarted,autoConnectStarted:d.autoConnectStarted,localDeviceId:d.localDevice?.deviceId??null}),d}async reconcileNativeManagedSession(e){if(!await this.shouldUseTauriSignaling())return null;if(!await this.ensureNativeAuth("reconcileNativeManagedSession",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for reconcileNativeManagedSession");return this.invokeIpc("reconcile_mobile_rtc_after_resume",{reason:e?.reason??"frontend"})}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let n=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:n}),n||!t)return n;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let r=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:r}),r}catch(n){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",n),!t)return null;throw n}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return E(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");return this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}):d("[NativeIpcBridge] connectToDevice using anonymous native ticket path"),this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await E(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(i("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){await this.canUseTauriIpc()&&await this.invokeIpc("set_auto_connect_excluded",{deviceId:e,excluded:t});}onDevicesChange(e,t){let i=false,n=new Map,r$1=null,a=false,o=false,l=()=>{if(o=false,i)return;let p=Array.from(n.values());t&&(p=p.filter(f=>f.ticket!==t&&f.deviceId!==t&&f.nodeId!==t)),e(p);},s=()=>{if(!o){if(o=true,typeof queueMicrotask=="function"){queueMicrotask(l);return}Promise.resolve().then(l);}},c=async()=>{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] onDevicesChange falling back to wasm signaling (Tauri IPC unavailable)"),d$1=this.fallback.onDevicesChange(e,t);return}for(;!i;)try{let f=Date.now()+15e3,g=this.getCurrentUserId();for(;!i&&!g&&Date.now()<f&&(this.hasLoggedMissingAuthForDevices||(this.hasLoggedMissingAuthForDevices=!0,d("[NativeIpcBridge] onDevicesChange waiting for authenticated user before subscription")),g=this.getCurrentUserId(),!g);)await r(250);if(!g){!i&&!a&&(console.warn("[NativeIpcBridge] onDevicesChange could not resolve authenticated user; keeping subscription in retry mode"),e([]),a=!0),await r(1e3);continue}if(!await this.ensureNativeAuth("onDevicesChange",{requireToken:!0,maxWaitMs:Math.max(0,f-Date.now())})){!i&&!a&&(console.warn("[NativeIpcBridge] onDevicesChange timed out waiting for auth token; keeping subscription in retry mode"),e([]),a=!0),await r(1e3);continue}this.hasLoggedMissingAuthForDevices=!1,a=!1,d(`[NativeIpcBridge] onDevicesChange starting subscription user_id=${g}`);let U=await this.searchDevices(t);n.clear();for(let T of U)n.set(T.deviceId,T);for(s(),r$1=(await this.subscribeDevices(g)).getReader();!i;){let{done:T,value:B}=await r$1.read();if(T||!B)break;for(let k of B){if(k.type==="removed"){n.delete(k.deviceId);continue}let O=k.device?.deviceId;if(!this.matchesTag(k.device??{})){O&&n.delete(O);continue}let P=this.normalizeDevice(k.device);P.deviceId&&n.set(P.deviceId,P);}s();}}catch(p){i||(console.error("[NativeIpcBridge] onDevicesChange stream failed; retrying subscription:",p),await r(1e3));}finally{if(r$1){try{await r$1.cancel();}catch{}r$1=null;}}},d$1=()=>{i=true,r$1&&(r$1.cancel(),r$1=null);};return c(),()=>d$1()}async subscribeDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeDevices",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for subscribeDevices");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=null,r=null,a=false,o=async()=>{if(!a&&(a=true,n&&(await Promise.resolve(n()),n=null),r)){try{await r();}catch{}r=null;}};return new ReadableStream({start:async l=>{d(`[NativeIpcBridge] subscribeDevices request start user_id=${e} request_id=${i}`),n=await this.listenIpc("rtc-device-events",s=>{if(a)return;let c$1=s.payload;if(c$1.requestId===i){if(c$1.type==="deviceEvents"){let d=Array.isArray(c$1.events)?c$1.events.length:0;c(`[NativeIpcBridge] subscribeDevices event batch request_id=${i} count=${d}`);try{l.enqueue(c$1.events);}catch{o();}}else if(c$1.type==="error"&&(console.warn(`[NativeIpcBridge] subscribeDevices stream error request_id=${i}: ${c$1.message}`),!a)){try{l.error(c$1.message);}catch{}o();}}}),r=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_device_subscription",{requestId:i,userId:e});}catch(s){try{l.error(s);}catch{}await o();}},cancel:async()=>{d(`[NativeIpcBridge] subscribeDevices request stop request_id=${i}`),await o();}})}return this.fallback.subscribeDevices(e)}async subscribeSessions(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeSessions",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for subscribeSessions");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=await this.resolveLocalDeviceId()||e,r=null,a=null,o=false,l=async()=>{if(!o&&(o=true,r&&(await Promise.resolve(r()),r=null),a)){try{await a();}catch{}a=null;}};return new ReadableStream({start:async s=>{r=await this.listenIpc("rtc-session-events",c=>{if(o)return;let d=c.payload;if(d.requestId===i){if(d.type==="sessionEvents")try{s.enqueue(d.events);}catch{l();}else if(d.type==="error"&&!o){try{s.error(d.message);}catch{}l();}}}),a=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_session_subscription",{requestId:i,localDeviceId:n});}catch(c){try{s.error(c);}catch{}await l();}},cancel:async()=>{await l();}})}return this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,n=3e5,r){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("updatePresence",{requireToken:!0,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for updatePresence");let o=this.resolveNativeAuthScopedUserId(),l=await this.resolveLocalDeviceId(),s=await this.resolveLocalDeviceName();await this.invokeIpc("update_rtc_presence",{userId:o,deviceName:s,ticket:t,metadata:this.withPresenceMetadata(r,l)}),await this.syncNativeRtdbPresenceTicket(t);return}catch(a){console.warn("[NativeIpcBridge] update_rtc_presence failed:",a);}return this.fallback.updatePresence(e,t,i,n,r)}startAutoConnect(e,t){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] startAutoConnect requires native Rust signaling; IPC unavailable");return}let i=await this.resolveLocalDeviceId()||t;await this.startAutoConnectOnce(e,i);}catch(i){console.warn("[NativeIpcBridge] startAutoConnect failed:",i);}})();}forceReconnectSnapshot(){(async()=>{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] forceReconnectSnapshot requires native Rust signaling; IPC unavailable");return}try{await this.invokeIpc("force_rtc_reconnect_snapshot");}catch(e){console.warn("[NativeIpcBridge] force_rtc_reconnect_snapshot failed:",e);}})();}startPresenceLoop(e,t,i,n,r){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] startPresenceLoop falling back to wasm signaling (Tauri IPC unavailable)"),this.fallback.startPresenceLoop(e,t,i,n,r);return}let a=await this.resolveLocalDeviceId(),o=this.shouldUseResolvedDeviceName(i)?await this.resolveLocalDeviceName():i.trim(),l=this.withPresenceMetadata(r,a);await this.startPresenceLoopOnce(e,t,o,n,l),await this.syncNativeRtdbPresenceTicket(n);}catch(a){console.warn("[NativeIpcBridge] startPresenceLoop failed:",a);}})();}async startAutoConnectOnce(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startAutoConnectOnce().");if(!await this.ensureNativeAuth("startAutoConnect",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for startAutoConnect");let n=this.resolveNativeAuthScopedUserId(e);if(!n)throw new Error("Native auto-connect requires a runtime auth-scoped user id.");await this.invokeIpc("start_rtc_auto_connect",{userId:n,localDeviceId:t});}async startPresenceLoopOnce(e,t,i,n,r){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startPresenceLoopOnce().");if(console.info("[NativeIpcBridge][presence][start-request]",{userId:e,localNodeId:t,deviceName:i,hasMetadata:typeof r=="string"&&r.trim().length>0,hasCompoundTicket:typeof n=="string"&&n.includes(".")}),!await this.ensureNativeAuth("startPresenceLoop",{requireToken:true,maxWaitMs:u.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for startPresenceLoop");let o=this.resolveNativeAuthScopedUserId(e);if(!o)throw new Error("Native presence loop requires a runtime auth-scoped user id.");console.info("[NativeIpcBridge][presence][auth-ready]",{requestedUserId:e,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:o,localNodeId:t}),await this.invokeIpc("start_rtc_presence_loop",{userId:o,localNodeId:t,deviceName:i,ticket:n,metadata:r,apiKey:this.options.apiKey??null}),console.info("[NativeIpcBridge][presence][ipc-started]",{requestedUserId:e,effectiveUserId:o,localNodeId:t,deviceName:i});}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(d("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):d("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let n=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return d("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:n}),n}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){d("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):d("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let n=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(n),transferId:e.transferId}),d("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>p(t)).filter(t=>!!t)}catch(e){return console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),p(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,n=Date.now(),r$1=0,a=()=>{let s=i;s&&Promise.resolve(s());},o=async()=>{try{let s=await this.getConnectionStates();s.length>0&&(c("[NativeIpcBridge] replaying current native connection states",s.map(c=>({connectionId:c.connectionId,deviceId:c.deviceId??null,deviceIdHint:c.deviceIdHint??null,remoteNodeId:c.remoteNodeId??null,state:c.state,transportState:c.transportState??null,protocolState:c.protocolState??null,routable:c.routable??null}))),s.forEach(c=>e(c)));}catch(s){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",s);}},l=async s=>{let c=await this.getConnectionState(s);c&&e(c);};for(;!t&&Date.now()-n<=u.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(r$1+=1,!await this.canUseTauriIpc()){await r(this.nextConnectionEventRetryDelayMs(r$1));continue}return i=await this.listenIpc("connection-state-changed",s=>{let c$1=p(s?.payload);c$1&&(c("[NativeIpcBridge] connection-state-changed trigger",{connectionId:c$1.connectionId}),l(c$1.connectionId));}),await o(),()=>{t=true,a();}}return ()=>{t=true,a();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let n=new Uint8Array(i.payload.data);if(n.length<2||n[0]!==0)return;let a=n.slice(1),o=new TextDecoder().decode(a),l=JSON.parse(o);e(i.payload.connectionId,i.payload.remoteNodeId??null,l);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};u.AUTH_REQUIRED_WAIT_MS=q.nativeIpc.authRequiredWaitMs,u.MANAGED_SESSION_IPC_TIMEOUT_MS=q.nativeIpc.managedSessionIpcTimeoutMs,u.MANAGED_SESSION_IPC_MAX_ATTEMPTS=q.nativeIpc.managedSessionIpcMaxAttempts,u.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=q.nativeIpc.connectionEventSubscribeWindowMs,u.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=q.nativeIpc.connectionEventRetryMinDelayMs,u.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=q.nativeIpc.connectionEventRetryMaxDelayMs,u.TAURI_IPC_NEGATIVE_CACHE_MS=q.nativeIpc.tauriIpcNegativeCacheMs;var D=u;var G=class extends y{constructor(e){let t=_(e.bridge,"IpcRuntimeAdapter");super(new D({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
2
- export{E as a,j as b,G as c};
@@ -1,2 +0,0 @@
1
- import {getApps,initializeApp}from'firebase/app';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';function _(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var E=new Set;function S(e,t){E.has(e)||(E.add(e),console.warn(t));}function ie(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function Ee(e,t){let n=`${e}:${t}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(d=>d.toString(16).padStart(2,"0")).join("")}function I(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return ie(t)||S(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function P(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||S("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function He(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(S("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),b)}function H(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Le(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?H(e.storagePrefix):"";return t||H(I(e))||"default"}var Be={devicesPerUser:2,maxRooms:10,maxMembersPerRoom:5,maxPersonalDevices:25},R="https://relay.cloudflare.mediaoverquic.com:443/moq",se=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],L={iceServers:se},F={relayUrl:R};var B=["iroh-relay","iroh","moq"];function ae(e){return (Array.isArray(e.urls)?e.urls:[e.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function ce(e){let n=(Array.isArray(e.urls)?e.urls:[e.urls]).filter(o=>typeof o=="string"&&!o.startsWith("stun:"));return n.length===0?null:{...e,urls:Array.isArray(e.urls)?n:n[0]}}function C(e){if(e)return e.map(t=>ce(t)).filter(t=>t!==null)}function A(e){return (e??"").trim().replace(/\/+$/,"").toLowerCase()}function W(e,t){let n=new Set(["iroh-relay","iroh","moq"]);t&&n.add("webrtc");let o=(e??B).filter(r=>n.has(r));return o.length>0?o:[...B]}function qe(e){return !!e?.transports?.webrtc}function Ke(e,t){let n=e?.transports?.webrtc||void 0;if(n)return e?.strictMode||n.privacyMode?{...n,iceServers:C(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(r=>ae(r)))?(t?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var le=["iroh-lan","webrtc-lan","ble","webrtc","moq","iroh"];function k(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function q(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function K(e){return {...e}}function de(e){return {...e}}function ue(e){if(e)return {iroh:typeof e.iroh=="object"?de(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?q(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?K(e.moq):e.moq}}function pe(e){e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),e.transports&&(e.transports.webrtc===true?e.transports.webrtc=q(L):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true?e.transports.moq=K(F):e.transports.moq===false&&(e.transports.moq=void 0),e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0));}function ge(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"auto",localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let n=e.transports.webrtc;n&&typeof n=="object"&&(e.transports.webrtc={...n,privacyMode:true,lanMode:false,iceServers:C(n.iceServers)??[],iceTransportPolicy:"relay"});let o=e.transports.moq;if(o&&typeof o=="object"){let r=o.relayUrl?.trim();if(!r||A(r)===A(R))throw new Error("[OpenRTC] strictMode requires transports.moq.relayUrl to point at a self-hosted MoQ relay; the default public relay is not allowed.");e.transports.moq={...o,relayUrl:r};}}function Qe(e){let t=k(e),n=I(t),o=P(t),r={strictMode:false,disableIrohFallback:false,transportPriority:[...le],...t,authMode:o,transports:ue(t.transports)};pe(r),ge(r),r.strictMode&&(r.transportPriority=W(t.transportPriority,!!r.transports?.webrtc));let i=j(r),s=(r.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:o,configuredPersistenceMode:i,options:r,roomCreationMode:s}}function j(e){let t=e.transports?.iroh;return e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"persistent"}function Ve(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:P(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:P(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:j(e)}}function Je(e,t){t&&(e.transports={...e.transports||{},...t});}var b="pluto-rtc-prod",z={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:b,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d"};function Xe(e){let t=k(e),n=typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():b;return {...t,projectId:n}}function $(e){return new Promise(t=>setTimeout(t,e))}function tt(e){let t=e.reduce((r,i)=>r+i.byteLength,0),n=new Uint8Array(t),o=0;for(let r of e)n.set(r,o),o+=r.byteLength;return n}function nt(e,t,n){let o=t*Math.pow(2,Math.max(0,e-1));return Math.min(n,o)}function rt(e){try{let t=e;return !!t&&!!t.send&&typeof t.send.getWriter=="function"&&!!t.recv&&typeof t.recv.getReader=="function"}catch{return false}}function ot(e,t){let n=e;if(!n)return null;try{let o=n.send,r=n.recv;if(!o||typeof o.getWriter!="function"||!r||typeof r.getReader!="function")return null;let i=typeof n.endpoint_id=="string"&&n.endpoint_id.trim().length>0?n.endpoint_id:t;return {send:o,recv:r,endpoint_id:i}}catch{return null}}function it(e,t){let n={send:e.send,recv:t,endpoint_id:typeof e.endpoint_id=="string"?e.endpoint_id:""};return e?.applicationCryptoWrapped===true&&(n.applicationCryptoWrapped=true),n}async function st(e,t){if(!e)return false;try{let n=e.send?.getWriter?.();if(n)try{await n.close();}catch{}finally{try{n.releaseLock();}catch{}}}catch{}try{let n=e.recv?.getReader?.();if(n)try{await n.cancel(t);}catch{}finally{try{n.releaseLock();}catch{}}}catch{}return true}function at(e,t,n={}){let o=n.context??"prependBytesToReader",r=n.traceId,i=t.byteLength===0,s=n.pendingRead??null,l=a=>n.release?.(a),d=(a,p)=>n.log?.(a,p);return new ReadableStream({async pull(a){if(!i){i=true,a.enqueue(t);return}if(s){let u=s;s=null;let g;try{g=await u;}catch(f){a.error(f),l("pending-read-error"),d("prepend-bytes:pending-read-error",{context:o,traceId:r||null,error:f?.message||String(f)});return}if(g.done){a.close(),l("pending-done");return}g.value&&a.enqueue(g.value);return}let p;try{p=await e.read();}catch(u){a.error(u),l("read-error"),d("prepend-bytes:read-error",{context:o,traceId:r||null,error:u?.message||String(u)});return}let{done:T,value:v}=p;if(T){a.close(),l("done");return}v&&a.enqueue(v);},async cancel(a){l("cancel");}})}async function ct(e,t){let n=e.read(),o=t-Date.now();if(o<=0)return {status:"timeout",pendingRead:n};let r=Symbol("probe-timeout"),i,s=new Promise(l=>{i=setTimeout(()=>l(r),o);});try{let l=await Promise.race([n,s]);if(l===r)return {status:"timeout",pendingRead:n};let{done:d,value:a}=l;return d?{status:"done"}:{status:"data",value:a&&a.byteLength>0?new Uint8Array(a):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function G(e,t,n){let o;return new Promise((r,i)=>{o=setTimeout(()=>{if(o=void 0,typeof n=="function"){i(n());return}let s=n?`${n} timed out`:"timeout";i(new Error(`${s} after ${t}ms`));},t),e.then(s=>{o!==void 0&&clearTimeout(o),r(s);},s=>{o!==void 0&&clearTimeout(o),i(s);});})}var X="pluto-rtc-auth",D=null;function Oe(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function c(e,t){if(Oe()){if(typeof t>"u"){console.log(e);return}console.log(e,t);}}function Rt(e){D=e;}function Me(){return _()}function re(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function ee(){return Me()&&re()}function m(e,t,n){return G(e,t,()=>new Error(`${n} timeout after ${t}ms`))}function te(e){let t="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(e);window.crypto.getRandomValues(n);let o="";for(let r=0;r<e;r+=1)o+=t[n[r]%t.length];return o}async function ne(e){let n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}var N=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;this.desktopTokenRefreshIntervalId=null;let t=getApps().find(r=>r.name===X);this.app=t||initializeApp(z,X);let n=re(),o=ee();if(n)try{let r=o?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,r),c("[PLUTO-RTC][AUTH-HOST] Using mobile-safe Firebase auth initialization",{appName:this.app.name,persistence:"browserLocalPersistence->inMemoryPersistence",redirectResolver:o?"disabled-for-tauri-mobile":"browserPopupRedirectResolver",tauriMobile:o});}catch{this.auth=getAuth(this.app),console.warn("[PLUTO-RTC][AUTH-HOST] Mobile-safe auth initialization unavailable; falling back to default getAuth");}else this.auth=getAuth(this.app);this.functions=getFunctions(this.app);try{let r=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",i=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",s=typeof import.meta<"u"?import.meta.env:null;if(!!r||!!i||!!s&&String(s.VITE_USE_EMULATORS)==="true"&&(s.DEV||String(s.VITE_E2E)==="true")){let d=String(s?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[a,p]=r.split(":"),[T,v]=i.split(":"),u=(a??"").trim()||d,g=(T??"").trim()||d,f=Number(p??s?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),oe=Number(v??s?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${f}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,g,oe);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(r=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:r?.message});}),c("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,r=>{c("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!r,uid:r?.uid,providerDataCount:r?.providerData?.length||0}),this.syncDesktopAuthToken(r);}),this.desktopTokenRefreshIntervalId||(this.desktopTokenRefreshIntervalId=setInterval(()=>{this.syncDesktopAuthToken(this.auth.currentUser,true);},600*1e3));}async syncDesktopAuthToken(t,n=false){if(!D)return;let o=t?await getIdToken(t,n).catch(()=>null):null,r=t?t.refreshToken??null:null;if(o===this.lastRelayedToken&&r===this.lastRelayedRefreshToken)return;this.lastRelayedToken=o,this.lastRelayedRefreshToken=r;let i=await Promise.allSettled([Promise.resolve(D({authToken:o,refreshToken:r}))]);i[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:i[0].reason?.message});}getApp(){return this.app}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,t)}onIdTokenChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,t)}async getIdToken(t){return this.auth.currentUser?getIdToken(this.auth.currentUser,t?.forceRefresh??true):null}async checkForSSOToken(){if(typeof window>"u")return;let t=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),o=t.get("token")||n.get("token")||(t.get("custom_token")==="true"||n.get("custom_token")==="true"?t.get("id_token")||n.get("id_token"):null);if(o)try{await this.persistenceReady,await signInWithCustomToken(this.auth,o),window.history.replaceState({},document.title,window.location.pathname);}catch(r){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",r);}}async signInWithCustomTokenValue(t){return await this.persistenceReady,(await signInWithCustomToken(this.auth,t)).user}async signInWithPluto(t){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=t?.redirectUri||window.location.href,o=t?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",r=new URL(o);r.searchParams.set("redirect_uri",n),window.location.assign(r.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(t=>{let n=onAuthStateChanged(this.auth,o=>{o&&(n(),t());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(t,n){return (await signInWithEmailAndPassword(this.auth,t,n)).user}async signUp(t,n){return (await createUserWithEmailAndPassword(this.auth,t,n)).user}async signOut(){await signOut(this.auth);}async deleteAccount(){if(!this.auth.currentUser)throw new Error("No user signed in");await deleteUser(this.auth.currentUser);}async signInWithCredential(t){let n=Date.now();if(c("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:t.callbackId,provider:t.provider,hasIdToken:!!t.idToken,hasAccessToken:!!t.accessToken,hasNonce:!!t.nonce}),t.isCustomToken){c("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(ee())c("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:t.callbackId});else {c("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await m(this.auth.authStateReady(),5e3,"authStateReady"),c("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:t.callbackId,message:s?.message});}}let i;try{i=await m(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:t.callbackId,message:s?.message,code:s?.code}),await $(250),i=await m(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:t.callbackId,provider:t.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user&&(t.displayName||t.photoURL))try{await updateProfile(i.user,{displayName:t.displayName||i.user.displayName||void 0,photoURL:t.photoURL||i.user.photoURL||void 0});}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:t.callbackId,message:s?.message});}return i.user}catch(r){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:t.callbackId,error:r?.message,code:r?.code,stack:r?.stack,elapsedMs:Date.now()-n}),r}}let o;t.provider==="google"?o=GoogleAuthProvider.credential(t.idToken,t.accessToken):o=new OAuthProvider("apple.com").credential({idToken:t.idToken,rawNonce:t.nonce,accessToken:t.accessToken});try{let r=await m(signInWithCredential(this.auth,o),1e4,"firebase signInWithCredential");return c("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:t.callbackId,provider:t.provider,uid:r.user?.uid,elapsedMs:Date.now()-n}),r.user}catch(r){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:t.callbackId,provider:t.provider,elapsedMs:Date.now()-n,code:r?.code,message:r?.message});let i=await m(this.mintSessionTokenFromProviderToken(t),15e3,"mintSessionTokenFromProviderToken"),s=await m(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:t.callbackId,provider:t.provider,uid:s.user?.uid,elapsedMs:Date.now()-n}),s.user}}async mintSessionTokenFromProviderToken(t){let n=httpsCallable(this.functions,"mintSessionToken");c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:t.provider,hasIdToken:!!t.idToken,hasNonce:!!t.nonce});let r=(await n({provider:t.provider,idToken:t.idToken,nonce:t.nonce})).data?.token;if(!r)throw new Error("mintSessionToken did not return a token for provider exchange");return c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:t.provider}),r}async signInWithPopup(t){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"});let s=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(s.user,true),refreshToken:s.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let o=te(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),n.setCustomParameters({nonce:await ne(o)});let r=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(r.user,true),refreshToken:r.user.refreshToken}}async signInWithRedirect(t,n){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,i);return}let o=new OAuthProvider("apple.com");o.addScope("email"),o.addScope("name");let r=n?.nonce||te(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),o.setCustomParameters({nonce:await ne(r)}),await signInWithRedirect(this.auth,o);}async consumeRedirectResult(){return this.redirectResultConsumed?(c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let t=await getRedirectResult(this.auth);if(!t)return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(t.user,!0).catch(()=>null),o=t.providerId||t.user.providerData?.[0]?.providerId||null;return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:t.user.uid,providerId:o,hasIdToken:!!n}),{fromRedirect:!0,user:t.user,providerId:o,idToken:n}}finally{this.redirectResultPromise=null;}})(),this.redirectResultPromise)}async startGoogleSignIn(){await this.signInWithRedirect("google");}async startAppleSignIn(){await this.signInWithRedirect("apple");}async mintSessionToken(){let o=(await httpsCallable(this.functions,"mintSessionToken")()).data;if(!o?.token)throw new Error("mintSessionToken did not return a token");return o.token}},M=null;function De(){return M||(M=new N),M}var Ct=new Proxy({},{get(e,t,n){let o=De(),r=o[t];return typeof r=="function"?r.bind(o):r}});
2
- export{G as A,Rt as B,De as C,Ct as D,_ as a,Ee as b,I as c,P as d,He as e,Le as f,Be as g,se as h,L as i,F as j,qe as k,Ke as l,k as m,Qe as n,Ve as o,Je as p,Xe as q,$ as r,tt as s,nt as t,rt as u,ot as v,it as w,st as x,at as y,ct as z};