openrtc 2.0.0 → 2.0.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.
- package/dist/{DelegatingRuntimeAdapter-BFZDC604.d.ts → DelegatingRuntimeAdapter-fgz5OPQx.d.ts} +3 -3
- package/dist/{ITransport-WV6gGMnX.d.ts → ITransport-UNOXiRJD.d.ts} +3 -3
- package/dist/{IpcRuntimeAdapter-CJq3dRBF.d.ts → IpcRuntimeAdapter-CI3vCzk0.d.ts} +2 -2
- package/dist/OpenRTCShared.d.ts +4 -4
- package/dist/WasmBridge-P5646IVR.js +1 -0
- package/dist/{assembly-q0jRRpsc.d.ts → assembly-CLdwe5T-.d.ts} +3 -3
- package/dist/{capabilities-BfZi4Cd7.d.ts → capabilities-BUe5YldR.d.ts} +1 -1
- package/dist/{chunk-H5R5ZXXN.js → chunk-5OTF7W2N.js} +1 -1
- package/dist/{chunk-Z6TZLF4B.js → chunk-HIXXBEWX.js} +1 -1
- package/dist/chunk-IKZ33R7R.js +2 -0
- package/dist/chunk-QCPSLUKO.js +1 -0
- package/dist/{chunk-D2OJN5S5.js → chunk-Y35AKFCM.js} +1 -1
- package/dist/chunk-ZQF5KSOK.js +2 -0
- package/dist/controlPlane-YAMXWHAF.js +1 -0
- package/dist/deviceEnrollment-33NZEARB.js +2 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/ipcFactory-JTMNUTZI.js +1 -0
- package/dist/native.d.ts +6 -6
- package/dist/native.js +1 -1
- package/dist/{openrtc-BFF336RG.js → openrtc-JUV7TOTL.js} +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +4 -4
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +2 -2
- package/dist/runtime/factories.d.ts +6 -6
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +10 -10
- package/dist/runtime/index.js +1 -1
- package/dist/testing.d.ts +118 -6
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-Di034GVQ.d.ts → types-DhmY9hBy.d.ts} +4 -5
- package/dist/{types-DVNSd5B9.d.ts → types-l3m3GrOe.d.ts} +1 -1
- package/package.json +3 -9
- package/dist/WasmBridge-5GYKXPXK.js +0 -1
- package/dist/chunk-OEVPKC3W.js +0 -1
- package/dist/chunk-VOCOZ57Q.js +0 -2
- package/dist/controlPlane-P66ZTVNW.js +0 -2
- package/dist/deviceEnrollment-GL4JPVGG.js +0 -2
- package/dist/ipcFactory-B6HBECSU.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import {t}from'./chunk-
|
|
1
|
+
import {t}from'./chunk-5OTF7W2N.js';import {a}from'./chunk-ZQF5KSOK.js';function v(i,d){let t$1=new t(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,s={runtime:t$1,async setAuthContext(e){await t$1.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await s.setAuthContext(null);return}let h=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),m=n.getCurrentUser()?.refreshToken??null,g=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await s.setAuthContext({userId:r,token:h,refreshToken:m,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:g});},bindPlutoAuthHost(){let e=a();return s.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{s.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t$1.signInWithPluto(),signOut:()=>t$1.signOut(),stopManagedSession:()=>t$1.stopManagedSession(),startManagedSession:e=>t$1.startManagedSession(e),onAuthChange:e=>t$1.onIdentityChange(e),getManagedNodeId:e=>t$1.getManagedNodeId(e),getRuntimeStatus:()=>t$1.getRuntimeStatus(),listDevicesWithStatus:()=>t$1.listDevicesWithStatus(),watchDevicesWithStatus:e=>t$1.watchDevicesWithStatus(e),connectDevice:(e,n)=>t$1.connectDevice(e,n),setAutoConnectExcluded:(e,n)=>t$1.setAutoConnectExcluded(e,n)};return Object.defineProperty(s,"identity",{get:()=>t$1.identity,enumerable:true}),s}export{v as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-XPL7PUBW.js';var A=1440*6e4,y=class extends Error{constructor(i,r,o){super(i);this.status=r;this.reason=o;this.name="OpenRtcError";let e=[502,503,504].includes(r),s=o==="device-reenrollment-auth-required";this.code=s?"auth/device-reenrollment-required":e?"coordination/service-unavailable":r===429?"coordination/rate-limited":r===401?"auth/expired":r===403?"admission/denied":"internal/error",this.retryable=s||e,this.plane=s||r===401?"auth":e||r===429?"coordination":r===403?"admission":"internal";}};function k(a){return !(a instanceof y)||a.status!==403?false:a.reason==="device-certificate-stale"||a.reason==="device-certificate-revoked"?true:!a.reason&&a.message==="Device certificate is revoked or stale."}function C(a,t,i){return `openrtc:v2:device-certificate:${a}:${t}:${i}`}function b(a,t){return `openrtc:v2:device-session:${a}:${t}`}async function O(a,t,i){let r=new TextEncoder().encode(`openrtc:v2:session\0${a}\0${t}\0${i}`),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r)),e="";for(let s of o)e+=String.fromCharCode(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function P(a){let t=a.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"="),r=atob(i);return Uint8Array.from(r,o=>o.charCodeAt(0))}async function S(a,t,i,r,o){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+A||!a.signingPublicJwk||a.signingPublicJwk.kty!=="OKP"||a.signingPublicJwk.crv!=="Ed25519"||typeof a.signingPublicJwk.x!="string")return null;let e=a.token.split(".");if(e.length!==3)return null;let s,n;try{s=JSON.parse(new TextDecoder().decode(P(e[0]))),n=b$1(a.token);}catch{return null}if(s.alg!=="EdDSA"||a.signingPublicJwk.kid&&s.kid!==a.signingPublicJwk.kid)return null;try{let d=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},d,P(e[2]),new TextEncoder().encode(`${e[0]}.${e[1]}`)))return null}catch{return null}let c=typeof n.principalId=="string"?n.principalId:"",l=Number(n.iat),p=Number(n.exp);return n.iss!=="openrtc"||n.aud!=="openrtc:v2:gateway-grant"||n.typ!=="device-certificate"||n.appTag!==t||!c||o!==void 0&&c!==o||typeof n.principalKey!="string"||n.principalKey.length===0||n.deviceId!==i||n.deviceKeyThumbprint!==r||typeof n.jti!="string"||n.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(p)||l>=p||p*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function D(a,t,i,r,o){try{let e=C(t,i,r),s=a.readSecureRecord?await a.readSecureRecord(t,e):globalThis.localStorage?.getItem(e);if(!s)return null;let n=JSON.parse(s),c=await S(n,t,r,o,i);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:i,signingPublicJwk:c.signingPublicJwk}:null}catch(e){if(a.readSecureRecord)throw e;return null}}async function E(a,t,i,r,o){try{let e=b(t,r),s=a.readSecureRecord?await a.readSecureRecord(i,e):globalThis.localStorage?.getItem(e);return s?await S(JSON.parse(s),i,r,o):null}catch(e){if(a.readSecureRecord)throw e;return null}}async function K(a,t,i,r,o){try{let e=C(t,i,r),s=JSON.stringify(o);a.writeSecureRecord?await a.writeSecureRecord(t,e,s):globalThis.localStorage?.setItem(e,s);}catch(e){if(a.writeSecureRecord)throw e}}async function x(a,t,i,r,o){try{let e=b(i,r),s=JSON.stringify({token:o.token,expiresAtMs:o.expiresAtMs,principalId:o.principalId,signingPublicJwk:o.signingPublicJwk});a.writeSecureRecord?await a.writeSecureRecord(t,e,s):globalThis.localStorage?.setItem(e,s);}catch(e){if(a.writeSecureRecord)throw e}}async function m(a,t,i,r,o){try{let e=C(t,i,r);if(a.deleteSecureRecord?await a.deleteSecureRecord(t,e):globalThis.localStorage?.removeItem(e),o){let s=b(o,r);a.deleteSecureRecord?await a.deleteSecureRecord(t,s):globalThis.localStorage?.removeItem(s);}}catch(e){if(a.deleteSecureRecord)throw e}}function M(a){return `${a}_${crypto.randomUUID()}`}async function G(a,t){let i=new TextEncoder().encode(`${a}:${t}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",i))].map(o=>o.toString(16).padStart(2,"0")).join("")}var R=class{constructor(t,i,r,o,e={},s){this.apiKey=t;this.endpoints=i;this.keyProvider=r;this.attestation=o;this.events=e;this.botVerification=s;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${t.slice(-16)}`;}record(t){this.events.onLogicalOperation?.(t);}before(t){this.events.beforeLogicalOperation?.(t);}authEpoch(t){let i=this.authEpochs.get(t);if(i)return i;let r={generation:0,devices:new Map};return this.authEpochs.set(t,r),t.subscribe&&(r.unsubscribe=t.subscribe(o=>{o?.type==="principal-changed"&&(r.generation+=1,r.devices.clear(),r.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(t));})),r}dispose(){for(let t of this.authEpochs.values())t.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async post(t,i){let r=M("request"),o=JSON.stringify({apiKey:this.apiKey,...i}),e=null;for(let s=0;s<2;s+=1)try{let n=await fetch(`${this.endpoints.controlPlane}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":r},body:o,signal:AbortSignal.timeout(15e3)});if(n.ok)return n.json();let c=`OpenRTC request failed (${n.status}).`,l;try{let d=await n.json();typeof d.error=="string"&&(c=d.error.slice(0,256)),typeof d.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(d.reason)&&(l=d.reason);}catch{}let p=new y(c,n.status,l);if(e=p,s===0&&[502,503,504].includes(n.status))continue;throw p}catch(n){if(e=n,s===0&&n instanceof TypeError)continue;throw n}throw e instanceof Error?e:new Error("OpenRTC request failed.")}async capability(t,i,r,o=false){this.before("capability.issue");let e=t==="space"?await G(this.apiKey,i):i,n=await(await this.key()).proof((d,u)=>["openrtc:v2:capability",this.apiKey,t,e,d,u].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,l=await this.post("/v2/capabilities",{avenue:{kind:t,id:e},deviceProof:n,...r?{maxPeers:r}:{},...o?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let p={type:"capability",token:l.capability,avenue:t==="ticket"?{kind:"session",id:e}:l.avenue,expiresAtMs:l.expiresAt*1e3};return p.renew=()=>this.capability(t,i,r,o),p}async deviceCertificate(t,i,r,o,e){let s=this.authEpoch(t),n=s.devices.get(i)??{};if(s.devices.set(i,n),e&&n.current&&n.current.token!==e.token)return this.deviceCertificateResult(t,i,r,o,{...n.current,enrolled:false});if(!e&&n.current&&n.current.expiresAtMs>Date.now()+A)return this.deviceCertificateResult(t,i,r,o,{...n.current,enrolled:false});if(!n.inFlight){let l=s.generation;e&&(n.current=void 0,n.recoverRevokedEnrollment=true);let p=e?m(this.keyProvider,this.appTag,e.principalId,i,s.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(t,i,s.sessionKeyHash,o,true)):this.resolveAuthenticatedDevice(t,i,s,o,n.recoverRevokedEnrollment===true);n.inFlight=p.then(d=>{if(s.generation!==l)throw new Error("The OpenRTC authentication identity changed during enrollment.");return n.recoverRevokedEnrollment=false,n.current=d,d}).finally(()=>{n.inFlight=void 0;});}let c=await n.inFlight;return this.deviceCertificateResult(t,i,r,o,c)}async resolveAuthenticatedDevice(t,i,r,o,e=false){let s=await this.key();if(t.getSessionKey){let n=await t.getSessionKey();if(!n)throw new Error("The OpenRTC auth provider has no active principal.");let c=await O(this.appTag,s.thumbprint,n);r.sessionKeyHash=c;let l=await E(this.keyProvider,c,this.appTag,i,s.thumbprint);if(l)return l}return this.enrollAuthenticatedDevice(t,i,r.sessionKeyHash,o,e)}deviceCertificateResult(t,i,r,o,e){let s={type:"device-certificate",token:e.token,avenue:r??{kind:"user",id:e.principalId},expiresAtMs:e.expiresAtMs};return s.renew=async()=>(await this.deviceCertificate(t,i,r,o)).source,s.recoverRejectedCertificate=async()=>(await this.deviceCertificate(t,i,r,o,e)).source,{principalId:e.principalId,source:s,enrolled:e.enrolled}}async enrollAuthenticatedDevice(t,i,r,o,e=false){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let s=async(h,g)=>{let w=await t.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:h,deviceId:i,...{}});if(!w)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:w,deviceId:i,...t.providerId?{providerId:t.providerId}:{}})},n;try{n=await s(!1);}catch(h){if(!(h instanceof y)||h.status!==401)throw h;n=await s(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let c=await this.key(),l=await D(this.keyProvider,this.appTag,n.principalId,i,c.thumbprint);if(l)return {...l,principalId:n.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let{enrollDevice:p}=await import('./deviceEnrollment-33NZEARB.js'),d=await p({apiKey:this.apiKey,appTag:this.appTag,auth:t,attestation:this.attestation,deviceId:i,identity:n,key:c,profile:o,recoverRevokedEnrollment:e||n.deviceRecoveryAuthorized===true,post:(h,g)=>this.post(h,g),recordAssertionExchange:()=>this.record("identity.assertion.exchange")});n=d.identity;let u=d.enrollment;this.record("device.enroll"),this.attestation&&this.record("security.attestation.verify");let v={principalId:n.principalId,token:u.deviceCertificate,expiresAtMs:u.expiresAt*1e3,signingPublicJwk:u.signingPublicJwk,enrolled:true};return await K(this.keyProvider,this.appTag,n.principalId,i,{token:v.token,expiresAtMs:v.expiresAtMs,signingPublicJwk:v.signingPublicJwk}),r&&await x(this.keyProvider,this.appTag,r,i,v),v}async listEnrolledDevices(t,i){let r=await this.deviceCertificate(t,i);return (await this.deviceManagement(r.source,i,"list")).devices??[]}async revokeDevice(t,i,r){let o=await this.deviceCertificate(t,i);if(await this.deviceManagement(o.source,i,"revoke",r),r===i){let e=this.authEpoch(t);await m(this.keyProvider,this.appTag,o.principalId,i,e.sessionKeyHash),e.devices.delete(i),await this.deleteDeviceKey();}}async revokeAllDevices(t,i,r){let o=await this.deviceCertificate(t,i);await this.deviceManagement(o.source,i,"revoke-all",void 0,r);let e=this.authEpoch(t);await m(this.keyProvider,this.appTag,o.principalId,i,e.sessionKeyHash),e.devices.delete(i),r?await this.deviceCertificate(t,i):(e.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(t,i,r,o,e=false){let s=r==="revoke"?"device.revoke":r==="revoke-all"?"identity.revoke-all":null;s&&this.before(s);let{manageDevice:n}=await import('./deviceManagement-PHY5TIOS.js'),c=await n({source:t,currentDeviceId:i,action:r,targetDeviceId:o,exceptCurrent:e,key:()=>this.key(),post:l=>this.post("/v2/devices/manage",l),isStale:k});return s&&this.record(s),c}async durableRoomMembership(t,i,r){if(t.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(r==="join"?"room.join":"room.leave");let o=b$1(t.token),e=String(o.jti??""),n=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",e,r,i,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:r,roomId:i,deviceCertificate:t.token,deviceProof:n}),this.record(r==="join"?"room.join":"room.leave");}grantProvider(t,i={}){let r=null,o=t;return async e=>{if(r)return r;let s=(async()=>{let n=false;o.expiresAtMs<=Date.now()+5*6e4&&o.renew&&(o=await o.renew(),n=true);let c=e.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),e.refreshGrant&&this.before("coordination.credential.refresh");let l=async d=>{let u=b$1(d.token),v=String(u.jti??""),g=await(await this.key()).proof((w,T)=>["openrtc:v2:gateway-grant",v,e.avenue.kind,e.avenue.id,e.runtimeInstanceId,w,T].join(":"));return this.post("/v2/gateway/grants",{credentialType:d.type,credential:d.token,avenue:e.avenue,runtimeInstanceId:e.runtimeInstanceId,ticketFingerprint:e.ticketFingerprint,deviceProof:g,...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},...i.maxPeers?{maxPeers:i.maxPeers}:{},...i.features?{features:i.features}:{},...d.type==="device-certificate"&&i.deviceProfile?{deviceProfile:i.deviceProfile}:{}})},p;try{p=await l(o);}catch(d){if(!k(d))throw d;let u=await o.recoverRejectedCertificate?.();if(!u)throw d;o=u,n=true,p=await l(o);}return this.record(c),e.refreshGrant&&this.record("coordination.credential.refresh"),n&&await i.onSourceRenewed?.({token:o.token,expiresAtMs:o.expiresAtMs}),p})();r=s;try{return await s}finally{r===s&&(r=null);}}}};
|
|
2
|
+
export{R as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a,b as b$1}from'./chunk-XPL7PUBW.js';import {a as a$1}from'./chunk-DUY34MGT.js';import {b}from'./chunk-NRXEG5GQ.js';var L={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":299532e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var w=new WeakMap;function G(r){let e=w.get(r);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function H(r){let e=r?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function y(r){let e=r?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var F=/^[A-Za-z0-9_.:@-]{1,160}$/,K=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function W(r){let e=typeof r=="string"?r.trim():"";if(!F.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return K.test(t)?t:e}function $(r){let e=`openrtc:v2:device-id:${r}`,t,n=(()=>{try{return t=globalThis.localStorage,W(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,n);}catch{}return n}function U(r){let e=typeof r=="string"?r.trim():"";if(!F.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function P(r){let e=b$1(r.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var S=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,n]of this.targets)t.channels.register({...e,delivery:e.delivery??n});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let n of this.descriptors.values())e.channels.register({...n,delivery:n.delivery??t});}detach(e){this.targets.delete(e);}},I=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:(L[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let n=this.options?.maxSessionCreditsUsd;if(n===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=n)return;let s={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:n,kind:"session-limit"};throw this.options?.onWarning?.(s),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let n=this.estimate({operation:e,units:t}).creditsUsd;this.total+=n;let i={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(i);let s=this.options?.warnAtSessionCreditsUsd;!this.warned&&s!==void 0&&this.total>=s&&(this.warned=true,this.options?.onWarning?.({...i,thresholdCreditsUsd:s,kind:"warning"}));}};function _(r){let e=r?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}function N(r,e,t){let n=JSON.stringify({__openrtc:2,kind:r,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function j(r){if(!r||typeof r!="object"||r instanceof Uint8Array)return null;let e=r;return e.__openrtc===2&&(e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var D=class{constructor(e){this.client=e;this.connections=new Map;this.connectionListeners=new Set;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.stopMessage=e.onMessage((t,n)=>this.receive(t,n)),this.stopConnection=e.onConnection(t=>this.add(t)),this.stopDisconnection=e.onDisconnection(t=>this.remove(t)),e.getConnections().forEach(t=>this.add(t));}state(e){let t=_(e);return {set:n=>{let i=N("state",t,n);this.localState.set(t,i);for(let{raw:s}of this.connections.values())this.sendState(s,t,i);},watch:n=>{let i=this.stateListeners.get(t);i||this.stateListeners.set(t,i=new Set);let s=(a,o)=>n({peerId:a,value:o});i.add(s);for(let[a,o]of this.remoteState)o.has(t)&&n({peerId:a,value:o.get(t)});return ()=>i?.delete(s)}}}channel(e){let t=_(e),n=i=>N("channel",t,i);return {send:async i=>{let s=n(i);await Promise.all([...this.connections.values()].map(({raw:a})=>a.send(s)));},sendTo:async(i,s)=>{let a=[...this.connections.values()].find(o=>o.view.peerId===i);if(!a)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await a.raw.send(n(s));},onMessage:i=>{let s=this.channelListeners.get(t);s||this.channelListeners.set(t,s=new Set);let a=(o,c)=>i({peerId:o,message:c});return s.add(a),()=>s?.delete(a)}}}onConnection(e){this.connectionListeners.add(e);for(let{view:t}of this.connections.values())e(t);return ()=>this.connectionListeners.delete(e)}close(){this.stopMessage(),this.stopConnection(),this.stopDisconnection();for(let e of this.stateSenders.values())for(let t of e.values())t.close();for(let e of [...this.connections.values()])this.remove(e.raw);this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear();}add(e){if(this.connections.has(e.id))return;let t=e.remoteNodeId||e.id,n={id:e.id,peerId:t,send:i=>e.send(i),onMessage:i=>{let s=this.rawListeners.get(e.id);s||this.rawListeners.set(e.id,s=new Set);let a=i;return s.add(a),()=>s?.delete(a)},onClose:i=>{let s=this.closeListeners.get(e.id);return s||this.closeListeners.set(e.id,s=new Set),s.add(i),()=>s?.delete(i)}};this.connections.set(e.id,{raw:e,view:n});for(let i of this.connectionListeners)i(n);for(let[i,s]of this.localState)this.sendState(e,i,s);}remove(e){let t=this.connections.get(e.id);if(!t)return;this.connections.delete(e.id);let n=this.stateSenders.get(e);if(n){for(let s of n.values())s.close();this.stateSenders.delete(e);}for(let s of this.closeListeners.get(e.id)??[])s();this.closeListeners.delete(e.id),this.rawListeners.delete(e.id);let i=this.remoteState.get(t.view.peerId);if(i){for(let s of i.keys())for(let a of this.stateListeners.get(s)??[])a(t.view.peerId,null);this.remoteState.delete(t.view.peerId);}}receive(e,t){this.add(e);let n=j(t);if(!n){for(let a of this.rawListeners.get(e.id)??[])a(t);return}let i=this.connections.get(e.id)?.view.peerId??e.remoteNodeId??e.id;if(n.kind==="channel"){for(let a of this.channelListeners.get(n.name)??[])a(i,n.value);return}let s=this.remoteState.get(i);s||this.remoteState.set(i,s=new Map),s.set(n.name,n.value);for(let a of this.stateListeners.get(n.name)??[])a(i,n.value);}sendState(e,t,n){let i=this.stateSenders.get(e);i||this.stateSenders.set(e,i=new Map);let s=i.get(t);s||(s=new a$1(a=>e.send(a)),i.set(t,s)),s.send(n).catch(()=>{});}},g=class{constructor(e,t,n,i){this.kind=e;this.id=t;this.client=n;this.onClosed=i;this.closed=false;w.set(this,n);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}async close(){if(!this.closed){this.closed=true,this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{w.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new D(this.client))}},f=class extends g{constructor(t,n,i,s){super("devices",t,n,i);this.roster=s;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(n=>t(this.roster.mergeDevices(n)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let a=n.devices.list,o=n.devices.listWithStatus,c=n.devices.watch,d=n.devices.watchWithStatus,l=v=>(this.roster.reconcileLiveSnapshot(v),v),p=async()=>this.roster.mergeDevices(l(await a())),h=async()=>this.roster.mergeStatus(await o()),u=v=>c(O=>v(this.roster.mergeDevices(l(O)))),C=v=>d(O=>v(this.roster.mergeStatus(O))),m=Object.create(n);Object.defineProperties(m,{listDevices:{value:p,enumerable:false},listDevicesWithStatus:{value:h,enumerable:false},watchDevices:{value:u,enumerable:false},watchDevicesWithStatus:{value:C,enumerable:false},devices:{value:{...n.devices,list:p,listWithStatus:h,watch:u,watchWithStatus:C},enumerable:true}}),w.set(this,m),this.stopRosterSync=c(l);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},k=class extends g{constructor(t,n,i,s){super("space",t,n,i);this.delivery=s;this.kind="space";this.leave=()=>this.close();}},T=class extends g{constructor(t,n,i,s,a){super("room",t,n,i);this.membership=s;this.onLeave=a;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},E=class extends g{constructor(t,n,i,s){super("ticket",t,n,i);this.token=s;this.kind="ticket";}},A=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new S;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let n=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId());for(let i of this.handles)i instanceof f&&i.replaceEnrolledDevices(n);return n},revoke:async(e,t={})=>{this.assertOpen();let n=t.auth??this.options.auth;if(!n)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let i=U(e),s=await this.deviceId();await(await this.controlPlane()).revokeDevice(n,s,i);for(let a of this.handles)a instanceof f&&a.removeEnrolledDevice(i);i===s&&this.retireAuthCapabilities(n);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let n=await this.deviceId();for(let i of this.handles)i instanceof f&&i.retainCurrentEnrolledDevice(n);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${y(e)}`,JSON.stringify({payload:t.payload??"reliable",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let n=t.access??"capability";return this.activateOnce(`room:${y(e)}`,JSON.stringify({access:n,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),n==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${y(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,n]of this.activations)n.handle===e&&this.activations.delete(t);};this.apiKey=H(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new I(e.usage);}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=Promise.all([import('./controlPlane-YAMXWHAF.js'),this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-SBNKLVYF.js').then(({browserDeviceKeyProvider:e})=>e)]).then(([{OpenRTCV2ControlPlane:e},t])=>new e(this.apiKey,this.internals.endpoints??a,t,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification)))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,n,i){this.assertOpen();let s=this.activations.get(e);if(s){if(s.fingerprint!==t||s.auth!==n)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return s.promise}let a={fingerprint:t,auth:n},o=i().then(c=>(a.handle=c,c)).catch(c=>{throw this.activations.get(e)===a&&this.activations.delete(e),c});return a.promise=o,this.activations.set(e,a),o}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(n=>n.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):$(this.appTag);return U(e)}runtimeOptions(e){let t=this.options.transports,n=t?.privacy==="relay-only";if(n&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");let i=n?b(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??a).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:n?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:typeof t?.webrtc=="object"?n?{...t.webrtc,privacyMode:true,useTurn:true,useDefaultIceServers:false}:t.webrtc:t?.webrtc===true?n?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:i},transportPriority:i}}async activate(e){let t=await this.controlPlane(),n={relay:this.options.transports?.relay===true,moq:!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},i=e.source,s=null,a=()=>({userId:e.principalId,token:i.token,tokenProvider:async()=>i.token,expiresAtMs:i.expiresAtMs}),o=this.runtimeOptions({avenue:e.source.avenue,grantProvider:t.grantProvider(e.source,{maxPeers:e.maxPeers,features:n,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async l=>{i={...i,...l},await s?.setAuth(a());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName,devicePlatform:e.devicePlatform}),[c,{wrapAssembly:d}]=await Promise.all([this.internals.runtimeFactory(o),import('./OpenRTCShared.js')]);s=d(c,this.internals.platform==="native"?"native":"web"),await s.setAuth(a()),this.channels.attach(s,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await s.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(l){throw this.channels.detach(s),await s.advanced.runtime.shutdown().catch(()=>{}),l}return this.usage.record("coordination.connection.open"),s}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:i}=await import('./deviceProfile-3BEQZLJF.js'),s=i(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),o=await a.deviceCertificate(t,n,void 0,s),c=await this.activate({kind:"devices",id:o.principalId,source:o.source,principalId:o.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:s.name,devicePlatform:s.platform,deviceMetadata:s.metadata}),d;try{d=await a.listEnrolledDevices(t,n);}catch(h){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),h}let{AuthenticatedDeviceRoster:l}=await import('./deviceRoster-VZA3TQOR.js'),p;return p=new f(o.principalId,c,()=>{this.channels.detach(c),this.onClosed(p);},new l(d)),this.handles.add(p),p}async joinSpace(e,t={}){this.assertOpen();let n=y(e),i=await(await this.controlPlane()).capability("space",n,t.maxPeers,t.advancedFanout),s=String(b$1(i.token).principalId),a=await this.activate({kind:"space",id:n,source:i,principalId:s,deviceId:P(i),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),o;return o=new k(n,a,()=>{this.channels.detach(a),this.onClosed(o);},t.payload??"reliable"),this.handles.add(o),o}async joinRoom(e,t={}){this.assertOpen();let n=y(e),i=t.membership??"ephemeral",s=t.access??"capability";if(i==="durable"&&s!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(s==="authenticated"){let l=t.auth??this.options.auth;if(!l)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let p=await this.deviceId(),h=await this.controlPlane(),u=await h.deviceCertificate(l,p,{kind:"room",id:n});i==="durable"&&await h.durableRoomMembership(u.source,n,"join");let C;try{C=await this.activate({kind:"room",id:n,source:u.source,principalId:u.principalId,deviceId:p,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:i==="durable",advancedFanout:t.advancedFanout});}catch(v){throw i==="durable"&&await h.durableRoomMembership(u.source,n,"leave").catch(()=>{}),v}let m;return m=new T(n,C,()=>{this.channels.detach(C),this.onClosed(m);},i,i==="durable"?async()=>{await h.durableRoomMembership(u.source,n,"leave");}:void 0),this.handles.add(m),m}let a=await(await this.controlPlane()).capability("room",n,t.maxPeers,t.advancedFanout),o=String(b$1(a.token).principalId),c=await this.activate({kind:"room",id:n,source:a,principalId:o,deviceId:P(a),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),d;return d=new T(n,c,()=>{this.channels.detach(c),this.onClosed(d);},"ephemeral"),this.handles.add(d),d}async issueTicket(e,t={}){this.assertOpen();let n=y(e),i=await(await this.controlPlane()).capability("ticket",n,t.maxPeers,t.advancedFanout),s=String(b$1(i.token).principalId),a=await this.activate({kind:"ticket",id:n,source:i,principalId:s,deviceId:P(i),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),o;return o=new E(n,a,()=>{this.channels.detach(a),this.onClosed(o);},i.token),this.handles.add(o),o}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{await this.controlPlanePromise?.then(e=>e.dispose(),()=>{}),this.activations.clear();}}}};function B(r,e){return new A(r,e)}export{G as a,B as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {v}from'./chunk-
|
|
1
|
+
import {v}from'./chunk-ZQF5KSOK.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,n,t){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,n,t);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,n){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,n)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,n,t,i,r){return this.backend.updatePresence(e,n,t,i,r)}async refreshLivePresence(e,n,t){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,n,t)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDevicesWithStatus(){if(typeof this.backend.listDevicesWithStatus!="function")throw new Error("Selected runtime adapter does not support listDevicesWithStatus().");return this.backend.listDevicesWithStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,n){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,n)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerConnectionRecords(e){return typeof this.backend.resolvePeerConnectionRecords!="function"?[]:this.backend.resolvePeerConnectionRecords(e)}async updateDevice(e,n){return this.backend.updateDevice(e,n)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,n){return this.backend.onDevicesChange(e,n)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,n,t,i){return this.backend.sendMessage(e,n,t,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,n){let t=this.backend;return t.watchFriendDevices?t.watchFriendDevices(e,n):()=>{}}async updateFriendTicket(e){let n=this.backend;n.updateFriendTicket&&await n.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,n){this.backend.startAutoConnect(e,n);}async submitDesiredPeerProjection(e,n){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,n);}startPresenceLoop(e,n,t,i,r){this.backend.startPresenceLoop(e,n,t,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,n){return this.backend.updateSession(e,n)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateLocalDeviceName(e){return typeof this.backend.updateLocalDeviceName!="function"?null:this.backend.updateLocalDeviceName(e)}async startManagedSessionNative(e){let n=this.backend;if(typeof n.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return n.startManagedSessionNative(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let n=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:n}),n}async startPresenceLoopOnce(e,n,t,i,r){let o=this.backend;if(typeof o.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return o.startPresenceLoopOnce(e,n,t,i,r)}async startAutoConnectOnce(e,n){let t=this.backend;if(typeof t.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return t.startAutoConnectOnce(e,n)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getEndpointTicketWithToken(e,n){let t=this.backend;return typeof t.getEndpointTicketWithToken!="function"?null:t.getEndpointTicketWithToken(e,n)}async registerSessionToken(e,n,t,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,n,t,i);}async revokeSessionTokensByScope(e){let n=this.backend;return typeof n.revokeSessionTokensByScope!="function"?[]:n.revokeSessionTokensByScope(e)}async openPeerBi(e,n){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,n)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,n){let t=this.backend;return typeof t.is_current_transport_stable_id!="function"?false:t.is_current_transport_stable_id(e,n)}async openPeerNativeBi(e,n,t){let i=this.backend;if(typeof i.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return i.openPeerNativeBi(e,n,t)}async openPeerBiTransportOnly(e,n){let t=this.backend;return typeof t.openPeerBiTransportOnly=="function"?t.openPeerBiTransportOnly(e,n):this.openPeerBi(e,n)}async openPeerUni(e,n){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,n)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async setAutoConnectExcluded(e,n){if(typeof this.backend.setAutoConnectExcluded!="function")throw new Error("Selected runtime adapter does not support setAutoConnectExcluded().");return this.backend.setAutoConnectExcluded(e,n)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange!="function"?()=>{}:this.backend.onConnectionStateChange(e)}async sendExplicitFilePath(e,n,t){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,n,t)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}getRuntimeCapabilities(){let e=this.backend;return typeof e.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():v()}async onIncomingNativeMessage(e){let n=this.backend;return typeof n.onIncomingNativeMessage!="function"?()=>{}:n.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let n=this.backend;typeof n.setCoreClient=="function"&&n.setCoreClient(e);}};export{a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {f,e as e$1,b,c as c$1,w,z as z$1,h as h$1,p}from'./chunk-AG2F6MOB.js';import {c as c$2,a,e as e$2}from'./chunk-CWGKLGJZ.js';import {c,e,d,f as f$1,b as b$1}from'./chunk-KJTJLLJE.js';import*as G from'tweetnacl';function M(){throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an OpenRTCAuthProvider; legacy runtimes must import openrtc/auth explicitly.");}var et=3e4,tt=5*6e4,nt=3e4,Ae=12,it=10*6e4,rt=5*6e4,X=15e3,ot=15e3,st=1e3,_e=250,at="openrtc.v2",ct="openrtc.auth.",g=class extends Error{constructor(t,i){super(t);this.retryable=i;this.name="CoordinationConnectError";this.code=a.COORDINATION_DISCONNECTED;this.plane="coordination";}},V=class extends Error{constructor(t,i,r){let o=e$2({code:t,message:i,retryable:r});super(`Coordination gateway ${t}: ${i}`);this.name="CoordinationGatewayProtocolError";this.code=o.code||t||a.COORDINATION_PROTOCOL,this.retryable=r,this.plane=o.plane;}};function Ee(n){return n instanceof g&&/\bstale-budget\b/i.test(n.message)}function Me(n){if(typeof n!="object"||n===null)return false;let e=n;if(e.retryable===false)return true;let t=e.status??e.statusCode,i=typeof t=="number"?t:Number.NaN;if(Number.isInteger(i)&&i>=400&&i<500&&![408,425,429].includes(i))return true;let r=String(e.code??"");return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(r)}function dt(n){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(n*(.75+e[0]/4294967295*.5)))}function C(n){if(typeof crypto.randomUUID=="function")return `${n}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${n}:${t}`}async function lt(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t="";for(let i of new Uint8Array(e))t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function ut(n,e,t){let i=new URL(n);if(i.search||i.hash||i.username||i.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(i.protocol==="https:")i.protocol="wss:";else if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol!=="wss:"&&i.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return i.pathname=`${i.pathname.replace(/\/+$/,"")}/v${t}/connect/${e}`,i.toString()}function ke(n){let e=new URL(n);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var J=class n{constructor(e){this.options=e;this.runtimeInstanceId=C("runtime");this.socket=null;this.socketReady=false;this.activeGrantToken=null;this.activeGrantProtocolVersion=1;this.leaseRefreshMode="off";this.pendingLeaseRefreshKey=null;this.connectPromise=null;this.desiredPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.deviceListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectOutageStartedAtMs=null;this.reconnectCircuitOpen=false;this.hostAvailable=true;this.connectionReadyWaiters=new Set;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;if(e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),i=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",r=t.protocol==="https:"||t.protocol==="wss:",o=e.gateway.testingAllowInsecureLoopback===true&&i&&(t.protocol==="http:"||t.protocol==="ws:");if(!r&&!o)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,t,i,r,o,s){let a=this.desiredPresence;this.desiredPresence={localNodeId:e,ticket:t,online:i,ttlMs:r,metadata:o,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!a||a.localNodeId!==e||a.ticket!==t||a.online!==i||a.ttlMs!==r||a.metadata!==o||a.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);let d=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(l){if(!(l instanceof g)||!l.retryable)throw l;await this.waitForConnectionReady();}this.appliedPresenceRevision>=d||(a&&a.ticket!==t&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:C("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,d));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:C("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<ot)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}setHostAvailability(e){let t=e.available&&!this.hostAvailable;this.hostAvailable=e.available;for(let i of this.roomConnections.values())i.setHostAvailability(e);for(let i of this.friendConnections.values())i.setHostAvailability(e);if(!e.available){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}t&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(i=>this.scheduleReconnect(i));}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=t;if(t.excludedPeers!==void 0){let r=[...new Set(t.excludedPeers.map(o=>String(o??"").trim().toLowerCase()).filter(Boolean))].sort();if(r.length>_e)throw new Error(`Coordination excluded-peer set exceeds ${_e} devices.`);this.desiredExcludedPeers=r,i={...t,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:C("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let t=new n({...this.options,credentialPurpose:"device-control"});try{await t.deleteDevice(e);}finally{t.stopAuthScopedActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:C("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,t){let i=r=>e(t?r.filter(o=>o.nodeId!==t):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected(),()=>this.deviceListeners.delete(i)}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&t.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:C("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:C("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:i=>{t=i,this.sessionStreams.add(i);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,i,r){await this.ensureConnected();let o=C("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:t,state:i,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){let i=[...new Set(e.map(a=>a.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let a of i)if(a.length>128||a.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,s=[];t(new Map);for(let a of i)!a||a===this.options.getCurrentUserId()||this.openFriendConnection(a).then(c=>{if(r.value){c.stopAuthScopedActivity();return}s.push(c.onDevicesChange(d=>{o.set(a,d.filter(l=>l.online)),t(new Map(o));}));}).catch(()=>{r.value||(o.set(a,[]),t(new Map(o)));});return ()=>{r.value=true;for(let a of s)a();for(let a of i)this.friendConnections.get(a)?.stopAuthScopedActivity(),this.friendConnections.delete(a);}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:C("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthScopedActivity(){this.stopped=true,this.reconnectOutageStartedAtMs=null,this.stopSocket(),this.rejectConnectionReadyWaiters(new g("Coordination activity stopped before capability admission completed.",false)),this.desiredExcludedPeers=[];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();this.pendingAcks.clear(),this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthScopedActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthScopedActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,t,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new n({...this.options,avenueOverride:{kind:"room",id:r}}),o.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(r,o));try{await o.updatePresence(t,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(s){if(!(s instanceof g)||!s.retryable)throw s;await o.waitForConnectionReady();}}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthScopedActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(r=>t(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new g("Coordination reconnect is parked until the host is foregrounded and online.",true);if(this.reconnectCircuitOpen)throw new g("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new g("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence??this.controlPresence(),t=this.desiredPresenceRevision,i=async()=>{let r=await this.mintGatewayCredential(e,false);await new Promise((o,s)=>{let a=new WebSocket(ut(r.gatewayUrl,r.routeKey,r.protocolVersion),[at,`${ct}${r.token}`]);this.socket=a;let c=false,d=null,l=setTimeout(()=>{a.close(4408,"authentication timeout"),d=new g("Coordination gateway authentication timed out.",true),s(d);},X);a.onopen=()=>{a.send(JSON.stringify({v:1,type:"auth",token:r.token,device:this.gatewayDevice(e)}));},a.onmessage=f=>{let p;try{p=JSON.parse(String(f.data));}catch{a.close(4400,"invalid gateway frame"),c||(clearTimeout(l),s(new Error("Coordination gateway returned an invalid frame.")));return}if(p.type==="ready"&&!c&&(this.activeGrantToken=r.token,this.activeGrantProtocolVersion=r.protocolVersion,this.leaseRefreshMode=p.leaseRefreshMode??"off",c=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?t:0),clearTimeout(l),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(r.expiresAtMs,r.protocolVersion),this.resolveConnectionReadyWaiters(),o()),p.type==="error"&&!c){d=new g(`Coordination gateway ${p.code}: ${p.message}`,p.retryable),clearTimeout(l),s(d),a.close(4403,p.code);return}this.handleFrame(p);},a.onerror=()=>{c||(clearTimeout(l),d??(d=new g("Coordination gateway connection failed.",true)),s(d));},a.onclose=f=>{clearTimeout(l),this.socket===a&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),this.rejectPendingAuthRefresh(new g("Coordination gateway closed during credential refresh.",f.code!==4401&&f.code!==4403)),!this.stopped&&this.desiredPresence&&f.code!==1e3&&!Ee(d)&&this.scheduleReconnect(d??new g(`Coordination gateway closed (${f.code}).`,f.code!==4401));};});};try{await i();}catch(r){if(!Ee(r))throw r;await i();}}async mintGatewayCredential(e,t){let r={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await lt(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:C("credential")},o;try{if(!this.options.gateway.grantProvider)throw new g("OpenRTC 2.0 coordination requires a v2 gateway grant provider.",!1);o=await this.options.gateway.grantProvider({...r,...t&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(a){throw a instanceof g?a:new g(a instanceof Error?a.message:"Coordination credential mint failed.",!Me(a))}if(o.protocolVersion!==2)throw new g("Unsupported coordination gateway protocol.",false);let s=ke(this.options.gateway.endpoint);if(ke(o.gatewayUrl)!==s)throw new g("Coordination credential returned an unexpected gateway origin.",false);return o}handleFrame(e){if(e.type==="auth.refreshed"){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),t.resolve());}else if(e.type==="lease.refreshed"){let t=this.pendingAuthRefresh;t&&e.idempotencyKey===this.pendingLeaseRefreshKey&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),t.resolve());}else if(e.type==="roster.snapshot"){this.devices.clear();for(let t of e.devices)this.devices.set(t.deviceId,this.toDevice(t));this.emitDevices();}else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let t=this.devices.has(e.device.deviceId),i=this.toDevice(e.device);this.devices.set(i.deviceId,i),this.emitDeviceEvents([{type:t?"modified":"added",device:i}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=st&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="session.changed"){let t=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let i of this.sessionStreams)i.enqueue(t);}else if(e.type==="ack"){let t=this.pendingAcks.get(e.idempotencyKey);t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let i=this.pendingAuthRefresh;clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,i.reject(new g(`Coordination gateway ${e.code}: ${e.message}`,e.retryable));return}let t=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.reject(new V(e.code,e.message,e.retryable)));}}async sendOperation(e){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let t=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(i){if(!(i instanceof V)||i.code!=="budget-renewal-required"&&i.code!==a.BUDGET_RENEWAL_REQUIRED||!i.retryable)throw i;this.budgetRenewalEpoch===t&&await this.renewBudget(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},X);this.pendingAcks.set(e.idempotencyKey,{resolve:i,reject:r,timer:o}),t.send(JSON.stringify(e));});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication().then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}snapshot(e){return [...this.devices.values()].filter(t=>!e||t.nodeId!==e).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}updateLocalDeviceExpiry(e){let t=this.options.getLocalDeviceId(),i=this.devices.get(t);if(!i||i.expiresAt===e)return;let r={...i,expiresAt:e};this.devices.set(t,r),this.emitDeviceEvents([{type:"modified",device:r}]),this.emitDevices();}scheduleAuthRefresh(e,t){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),r=t===2?tt:et,o=i>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!o){this.stopSocket(false),this.scheduleReconnect(new g("Coordination credential crossed a billing boundary.",true));return}(t===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(a=>{this.stopSocket(false),this.scheduleReconnect(a);});},o?i-r:Math.max(1e3,i+1e3));}async refreshAuthentication(e=false){let t=this.socket,i=this.desiredPresence;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady||!i)throw new g("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let r=await this.mintGatewayCredential(i,!e),o,s,a=new Promise((d,l)=>{o=d,s=l;}),c=setTimeout(()=>{this.pendingAuthRefresh?.timer===c&&(this.pendingAuthRefresh=null),s(new g("Coordination credential refresh timed out.",true));},X);this.pendingAuthRefresh={promise:a,resolve:o,reject:s,timer:c},t.send(JSON.stringify({v:1,type:"auth.refresh",token:r.token})),await a,this.activeGrantToken=r.token,this.activeGrantProtocolVersion=r.protocolVersion;}async refreshLease(){let e=this.socket;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady)throw new g("Coordination socket is unavailable for lease refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let t=C("lease"),i,r,o=new Promise((a,c)=>{i=a,r=c;}),s=setTimeout(()=>{this.pendingAuthRefresh?.timer===s&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),r(new g("Coordination lease refresh timed out.",true));},X);this.pendingLeaseRefreshKey=t,this.pendingAuthRefresh={promise:o,resolve:i,reject:r,timer:s},e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:t}));try{await o;}catch{await this.refreshAuthentication(true);}}scheduleReconnect(e){if(this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof g?e.retryable:!Me(e))){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new g("Coordination reconnect circuit is open.",false));return}if(this.reconnectOutageStartedAtMs??(this.reconnectOutageStartedAtMs=Date.now()),!this.hostAvailable)return;let i=Math.min(this.reconnectAttempt,Ae),r=Date.now()-this.reconnectOutageStartedAtMs>=it,o=dt(r?rt:h$1(i,250,nt));this.reconnectAttempt=Math.min(i+1,Ae),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(s=>this.scheduleReconnect(s));},o);}stopSocket(e=true){e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null,this.leaseRefreshMode="off",this.pendingLeaseRefreshKey=null,this.rejectPendingAuthRefresh(new g("Coordination credential refresh was canceled.",true));let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new g("Coordination reconnect circuit is unavailable.",false)):new Promise((e,t)=>{this.connectionReadyWaiters.add({resolve:e,reject:t});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let t of this.connectionReadyWaiters)t.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,t.reject(e));}rejectPendingAcks(e){for(let t of this.pendingAcks.values())clearTimeout(t.timer),t.reject(new Error(e));this.pendingAcks.clear();}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);if(!i)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return i}async openFriendConnection(e){let t=this.friendConnections.get(e);if(t||(t=new n({...this.options,avenueOverride:{kind:"user",id:e}}),t.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,t)),!t.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");t.desiredPresence={...this.desiredPresence};}return await t.ensureConnected(),t}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var Q=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let t=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>t+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",s=Number(r?.expiresAtMs),a=Date.now();if(!o||!Number.isFinite(s)||s<=a+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let c={token:o,expiresAtMs:s};return this.cached=c,this.refreshRetryUsed=false,this.notify(c),this.scheduleRefresh(c),c})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,t){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(t?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let t of this.listeners)t(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let t=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},t);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};function Z(n){if(!n)return null;let e=2166136261;for(let t=0;t<n.length;t+=1)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var v=class v{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.durablePresenceRetryTimer=null;this.durablePresenceRetryAttempt=0;this.localExcludedPeers=new Set;}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),r=`${e}::${i}`;this.startedAutoConnectKey===r&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=r,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let t=this.normalizeDesiredPeers(e);this.desiredPeersByDeviceId=new Map(t.map(r=>[r.deviceId,r]));let i=JSON.stringify(t);i!==this.desiredPeerSignature&&(this.desiredPeerSignature=i,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let r=this.normalizeDesiredPeers(t),o=JSON.stringify(r),s=o!==this.desiredPeerSignature;this.desiredPeerSignature=o,this.desiredPeersByDeviceId=new Map(r.map(a=>[a.deviceId,a])),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),s&&this.deps.onDesiredPeersChanged?.(),await this.enqueueDesiredPeerSubmission(i,e,r);}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",r=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!r||!o.nodeId||o.nodeId===r))return o}return r?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===r)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}async setAutoConnectExcluded(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let r=this.deps.resolveWebLogicalDeviceId();r&&await this.deps.updateExcludedPeers(r,this.currentExcludedPeersSnapshot());}startPresenceLoop(e,t,i,r,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let s=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:r,metadata:o,deviceName:i};let a=this.deps.resolveWebLogicalDeviceId();(async()=>{let d=await this.deps.withWebPresenceMetadata(o,a);if(!(s===this.presenceStartGeneration&&this.presenceState!==null))return;let f=false,p=null,y=(w,P)=>{this.scheduleDurableRosterRetry(a,s,v.PRESENCE_LEASE_MS,w,P);};p=setTimeout(()=>{f||y("initial coordination presence write timed out");},v.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),this.deps.updatePresence(t,r,true,v.PRESENCE_LEASE_MS,d,i).then(()=>{f=true,p&&(clearTimeout(p),p=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(w=>{p&&(clearTimeout(p),p=null),y("initial coordination presence write failed",w);});})();}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,i,r,o){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer||this.isPermanentProviderError(o))return;let s=this.durablePresenceRetryAttempt+1;if(s>v.PRESENCE_RETRY_LIMIT){console.warn(`[WasmBridge] ${r}; durable roster retry circuit opened after ${v.PRESENCE_RETRY_LIMIT} attempts`,o);return}this.durablePresenceRetryAttempt=s;let a=Math.min(v.PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,s-1),v.PRESENCE_RETRY_MAX_DELAY_MS),c=(s*17%21-10)/100,d=Math.max(v.PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying coordination presence in ${d}ms`,o),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let l=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,true,i,l,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(l=>{this.scheduleDurableRosterRetry(e,t,i,"durable roster registration retry failed",l);});},d);}isPermanentProviderError(e){let t=e&&typeof e=="object"?e:null;if(t?.retryable===false)return true;let r=(t?String(t.code??""):"").toLowerCase().replace(/^functions\//,"");return ["auth/invalid-user-token","auth/user-token-expired","auth/user-disabled","permission-denied","unauthenticated","invalid-argument","failed-precondition"].some(o=>r===o||r.endsWith(`/${o}`))}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};v.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,v.PRESENCE_RETRY_MIN_DELAY_MS=2e3,v.PRESENCE_RETRY_MAX_DELAY_MS=6e4,v.PRESENCE_RETRY_LIMIT=8,v.PRESENCE_LEASE_MS=15*6e4;var ee=v;function te(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var pt="[OpenRTC][teardown-trace]";function ht(){try{let n=globalThis;if(n.OPENRTC_TEARDOWN_TRACE===!0||n.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function De(n,e={}){console.info(pt,{kind:n,ts:new Date().toISOString(),...e}),ht()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:n,stack:new Error(`teardown: ${n}`).stack});}var ie="trustedDevice",ft="plutonium:e2ee:identity:v1",mt="plutonium:e2ee:identity:session:v1",gt="openrtc-trust",W="identity",Ne="transport-trust:v1",yt=1,S=null,U=null;function A(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)t[i]=e.charCodeAt(i);return t}function H(n){let e="";for(let t=0;t<n.length;t+=1)e+=String.fromCharCode(n[t]);return btoa(e)}async function oe(n){let e=await crypto.subtle.digest("SHA-256",n),t=new Uint8Array(e);return Array.from(t).map(i=>i.toString(16).padStart(2,"0")).join("")}function vt(){return typeof sessionStorage>"u"?null:sessionStorage}function wt(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ft);}catch{}}var ne=null;async function xe(){return ne||(ne=(async()=>{let n=globalThis.crypto?.subtle;if(!n||typeof n.generateKey!="function")return false;try{let e=await n.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),ne)}async function bt(n){let e=await crypto.subtle.exportKey("raw",n);return new Uint8Array(e)}function It(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Oe(){let n=It();return n?new Promise(e=>{let t;try{t=n.open(gt,1);}catch{e(null);return}t.onupgradeneeded=()=>{let i=t.result;i.objectStoreNames.contains(W)||i.createObjectStore(W);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function St(){let n=await Oe();if(!n)return null;try{return await new Promise(e=>{let r=n.transaction(W,"readonly").objectStore(W).get(Ne);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{n.close();}}async function Rt(n){let e=await Oe();if(!e)return false;try{return await new Promise(t=>{let i=e.transaction(W,"readwrite");i.objectStore(W).put(n,Ne),i.oncomplete=()=>t(!0),i.onerror=()=>t(!1),i.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Le(n,e){let t=await bt(n.publicKey),i=await oe(t),r=n.privateKey;return {publicKey:t,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let s=await crypto.subtle.sign({name:"Ed25519"},r,A(o));return H(new Uint8Array(s))}}}function Ct(n,e,t){let i=n.secretKey;return {publicKey:n.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return Pt(r,i)}}}function tn(n=32){let e=crypto.getRandomValues(new Uint8Array(n));return H(e)}function Pt(n,e){let t=G.sign.detached(A(n),e);return H(t)}function Tt(n,e,t){try{return G.sign.detached.verify(A(n),A(e),A(t))}catch{return false}}async function nn(n,e,t){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",A(t),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,A(e),A(n))}catch{}return Tt(n,e,t)}function rn(n){return H(n)}function on(n){if(!n||!n.trim())return null;try{let e=JSON.parse(n),t=e&&typeof e=="object"&&!Array.isArray(e)?e[ie]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let i=t,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,s=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!s?null:{version:r,identityPublicKey:o,identityFingerprint:s}}catch{return null}}async function At(){let n=await Dt().catch(()=>null);return n?{version:yt,identityPublicKey:H(n.publicKey),identityFingerprint:n.fingerprint}:null}async function se(n){let e=await At();if(!e)return n??void 0;let t=typeof n=="string"?n.trim():"";if(!t)return JSON.stringify({[ie]:e});try{let i=JSON.parse(t);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[ie]:e})}catch{}return JSON.stringify({metadata:n,[ie]:e})}function _t(){if(typeof window>"u")return null;let n=window.__TAURI_INTERNALS__;return !n||typeof n.invoke!="function"?null:n.invoke.bind(n)}async function Et(){if(typeof window>"u")return null;let n=_t();if(!te()&&!n)return null;if(!n)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await n("openrtc_get_transport_trust_identity"),t=A(e.publicKeyBase64);if(t.byteLength!==G.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await oe(t);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:t,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return n("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let t=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw t.cause=e,t}}function Mt(){let n=vt();n&&n.removeItem(mt);}async function kt(){if(wt(),Mt(),S)return S;let n=await Et();if(n)return S=n,S;if(await xe()){let e=await St();if(e)return S=await Le(e,true),S}return null}async function Dt(n={}){let e=await kt();if(e)return e;if(U)return U;let t=Nt(n);U=t;try{return await t}finally{U===t&&(U=null);}}async function Nt(n){if(S)return S;let e=n.ephemeral===true;if(await xe())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await Rt(t)),S=await Le(t,i),S}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let t=G.sign.keyPair(),i=await oe(f(t.publicKey));return S=Ct(t,i,!1),S}catch{return null}}var ae={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function an(){return ae}var xt={adapter:"browser-wasm",signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:false,irohLan:false,webRtcUpgrade:true,webRtcLan:true,nativeWebRtc:false,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},Ot={adapter:"native-ipc",signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:false,webRtcLan:false,nativeWebRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function We(n){return {adapter:n.adapter,signaling:{...n.signaling},transport:{...n.transport},nativeProtocols:{...n.nativeProtocols},lifecycle:{...n.lifecycle},transfers:{...n.transfers},fallback:{...n.fallback}}}function Fe(n=globalThis){let e=We(xt),t=typeof n?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function L(n){return n?.compiled===true&&n.enabled===true}function dn(n,e=false){let t=We(Ot),i=n?.transport;return i&&(t.transport.irohQuic=L(i.irohQuic),t.transport.irohLan=L(i.irohLan),t.transport.webRtcUpgrade=L(i.webRtc),t.transport.nativeWebRtc=L(i.webRtc),t.transport.webRtcLan=L(i.webRtcLan),t.transport.moq=L(i.moq),t.transport.ble=L(i.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function ln(n){return {environment:n.adapter==="native-ipc"||n.adapter==="tauri-ipc"?"native":n.adapter==="browser-wasm"?"web":"unknown",transports:{quic:n.transport.irohQuic,irohRelay:n.transport.irohQuic||n.adapter==="browser-wasm",irohLan:n.transport.irohLan,webRtc:n.transport.webRtcUpgrade||n.transport.nativeWebRtc,webRtcLan:n.transport.webRtcLan,moq:n.transport.moq,ble:n.transport.ble},lifecycle:{...n.lifecycle},storage:{localFileSystem:n.transfers.explicitFilePath,transferHistory:n.transfers.history},nativeProtocols:{...n.nativeProtocols}}}function Be(n){if(n.errorCode)return n;let e=n.error||n.readinessReason;if(!e)return n;let t=c$2(e);return {...n,errorCode:t.errorCode,retryable:t.retryable,errorPlane:t.errorPlane}}function F(n){return !n||typeof n!="object"?{}:n instanceof Map?Object.fromEntries(n):n}function ce(n){let e=F(n),t=F(e.device);if(!Object.keys(t).length)return e;let i={...t,...e};return delete i.device,i}function u(n,...e){for(let t of e){let i=n[t];if(typeof i=="string"&&i.trim().length>0)return i}}function k(n,...e){for(let t of e){let i=n[t];if(typeof i=="boolean")return i}}function h(n,...e){for(let t of e){let i=n[t];if(typeof i=="number"&&Number.isFinite(i))return i}}function D(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(n instanceof Date){let e=n.getTime();return Number.isFinite(e)?e:void 0}if(typeof n=="string"){let e=Date.parse(n);return Number.isFinite(e)?e:void 0}if(n&&typeof n=="object"){let e=n;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let t=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(t!==void 0&&Number.isFinite(t)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function de(...n){let e=n.map(D).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function le(n){if(typeof n!="string")return;let e=n.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ue(n){let e=le("presenceStatus"in n?n.presenceStatus:void 0),t="presenceUpdatedAt"in n?D(n.presenceUpdatedAt):void 0,i="presenceExpiresAt"in n?D(n.presenceExpiresAt):void 0,r=t??de(n.lastSeenAt,n.updatedAt,n.createdAt),o=i??D(n.expiresAt),s=e;s||(n.online?r!==void 0&&r+3e5<=Date.now()?s="idle":s="online":s="offline");let a=typeof n.ticket=="string"?n.ticket.trim():"",c="connectable"in n&&typeof n.connectable=="boolean"?n.connectable:s==="online"&&a.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:c}}function Ge(n){return p(n)}function B(n,...e){return Ge(u(n,...e))}function z(n){if(!Array.isArray(n))return;let e=Array.from(new Set(n.map(Ge).filter(t=>!!t)));return e.length?e:void 0}function He(n){let e=F(n),t={webrtc:h(e,"webrtc"),webrtcLan:h(e,"webrtcLan","webrtc_lan"),webrtcTurn:h(e,"webrtcTurn","webrtc_turn"),iroh:h(e,"iroh"),irohLan:h(e,"irohLan","iroh_lan"),irohRelay:h(e,"irohRelay","iroh_relay"),irohWebrtc:h(e,"irohWebrtc","iroh_webrtc"),irohMoq:h(e,"irohMoq","iroh_moq"),ble:h(e,"ble"),moq:h(e,"moq")};return Object.values(t).some(i=>i!==void 0)?t:void 0}function Ke(n){return (n.discoveryMode??"space")==="space"&&typeof n.apiKey=="string"&&n.apiKey.trim().length>0&&typeof n.spaceKey=="string"&&n.spaceKey.trim().length>0}function ze(n,e,t){return t?true:(typeof n.appTag=="string"?n.appTag:typeof n.tag=="string"?n.tag:void 0)===e}function ue(n,e){let t=ce(n),i=u(t,"deviceId","device_id")||e||"",r=u(t,"nodeId","node_id")||"",o=u(t,"ticket")||"";return {deviceId:i,deviceName:u(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:o,friendTicket:u(t,"friendTicket","friend_ticket"),presenceStatus:le(u(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:h(t,"presenceUpdatedAt","presence_updated_at")??de(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:h(t,"presenceExpiresAt","presence_expires_at")??D(t.presenceExpiresAt??t.presence_expires_at)??D(t.expiresAt??t.expires_at),connectable:k(t,"connectable"),kind:u(t,"kind"),nodeId:r||void 0,platformType:u(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:u(t,"sessionId","session_id"),userId:u(t,"userId","user_id"),lastSeenAt:t.lastSeenAt??t.last_seen_at,expiresAt:t.expiresAt??t.expires_at,createdAt:t.createdAt??t.created_at,updatedAt:t.updatedAt??t.updated_at,metadata:u(t,"metadata"),excludedPeers:pe(t.excludedPeers??t.excluded_peers),availableTransports:z(t.availableTransports??t.available_transports),transports:z(t.transports)}}function pe(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Lt(n){let e=Ue(n);return {...n,...e,connectionStatus:"connectionStatus"in n&&typeof n.connectionStatus=="string"?n.connectionStatus:n.online?"online":"disconnected",settledReady:"settledReady"in n&&typeof n.settledReady=="boolean"?n.settledReady:false,readinessState:"readinessState"in n&&typeof n.readinessState=="string"?n.readinessState:void 0,readinessReason:"readinessReason"in n&&typeof n.readinessReason=="string"?n.readinessReason:void 0,peerHealth:"peerHealth"in n&&typeof n.peerHealth=="string"?n.peerHealth:"unknown",peerId:"peerId"in n&&typeof n.peerId=="string"?n.peerId:void 0,promotionEligible:"promotionEligible"in n&&typeof n.promotionEligible=="boolean"?n.promotionEligible:true,scopes:"scopes"in n?pe(n.scopes):[],connectionId:"connectionId"in n&&typeof n.connectionId=="string"?n.connectionId:void 0,deviceIdHint:"deviceIdHint"in n&&typeof n.deviceIdHint=="string"?n.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in n&&typeof n.activeTransportStableId=="number"?n.activeTransportStableId:"activeTransportStableId"in n?n.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in n&&typeof n.transportGeneration=="number"?n.transportGeneration:void 0,routeGeneration:"routeGeneration"in n&&typeof n.routeGeneration=="number"?n.routeGeneration:void 0,activeTransport:"activeTransport"in n?n.activeTransport:void 0,parallelTransport:"parallelTransport"in n?n.parallelTransport:void 0,availableTransports:"availableTransports"in n?z(n.availableTransports):"transports"in n?z(n.transports):void 0,latencyMs:"latencyMs"in n&&typeof n.latencyMs=="number"?n.latencyMs:void 0,latencyByTransport:"latencyByTransport"in n?He(n.latencyByTransport):void 0}}function K(n,e){return e===void 0?true:e===null?n==null:n==null||n===e}function qe(n,e){let t=K(n.connectionId,e.connectionId)&&K(n.nodeId,e.nodeId)&&K(n.activeTransportStableId,e.activeTransportStableId)&&K(n.transportGeneration,e.transportGeneration)&&K(n.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:t?o:void 0;return {inheritsSnapshot:t,fields:{connectionId:i(e.connectionId??void 0,n.connectionId),activeTransportStableId:i(e.activeTransportStableId,n.activeTransportStableId),transportGeneration:i(e.transportGeneration,n.transportGeneration),routeGeneration:i(e.routeGeneration,n.routeGeneration),activeTransport:i(e.activeTransport,n.activeTransport),parallelTransport:i(e.parallelTransport,n.parallelTransport),latencyMs:t?n.latencyMs:void 0,latencyByTransport:t?n.latencyByTransport:void 0}}}var Wt={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Ft(n,e,t){let i=qe(n,{connectionId:e.activeConnectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):n.promotionEligible??true;if(!r)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields,readinessReason:e.readinessReason??n.readinessReason};let o=e.status??n.connectionStatus,s=typeof o=="string"?o.trim().toLowerCase():"",a=s==="failed"||s==="closed"||s==="disconnected",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,l=n.settledReady===true||n.readinessState==="routable";if(i.inheritsSnapshot&&l&&!a&&!d)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields,readinessReason:e.readinessReason??n.readinessReason};let f=a?false:d,p=d&&!a&&(s==="connecting"||s==="connected")?"connected":o,y=d?"routable":e.readinessState??(i.inheritsSnapshot?n.readinessState:void 0),w=f?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?n.readinessReason:void 0);return {...n,connectionStatus:p,settledReady:f,readinessState:y,readinessReason:w,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields}}function Bt(n,e){let t=qe(n,{connectionId:e.connectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:false,nodeId:e.nodeId??n.nodeId,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let i=e.status??n.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",s=n.settledReady===true||n.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&s&&o&&!a)return {...n,peerHealth:n.peerHealth??e.health,peerId:n.peerId??e.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,connectionId:n.connectionId??e.connectionId,deviceIdHint:n.deviceIdHint??e.deviceIdHint,scopes:n.scopes?.length?n.scopes:e.scopes??n.scopes};if(s&&o)return {...n,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??n.readinessReason,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...Wt,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let c=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&s&&!o&&!c)return {...n,peerHealth:n.peerHealth??e.health,peerId:n.peerId??e.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,connectionId:n.connectionId??e.connectionId,deviceIdHint:n.deviceIdHint??e.deviceIdHint,activeTransportStableId:n.activeTransportStableId??e.activeTransportStableId,transportGeneration:n.transportGeneration??e.transportGeneration,routeGeneration:n.routeGeneration??e.routeGeneration,activeTransport:n.activeTransport??e.activeTransport,parallelTransport:n.parallelTransport===void 0?e.parallelTransport:n.parallelTransport,scopes:n.scopes?.length?n.scopes:e.scopes??n.scopes};let d=e.transportState==="connected"&&e.health==="healthy",l=o?false:c,f=!o&&(c||d)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,p=l?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?n.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=l?(t.inheritsSnapshot?n.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?n.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...n,connectionStatus:f,settledReady:l,readinessState:p,readinessReason:y,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,nodeId:e.nodeId??n.nodeId,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:n.scopes}}function Ut(n){let{device:e,session:t=null,peer:i=null,isPromotionEligible:r}=n,o=Lt(e);return t&&(o=Ft(o,t,r)),i&&(o=Bt(o,i)),Be(o)}function je(n){let e=ce(n),t=ue(e),i=le(u(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ue({...t,...i?{presenceStatus:i}:{},presenceUpdatedAt:h(e,"presenceUpdatedAt","presence_updated_at")??de(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:h(e,"presenceExpiresAt","presence_expires_at")??D(e.presenceExpiresAt??e.presence_expires_at)??D(e.expiresAt??e.expires_at),connectable:k(e,"connectable")}),o={...t,...r,connectionStatus:u(e,"connectionStatus","connection_status")||"disconnected",settledReady:k(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,peerHealth:u(e,"peerHealth","peer_health")||"unknown",peerId:u(e,"peerId","peer_id"),scopes:pe(e.scopes),connectionId:u(e,"connectionId","connection_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),activeTransportStableId:h(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:h(e,"transportGeneration","transport_generation")??void 0,routeGeneration:h(e,"routeGeneration","route_generation")??void 0,activeTransport:B(e,"activeTransport","active_transport"),parallelTransport:B(e,"parallelTransport","parallel_transport")??null,availableTransports:z(e.availableTransports??e.available_transports),latencyMs:h(e,"latencyMs","latency_ms"),latencyByTransport:He(e.latencyByTransport??e.latency_by_transport)};return Ut({device:o})}function $e(n){let e=ce(n);return Be({peerId:u(e,"peerId","peer_id")||"",deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),nodeId:u(e,"nodeId","node_id"),activeConnectionId:u(e,"activeConnectionId","active_connection_id"),candidateConnectionIds:Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(t=>typeof t=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(t=>typeof t=="string"):[],status:u(e,"status")||"disconnected",health:u(e,"health")||"unknown",settledReady:k(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,activeTransportStableId:h(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:h(e,"transportGeneration","transport_generation")??void 0,routeGeneration:h(e,"routeGeneration","route_generation")??void 0,activeTransport:B(e,"activeTransport","active_transport"),parallelTransport:B(e,"parallelTransport","parallel_transport")??null,replacementPending:k(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:h(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transitionCount:h(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:h(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:h(e,"replacementCount","replacement_count")??void 0,retireCount:h(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(t=>typeof t=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:u(e,"error"),errorCode:u(e,"errorCode","error_code")??void 0,retryable:k(e,"retryable")??void 0,errorPlane:u(e,"errorPlane","error_plane")??void 0})}function mn(n){let e=F(n);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectingTransitionCount:typeof e.connectingTransitionCount=="number"?e.connectingTransitionCount:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function gn(n){let e=F(n);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function Gt(n){switch(n){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Ye(n){let e=n.activeConnectionId||n.candidateConnectionIds[0]||null;if(!e)return null;let t=Gt(n.status),i=t==="connected"?"connected":t==="connecting"?"connecting":"closed",r=t==="connected"?n.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.nodeId??null,state:t,transportState:i,protocolState:r,routable:!!n.settledReady,readinessState:n.readinessState,readinessReason:n.readinessReason,transportGeneration:n.transportGeneration,routeGeneration:n.routeGeneration,activeTransportStableId:n.activeTransportStableId,activeTransport:n.activeTransport,parallelTransport:n.parallelTransport??null,replacementInProgress:n.replacementPending,lastLifecycleTransitionAtMs:n.lastLifecycleTransitionAtMs,transitionCount:n.transitionCount,connectingTransitionCount:n.connectingTransitionCount,replacementCount:n.replacementCount,retireCount:n.retireCount,lastDisconnectReason:n.lastDisconnectReason??void 0,lastReconnectReason:n.lastReconnectReason??void 0,updatedAt:n.lastSeenAtMs,error:n.error??void 0}}function Xe(n){let e=F(n),t=u(e,"connectionId","connection_id");if(!t)return null;let i=u(e,"state")||"connecting",r=h(e,"createdAt","created_at")??h(e,"updatedAt","updated_at")??Date.now(),o=h(e,"updatedAt","updated_at")??r;return {connectionId:t,deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),remoteNodeId:u(e,"remoteNodeId","remote_node_id"),state:i,transportState:u(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:u(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:k(e,"routable")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transportGeneration:h(e,"transportGeneration","transport_generation")??void 0,routeGeneration:h(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:h(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:B(e,"activeTransport","active_transport"),parallelTransport:B(e,"parallelTransport","parallel_transport")??null,replacementInProgress:k(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:h(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:h(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:h(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:h(e,"replacementCount","replacement_count")??void 0,retireCount:h(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:u(e,"error")??void 0,createdAt:r,updatedAt:o}}function Ve(n,e){return n?n.connectionId===e.connectionId&&(n.deviceId??null)===(e.deviceId??null)&&(n.deviceIdHint??null)===(e.deviceIdHint??null)&&(n.remoteNodeId??null)===(e.remoteNodeId??null)&&n.state===e.state&&(n.transportState??null)===(e.transportState??null)&&(n.protocolState??null)===(e.protocolState??null)&&!!n.routable==!!e.routable&&(n.activeTransport??null)===(e.activeTransport??null)&&(n.parallelTransport??null)===(e.parallelTransport??null)&&(n.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(n.transportGeneration??null)===(e.transportGeneration??null)&&(n.routeGeneration??null)===(e.routeGeneration??null)&&!!n.replacementInProgress==!!e.replacementInProgress&&(n.transitionCount??null)===(e.transitionCount??null)&&(n.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(n.replacementCount??null)===(e.replacementCount??null)&&(n.retireCount??null)===(e.retireCount??null)&&(n.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(n.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(n.error??null)===(e.error??null):false}function Ht(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(i,"base64").toString("utf8"))}catch{return null}return null}function Kt(n){let e=typeof n=="string"?n.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,o=r?Ht(r):null,s=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,a=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:Z(i),tokenFingerprint:Z(s),tokenSuffixFingerprint:Z(r),scope:a,maxConnections:c}}function q(n,e,t={}){let i=typeof n.finishSend=="function"?n.finishSend.bind(n):typeof n.finish_send=="function"?n.finish_send.bind(n):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let r=e.getWriter();return new WritableStream({write:o=>r.write(o),async close(){await r.close(),await i();},abort:o=>r.abort(o)})}var m=class m{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.coordinationHostAvailability={available:true,reason:"initial"};this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.applicationRouteEscalationSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;if(this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.nativeTrustTokens=this.options.coordinationGateway?new Q(this.options.coordinationGateway.nativeTrustTokenProvider):null,this.presenceManager=new ee({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(i,r)=>this.waitForWasmClient(i,r),warnMissingWasmOnce:i=>this.warnMissingWasmOnce(i),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(i,r)=>this.withWebPresenceMetadata(i,r),updatePresence:(i,r,o,s,a,c)=>this.updatePresence(i,r,o,s,a,c),updateExcludedPeers:(i,r)=>this.getCoordinationSignaling().updateDevice(i,{excludedPeers:r}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:i=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(i)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations()}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let t=M();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(i=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(s=>s(this.toRuntimeIdentity(i)));return}let r=i?.uid??null,o=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=r,o&&o!==r&&this.stopAuthScopedActivity({userId:o}),this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(s=>s(this.toRuntimeIdentity(i)));});}get tag(){return this.appTag}getRuntimeCapabilities(){return Fe()}getDeviceIdentityStorageKey(){let e=f$1(this.options);return `${m.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),r=Date.now(),o=null;try{let l=localStorage.getItem(i);o=l?JSON.parse(l):null;}catch{o=null;}let s=typeof o?.deviceId=="string"?o.deviceId.trim():"",a=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let l=s||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:l})),l}if(s&&typeof a=="number"&&a>r){let l=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:s,expiresAt:l})),s}let c=this.createRandomDeviceId(),d=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:d})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');if(!this.options.coordinationGateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");return this.browserCoordinationSignaling||(this.browserCoordinationSignaling=new J({projectId:this.options.projectId,gateway:this.options.coordinationGateway,appTag:this.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(e=false)=>{let t=this.currentUser;return t?.getToken?t.getToken(e):null},getAppCheckToken:async(e=false)=>{let t=this.authContext?.appCheckTokenProvider??this.options.platformAttestationTokenProvider;return t?t(e):M().getAppCheckToken(e)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t),avenueOverride:this.options.coordinationAvenueOverride,nativeTrustTokens:this.nativeTrustTokens}),this.browserCoordinationSignaling.setHostAvailability?.(this.coordinationHostAvailability)),this.browserCoordinationSignaling}usesCoordinationGateway(){return !!this.options.coordinationGateway}setCoordinationHostAvailability(e){this.coordinationHostAvailability=e,this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){await this.browserCoordinationSignaling?.reconnectAfterHostResume?.();}async getCoordinationNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateCoordinationNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeCoordinationNativeTrustToken(e,t){return this.nativeTrustTokens?this.nativeTrustTokens.subscribe(e,t):()=>{}}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let r=this.getCoordinationSignaling();if(!r.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await r.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return i=JSON.stringify({...r,deviceId:t}),await se(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await se(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,r=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(te()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==r&&await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await M().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,r=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===r)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=r,this.hasSyncedAuthToWasmClient=true,r===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,r);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return Ke(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return ze(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthScopedActivity(e){De("WasmBridge.stopAuthScopedActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthScopedActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,r){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(r))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await e$1(t);return this.wasmClient??null}normalizeDevice(e,t){return ue(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return je(e)}normalizePeerSessionSnapshot(e){return $e(e)}toBackendConnectionStateFromPeerSession(e){return Ye(e)}normalizeConnectionStateSnapshot(e){return Xe(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return Ve(e,t)}deliverConnectionState(e,t,i,r){let o=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(o),this.lastDeliveredConnectionStates.set(o.connectionId,o);let a=(r??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(a,o)||(r&&r.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let r=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(r&&r.uid===this.authContext?.userId)try{return await r.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await M().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await M().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await M().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await M().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,r=3e5,o,s){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?m.EPHEMERAL_DEVICE_ID_TTL_MS:r,d=await this.withWebPresenceMetadata(o,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:d,deviceName:s?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,d,s);}async refreshLivePresence(e,t,i,r){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),s=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:s,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,s,r);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,r){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,r)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDevicesWithStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async r=>{let o=this.normalizeDeviceStatusSnapshot({...r,connectionStatus:r.online?"online":"disconnected"}),s=typeof r.nodeId=="string"?r.nodeId.trim():"";if(!s||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[a,c]=await Promise.all([i.iroh_path_kind(s),i.iroh_transport_rtt_ms(s)]);if(typeof c!="number"||!Number.isFinite(c))return o;let d=Math.max(0,Math.round(c)),l={};if(a==="direct-lan")l.irohLan=d;else if(a==="direct-quic")l.iroh=d;else if(a==="ble")l.ble=d;else if(a==="relay")l.irohRelay=d;else if(a==="iroh-webrtc")l.irohWebrtc=d;else if(a==="iroh-moq")l.irohMoq=d;else return o;return {...o,latencyMs:d,latencyByTransport:l}}catch(a){return b("[WasmBridge] iroh transport latency unavailable",{deviceId:r.deviceId,error:a instanceof Error?a.message:String(a)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(r=>this.normalizePeerSessionSnapshot(r)).filter(r=>!!(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId||r.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_peer=="function"){let r=await i.wait_for_settled_peer(e,t);return !r||typeof r!="object"?null:this.normalizePeerSessionSnapshot(r)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let r=await i.open_peer_bi(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:r.recv,writable:q(r,r.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,i){let r=await this.waitForWasmClient(500),o=r&&r.open_peer_native_bi;if(typeof o=="function"){let s=await o.call(r,e,t,i);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:s.recv,writable:q(s,s.send)}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_bi()")}async openPeerBiTransportOnly(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiTransportOnly is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),r=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!i,hasTransportOnly:r,timeoutMs:t}),r){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:q(o,o.send)}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let r=await i.open_peer_uni(e,t),o=r?.writable??r;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:q(r,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}async resolvePeerConnectionRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(r=>({connectionId:typeof r.connectionId=="string"?r.connectionId:"",nodeId:typeof r.nodeId=="string"?r.nodeId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,endpointId:typeof r.endpointId=="string"?r.endpointId:null,transportGeneration:typeof r.transportGeneration=="number"?r.transportGeneration:0,routeGeneration:typeof r.routeGeneration=="number"?r.routeGeneration:void 0,transportStableId:typeof r.transportStableId=="number"?r.transportStableId:null,transportSource:typeof r.transportSource=="string"?r.transportSource:null,lastTransportChangeAtMs:typeof r.lastTransportChangeAtMs=="number"?r.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof r.lastRouteChangeAtMs=="number"?r.lastRouteChangeAtMs:void 0,state:typeof r.state=="string"?r.state:"pending",statusReason:typeof r.statusReason=="string"?r.statusReason:null,createdAtMs:typeof r.createdAtMs=="number"?r.createdAtMs:0,updatedAtMs:typeof r.updatedAtMs=="number"?r.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerConnectionRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=r=>{if(!r||typeof r!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=r;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let r=await t.peer_session(e),o=i(r);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let r=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!r||typeof r.start_auto_connect!="function")return;await r.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(r){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:r});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnectSnapshot();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async setAutoConnectExcluded(e,t){await this.presenceManager.setAutoConnectExcluded(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.setAutoConnectExcluded(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}setCoreClient(e){e&&typeof e.connect=="function"?(this.coreClient=e,this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.applicationRouteEscalationSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onConnectionStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.applicationRouteEscalationSubscriptionGeneration=e,Promise.resolve(i).then(r=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){r();return}this.applicationRouteEscalationUnsubscribe=r,this.applicationRouteEscalationSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.applicationRouteEscalationSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=e.readinessReason==="application-crypto-key-pending"||e.readinessReason==="application-crypto-confirmation-pending",i=t?[e.transportGeneration??0,e.routeGeneration??0,e.readinessReason].join(":"):null,r=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i&&r.get(e.connectionId)===i||this.applicationRouteEscalations.has(e.connectionId)||!t&&e.remoteNodeId&&this.coreClient.hasApplicationRouteForPeer?.(e.connectionId,e.remoteNodeId)===true)return;let o=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!o?.ticket)return;let s=this.authScopedRuntimeGeneration,a=this.coreClient;i&&r.set(e.connectionId,i);let c;c=(async()=>{let d=typeof a.ensureManagedApplicationRoute=="function"?await a.ensureManagedApplicationRoute({ticket:o.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??o.nodeId,expectedDeviceId:o.deviceId,timeoutMs:2e4}):await a.connect(o.ticket,2e4,o.deviceId,void 0,{admissionAlreadyPresented:true});if(s!==this.authScopedRuntimeGeneration)return;let l=d,f=l.id?.trim()||e.connectionId,p=l.remoteNodeId?.trim()||e.remoteNodeId?.trim()||l.deviceId?.trim()||o.deviceId;if(a.hasApplicationRouteForPeer?.(f,p)!==true&&a.hasApplicationRouteForPeer?.(f,p)!==true)throw new Error(`application crypto was not ready for ${p}`)})().catch(d=>{s===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:o.deviceId,remoteNodeId:e.remoteNodeId??o.nodeId,error:d?.message??String(d)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===c){this.applicationRouteEscalations.delete(e.connectionId);let d=this.lastDeliveredConnectionStates?.get(e.connectionId);d&&s===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(d));}}),this.applicationRouteEscalations.set(e.connectionId,c);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=Date.now();c$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:Kt(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);c$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,elapsedMs:Date.now()-i});let o=e.endpointTicket;if(o&&this.coreClient){let s=this.coreClient;try{c$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null});let a=typeof s.ensureManagedApplicationRoute=="function"?await s.ensureManagedApplicationRoute({ticket:o,connectionId:r?.connectionId??null,remoteNodeId:r?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:r?.approvedScope??null,timeoutMs:2e4}):await s.connect(o,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0,approvedScope:r?.approvedScope??null}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",d=typeof a?.deviceId=="string"?a.deviceId.trim():"",l=c||r?.remoteNodeId?.trim?.()||d||e.deviceId?.trim?.()||"",f=typeof s.hasApplicationRouteForPeer=="function"?s.hasApplicationRouteForPeer.bind(s):null;if(!(!!l&&f?.(a?.id??void 0,l)===!0)&&l&&typeof s.waitForApplicationCryptoForPeer=="function"&&!(!!await s.waitForApplicationCryptoForPeer(l,2e4)&&(!f||f(a?.id??void 0,l)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:l,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${l}`),{applicationCryptoNotReady:!0});c$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,elapsedMs:Date.now()-i});}catch(a){if(a?.applicationCryptoNotReady)throw a;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,error:a?.message??String(a)}),r}}return r}forceReconnectSnapshot(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,r,o){this.presenceManager.startPresenceLoop(e,t,i,r,o);}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"&&await t.is_connected(e)?true:this.hasConnectedIndependentPeerRoute(t,e)}async hasConnectedIndependentPeerRoute(e,t){if(!e||typeof t!="string"||t.trim().length===0)return false;let i=t.trim(),r=[];if(typeof e.peer_session=="function")try{let o=await e.peer_session(i);o&&typeof o=="object"&&r.push(this.normalizePeerSessionSnapshot(o));}catch{}if(typeof e.peer_sessions=="function")try{let o=await e.peer_sessions();Array.isArray(o)&&r.push(...o.filter(s=>!!s&&typeof s=="object").map(s=>this.normalizePeerSessionSnapshot(s)));}catch{}return r.some(o=>{let s=typeof o.peerId=="string"?o.peerId.trim():"",a=typeof o.deviceId=="string"?o.deviceId.trim():"",c=typeof o.deviceIdHint=="string"?o.deviceIdHint.trim():"",d=typeof o.nodeId=="string"?o.nodeId.trim():"";return (i===s||i===a||i===c||i===d)&&o.status==="connected"&&o.settledReady===true&&o.replacementPending!==true&&w(o.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let r=await e.connection_states(),o=(Array.isArray(r)?r:[]).map(s=>this.normalizeConnectionStateSnapshot(s)).filter(s=>!!s);return o.length>0&&b("[WasmBridge] replaying current wasm connection states",o.map(s=>({connectionId:s.connectionId,deviceId:s.deviceId??null,deviceIdHint:s.deviceIdHint??null,remoteNodeId:s.remoteNodeId??null,state:s.state,transportState:s.transportState??null,protocolState:s.protocolState??null,routable:s.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(r=>this.toBackendConnectionStateFromPeerSession(r)).filter(r=>!!r);return i.length>0&&b("[WasmBridge] replaying current wasm connection states",i.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),i}onConnectionStateChange(e){let t=new Map,i=new Map,r=this.authScopedRuntimeGeneration,o=false,s=d=>{let l=d.detail,f=this.normalizeConnectionStateSnapshot(l),p=typeof l?.connectionId=="string"?l.connectionId.trim():"";if(!p||o)return;if(f&&(f.state==="closed"||f.state==="failed"||f.state==="disconnected")){this.deliverConnectionState(f,e,"rust-event-detail",t);return}let y=(i.get(p)??0)+1;i.set(p,y);let w=this.authScopedRuntimeGeneration;(async()=>{let P=await this.waitForWasmClient(500);if(!(o||w!==this.authScopedRuntimeGeneration||i.get(p)!==y)){if(P&&typeof P.connection_state=="function"){let re=await P.connection_state(p),b=this.normalizeConnectionStateSnapshot(re);if(!o&&w===this.authScopedRuntimeGeneration&&i.get(p)===y&&b){this.deliverConnectionState(b,e,"rust-event",t);return}}!o&&w===this.authScopedRuntimeGeneration&&i.get(p)===y&&f&&this.deliverConnectionState(f,e,"rust-event-detail",t);}})().catch(P=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:p,error:P});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",s),this.getConnectionStates().then(d=>{!o&&r===this.authScopedRuntimeGeneration&&d.forEach(l=>{i.has(l.connectionId)||this.deliverConnectionState(l,e,"replay",t);});}).catch(d=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",d);}),()=>{o=true,i.clear(),c&&a.removeEventListener("connection-state-changed",s);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(s=>s.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return m.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let s of i){if([...r].length>=m.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=s.charCodeAt(0);s==="/"||s==="\\"||s==="\0"||a<32||a===127?r+="_":r+=s;}let o=r.trim();return !o||o==="."||o===".."?m.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return m.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let r of t){if(i.length>=m.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=r.charCodeAt(0);o<33||o>126||r==='"'||r==="\\"?i+="_":i+=r;}return i.length>0?i:m.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>m.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,r,o){let s=o?.headerFrame===true?4:0,a=new Uint8Array(25+s+r.byteLength);a[0]=m.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let d=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,r.byteLength,false),a.set(r,d),a}async sendExplicitFileData(e){let t=e.connection,i=e.file,r=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!r)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let s=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(c$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:s}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let d=await this.waitForWasmClient();if(!d)throw new Error("WASM explicit transfer requires an initialized WASM client");let l=new TextEncoder,f={transfer_id:s,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},p=l.encode(JSON.stringify(f));this.assertExplicitTransferHeaderSize(p);let y=new Uint8Array(4);new DataView(y.buffer).setUint32(0,p.byteLength,false);let w=new Uint8Array(y.byteLength+p.byteLength);w.set(y,0),w.set(p,y.byteLength);let P=async()=>{if(a!=="web"||!t||typeof t.sendOnWebRTC!="function"||typeof t.isWebRtcApplicationRouteReady!="function"||t.isWebRtcApplicationRouteReady()!==true)return a&&a!=="web"&&typeof t?.isWebRtcApplicationRouteReady=="function"&&t.isWebRtcApplicationRouteReady()===true&&c$1("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:c,transferId:s,receiverPlatformType:a}),false;let b=r?z$1(r):null,_=O=>b?b.protectFrame(O):O,T=new Uint8Array(await i.arrayBuffer()),E=this.createWebRTCExplicitTransferId(),N=Math.max(1,Math.ceil(T.byteLength/m.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),I=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,x=async()=>{I&&typeof I.getBufferedAmount=="function"&&typeof I.waitForDrain=="function"&&I.getBufferedAmount()>m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await I.waitForDrain(m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,4294967295,N,_(p),{headerFrame:true})),await x(),T.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,0,N,_(new Uint8Array(0)))),true;let j=0;for(let O=0;O<T.byteLength;O+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Qe=T.slice(O,Math.min(O+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,T.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,j,N,_(Qe))),j+=1,await x();}return c$1("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:s,chunks:N,encrypted:!!b}),true},re=async()=>{let b=d.open_peer_bi_explicit_file_sender;if(typeof b!="function")return false;let _=await b.call(d,c,5e3),T=_?.writable??_?.send;if(!T||typeof T.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");c$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:_.applicationCryptoWrapped===true});let E=q(_,T,{requireFinish:true}).getWriter(),N=false;try{await E.write(w);let I=new Uint8Array(await i.arrayBuffer());for(let x=0;x<I.byteLength;x+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let j=I.slice(x,Math.min(x+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await E.write(j);}}catch(I){throw N=true,I}finally{try{await E.close();}catch(I){if(!N)throw I}finally{E.releaseLock();}}return true};try{try{if(await P())return}catch(b){c$1("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:s,error:b instanceof Error?b.message:String(b)});}if(await re())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{c$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:s,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};m.EXPLICIT_FILE_PROTOCOL_TYPE=2,m.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,m.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,m.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",m.MAX_EXPLICIT_FILE_NAME_CHARS=180,m.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",m.MAX_EXPLICIT_MIME_TYPE_CHARS=255,m.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",m.EPHEMERAL_DEVICE_ID_TTL_MS=ae.browserIdentity.ephemeralDeviceIdTtlMs;var Je=m;
|
|
2
|
+
export{M as a,te as b,tn as c,nn as d,rn as e,on as f,se as g,Dt as h,De as i,ce as j,Ut as k,je as l,$e as m,mn as n,gn as o,Xe as p,ae as q,an as r,xt as s,Ot as t,We as u,Fe as v,dn as w,ln as x,Je as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as OpenRTCV2ControlPlane}from'./chunk-IKZ33R7R.js';export{a as OPENRTC_PRODUCTION_V2_ENDPOINTS,b as decodeOpenRTCV2Claims}from'./chunk-XPL7PUBW.js';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {d,a}from'./chunk-CWGKLGJZ.js';function v(e){return e.status===403&&e.reason==="device-enrollment-revoked"}async function f(e){let r=e.identity,a$1=async(o=false,t=e.recoverRevokedEnrollment)=>{let n=await e.key.proof((d,l)=>["openrtc:v2:device-enroll",e.appTag,r.principalId,e.deviceId,d,l].join(":")),i=e.attestation?{kind:e.attestation.kind,...await e.attestation.getEvidence({challenge:`openrtc:v2:attestation:${e.appTag}:${r.principalId}:${e.deviceId}:${n.nonce}`,apiKey:e.apiKey})}:void 0;return e.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:e.deviceId,deviceProof:n,...e.profile?.name||e.profile?.platform?{deviceProfile:{...e.profile.name?{name:e.profile.name}:{},...e.profile.platform?{platform:e.profile.platform}:{}}}:{},...t?{recoverRevokedEnrollment:true}:{},...o?{recoverDeviceKey:true}:{},...i?{attestation:i}:{}})};try{return {identity:r,enrollment:await a$1()}}catch(o){let t=o;if(!(t instanceof Error))throw o;if(v(t)){if(r.deviceRecoveryAuthorized===false)throw d(a.AUTH_DEVICE_REENROLLMENT_REQUIRED,"This device was removed. Sign in again to authorize re-enrollment.",{retryable:true,plane:"auth",cause:o});return {identity:r,enrollment:await a$1(false,true)}}if(t.status!==412||t.reason!=="device-key-recovery-required")throw o;let n=await e.auth.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:true,deviceId:e.deviceId,recoveryReason:"device-key-rotation"});if(!n)throw new Error("The OpenRTC auth provider returned no assertion.");let i=await e.post("/v2/assertions/exchange",{assertion:n,...e.auth.providerId?{providerId:e.auth.providerId}:{}});if(e.recordAssertionExchange(),i.principalId!==r.principalId)throw new Error("The authenticated principal changed during device-key recovery.");return r=i,{identity:r,enrollment:await a$1(true)}}}
|
|
2
|
+
export{f as enrollDevice};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { P as PlutoIpcBridge } from './ipc-CflAVodw.js';
|
|
2
|
-
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-
|
|
3
|
-
export { c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, f as OpenRTCCapabilityHandle, g as OpenRTCChannel, i as OpenRTCConnection, j as OpenRTCDeviceProfile, k as OpenRTCDevicesHandle, l as OpenRTCDevicesStartOptions, m as OpenRTCEnrolledDevice, o as OpenRTCRoomHandle, p as OpenRTCRoomJoinOptions, q as OpenRTCSpaceHandle, r as OpenRTCSpaceJoinOptions, s as OpenRTCState, t as OpenRTCTicketHandle, u as OpenRTCTicketIssueOptions, v as OpenRTCTransportPreferences, x as OpenRTCUsageUpdate, y as OpenRTCUsageWarning } from './types-
|
|
2
|
+
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-DhmY9hBy.js';
|
|
3
|
+
export { c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, f as OpenRTCCapabilityHandle, g as OpenRTCChannel, i as OpenRTCConnection, j as OpenRTCDeviceProfile, k as OpenRTCDevicesHandle, l as OpenRTCDevicesStartOptions, m as OpenRTCEnrolledDevice, o as OpenRTCRoomHandle, p as OpenRTCRoomJoinOptions, q as OpenRTCSpaceHandle, r as OpenRTCSpaceJoinOptions, s as OpenRTCState, t as OpenRTCTicketHandle, u as OpenRTCTicketIssueOptions, v as OpenRTCTransportPreferences, x as OpenRTCUsageUpdate, y as OpenRTCUsageWarning } from './types-DhmY9hBy.js';
|
|
4
4
|
import './OpenRTCShared.js';
|
|
5
|
-
import './assembly-
|
|
6
|
-
import './types-
|
|
7
|
-
import './ITransport-
|
|
8
|
-
import './capabilities-
|
|
5
|
+
import './assembly-CLdwe5T-.js';
|
|
6
|
+
import './types-l3m3GrOe.js';
|
|
7
|
+
import './ITransport-UNOXiRJD.js';
|
|
8
|
+
import './capabilities-BUe5YldR.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Create a lazy OpenRTC 2.0 browser client. Construction validates only local
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-7FPG3MFF.js';import'./chunk-VBUDERMM.js';import {b}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-7FPG3MFF.js';import'./chunk-VBUDERMM.js';import {b}from'./chunk-QCPSLUKO.js';import'./chunk-XPL7PUBW.js';import {d}from'./chunk-Z2WVSXPW.js';import'./chunk-DUY34MGT.js';export{a as OPENRTC_ERROR_CODES,b as OpenRtcError,e as classifyOpenRtcFailure,d as openRtcError,c as projectOpenRtcErrorFields}from'./chunk-CWGKLGJZ.js';import'./chunk-NRXEG5GQ.js';function i(n){return b(n,{platform:"web",runtimeFactory:async e=>{let{createWasmClient:t}=await import('./runtime/factories.js');return t(e)}})}i.native=function(n,e=d()){return b(n,{platform:"native",deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:O}=await import('./ipcFactory-JTMNUTZI.js');return O(t,e)}})};export{i as OpenRTC};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-HIXXBEWX.js';import {u}from'./chunk-5OTF7W2N.js';import'./chunk-LRT5GEGH.js';import'./chunk-Z2WVSXPW.js';import'./chunk-DUY34MGT.js';import'./chunk-Y35AKFCM.js';import'./chunk-ZQF5KSOK.js';import'./chunk-AG2F6MOB.js';import'./chunk-CWGKLGJZ.js';import {a}from'./chunk-KJTJLLJE.js';import'./chunk-45WBH7E3.js';import'./chunk-NRXEG5GQ.js';function s(i,r){let t=a(i);return a$1(t,new u({...t,bridge:r}))}export{s as createIpcClient};
|
package/dist/native.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { P as PlutoIpcBridge } from './ipc-CflAVodw.js';
|
|
2
2
|
export { c as classifyNativeIpcFailure, i as isNativeIpcCommandUnavailable } from './ipc-CflAVodw.js';
|
|
3
|
-
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-
|
|
4
|
-
export { b as OpenRTCAccessMode, c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, e as OpenRTCBotVerificationProvider, f as OpenRTCCapabilityHandle, g as OpenRTCChannel, h as OpenRTCChannelCatalog, i as OpenRTCConnection, j as OpenRTCDeviceProfile, k as OpenRTCDevicesHandle, l as OpenRTCDevicesStartOptions, m as OpenRTCEnrolledDevice, n as OpenRTCLatestStateMode, o as OpenRTCRoomHandle, p as OpenRTCRoomJoinOptions, q as OpenRTCSpaceHandle, r as OpenRTCSpaceJoinOptions, s as OpenRTCState, t as OpenRTCTicketHandle, u as OpenRTCTicketIssueOptions, v as OpenRTCTransportPreferences, w as OpenRTCUsageNamespace, x as OpenRTCUsageUpdate, y as OpenRTCUsageWarning } from './types-
|
|
3
|
+
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-DhmY9hBy.js';
|
|
4
|
+
export { b as OpenRTCAccessMode, c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, e as OpenRTCBotVerificationProvider, f as OpenRTCCapabilityHandle, g as OpenRTCChannel, h as OpenRTCChannelCatalog, i as OpenRTCConnection, j as OpenRTCDeviceProfile, k as OpenRTCDevicesHandle, l as OpenRTCDevicesStartOptions, m as OpenRTCEnrolledDevice, n as OpenRTCLatestStateMode, o as OpenRTCRoomHandle, p as OpenRTCRoomJoinOptions, q as OpenRTCSpaceHandle, r as OpenRTCSpaceJoinOptions, s as OpenRTCState, t as OpenRTCTicketHandle, u as OpenRTCTicketIssueOptions, v as OpenRTCTransportPreferences, w as OpenRTCUsageNamespace, x as OpenRTCUsageUpdate, y as OpenRTCUsageWarning } from './types-DhmY9hBy.js';
|
|
5
5
|
import './OpenRTCShared.js';
|
|
6
|
-
import './assembly-
|
|
7
|
-
import './types-
|
|
8
|
-
import './ITransport-
|
|
9
|
-
import './capabilities-
|
|
6
|
+
import './assembly-CLdwe5T-.js';
|
|
7
|
+
import './types-l3m3GrOe.js';
|
|
8
|
+
import './ITransport-UNOXiRJD.js';
|
|
9
|
+
import './capabilities-BUe5YldR.js';
|
|
10
10
|
|
|
11
11
|
/** Native-only OpenRTC 2.0 entrypoint. */
|
|
12
12
|
|
package/dist/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-7FPG3MFF.js';import'./chunk-VBUDERMM.js';import {b}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-7FPG3MFF.js';import'./chunk-VBUDERMM.js';import {b}from'./chunk-QCPSLUKO.js';import'./chunk-XPL7PUBW.js';export{a as classifyNativeIpcFailure,b as isNativeIpcCommandUnavailable}from'./chunk-Z2WVSXPW.js';import'./chunk-DUY34MGT.js';import'./chunk-NRXEG5GQ.js';function m(n,e){return b(n,{platform:"native",deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:o}=await import('./ipcFactory-JTMNUTZI.js');return o(t,e)}})}export{m as createNativeOpenRTC};
|