openrtc 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/{DelegatingRuntimeAdapter-BkLR3TNN.d.ts → DelegatingRuntimeAdapter-DE4LTGAJ.d.ts} +3 -3
  2. package/dist/{ITransport-yaruAmx3.d.ts → ITransport-CjxCQ6q7.d.ts} +3 -4
  3. package/dist/{IpcRuntimeAdapter-DDKeQ6UC.d.ts → IpcRuntimeAdapter-CE0va9Tr.d.ts} +2 -2
  4. package/dist/WasmBridge-75F6GKHG.js +1 -0
  5. package/dist/{assembly-BTzwQuwI.d.ts → assembly-Bmi65-tK.d.ts} +3 -3
  6. package/dist/{capabilities-BwzPe51I.d.ts → capabilities-BPuynml5.d.ts} +1 -1
  7. package/dist/{chunk-SUWCBTBQ.js → chunk-2L6ULC32.js} +1 -1
  8. package/dist/{chunk-LN4ALFT6.js → chunk-2SUSPEC4.js} +1 -1
  9. package/dist/{chunk-FKEKINIM.js → chunk-7BJKDBLP.js} +1 -1
  10. package/dist/chunk-HEAJ7ZUR.js +1 -0
  11. package/dist/{chunk-GND6UW37.js → chunk-KRJECX7X.js} +1 -1
  12. package/dist/chunk-Q6KXVTSH.js +2 -0
  13. package/dist/{chunk-F4BJ72HN.js → chunk-R35AWMNY.js} +1 -1
  14. package/dist/chunk-UILOGUOU.js +1 -0
  15. package/dist/chunk-WA434EWD.js +2 -0
  16. package/dist/chunk-XAL4T6TB.js +3 -0
  17. package/dist/{chunk-OUFHVLDQ.js → chunk-Z2IS6NH2.js} +1 -1
  18. package/dist/{controlPlane-JJFURVOX.js → controlPlane-KVFZ7BR5.js} +1 -1
  19. package/dist/coreClient.d.ts +4 -4
  20. package/dist/coreClient.js +1 -1
  21. package/dist/{deviceEnrollment-Z2EHP2EX.js → deviceEnrollment-VACC64CQ.js} +2 -2
  22. package/dist/index.d.ts +6 -6
  23. package/dist/index.js +1 -1
  24. package/dist/ipcFactory-32R47AVK.js +1 -0
  25. package/dist/openrtc-4EZPCHWM.js +2 -0
  26. package/dist/openrtc_bg.wasm +0 -0
  27. package/dist/runtime/WasmRuntimeAdapter.d.ts +4 -4
  28. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  29. package/dist/runtime/device-status.d.ts +2 -2
  30. package/dist/runtime/factories.d.ts +6 -6
  31. package/dist/runtime/factories.js +1 -1
  32. package/dist/runtime/index.d.ts +10 -10
  33. package/dist/runtime/index.js +1 -1
  34. package/dist/testing.d.ts +10 -5
  35. package/dist/testing.js +1 -1
  36. package/dist/transport/index.d.ts +2 -2
  37. package/dist/transport/index.js +1 -1
  38. package/dist/{types-C4TIUgOJ.d.ts → types--jQzenZR.d.ts} +3 -2
  39. package/dist/{types-D67HlF0p.d.ts → types-DDhMQkK8.d.ts} +1 -1
  40. package/package.json +1 -1
  41. package/dist/WasmBridge-DVQ2YPRB.js +0 -1
  42. package/dist/chunk-2IRNZN3N.js +0 -1
  43. package/dist/chunk-DI5VSZ2T.js +0 -2
  44. package/dist/chunk-NRXEG5GQ.js +0 -1
  45. package/dist/chunk-NXM5ZGHD.js +0 -2
  46. package/dist/chunk-UGZJJQPM.js +0 -3
  47. package/dist/ipcFactory-DQFK65VE.js +0 -1
  48. package/dist/openrtc-INQDCF23.js +0 -2
@@ -1,6 +1,6 @@
1
- import { D as Device, k as DiscoveryMode, A as AuthMode, S as SignalingMode, h as ClientOptions, E as ExplicitFileDataSendParams, I as ISignalingBackend, L as LocalDeviceInfo, l as RoomMember, m as RuntimeIdentity, n as SignalingEnvelope, o as DeviceStatusSnapshot, d as PeerSessionSnapshot, B as BackendPeerBiStream, p as BackendPeerUniStream, M as ManagedConnectionRecord, e as ResolvedPeerIdentity, q as DeviceEvent, r as DesiredPeerProjection, s as CoreClientBridgeHost, N as NativeConnectParams, t as NativeConnectResult, u as SignalingSession, v as SessionEvent, w as BackendConnectionState, x as NativeManagedSessionStartResult, G as GrantScope } from './ITransport-yaruAmx3.js';
2
- import { B as BrowserProtocolStore, N as NamespaceDescriptor, p as IrohMutationReceipt, q as IrohDocEntry, A as AuthContext } from './types-D67HlF0p.js';
3
- import { R as RuntimeCapabilities } from './capabilities-BwzPe51I.js';
1
+ import { D as Device, k as DiscoveryMode, A as AuthMode, S as SignalingMode, h as ClientOptions, E as ExplicitFileDataSendParams, I as ISignalingBackend, L as LocalDeviceInfo, l as RoomMember, m as RuntimeIdentity, n as SignalingEnvelope, o as DeviceStatusSnapshot, d as PeerSessionSnapshot, B as BackendPeerBiStream, p as BackendPeerUniStream, M as ManagedConnectionRecord, e as ResolvedPeerIdentity, q as DeviceEvent, r as DesiredPeerProjection, s as CoreClientBridgeHost, N as NativeConnectParams, t as NativeConnectResult, u as SignalingSession, v as SessionEvent, w as BackendConnectionState, x as NativeManagedSessionStartResult, G as GrantScope } from './ITransport-CjxCQ6q7.js';
2
+ import { B as BrowserProtocolStore, N as NamespaceDescriptor, p as IrohMutationReceipt, q as IrohDocEntry, A as AuthContext } from './types-DDhMQkK8.js';
3
+ import { R as RuntimeCapabilities } from './capabilities-BPuynml5.js';
4
4
 
5
5
  interface NativeTrustToken {
6
6
  token: string;
@@ -61,8 +61,6 @@ interface AppLimits {
61
61
  maxPersonalDevices: number;
62
62
  }
63
63
  interface PlutoRTCConfiguration extends RTCConfiguration {
64
- /** Keep the legacy route, carry Iroh packets, or try the carrier before fallback. */
65
- implementation?: TransportImpl;
66
64
  iceServers?: RTCIceServer[];
67
65
  /**
68
66
  * Populate public STUN defaults when no ICE servers are configured.
@@ -84,7 +82,6 @@ interface PlutoMoQServerCertificateHash {
84
82
  value: ArrayBuffer;
85
83
  }
86
84
  interface PlutoMoQConfiguration {
87
- implementation?: TransportImpl;
88
85
  relayUrl?: string;
89
86
  /** Relay JWT appended only at WebTransport connection time. Never include it in relayUrl. */
90
87
  accessToken?: string;
@@ -159,7 +156,6 @@ interface ChannelDescriptor {
159
156
  }
160
157
  type ProtocolName = 'iroh' | 'iroh-quic' | 'iroh-relay' | 'iroh-lan' | 'iroh-webrtc' | 'iroh-moq' | 'ble' | 'webrtc' | 'webrtc-lan' | 'webrtc-turn' | 'moq';
161
158
  type ProtocolMaturity = 'stable' | 'experimental' | 'unsupported';
162
- type TransportImpl = 'external' | 'iroh-carrier' | 'auto';
163
159
  type TransportPrivacy = 'direct' | 'relay-only';
164
160
  type RouteOptimization = 'balanced' | 'lowest-latency';
165
161
  type ProtocolBaseName = 'iroh' | 'webrtc' | 'moq';
@@ -320,6 +316,8 @@ interface ClientOptions {
320
316
  onAutoConnect?: (devices: Device[]) => void;
321
317
  onIncomingSession?: (session: SignalingSession) => Promise<void>;
322
318
  transports?: {
319
+ /** Allow Iroh, TURN, and MoQ relay routes. Defaults to true. */
320
+ relay?: boolean;
323
321
  iroh?: boolean | PlutoIrohConfiguration;
324
322
  webrtc?: boolean | PlutoRTCConfiguration;
325
323
  ble?: boolean | PlutoBleConfiguration;
@@ -956,6 +954,7 @@ interface TransportContext {
956
954
  isMoQApplicationRouteProven?: () => boolean;
957
955
  requestMoQApplicationRouteProof?: () => void;
958
956
  clearMoQApplicationRouteProof?: () => void;
957
+ requestIrohCarrier?: () => void;
959
958
  runtimeFlow?: 'default' | 'ticket-only';
960
959
  readerCloseStrategy?: 'cancel' | 'release-lock';
961
960
  }
@@ -1,5 +1,5 @@
1
- import { h as ClientOptions } from './ITransport-yaruAmx3.js';
2
- import { a as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-BkLR3TNN.js';
1
+ import { h as ClientOptions } from './ITransport-CjxCQ6q7.js';
2
+ import { a as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-DE4LTGAJ.js';
3
3
  import { P as PlutoIpcBridge } from './ipc-CPnNwv6f.js';
4
4
 
5
5
  interface NativeIpcBridgeOptions extends WasmBridgeOptions {
@@ -0,0 +1 @@
1
+ export{z as WasmBridge}from'./chunk-Z2IS6NH2.js';import'./chunk-AJQVMVYW.js';import'./chunk-WA434EWD.js';import'./chunk-HEAJ7ZUR.js';import'./chunk-2L6ULC32.js';import'./chunk-2SUSPEC4.js';
@@ -1,6 +1,6 @@
1
- import { R as RuntimePeerState, g as ConnectionState, b as PeerReadiness, P as PeerConnectOptions, a as Connection, I as IncomingStream, o as RuntimeClientOptions, r as RuntimeAuthIdentity, A as AuthContext, L as LocalDeviceInfo, l as DeviceProfile, B as BrowserProtocolStore, N as NamespaceDescriptor, p as IrohMutationReceipt, q as IrohDocEntry, e as RuntimeDevice, M as ManagedOptions, j as ManagedSession, D as DeviceStatus, k as DeviceConnectOptions, s as RuntimeSession, J as JoinRoomOptions, n as RuntimeRoomMember, t as ConnectionTarget, S as ScopedChannelOptions, f as ScopedLogicalChannel, d as PeerStreamOptions, m as RawConnection, C as ChannelDescriptor, u as PresenceLoopOptions, c as RuntimePeerHealth, h as ReadinessOptions, i as ConnectionEvent } from './types-D67HlF0p.js';
2
- import { G as GrantScope, I as ISignalingBackend, f as ConnectDeviceHooks, g as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, d as PeerSessionSnapshot, e as ResolvedPeerIdentity, a6 as AppLimits, N as NativeConnectParams, t as NativeConnectResult, E as ExplicitFileDataSendParams } from './ITransport-yaruAmx3.js';
3
- import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-BwzPe51I.js';
1
+ import { R as RuntimePeerState, g as ConnectionState, b as PeerReadiness, P as PeerConnectOptions, a as Connection, I as IncomingStream, o as RuntimeClientOptions, r as RuntimeAuthIdentity, A as AuthContext, L as LocalDeviceInfo, l as DeviceProfile, B as BrowserProtocolStore, N as NamespaceDescriptor, p as IrohMutationReceipt, q as IrohDocEntry, e as RuntimeDevice, M as ManagedOptions, j as ManagedSession, D as DeviceStatus, k as DeviceConnectOptions, s as RuntimeSession, J as JoinRoomOptions, n as RuntimeRoomMember, t as ConnectionTarget, S as ScopedChannelOptions, f as ScopedLogicalChannel, d as PeerStreamOptions, m as RawConnection, C as ChannelDescriptor, u as PresenceLoopOptions, c as RuntimePeerHealth, h as ReadinessOptions, i as ConnectionEvent } from './types-DDhMQkK8.js';
2
+ import { G as GrantScope, I as ISignalingBackend, f as ConnectDeviceHooks, g as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, d as PeerSessionSnapshot, e as ResolvedPeerIdentity, a6 as AppLimits, N as NativeConnectParams, t as NativeConnectResult, E as ExplicitFileDataSendParams } from './ITransport-CjxCQ6q7.js';
3
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-BPuynml5.js';
4
4
 
5
5
  /**
6
6
  * Coalesced peer reconciliation scheduler and full reconcile orchestration.
@@ -1,4 +1,4 @@
1
- import { c as ProtocolName, R as RouteOptimization } from './ITransport-yaruAmx3.js';
1
+ import { c as ProtocolName, R as RouteOptimization } from './ITransport-CjxCQ6q7.js';
2
2
 
3
3
  type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
4
4
  interface RuntimeCapabilities {
@@ -1 +1 @@
1
- import {b,e}from'./chunk-LN4ALFT6.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';function I(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function x(t,e,r){if(I()){if(typeof r>"u"){console[t](e);return}console[t](e,r);}}function Y(t,e){x("debug",t,e);}function $(t,e){x("info",t,e);}function G(t,e){x("log",t,e);}function H(t){return new Promise(e=>setTimeout(e,t))}function K(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}function B(t){let e=t.reduce((s,c)=>s+c.byteLength,0),r=new Uint8Array(e),a=0;for(let s of t)r.set(s,a),a+=s.byteLength;return r}function Q(t,e,r){let a=e*Math.pow(2,Math.max(0,t-1));return Math.min(r,a)}function j(t){try{let e=t;return !!e&&!!e.send&&typeof e.send.getWriter=="function"&&!!e.recv&&typeof e.recv.getReader=="function"}catch{return false}}function J(t,e,r){let a=t;if(!a)return null;try{let s=a.send,c=a.recv;if(!s||typeof s.getWriter!="function"||!c||typeof c.getReader!="function")return null;let p=typeof a.endpoint_id=="string"&&a.endpoint_id.trim().length>0?a.endpoint_id:e,i=Number.isSafeInteger(a.transport_stable_id)&&Number(a.transport_stable_id)>0?Number(a.transport_stable_id):void 0,f=Number.isSafeInteger(r)&&Number(r)>0?Number(r):void 0;if(i!==void 0&&f!==void 0&&i!==f)return null;let o=i??f;return {send:s,recv:c,endpoint_id:p,...o?{transport_stable_id:o}:{}}}catch{return null}}function Z(t,e){let r={send:t.send,recv:e,endpoint_id:typeof t.endpoint_id=="string"?t.endpoint_id:"",...Number.isSafeInteger(t.transport_stable_id)&&Number(t.transport_stable_id)>0?{transport_stable_id:Number(t.transport_stable_id)}:{}};return t?.applicationCryptoWrapped===true&&(r.applicationCryptoWrapped=true),r}async function ee(t,e){if(!t)return false;try{let r=t.send?.getWriter?.();if(r)try{await r.close();}catch{}finally{try{r.releaseLock();}catch{}}}catch{}try{let r=t.recv?.getReader?.();if(r)try{await r.cancel(e);}catch{}finally{try{r.releaseLock();}catch{}}}catch{}return true}function te(t,e,r={}){let a=r.context??"prependBytesToReader",s=r.traceId,c=e.byteLength===0,p=r.pendingRead??null,i=o=>r.release?.(o),f=(o,n)=>r.log?.(o,n);return new ReadableStream({async pull(o){if(!c){c=true,o.enqueue(e);return}if(p){let l=p;p=null;let d;try{d=await l;}catch(u){o.error(u),i("pending-read-error"),f("prepend-bytes:pending-read-error",{context:a,traceId:s||null,error:u?.message||String(u)});return}if(d.done){o.close(),i("pending-done");return}d.value&&o.enqueue(d.value);return}let n;try{n=await t.read();}catch(l){o.error(l),i("read-error"),f("prepend-bytes:read-error",{context:a,traceId:s||null,error:l?.message||String(l)});return}let{done:y,value:b}=n;if(y){o.close(),i("done");return}b&&o.enqueue(b);},async cancel(o){i("cancel");}})}async function re(t,e){let r=t.read(),a=e-Date.now();if(a<=0)return {status:"timeout",pendingRead:r};let s=Symbol("probe-timeout"),c,p=new Promise(i=>{c=setTimeout(()=>i(s),a);});try{let i=await Promise.race([r,p]);if(i===s)return {status:"timeout",pendingRead:r};let{done:f,value:o}=i;return f?{status:"done"}:{status:"data",value:o&&o.byteLength>0?new Uint8Array(o):new Uint8Array(0)}}finally{c&&clearTimeout(c);}}var N=b,k=new Set(N);function w(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return k.has(e)?e:void 0}function oe(t){let e$1=w(t);return e$1?e(e$1).baseProtocol==="iroh":false}function ie(t){let e$1=w(t);if(!e$1)return false;let r=e(e$1);return r.baseProtocol==="iroh"&&(r.locality==="nearby"||r.locality==="direct-internet")}function se(t){let e$1=w(t);return e$1?e(e$1).family==="optional-route":false}function ue(t){let e$1=w(t);return e$1?e(e$1).baseProtocol==="webrtc":false}function ce(t){let e$1=w(t);if(!e$1)return false;let r=e(e$1);return r.baseProtocol==="iroh"&&r.implementation==="carrier-adapter"}function le(t,e,r=false){return t==="relay"||e==="relay"?"webrtc-turn":t==="host"&&e==="host"||r&&t&&e?"webrtc-lan":"webrtc"}function de(t){let e$1=w(t);return e$1?e(e$1).independent:false}var g=new Uint8Array([79,82,84,67,69,49]),T=2,R=8,A=24,_=32,C=3,D=16*1024*1024,q=4096;function F(t,e){if(t.byteLength<e.byteLength)return false;let r=0;for(let a=0;a<e.byteLength;a+=1)r|=t[a]^e[a];return r===0}function W(t){let e=new Uint8Array(t),r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return r.getRandomValues(e),e}function V(t,e){let r="";for(let a of e)r+=a.toString(16).padStart(2,"0");return `${t}:${r}`}function v(t){if(!F(t,g))return null;let e=t[g.byteLength];return e===T?e:null}function M(t){return v(t)===T&&t.byteLength>g.byteLength+1+R+A}function be(t,e={}){if(!(t instanceof Uint8Array)||t.byteLength!==_)throw new Error(`[OpenRTC] application payload crypto key must be ${_} bytes`);let r=new Uint8Array(t),a=e.requireEncrypted??true,s=e.randomBytes??W,c=e.replayProtection??true,p=0,i=new Set,f=[];return {requireEncrypted:a,protectPayload(o,n){let y=s(A);if(!(y instanceof Uint8Array)||y.byteLength!==A)throw new Error(`[OpenRTC] application payload crypto nonce must be ${A} bytes`);let b=new Uint8Array(1+n.byteLength);b[0]=o,b.set(n,1);let l=xchacha20poly1305(r,y).encrypt(b);if(!c)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let d=new Uint8Array(g.byteLength+1+R+y.byteLength+l.byteLength),u=0;d.set(g,u),u+=g.byteLength,d[u]=T,u+=1;let S=p;return p+=1,new DataView(d.buffer,d.byteOffset+u,R).setBigUint64(0,BigInt(S),false),u+=R,d.set(y,u),u+=y.byteLength,d.set(l,u),d},openPayload(o,n){if(!M(n))return a?null:n;if(v(n)!==T)return null;let b=g.byteLength+1,l=Number(new DataView(n.buffer,n.byteOffset+b,R).getBigUint64(0,false));if(!Number.isFinite(l))return null;let d=b+R,u=d+A,S=n.slice(d,u),h=c?V(l,S):null;if(h&&i.has(h))return null;let O=n.slice(u),U;try{U=xchacha20poly1305(r,S).decrypt(O);}catch{return null}if(U.byteLength<1||U[0]!==o)return null;if(h)for(i.add(h),f.push(h);f.length>q;){let L=f.shift();L&&i.delete(L);}return U.slice(1)}}}function z(t){let e=new Uint8Array(4+t.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,t.byteLength,false),e.set(t,4),e}function me(t,e={}){let r=e.typeId??C,a=e.maxFrameBytes??D;if(!Number.isInteger(r)||r<0||r>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(a)||a<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let s=n=>t.protectPayload(r,n),c=n=>t.openPayload(r,n),p=()=>new TransformStream({transform(n,y){y.enqueue(z(s(new Uint8Array(n))));}}),i=()=>{let n=new Uint8Array(0);return new TransformStream({transform(y,b){for(n=B([n,new Uint8Array(y)]);n.byteLength>=4;){let l=new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,false);if(l===0||l>a)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(n.byteLength<4+l)return;let d=n.slice(4,4+l);n=n.slice(4+l);let u=c(d);if(!u)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");b.enqueue(u);}},flush(){if(n.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},f=n=>n.pipeThrough(i()),o=n=>{let y=p();return y.readable.pipeTo(n).catch(()=>{}),y.writable};return {typeId:r,protectFrame:s,openFrame:c,outboundTransform:p,inboundTransform:i,wrapReadable:f,wrapWritable:o,wrapBiStream(n){return {...n,send:o(n.send),recv:f(n.recv)}}}}export{I as a,Y as b,$ as c,G as d,H as e,K as f,B as g,Q as h,j as i,J as j,Z as k,ee as l,te as m,re as n,N as o,w as p,oe as q,ie as r,se as s,ue as t,ce as u,le as v,de as w,M as x,be as y,me as z};
1
+ import {b,e}from'./chunk-2SUSPEC4.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';function I(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function x(t,e,r){if(I()){if(typeof r>"u"){console[t](e);return}console[t](e,r);}}function Y(t,e){x("debug",t,e);}function $(t,e){x("info",t,e);}function G(t,e){x("log",t,e);}function H(t){return new Promise(e=>setTimeout(e,t))}function K(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}function B(t){let e=t.reduce((s,c)=>s+c.byteLength,0),r=new Uint8Array(e),a=0;for(let s of t)r.set(s,a),a+=s.byteLength;return r}function Q(t,e,r){let a=e*Math.pow(2,Math.max(0,t-1));return Math.min(r,a)}function j(t){try{let e=t;return !!e&&!!e.send&&typeof e.send.getWriter=="function"&&!!e.recv&&typeof e.recv.getReader=="function"}catch{return false}}function J(t,e,r){let a=t;if(!a)return null;try{let s=a.send,c=a.recv;if(!s||typeof s.getWriter!="function"||!c||typeof c.getReader!="function")return null;let p=typeof a.endpoint_id=="string"&&a.endpoint_id.trim().length>0?a.endpoint_id:e,i=Number.isSafeInteger(a.transport_stable_id)&&Number(a.transport_stable_id)>0?Number(a.transport_stable_id):void 0,f=Number.isSafeInteger(r)&&Number(r)>0?Number(r):void 0;if(i!==void 0&&f!==void 0&&i!==f)return null;let o=i??f;return {send:s,recv:c,endpoint_id:p,...o?{transport_stable_id:o}:{}}}catch{return null}}function Z(t,e){let r={send:t.send,recv:e,endpoint_id:typeof t.endpoint_id=="string"?t.endpoint_id:"",...Number.isSafeInteger(t.transport_stable_id)&&Number(t.transport_stable_id)>0?{transport_stable_id:Number(t.transport_stable_id)}:{}};return t?.applicationCryptoWrapped===true&&(r.applicationCryptoWrapped=true),r}async function ee(t,e){if(!t)return false;try{let r=t.send?.getWriter?.();if(r)try{await r.close();}catch{}finally{try{r.releaseLock();}catch{}}}catch{}try{let r=t.recv?.getReader?.();if(r)try{await r.cancel(e);}catch{}finally{try{r.releaseLock();}catch{}}}catch{}return true}function te(t,e,r={}){let a=r.context??"prependBytesToReader",s=r.traceId,c=e.byteLength===0,p=r.pendingRead??null,i=o=>r.release?.(o),f=(o,n)=>r.log?.(o,n);return new ReadableStream({async pull(o){if(!c){c=true,o.enqueue(e);return}if(p){let l=p;p=null;let d;try{d=await l;}catch(u){o.error(u),i("pending-read-error"),f("prepend-bytes:pending-read-error",{context:a,traceId:s||null,error:u?.message||String(u)});return}if(d.done){o.close(),i("pending-done");return}d.value&&o.enqueue(d.value);return}let n;try{n=await t.read();}catch(l){o.error(l),i("read-error"),f("prepend-bytes:read-error",{context:a,traceId:s||null,error:l?.message||String(l)});return}let{done:y,value:b}=n;if(y){o.close(),i("done");return}b&&o.enqueue(b);},async cancel(o){i("cancel");}})}async function re(t,e){let r=t.read(),a=e-Date.now();if(a<=0)return {status:"timeout",pendingRead:r};let s=Symbol("probe-timeout"),c,p=new Promise(i=>{c=setTimeout(()=>i(s),a);});try{let i=await Promise.race([r,p]);if(i===s)return {status:"timeout",pendingRead:r};let{done:f,value:o}=i;return f?{status:"done"}:{status:"data",value:o&&o.byteLength>0?new Uint8Array(o):new Uint8Array(0)}}finally{c&&clearTimeout(c);}}var N=b,k=new Set(N);function w(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return k.has(e)?e:void 0}function oe(t){let e$1=w(t);return e$1?e(e$1).baseProtocol==="iroh":false}function ie(t){let e$1=w(t);if(!e$1)return false;let r=e(e$1);return r.baseProtocol==="iroh"&&(r.locality==="nearby"||r.locality==="direct-internet")}function se(t){let e$1=w(t);return e$1?e(e$1).family==="optional-route":false}function ue(t){let e$1=w(t);return e$1?e(e$1).baseProtocol==="webrtc":false}function ce(t){let e$1=w(t);if(!e$1)return false;let r=e(e$1);return r.baseProtocol==="iroh"&&r.implementation==="carrier-adapter"}function le(t,e,r=false){return t==="relay"||e==="relay"?"webrtc-turn":t==="host"&&e==="host"||r&&t&&e?"webrtc-lan":"webrtc"}function de(t){let e$1=w(t);return e$1?e(e$1).independent:false}var g=new Uint8Array([79,82,84,67,69,49]),T=2,R=8,A=24,_=32,C=3,D=16*1024*1024,q=4096;function F(t,e){if(t.byteLength<e.byteLength)return false;let r=0;for(let a=0;a<e.byteLength;a+=1)r|=t[a]^e[a];return r===0}function W(t){let e=new Uint8Array(t),r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return r.getRandomValues(e),e}function V(t,e){let r="";for(let a of e)r+=a.toString(16).padStart(2,"0");return `${t}:${r}`}function v(t){if(!F(t,g))return null;let e=t[g.byteLength];return e===T?e:null}function M(t){return v(t)===T&&t.byteLength>g.byteLength+1+R+A}function be(t,e={}){if(!(t instanceof Uint8Array)||t.byteLength!==_)throw new Error(`[OpenRTC] application payload crypto key must be ${_} bytes`);let r=new Uint8Array(t),a=e.requireEncrypted??true,s=e.randomBytes??W,c=e.replayProtection??true,p=0,i=new Set,f=[];return {requireEncrypted:a,protectPayload(o,n){let y=s(A);if(!(y instanceof Uint8Array)||y.byteLength!==A)throw new Error(`[OpenRTC] application payload crypto nonce must be ${A} bytes`);let b=new Uint8Array(1+n.byteLength);b[0]=o,b.set(n,1);let l=xchacha20poly1305(r,y).encrypt(b);if(!c)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let d=new Uint8Array(g.byteLength+1+R+y.byteLength+l.byteLength),u=0;d.set(g,u),u+=g.byteLength,d[u]=T,u+=1;let S=p;return p+=1,new DataView(d.buffer,d.byteOffset+u,R).setBigUint64(0,BigInt(S),false),u+=R,d.set(y,u),u+=y.byteLength,d.set(l,u),d},openPayload(o,n){if(!M(n))return a?null:n;if(v(n)!==T)return null;let b=g.byteLength+1,l=Number(new DataView(n.buffer,n.byteOffset+b,R).getBigUint64(0,false));if(!Number.isFinite(l))return null;let d=b+R,u=d+A,S=n.slice(d,u),h=c?V(l,S):null;if(h&&i.has(h))return null;let O=n.slice(u),U;try{U=xchacha20poly1305(r,S).decrypt(O);}catch{return null}if(U.byteLength<1||U[0]!==o)return null;if(h)for(i.add(h),f.push(h);f.length>q;){let L=f.shift();L&&i.delete(L);}return U.slice(1)}}}function z(t){let e=new Uint8Array(4+t.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,t.byteLength,false),e.set(t,4),e}function me(t,e={}){let r=e.typeId??C,a=e.maxFrameBytes??D;if(!Number.isInteger(r)||r<0||r>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(a)||a<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let s=n=>t.protectPayload(r,n),c=n=>t.openPayload(r,n),p=()=>new TransformStream({transform(n,y){y.enqueue(z(s(new Uint8Array(n))));}}),i=()=>{let n=new Uint8Array(0);return new TransformStream({transform(y,b){for(n=B([n,new Uint8Array(y)]);n.byteLength>=4;){let l=new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,false);if(l===0||l>a)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(n.byteLength<4+l)return;let d=n.slice(4,4+l);n=n.slice(4+l);let u=c(d);if(!u)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");b.enqueue(u);}},flush(){if(n.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},f=n=>n.pipeThrough(i()),o=n=>{let y=p();return y.readable.pipeTo(n).catch(()=>{}),y.writable};return {typeId:r,protectFrame:s,openFrame:c,outboundTransform:p,inboundTransform:i,wrapReadable:f,wrapWritable:o,wrapBiStream(n){return {...n,send:o(n.send),recv:f(n.recv)}}}}export{I as a,Y as b,$ as c,G as d,H as e,K as f,B as g,Q as h,j as i,J as j,Z as k,ee as l,te as m,re as n,N as o,w as p,oe as q,ie as r,se as s,ue as t,ce as u,le as v,de as w,M as x,be as y,me as z};
@@ -1 +1 @@
1
- var t=Object.freeze([Object.freeze({id:"iroh-lan",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"nearby",maturity:"stable",defaultRank:0,browser:false,native:true,independent:false}),Object.freeze({id:"webrtc-lan",baseProtocol:"webrtc",family:"optional-route",implementation:"path-label",locality:"nearby",maturity:"stable",defaultRank:1,browser:true,native:true,independent:false}),Object.freeze({id:"ble",baseProtocol:"iroh",family:"iroh-physical",implementation:"host-installed",locality:"nearby",maturity:"experimental",defaultRank:2,browser:false,native:true,independent:false}),Object.freeze({id:"iroh-webrtc",baseProtocol:"iroh",family:"iroh-physical",implementation:"carrier-adapter",locality:"mixed",maturity:"stable",defaultRank:3,browser:true,native:true,independent:false}),Object.freeze({id:"webrtc",baseProtocol:"webrtc",family:"optional-route",implementation:"route-adapter",locality:"mixed",maturity:"stable",defaultRank:4,browser:true,native:true,independent:true}),Object.freeze({id:"iroh-moq",baseProtocol:"iroh",family:"iroh-physical",implementation:"carrier-adapter",locality:"relay",maturity:"experimental",defaultRank:5,browser:true,native:true,independent:false}),Object.freeze({id:"moq",baseProtocol:"moq",family:"optional-route",implementation:"route-adapter",locality:"relay",maturity:"experimental",defaultRank:6,browser:true,native:true,independent:true}),Object.freeze({id:"iroh",baseProtocol:"iroh",family:"iroh-path",implementation:"core",locality:"mixed",maturity:"stable",defaultRank:7,browser:true,native:true,independent:false}),Object.freeze({id:"iroh-quic",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"direct-internet",maturity:"stable",defaultRank:8,browser:false,native:true,independent:false}),Object.freeze({id:"iroh-relay",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"relay",maturity:"stable",defaultRank:9,browser:true,native:true,independent:false}),Object.freeze({id:"webrtc-turn",baseProtocol:"webrtc",family:"optional-route",implementation:"path-label",locality:"relay",maturity:"stable",defaultRank:10,browser:true,native:true,independent:false})]),r=Object.freeze(Object.fromEntries(t.map(e=>[e.id,e]))),o=Object.freeze(["iroh-lan","webrtc-lan","ble","iroh-webrtc","webrtc","iroh-moq","moq","iroh","iroh-quic","iroh-relay","webrtc-turn"]),a=Object.freeze(["iroh-lan","webrtc-lan","ble","iroh-webrtc","webrtc","iroh-moq","moq","iroh"]),i=Object.freeze({iroh:80,"iroh-quic":30,"iroh-relay":70,"iroh-lan":10,ble:25,"iroh-webrtc":27,webrtc:40,"webrtc-lan":20,"webrtc-turn":60,"iroh-moq":55,moq:50});var l=t,n=r,m=o,b=a,p=i;function s(e){return n[e]}function u(){return l}export{l as a,m as b,b as c,p as d,s as e,u as f};
1
+ var t=Object.freeze([Object.freeze({id:"iroh-lan",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"nearby",maturity:"stable",defaultRank:0,browser:false,native:true,independent:false}),Object.freeze({id:"webrtc-lan",baseProtocol:"webrtc",family:"optional-route",implementation:"path-label",locality:"nearby",maturity:"stable",defaultRank:1,browser:true,native:true,independent:false}),Object.freeze({id:"ble",baseProtocol:"iroh",family:"iroh-physical",implementation:"host-installed",locality:"nearby",maturity:"experimental",defaultRank:2,browser:false,native:true,independent:false}),Object.freeze({id:"iroh-webrtc",baseProtocol:"iroh",family:"iroh-physical",implementation:"carrier-adapter",locality:"mixed",maturity:"stable",defaultRank:3,browser:true,native:true,independent:false}),Object.freeze({id:"webrtc",baseProtocol:"webrtc",family:"optional-route",implementation:"route-adapter",locality:"mixed",maturity:"stable",defaultRank:4,browser:true,native:true,independent:true}),Object.freeze({id:"iroh-moq",baseProtocol:"iroh",family:"iroh-physical",implementation:"carrier-adapter",locality:"relay",maturity:"experimental",defaultRank:5,browser:true,native:true,independent:false}),Object.freeze({id:"moq",baseProtocol:"moq",family:"optional-route",implementation:"route-adapter",locality:"relay",maturity:"experimental",defaultRank:6,browser:true,native:true,independent:true}),Object.freeze({id:"iroh",baseProtocol:"iroh",family:"iroh-path",implementation:"core",locality:"mixed",maturity:"stable",defaultRank:7,browser:true,native:true,independent:false}),Object.freeze({id:"iroh-quic",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"direct-internet",maturity:"stable",defaultRank:8,browser:false,native:true,independent:false}),Object.freeze({id:"iroh-relay",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"relay",maturity:"stable",defaultRank:9,browser:true,native:true,independent:false}),Object.freeze({id:"webrtc-turn",baseProtocol:"webrtc",family:"optional-route",implementation:"path-label",locality:"relay",maturity:"stable",defaultRank:10,browser:true,native:true,independent:false})]),r=Object.freeze(Object.fromEntries(t.map(e=>[e.id,e]))),o=Object.freeze(["iroh-lan","webrtc-lan","ble","iroh-webrtc","webrtc","iroh-moq","moq","iroh","iroh-quic","iroh-relay","webrtc-turn"]),a=Object.freeze(["iroh-lan","iroh-quic","iroh-webrtc","iroh-moq","iroh-relay"]),i=Object.freeze({iroh:80,"iroh-quic":30,"iroh-relay":70,"iroh-lan":10,ble:25,"iroh-webrtc":27,webrtc:40,"webrtc-lan":20,"webrtc-turn":60,"iroh-moq":55,moq:50});var l=t,n=r,m=o,b=a,p=i;function s(e){return n[e]}function u(){return l}export{l as a,m as b,b as c,p as d,s as e,u as f};
@@ -1,2 +1,2 @@
1
- import {d as d$2,c}from'./chunk-SUWCBTBQ.js';import {a,d as d$1}from'./chunk-LN4ALFT6.js';import {x25519}from'@noble/curves/ed25519.js';import {hkdf}from'@noble/hashes/hkdf.js';import {sha256}from'@noble/hashes/sha2.js';var v=3e4,d=class d{constructor(){this.name="webrtc";this.pc=null;this.dc=null;this.state="disconnected";this.pendingCandidates=[];this.connectTimeoutId=null;this.iceDisconnectedGraceTimer=null;this.iceRestartAttempted=false;this.localNodeId="";this.remoteNodeId="";this.candidatesGathered=0;this.sdpOfferSent=false;this.sdpAnswerReceived=false;this._terminalFailure=false;this.activeAttemptId=0;this.negotiationId=null;this.disconnectedGraceExtensions=0;this.offerInFlight=false;this.messageListeners=[];this.stateListeners=[];this.internalSignalSender=null;}get isReady(){return this.state==="connected"}isTerminalFailure(){return this._terminalFailure}getNegotiationId(){return this.negotiationId}getDataChannelReadyState(){return this.dc?.readyState??null}getNativeTransport(){return this.pc}setSignalSender(e){this.internalSignalSender=e;}async init(e,n,t){this.closePeerResources();let i=++this.activeAttemptId;this.localNodeId=e,this.remoteNodeId=n,this.candidatesGathered=0,this.sdpOfferSent=false,this.sdpAnswerReceived=false,this._terminalFailure=false,this.offerInFlight=false,this.pendingCandidates=[],this.disconnectedGraceExtensions=0,this.negotiationId=typeof t?.negotiationId=="string"&&t.negotiationId.trim().length>0?t.negotiationId.trim():this.createNegotiationId(),this.setState("connecting"),this.startConnectTimeout(i);let a=t.rtcConfig||{},s=typeof t?.forceRole=="string"&&(t.forceRole==="initiator"||t.forceRole==="responder")?t.forceRole:null,c=s?s==="initiator":e>n;d$2(`[WebRTCTransport] init \u2014 role=${c?"initiator":"responder"}`,{local:e.slice(0,12),remote:n.slice(0,12),negotiationId:this.negotiationId,forcedRole:s});try{d$2("[WebRTCTransport] Creating RTCPeerConnection",{iceServers:a.iceServers?.length??0}),this.pc=new RTCPeerConnection(a);}catch(R){console.error("[WebRTCTransport] RTCPeerConnection constructor failed",R),this.setState("failed");return}let T=this.pc.createDataChannel("pluto-dc",{negotiated:true,id:0});this.setupDataChannel(T,i),this.setupPCHandlers(c,i),c&&queueMicrotask(()=>{this.createAndSendOffer(i,"initial-initiator");});}setupDataChannel(e,n){this.dc=e,e.onopen=()=>{this.isCurrentAttempt(n,e)&&(d$2("[WebRTCTransport] DataChannel opened \u2014 upgrade complete"),this.promoteConnectedIfReady("datachannel-open"));},e.onmessage=t=>{if(!this.isCurrentAttempt(n,e))return;let i=typeof t.data=="string"?new TextEncoder().encode(t.data):new Uint8Array(t.data);this.messageListeners.forEach(a=>a(i));},e.onclose=()=>{this.isCurrentAttempt(n,e)&&(d$2("[WebRTCTransport] DataChannel closed"),(this.state==="connected"||this.state==="connecting")&&this.setState("disconnected"));},e.onerror=t=>{if(!this.isCurrentAttempt(n,e))return;console.warn("[WebRTCTransport] DataChannel error",t);let i=t?.error?.message??"";if((i.includes("User-Initiated Abort")||i.includes("Close called"))&&this.state==="connected"&&e.readyState!=="open"){console.warn("[WebRTCTransport] DataChannel aborted post-connect; forcing disconnected state",{readyState:e.readyState,connectionState:this.pc?.connectionState,iceConnectionState:this.pc?.iceConnectionState}),this.setState("disconnected");return}this.state==="connecting"&&this.setState("failed");};}setupPCHandlers(e,n){let t=this.pc;t&&(t.onicecandidate=i=>{this.isCurrentAttempt(n,void 0,t)&&(i.candidate?(this.candidatesGathered++,d$2(`[WebRTCTransport] ICE candidate #${this.candidatesGathered}: ${i.candidate.type} ${i.candidate.protocol} ${i.candidate.address??"?"}:${i.candidate.port}`),this.internalSignalSender?this.internalSignalSender({transport:"webrtc",type:"candidate",candidate:i.candidate,negotiationId:this.negotiationId??void 0}).catch(a=>{console.warn("[WebRTCTransport] Failed sending local ICE candidate signal",{error:a,gatheringState:t?.iceGatheringState,iceConnectionState:t?.iceConnectionState});}):console.warn("[WebRTCTransport] ICE candidate dropped \u2014 no signal sender!")):this.candidatesGathered===0?(console.warn("[WebRTCTransport] ICE gathering complete with 0 candidates \u2014 failing immediately.","If both peers are on the same page, WebRTC requires separate tabs or devices.",{local:this.localNodeId.slice(0,12),remote:this.remoteNodeId.slice(0,12)}),this._terminalFailure=true,this.setState("failed")):d$2(`[WebRTCTransport] ICE gathering complete \u2014 ${this.candidatesGathered} candidate(s)`));},t.onnegotiationneeded=async()=>{e&&await this.createAndSendOffer(n,"negotiationneeded");},t.onconnectionstatechange=()=>{if(!this.isCurrentAttempt(n,void 0,t))return;let i=t.connectionState;if(d$2(`[WebRTCTransport] Connection state: ${i}`),i==="connected")this.promoteConnectedIfReady("pc-connected");else if(i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] pc.connectionState=failed during grace window \u2014 deferring to grace timer",{iceState:t.iceConnectionState,iceRestartAttempted:this.iceRestartAttempted});return}console.error("[WebRTCTransport] Connection failed",{iceState:t.iceConnectionState,gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived}),this.clearIceDisconnectedGrace("pc-failed"),this.setState("failed");}else i==="closed"?(this.clearIceDisconnectedGrace("pc-closed"),this.setState("disconnected")):i==="disconnected"&&(d$2("[WebRTCTransport] pc.connectionState=disconnected, deferring to ICE grace period"),this.startIceDisconnectedGrace(n,t,e,"pc-disconnected"));},t.oniceconnectionstatechange=()=>{if(!this.isCurrentAttempt(n,void 0,t))return;let i=t.iceConnectionState;if(d$2(`[WebRTCTransport] ICE connection state: ${i}`,{gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered,hasSdpOffer:this.sdpOfferSent,hasSdpAnswer:this.sdpAnswerReceived,hasRemoteDescription:!!t.remoteDescription,hasLocalDescription:!!t.localDescription}),i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] ice failed during grace window \u2014 deferring to grace timer");return}console.error("[WebRTCTransport] ICE failed \u2014 likely NAT traversal issue or no matching candidates",{gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered}),this.clearIceDisconnectedGrace("ice-failed"),this.setState("failed");}else i==="disconnected"?this.startIceDisconnectedGrace(n,t,e,"ice-disconnected"):(i==="connected"||i==="completed")&&(this.iceDisconnectedGraceTimer&&d$2("[WebRTCTransport] ice-recovered \u2014 cancelling grace timer"),this.clearIceDisconnectedGrace("ice-recovered"),this.iceRestartAttempted=false,this.promoteConnectedIfReady("ice-connected"));},t.onicegatheringstatechange=()=>{this.isCurrentAttempt(n,void 0,t)&&d$2(`[WebRTCTransport] ICE gathering state: ${t.iceGatheringState}`,{iceConnectionState:t.iceConnectionState,signalingState:t.signalingState,hasLocalDesc:!!t.localDescription,hasRemoteDesc:!!t.remoteDescription});});}async createAndSendOffer(e,n){let t=this.pc;if(!(!t||!this.isCurrentAttempt(e,void 0,t))&&t.signalingState==="stable"&&!(this.sdpOfferSent&&t.localDescription?.type==="offer")&&!this.offerInFlight){d$2(`[WebRTCTransport] Creating offer (${n})`),this.offerInFlight=true;try{let i=await t.createOffer();if(await t.setLocalDescription(i),!this.isCurrentAttempt(e,void 0,t))return;if(this.sdpOfferSent=!0,this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:i,negotiationId:this.negotiationId??void 0});}catch(a){console.warn("[WebRTCTransport] Offer signaling failed (non-fatal)",{error:a,negotiationId:this.negotiationId,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState});}else console.warn("[WebRTCTransport] No signal sender \u2014 offer not transmitted");}catch(i){console.error("[WebRTCTransport] Offer creation failed",i),this.closePeerResources(),this.setState("failed");}finally{this.isCurrentAttempt(e,void 0,t)&&(this.offerInFlight=false);}}}handleSignalingMessage(e){if(!this.pc||e.transport!=="webrtc")return;let n=this.normalizeNegotiationId(e?.negotiationId);if(n&&this.negotiationId&&n!==this.negotiationId){c("[WebRTCTransport] Ignoring stale signaling message for a different negotiation",{signalType:e?.type??null,signalNegotiationId:n,activeNegotiationId:this.negotiationId});return}if(e.type==="candidate"){let t=e.candidate;d$2("[WebRTCTransport] Received remote ICE candidate",{hasRemoteDesc:!!this.pc.remoteDescription,type:t?.type,protocol:t?.protocol,address:t?.address}),this.pc.remoteDescription?this.pc.addIceCandidate(t).catch(i=>{console.warn("[WebRTCTransport] addIceCandidate failed",i);}):(this.pendingCandidates.push(t),d$2(`[WebRTCTransport] Buffered remote candidate \u2014 ${this.pendingCandidates.length} pending`));}else if(e.type==="sdp"){let t=e.sdp,i=t.type==="offer",a=t.type==="answer";if(a&&this.pc.signalingState!=="have-local-offer"){c("[WebRTCTransport] Ignoring SDP answer because no local offer is pending",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,signalNegotiationId:n,activeNegotiationId:this.negotiationId,hasLocalDescription:!!this.pc.localDescription,hasRemoteDescription:!!this.pc.remoteDescription});return}d$2(`[WebRTCTransport] Received SDP ${t.type} \u2014 applying remote description`),a&&(this.sdpAnswerReceived=true),this.pc.setRemoteDescription(t).then(async()=>{if(a&&(d$2("[WebRTCTransport] Remote SDP answer applied",{signalingState:this.pc?.signalingState,iceConnectionState:this.pc?.iceConnectionState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),this.promoteConnectedIfReady("sdp-answer-applied")),this.pendingCandidates.length&&(d$2(`[WebRTCTransport] Flushing ${this.pendingCandidates.length} buffered candidate(s)`),this.pendingCandidates.forEach(s=>this.pc?.addIceCandidate(s)),this.pendingCandidates=[]),i){d$2("[WebRTCTransport] Creating answer (responder)");let s=await this.pc.createAnswer();if(await this.pc.setLocalDescription(s),d$2("[WebRTCTransport] Answer sent"),this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:s,negotiationId:n??this.negotiationId??void 0});}catch(c){throw console.warn("[WebRTCTransport] Failed sending SDP answer signal",{error:c,signalingState:this.pc?.signalingState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),c}else console.warn("[WebRTCTransport] No signal sender \u2014 answer not transmitted");}}).catch(s=>{console.error(`[WebRTCTransport] setRemoteDescription (${t.type}) failed`,s),this.setState("failed");});}}async send(e){if(this.dc&&this.dc.readyState==="open"){let n=new Uint8Array(e);this.dc.send(n);}else throw new Error("WebRTC DataChannel not open")}getBufferedAmount(){return this.dc?.bufferedAmount??0}async waitForDrain(e){!this.dc||this.dc.bufferedAmount<=e||await new Promise(n=>{let t=this.dc;if(!t){n();return}t.bufferedAmountLowThreshold=e,t.onbufferedamountlow=()=>{t.onbufferedamountlow=null,n();};});}close(){this.closePeerResources(),this.setState("disconnected");}onMessage(e){this.messageListeners.push(e);}onStateChange(e){this.stateListeners.push(e);}setState(e){this.state!==e&&(this.state=e,(e==="connected"||e==="failed"||e==="disconnected")&&this.clearConnectTimeout(),this.stateListeners.forEach(n=>n(e)));}startConnectTimeout(e){this.clearConnectTimeout(),this.connectTimeoutId=setTimeout(()=>{this.activeAttemptId===e&&this.state==="connecting"&&(console.warn(`[WebRTCTransport] Timed out after ${d.ICE_CONNECT_TIMEOUT_MS}ms`,{iceState:this.pc?.iceConnectionState,gatheringState:this.pc?.iceGatheringState,signalingState:this.pc?.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived,hasRemoteDescription:!!this.pc?.remoteDescription,hasLocalDescription:!!this.pc?.localDescription}),this.setState("failed"));},d.ICE_CONNECT_TIMEOUT_MS);}clearConnectTimeout(){this.connectTimeoutId&&(clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null);}startIceDisconnectedGrace(e,n,t,i){if(!this.iceDisconnectedGraceTimer){if(this.iceRestartAttempted)d$2("[WebRTCTransport] ice-disconnected grace (restart already attempted)",{reason:i});else if(this.iceRestartAttempted=true,t){try{d$2("[WebRTCTransport] ice-restart-attempted",{reason:i,isInitiator:t}),n.restartIce();}catch(a){console.warn("[WebRTCTransport] restartIce threw",a);}this.sendIceRestartOffer(e,n);}else d$2("[WebRTCTransport] ice-restart deferred to initiator",{reason:i});this.iceDisconnectedGraceTimer=setTimeout(()=>{if(this.iceDisconnectedGraceTimer=null,this.activeAttemptId!==e||this.pc!==n)return;let a=n.iceConnectionState,s=n.connectionState,c=this.dc?.readyState??"missing";if(a==="connected"||a==="completed"||s==="connected"||c==="open"){d$2("[WebRTCTransport] ice-grace expired \u2014 recovered",{ice:a,conn:s,dcReadyState:c});return}if(this.disconnectedGraceExtensions<1){this.disconnectedGraceExtensions+=1,console.warn("[WebRTCTransport] ice-grace expired \u2014 extending once before fail",{ice:a,conn:s,dcReadyState:c,extension:this.disconnectedGraceExtensions}),this.startIceDisconnectedGrace(e,n,t,`${i}:extended`);return}console.warn("[WebRTCTransport] ice-grace expired \u2014 marking failed",{ice:a,conn:s}),this.setState("failed");},d.ICE_DISCONNECTED_GRACE_MS);}}async sendIceRestartOffer(e,n){try{let t=await n.createOffer({iceRestart:!0});if(!this.isCurrentAttempt(e,void 0,n)||(await n.setLocalDescription(t),!this.isCurrentAttempt(e,void 0,n)))return;this.internalSignalSender?(await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:t,negotiationId:this.negotiationId??void 0}),d$2("[WebRTCTransport] ice-restart re-offer sent",{negotiationId:this.negotiationId})):console.warn("[WebRTCTransport] ice-restart re-offer dropped \u2014 no signal sender");}catch(t){console.warn("[WebRTCTransport] ice-restart re-offer failed",t);}}clearIceDisconnectedGrace(e){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null);}promoteConnectedIfReady(e){let n=this.dc?.readyState??"missing";if(n!=="open"){d$2("[WebRTCTransport] Deferring connected state until DataChannel is open",{reason:e,dcReadyState:n,iceConnectionState:this.pc?.iceConnectionState,connectionState:this.pc?.connectionState});return}this.clearIceDisconnectedGrace(`connected:${e}`),this.disconnectedGraceExtensions=0,this.setState("connected");}closePeerResources(){this.activeAttemptId+=1,this.clearConnectTimeout(),this.clearIceDisconnectedGrace("close"),this.iceRestartAttempted=false,this.pendingCandidates=[],this._terminalFailure=false,this.negotiationId=null,this.disconnectedGraceExtensions=0,this.offerInFlight=false,this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,this.dc.readyState!=="closed"&&this.dc.close(),this.dc=null),this.pc&&(this.pc.onicecandidate=null,this.pc.onnegotiationneeded=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.connectionState!=="closed"&&this.pc.close(),this.pc=null);}isCurrentAttempt(e,n,t){return !(this.activeAttemptId!==e||n&&this.dc!==n||t&&this.pc!==t)}createNegotiationId(){return `ts-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}normalizeNegotiationId(e){if(typeof e!="string")return null;let n=e.trim();return n.length>0?n:null}};d.ICE_CONNECT_TIMEOUT_MS=v,d.ICE_DISCONNECTED_GRACE_MS=3e4;var h=d;var I={iroh:{available:false,reason:"iroh is constructed by the OpenRTC runtime, not the legacy ITransport factory."},"iroh-quic":{available:false,reason:"iroh-quic is a path label, not a standalone transport."},"iroh-relay":{available:false,reason:"iroh-relay is a path label, not a standalone transport."},"iroh-lan":{available:false,reason:"iroh-lan is a path label, not a standalone transport."},"iroh-webrtc":{available:false,reason:"iroh-webrtc is a runtime-owned carrier path, not a standalone transport."},"iroh-moq":{available:false,reason:"iroh-moq is a runtime-owned carrier path, not a standalone transport."},ble:{available:false,reason:"ble requires a separately licensed native host companion and current physical-device evidence."},webrtc:{available:true},"webrtc-lan":{available:false,reason:"webrtc-lan is a path label, not a standalone transport."},"webrtc-turn":{available:false,reason:"webrtc-turn is a path label, not a standalone transport."},moq:{available:false,reason:"MoQ is constructed by the route lifecycle, not the legacy ITransport factory."}};function w(r){return r.implementation==="route-adapter"?"plugin":r.implementation==="core"?"native":"path-label"}function A(){return Object.fromEntries(a.map(r=>[r.id,{...r,routeImplementation:r.implementation,implementation:w(r),protocol:r.id,preferredRank:d$1[r.id],...I[r.id]}]))}var f=class{static createTransport(e){if(this.assertProtocolAvailable(e),e==="webrtc")return new h;throw new Error(`[TransportFactory] '${e}' is not implemented as an ITransport plugin.`)}static getProtocolCapability(e){return {...this.capabilityMap[e]}}static getProtocolCapabilities(){return Object.fromEntries(a.map(e=>[e.id,this.getProtocolCapability(e.id)]))}static preferredProtocols(e={}){let n=e.runtime??"any",t=e.includePathLabels??true;return a.filter(i=>t||i.implementation!=="path-label").filter(i=>n==="browser"?i.browser:n==="native"?i.native:i.browser||i.native).sort((i,a)=>d$1[i.id]-d$1[a.id]).map(i=>i.id)}static assertProtocolAvailable(e){let n=this.capabilityMap[e];if(!n.available||n.maturity==="unsupported"){let t=n.reason?` ${n.reason}`:"";throw new Error(`[TransportFactory] Protocol '${e}' is unsupported.${t}`)}}};f.capabilityMap=A();function _(r){return f.preferredProtocols(r)}var g=32,S="openrtc:x25519-hkdf:v1",C=new TextEncoder().encode("openrtc:application-crypto:v1");function u(r,e){if(!(e instanceof Uint8Array)||e.byteLength!==g)throw new Error(`[OpenRTC] ${r} must be ${g} bytes`)}function E(r,e){let[n,t]=r<=e?[r,e]:[e,r],i=new TextEncoder().encode(n),a=new TextEncoder().encode(t),s=new Uint8Array(C.byteLength+1+i.byteLength+1+a.byteLength),c=0;return s.set(C,c),c+=C.byteLength,s[c]=0,c+=1,s.set(i,c),c+=i.byteLength,s[c]=0,c+=1,s.set(a,c),s}function K(r=e=>{let n=new Uint8Array(e);return globalThis.crypto.getRandomValues(n),n}){let e=r(g);return u("key agreement secret",e),{publicKey:x25519.getPublicKey(e),secretKey:e}}function M(r,e,n,t){u("key agreement local secret",r),u("key agreement remote public key",e);let i=x25519.getSharedSecret(r,e);return hkdf(sha256,i,void 0,E(n,t),32)}function $(r){return Array.from(sha256(r).slice(0,6),e=>e.toString(16).padStart(2,"0")).join("")}function F(r){u("key agreement public key",r);let e="";for(let t=0;t<r.byteLength;t+=1)e+=String.fromCharCode(r[t]);let n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return {algorithm:S,publicKey:n}}function k(r){if(!r||r.algorithm!==S)return null;let e=typeof r.publicKey=="string"?r.publicKey.trim():"";if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/"),t=n.length%4===0?n:n+"=".repeat(4-n.length%4),i=Uint8Array.from(atob(t),a=>a.charCodeAt(0));return i.byteLength!==g?null:i}
1
+ import {d as d$2,c}from'./chunk-2L6ULC32.js';import {a,d as d$1}from'./chunk-2SUSPEC4.js';import {x25519}from'@noble/curves/ed25519.js';import {hkdf}from'@noble/hashes/hkdf.js';import {sha256}from'@noble/hashes/sha2.js';var v=3e4,d=class d{constructor(){this.name="webrtc";this.pc=null;this.dc=null;this.state="disconnected";this.pendingCandidates=[];this.connectTimeoutId=null;this.iceDisconnectedGraceTimer=null;this.iceRestartAttempted=false;this.localNodeId="";this.remoteNodeId="";this.candidatesGathered=0;this.sdpOfferSent=false;this.sdpAnswerReceived=false;this._terminalFailure=false;this.activeAttemptId=0;this.negotiationId=null;this.disconnectedGraceExtensions=0;this.offerInFlight=false;this.messageListeners=[];this.stateListeners=[];this.internalSignalSender=null;}get isReady(){return this.state==="connected"}isTerminalFailure(){return this._terminalFailure}getNegotiationId(){return this.negotiationId}getDataChannelReadyState(){return this.dc?.readyState??null}getNativeTransport(){return this.pc}setSignalSender(e){this.internalSignalSender=e;}async init(e,n,t){this.closePeerResources();let i=++this.activeAttemptId;this.localNodeId=e,this.remoteNodeId=n,this.candidatesGathered=0,this.sdpOfferSent=false,this.sdpAnswerReceived=false,this._terminalFailure=false,this.offerInFlight=false,this.pendingCandidates=[],this.disconnectedGraceExtensions=0,this.negotiationId=typeof t?.negotiationId=="string"&&t.negotiationId.trim().length>0?t.negotiationId.trim():this.createNegotiationId(),this.setState("connecting"),this.startConnectTimeout(i);let a=t.rtcConfig||{},s=typeof t?.forceRole=="string"&&(t.forceRole==="initiator"||t.forceRole==="responder")?t.forceRole:null,c=s?s==="initiator":e>n;d$2(`[WebRTCTransport] init \u2014 role=${c?"initiator":"responder"}`,{local:e.slice(0,12),remote:n.slice(0,12),negotiationId:this.negotiationId,forcedRole:s});try{d$2("[WebRTCTransport] Creating RTCPeerConnection",{iceServers:a.iceServers?.length??0}),this.pc=new RTCPeerConnection(a);}catch(R){console.error("[WebRTCTransport] RTCPeerConnection constructor failed",R),this.setState("failed");return}let T=this.pc.createDataChannel("pluto-dc",{negotiated:true,id:0});this.setupDataChannel(T,i),this.setupPCHandlers(c,i),c&&queueMicrotask(()=>{this.createAndSendOffer(i,"initial-initiator");});}setupDataChannel(e,n){this.dc=e,e.onopen=()=>{this.isCurrentAttempt(n,e)&&(d$2("[WebRTCTransport] DataChannel opened \u2014 upgrade complete"),this.promoteConnectedIfReady("datachannel-open"));},e.onmessage=t=>{if(!this.isCurrentAttempt(n,e))return;let i=typeof t.data=="string"?new TextEncoder().encode(t.data):new Uint8Array(t.data);this.messageListeners.forEach(a=>a(i));},e.onclose=()=>{this.isCurrentAttempt(n,e)&&(d$2("[WebRTCTransport] DataChannel closed"),(this.state==="connected"||this.state==="connecting")&&this.setState("disconnected"));},e.onerror=t=>{if(!this.isCurrentAttempt(n,e))return;console.warn("[WebRTCTransport] DataChannel error",t);let i=t?.error?.message??"";if((i.includes("User-Initiated Abort")||i.includes("Close called"))&&this.state==="connected"&&e.readyState!=="open"){console.warn("[WebRTCTransport] DataChannel aborted post-connect; forcing disconnected state",{readyState:e.readyState,connectionState:this.pc?.connectionState,iceConnectionState:this.pc?.iceConnectionState}),this.setState("disconnected");return}this.state==="connecting"&&this.setState("failed");};}setupPCHandlers(e,n){let t=this.pc;t&&(t.onicecandidate=i=>{this.isCurrentAttempt(n,void 0,t)&&(i.candidate?(this.candidatesGathered++,d$2(`[WebRTCTransport] ICE candidate #${this.candidatesGathered}: ${i.candidate.type} ${i.candidate.protocol} ${i.candidate.address??"?"}:${i.candidate.port}`),this.internalSignalSender?this.internalSignalSender({transport:"webrtc",type:"candidate",candidate:i.candidate,negotiationId:this.negotiationId??void 0}).catch(a=>{console.warn("[WebRTCTransport] Failed sending local ICE candidate signal",{error:a,gatheringState:t?.iceGatheringState,iceConnectionState:t?.iceConnectionState});}):console.warn("[WebRTCTransport] ICE candidate dropped \u2014 no signal sender!")):this.candidatesGathered===0?(console.warn("[WebRTCTransport] ICE gathering complete with 0 candidates \u2014 failing immediately.","If both peers are on the same page, WebRTC requires separate tabs or devices.",{local:this.localNodeId.slice(0,12),remote:this.remoteNodeId.slice(0,12)}),this._terminalFailure=true,this.setState("failed")):d$2(`[WebRTCTransport] ICE gathering complete \u2014 ${this.candidatesGathered} candidate(s)`));},t.onnegotiationneeded=async()=>{e&&await this.createAndSendOffer(n,"negotiationneeded");},t.onconnectionstatechange=()=>{if(!this.isCurrentAttempt(n,void 0,t))return;let i=t.connectionState;if(d$2(`[WebRTCTransport] Connection state: ${i}`),i==="connected")this.promoteConnectedIfReady("pc-connected");else if(i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] pc.connectionState=failed during grace window \u2014 deferring to grace timer",{iceState:t.iceConnectionState,iceRestartAttempted:this.iceRestartAttempted});return}console.error("[WebRTCTransport] Connection failed",{iceState:t.iceConnectionState,gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived}),this.clearIceDisconnectedGrace("pc-failed"),this.setState("failed");}else i==="closed"?(this.clearIceDisconnectedGrace("pc-closed"),this.setState("disconnected")):i==="disconnected"&&(d$2("[WebRTCTransport] pc.connectionState=disconnected, deferring to ICE grace period"),this.startIceDisconnectedGrace(n,t,e,"pc-disconnected"));},t.oniceconnectionstatechange=()=>{if(!this.isCurrentAttempt(n,void 0,t))return;let i=t.iceConnectionState;if(d$2(`[WebRTCTransport] ICE connection state: ${i}`,{gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered,hasSdpOffer:this.sdpOfferSent,hasSdpAnswer:this.sdpAnswerReceived,hasRemoteDescription:!!t.remoteDescription,hasLocalDescription:!!t.localDescription}),i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] ice failed during grace window \u2014 deferring to grace timer");return}console.error("[WebRTCTransport] ICE failed \u2014 likely NAT traversal issue or no matching candidates",{gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered}),this.clearIceDisconnectedGrace("ice-failed"),this.setState("failed");}else i==="disconnected"?this.startIceDisconnectedGrace(n,t,e,"ice-disconnected"):(i==="connected"||i==="completed")&&(this.iceDisconnectedGraceTimer&&d$2("[WebRTCTransport] ice-recovered \u2014 cancelling grace timer"),this.clearIceDisconnectedGrace("ice-recovered"),this.iceRestartAttempted=false,this.promoteConnectedIfReady("ice-connected"));},t.onicegatheringstatechange=()=>{this.isCurrentAttempt(n,void 0,t)&&d$2(`[WebRTCTransport] ICE gathering state: ${t.iceGatheringState}`,{iceConnectionState:t.iceConnectionState,signalingState:t.signalingState,hasLocalDesc:!!t.localDescription,hasRemoteDesc:!!t.remoteDescription});});}async createAndSendOffer(e,n){let t=this.pc;if(!(!t||!this.isCurrentAttempt(e,void 0,t))&&t.signalingState==="stable"&&!(this.sdpOfferSent&&t.localDescription?.type==="offer")&&!this.offerInFlight){d$2(`[WebRTCTransport] Creating offer (${n})`),this.offerInFlight=true;try{let i=await t.createOffer();if(await t.setLocalDescription(i),!this.isCurrentAttempt(e,void 0,t))return;if(this.sdpOfferSent=!0,this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:i,negotiationId:this.negotiationId??void 0});}catch(a){console.warn("[WebRTCTransport] Offer signaling failed (non-fatal)",{error:a,negotiationId:this.negotiationId,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState});}else console.warn("[WebRTCTransport] No signal sender \u2014 offer not transmitted");}catch(i){console.error("[WebRTCTransport] Offer creation failed",i),this.closePeerResources(),this.setState("failed");}finally{this.isCurrentAttempt(e,void 0,t)&&(this.offerInFlight=false);}}}handleSignalingMessage(e){if(!this.pc||e.transport!=="webrtc")return;let n=this.normalizeNegotiationId(e?.negotiationId);if(n&&this.negotiationId&&n!==this.negotiationId){c("[WebRTCTransport] Ignoring stale signaling message for a different negotiation",{signalType:e?.type??null,signalNegotiationId:n,activeNegotiationId:this.negotiationId});return}if(e.type==="candidate"){let t=e.candidate;d$2("[WebRTCTransport] Received remote ICE candidate",{hasRemoteDesc:!!this.pc.remoteDescription,type:t?.type,protocol:t?.protocol,address:t?.address}),this.pc.remoteDescription?this.pc.addIceCandidate(t).catch(i=>{console.warn("[WebRTCTransport] addIceCandidate failed",i);}):(this.pendingCandidates.push(t),d$2(`[WebRTCTransport] Buffered remote candidate \u2014 ${this.pendingCandidates.length} pending`));}else if(e.type==="sdp"){let t=e.sdp,i=t.type==="offer",a=t.type==="answer";if(a&&this.pc.signalingState!=="have-local-offer"){c("[WebRTCTransport] Ignoring SDP answer because no local offer is pending",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,signalNegotiationId:n,activeNegotiationId:this.negotiationId,hasLocalDescription:!!this.pc.localDescription,hasRemoteDescription:!!this.pc.remoteDescription});return}d$2(`[WebRTCTransport] Received SDP ${t.type} \u2014 applying remote description`),a&&(this.sdpAnswerReceived=true),this.pc.setRemoteDescription(t).then(async()=>{if(a&&(d$2("[WebRTCTransport] Remote SDP answer applied",{signalingState:this.pc?.signalingState,iceConnectionState:this.pc?.iceConnectionState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),this.promoteConnectedIfReady("sdp-answer-applied")),this.pendingCandidates.length&&(d$2(`[WebRTCTransport] Flushing ${this.pendingCandidates.length} buffered candidate(s)`),this.pendingCandidates.forEach(s=>this.pc?.addIceCandidate(s)),this.pendingCandidates=[]),i){d$2("[WebRTCTransport] Creating answer (responder)");let s=await this.pc.createAnswer();if(await this.pc.setLocalDescription(s),d$2("[WebRTCTransport] Answer sent"),this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:s,negotiationId:n??this.negotiationId??void 0});}catch(c){throw console.warn("[WebRTCTransport] Failed sending SDP answer signal",{error:c,signalingState:this.pc?.signalingState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),c}else console.warn("[WebRTCTransport] No signal sender \u2014 answer not transmitted");}}).catch(s=>{console.error(`[WebRTCTransport] setRemoteDescription (${t.type}) failed`,s),this.setState("failed");});}}async send(e){if(this.dc&&this.dc.readyState==="open"){let n=new Uint8Array(e);this.dc.send(n);}else throw new Error("WebRTC DataChannel not open")}getBufferedAmount(){return this.dc?.bufferedAmount??0}async waitForDrain(e){!this.dc||this.dc.bufferedAmount<=e||await new Promise(n=>{let t=this.dc;if(!t){n();return}t.bufferedAmountLowThreshold=e,t.onbufferedamountlow=()=>{t.onbufferedamountlow=null,n();};});}close(){this.closePeerResources(),this.setState("disconnected");}onMessage(e){this.messageListeners.push(e);}onStateChange(e){this.stateListeners.push(e);}setState(e){this.state!==e&&(this.state=e,(e==="connected"||e==="failed"||e==="disconnected")&&this.clearConnectTimeout(),this.stateListeners.forEach(n=>n(e)));}startConnectTimeout(e){this.clearConnectTimeout(),this.connectTimeoutId=setTimeout(()=>{this.activeAttemptId===e&&this.state==="connecting"&&(console.warn(`[WebRTCTransport] Timed out after ${d.ICE_CONNECT_TIMEOUT_MS}ms`,{iceState:this.pc?.iceConnectionState,gatheringState:this.pc?.iceGatheringState,signalingState:this.pc?.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived,hasRemoteDescription:!!this.pc?.remoteDescription,hasLocalDescription:!!this.pc?.localDescription}),this.setState("failed"));},d.ICE_CONNECT_TIMEOUT_MS);}clearConnectTimeout(){this.connectTimeoutId&&(clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null);}startIceDisconnectedGrace(e,n,t,i){if(!this.iceDisconnectedGraceTimer){if(this.iceRestartAttempted)d$2("[WebRTCTransport] ice-disconnected grace (restart already attempted)",{reason:i});else if(this.iceRestartAttempted=true,t){try{d$2("[WebRTCTransport] ice-restart-attempted",{reason:i,isInitiator:t}),n.restartIce();}catch(a){console.warn("[WebRTCTransport] restartIce threw",a);}this.sendIceRestartOffer(e,n);}else d$2("[WebRTCTransport] ice-restart deferred to initiator",{reason:i});this.iceDisconnectedGraceTimer=setTimeout(()=>{if(this.iceDisconnectedGraceTimer=null,this.activeAttemptId!==e||this.pc!==n)return;let a=n.iceConnectionState,s=n.connectionState,c=this.dc?.readyState??"missing";if(a==="connected"||a==="completed"||s==="connected"||c==="open"){d$2("[WebRTCTransport] ice-grace expired \u2014 recovered",{ice:a,conn:s,dcReadyState:c});return}if(this.disconnectedGraceExtensions<1){this.disconnectedGraceExtensions+=1,console.warn("[WebRTCTransport] ice-grace expired \u2014 extending once before fail",{ice:a,conn:s,dcReadyState:c,extension:this.disconnectedGraceExtensions}),this.startIceDisconnectedGrace(e,n,t,`${i}:extended`);return}console.warn("[WebRTCTransport] ice-grace expired \u2014 marking failed",{ice:a,conn:s}),this.setState("failed");},d.ICE_DISCONNECTED_GRACE_MS);}}async sendIceRestartOffer(e,n){try{let t=await n.createOffer({iceRestart:!0});if(!this.isCurrentAttempt(e,void 0,n)||(await n.setLocalDescription(t),!this.isCurrentAttempt(e,void 0,n)))return;this.internalSignalSender?(await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:t,negotiationId:this.negotiationId??void 0}),d$2("[WebRTCTransport] ice-restart re-offer sent",{negotiationId:this.negotiationId})):console.warn("[WebRTCTransport] ice-restart re-offer dropped \u2014 no signal sender");}catch(t){console.warn("[WebRTCTransport] ice-restart re-offer failed",t);}}clearIceDisconnectedGrace(e){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null);}promoteConnectedIfReady(e){let n=this.dc?.readyState??"missing";if(n!=="open"){d$2("[WebRTCTransport] Deferring connected state until DataChannel is open",{reason:e,dcReadyState:n,iceConnectionState:this.pc?.iceConnectionState,connectionState:this.pc?.connectionState});return}this.clearIceDisconnectedGrace(`connected:${e}`),this.disconnectedGraceExtensions=0,this.setState("connected");}closePeerResources(){this.activeAttemptId+=1,this.clearConnectTimeout(),this.clearIceDisconnectedGrace("close"),this.iceRestartAttempted=false,this.pendingCandidates=[],this._terminalFailure=false,this.negotiationId=null,this.disconnectedGraceExtensions=0,this.offerInFlight=false,this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,this.dc.readyState!=="closed"&&this.dc.close(),this.dc=null),this.pc&&(this.pc.onicecandidate=null,this.pc.onnegotiationneeded=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.connectionState!=="closed"&&this.pc.close(),this.pc=null);}isCurrentAttempt(e,n,t){return !(this.activeAttemptId!==e||n&&this.dc!==n||t&&this.pc!==t)}createNegotiationId(){return `ts-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}normalizeNegotiationId(e){if(typeof e!="string")return null;let n=e.trim();return n.length>0?n:null}};d.ICE_CONNECT_TIMEOUT_MS=v,d.ICE_DISCONNECTED_GRACE_MS=3e4;var h=d;var I={iroh:{available:false,reason:"iroh is constructed by the OpenRTC runtime, not the legacy ITransport factory."},"iroh-quic":{available:false,reason:"iroh-quic is a path label, not a standalone transport."},"iroh-relay":{available:false,reason:"iroh-relay is a path label, not a standalone transport."},"iroh-lan":{available:false,reason:"iroh-lan is a path label, not a standalone transport."},"iroh-webrtc":{available:false,reason:"iroh-webrtc is a runtime-owned carrier path, not a standalone transport."},"iroh-moq":{available:false,reason:"iroh-moq is a runtime-owned carrier path, not a standalone transport."},ble:{available:false,reason:"ble requires a separately licensed native host companion and current physical-device evidence."},webrtc:{available:true},"webrtc-lan":{available:false,reason:"webrtc-lan is a path label, not a standalone transport."},"webrtc-turn":{available:false,reason:"webrtc-turn is a path label, not a standalone transport."},moq:{available:false,reason:"MoQ is constructed by the route lifecycle, not the legacy ITransport factory."}};function w(r){return r.implementation==="route-adapter"?"plugin":r.implementation==="core"?"native":"path-label"}function A(){return Object.fromEntries(a.map(r=>[r.id,{...r,routeImplementation:r.implementation,implementation:w(r),protocol:r.id,preferredRank:d$1[r.id],...I[r.id]}]))}var f=class{static createTransport(e){if(this.assertProtocolAvailable(e),e==="webrtc")return new h;throw new Error(`[TransportFactory] '${e}' is not implemented as an ITransport plugin.`)}static getProtocolCapability(e){return {...this.capabilityMap[e]}}static getProtocolCapabilities(){return Object.fromEntries(a.map(e=>[e.id,this.getProtocolCapability(e.id)]))}static preferredProtocols(e={}){let n=e.runtime??"any",t=e.includePathLabels??true;return a.filter(i=>t||i.implementation!=="path-label").filter(i=>n==="browser"?i.browser:n==="native"?i.native:i.browser||i.native).sort((i,a)=>d$1[i.id]-d$1[a.id]).map(i=>i.id)}static assertProtocolAvailable(e){let n=this.capabilityMap[e];if(!n.available||n.maturity==="unsupported"){let t=n.reason?` ${n.reason}`:"";throw new Error(`[TransportFactory] Protocol '${e}' is unsupported.${t}`)}}};f.capabilityMap=A();function _(r){return f.preferredProtocols(r)}var g=32,S="openrtc:x25519-hkdf:v1",C=new TextEncoder().encode("openrtc:application-crypto:v1");function u(r,e){if(!(e instanceof Uint8Array)||e.byteLength!==g)throw new Error(`[OpenRTC] ${r} must be ${g} bytes`)}function E(r,e){let[n,t]=r<=e?[r,e]:[e,r],i=new TextEncoder().encode(n),a=new TextEncoder().encode(t),s=new Uint8Array(C.byteLength+1+i.byteLength+1+a.byteLength),c=0;return s.set(C,c),c+=C.byteLength,s[c]=0,c+=1,s.set(i,c),c+=i.byteLength,s[c]=0,c+=1,s.set(a,c),s}function K(r=e=>{let n=new Uint8Array(e);return globalThis.crypto.getRandomValues(n),n}){let e=r(g);return u("key agreement secret",e),{publicKey:x25519.getPublicKey(e),secretKey:e}}function M(r,e,n,t){u("key agreement local secret",r),u("key agreement remote public key",e);let i=x25519.getSharedSecret(r,e);return hkdf(sha256,i,void 0,E(n,t),32)}function $(r){return Array.from(sha256(r).slice(0,6),e=>e.toString(16).padStart(2,"0")).join("")}function F(r){u("key agreement public key",r);let e="";for(let t=0;t<r.byteLength;t+=1)e+=String.fromCharCode(r[t]);let n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return {algorithm:S,publicKey:n}}function k(r){if(!r||r.algorithm!==S)return null;let e=typeof r.publicKey=="string"?r.publicKey.trim():"";if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/"),t=n.length%4===0?n:n+"=".repeat(4-n.length%4),i=Uint8Array.from(atob(t),a=>a.charCodeAt(0));return i.byteLength!==g?null:i}
2
2
  export{v as a,f as b,_ as c,g as d,S as e,K as f,M as g,$ as h,F as i,k as j};
@@ -0,0 +1 @@
1
+ var o=["iroh-relay","iroh-moq","iroh"],l=new Set(["iroh","iroh-quic","iroh-relay","iroh-lan","iroh-webrtc","iroh-moq","ble"]);function T(r){return r?.filter(n=>l.has(n))}function u(r){return (Array.isArray(r.urls)?r.urls:[r.urls]).some(e=>typeof e=="string"&&(e.startsWith("turn:")||e.startsWith("turns:")))}function a(r){let e=(Array.isArray(r.urls)?r.urls:[r.urls]).filter(t=>typeof t=="string"&&!t.startsWith("stun:"));return e.length===0?null:{...r,urls:Array.isArray(r.urls)?e:e[0]}}function c(r){let e=(Array.isArray(r.urls)?r.urls:[r.urls]).filter(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";return !i.startsWith("turn:")&&!i.startsWith("turns:")});return e.length===0?null:{...r,urls:Array.isArray(r.urls)?e:e[0]}}function f(r){return r?.map(n=>c(n)).filter(n=>n!==null)}function d(r){if(r)return r.map(n=>a(n)).filter(n=>n!==null)}function y(r,n){let e=new Set(["iroh-relay","iroh-moq","iroh"]);n&&e.add("iroh-webrtc");let t=(r??o).filter(i=>e.has(i));return t.length>0?t:[...o]}function C(r){return false}function p(r,n){}function R(r,n){let e=r?.transports?.webrtc;if(e)return e===true?{}:s(r,n)}function s(r,n){let e=r?.transports?.webrtc||void 0;if(e)return r?.transports?.relay===false?{...e,useTurn:false,privacyMode:false,iceTransportPolicy:"all",iceServers:f(e.iceServers)}:r?.strictMode||r?.transports?.privacy==="relay-only"||e.privacyMode?{...e,iceServers:d(e.iceServers),iceTransportPolicy:"relay"}:e.iceTransportPolicy==="relay"&&!(Array.isArray(e.iceServers)&&e.iceServers.some(i=>u(i)))?(n?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...e,iceTransportPolicy:"all"}):e}export{T as a,d as b,y as c,C as d,p as e,R as f};
@@ -1 +1 @@
1
- import {s}from'./chunk-UGZJJQPM.js';import {a}from'./chunk-OUFHVLDQ.js';function v(i,d){let t=new s(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,o={runtime:t,async setAuthContext(e){await t.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 o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
1
+ import {s}from'./chunk-XAL4T6TB.js';import {a}from'./chunk-Z2IS6NH2.js';function v(i,d){let t=new s(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,o={runtime:t,async setAuthContext(e){await t.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 o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
@@ -0,0 +1,2 @@
1
+ import {b as b$1}from'./chunk-ZA44REGI.js';var D=1440*6e4,g=class extends Error{constructor(i,r,n){super(i);this.status=r;this.reason=n;this.name="RTCError";let e=[502,503,504].includes(r),a=n==="device-reenrollment-auth-required";this.code=a?"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=a||e,this.plane=a||r===401?"auth":e||r===429?"coordination":r===403?"admission":"internal";}};function C(s){return !(s instanceof g)||s.status!==403?false:s.reason==="device-certificate-stale"||s.reason==="device-certificate-revoked"?true:!s.reason&&s.message==="Device certificate is revoked or stale."}function b(s,t,i){return `openrtc:v2:device-certificate:${s}:${t}:${i}`}function k(s,t){return `openrtc:v2:device-session:${s}:${t}`}async function K(s,t,i){let r=new TextEncoder().encode(`openrtc:v2:session\0${s}\0${t}\0${i}`),n=new Uint8Array(await crypto.subtle.digest("SHA-256",r)),e="";for(let a of n)e+=String.fromCharCode(a);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function P(s){let t=s.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"="),r=atob(i);return Uint8Array.from(r,n=>n.charCodeAt(0))}async function R(s,t,i,r,n){if(typeof s.token!="string"||typeof s.expiresAtMs!="number"||s.expiresAtMs<=Date.now()+D||!s.signingPublicJwk||s.signingPublicJwk.kty!=="OKP"||s.signingPublicJwk.crv!=="Ed25519"||typeof s.signingPublicJwk.x!="string")return null;let e=s.token.split(".");if(e.length!==3)return null;let a,o;try{a=JSON.parse(new TextDecoder().decode(P(e[0]))),o=b$1(s.token);}catch{return null}if(a.alg!=="EdDSA"||s.signingPublicJwk.kid&&a.kid!==s.signingPublicJwk.kid)return null;try{let l=await crypto.subtle.importKey("jwk",s.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},l,P(e[2]),new TextEncoder().encode(`${e[0]}.${e[1]}`)))return null}catch{return null}let c=typeof o.principalId=="string"?o.principalId:"",d=Number(o.iat),u=Number(o.exp);return o.iss!=="openrtc"||o.aud!=="openrtc:v2:gateway-grant"||o.typ!=="device-certificate"||o.appTag!==t||!c||n!==void 0&&c!==n||typeof o.principalKey!="string"||o.principalKey.length===0||o.deviceId!==i||o.deviceKeyThumbprint!==r||typeof o.jti!="string"||o.jti.length===0||!Number.isSafeInteger(d)||!Number.isSafeInteger(u)||d>=u||u*1e3!==s.expiresAtMs?null:{token:s.token,expiresAtMs:s.expiresAtMs,principalId:c,signingPublicJwk:s.signingPublicJwk,enrolled:false,relay:o.relay!==false}}async function x(s,t,i,r,n){try{let e=b(t,i,r),a=s.readSecureRecord?await s.readSecureRecord(t,e):globalThis.localStorage?.getItem(e);if(!a)return null;let o=JSON.parse(a),c=await R(o,t,r,n,i);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:i,signingPublicJwk:c.signingPublicJwk}:null}catch(e){if(s.readSecureRecord)throw e;return null}}async function T(s,t,i,r,n){try{let e=k(t,r),a=s.readSecureRecord?await s.readSecureRecord(i,e):globalThis.localStorage?.getItem(e);return a?await R(JSON.parse(a),i,r,n):null}catch(e){if(s.readSecureRecord)throw e;return null}}async function M(s,t,i,r,n){try{let e=b(t,i,r),a=JSON.stringify(n);s.writeSecureRecord?await s.writeSecureRecord(t,e,a):globalThis.localStorage?.setItem(e,a);}catch(e){if(s.writeSecureRecord)throw e}}async function G(s,t,i,r,n){try{let e=k(i,r),a=JSON.stringify({token:n.token,expiresAtMs:n.expiresAtMs,principalId:n.principalId,signingPublicJwk:n.signingPublicJwk});s.writeSecureRecord?await s.writeSecureRecord(t,e,a):globalThis.localStorage?.setItem(e,a);}catch(e){if(s.writeSecureRecord)throw e}}async function m(s,t,i,r,n){try{let e=b(t,i,r);if(s.deleteSecureRecord?await s.deleteSecureRecord(t,e):globalThis.localStorage?.removeItem(e),n){let a=k(n,r);s.deleteSecureRecord?await s.deleteSecureRecord(t,a):globalThis.localStorage?.removeItem(a);}}catch(e){if(s.deleteSecureRecord)throw e}}function S(s){return `${s}_${crypto.randomUUID()}`}async function I(s,t){let i=new TextEncoder().encode(`${s}:${t}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",i))].map(n=>n.toString(16).padStart(2,"0")).join("")}var A=class{constructor(t,i,r,n,e={},a){this.apiKey=t;this.endpoints=i;this.keyProvider=r;this.attestation=n;this.events=e;this.botVerification=a;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(n=>{n?.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=S("request"),n=JSON.stringify({apiKey:this.apiKey,...i}),e=null;for(let a=0;a<2;a+=1)try{let o=await fetch(`${this.endpoints.controlPlane}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":r},body:n,signal:AbortSignal.timeout(15e3)});if(o.ok)return o.json();let c=`OpenRTC request failed (${o.status}).`,d;try{let l=await o.json();typeof l.error=="string"&&(c=l.error.slice(0,256)),typeof l.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(l.reason)&&(d=l.reason);}catch{}let u=new g(c,o.status,d);if(e=u,a===0&&[502,503,504].includes(o.status))continue;throw u}catch(o){if(e=o,a===0&&o instanceof TypeError)continue;throw o}throw e instanceof Error?e:new Error("OpenRTC request failed.")}async capability(t,i,r,n=false){this.before("capability.issue");let e=t==="space"?await I(this.apiKey,i):i,o=await(await this.key()).proof((l,p)=>["openrtc:v2:capability",this.apiKey,t,e,l,p].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,d=await this.post("/v2/capabilities",{avenue:{kind:t,id:e},deviceProof:o,...r?{maxPeers:r}:{},...n?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let u={type:"capability",token:d.capability,avenue:t==="ticket"?{kind:"session",id:e}:d.avenue,expiresAtMs:d.expiresAt*1e3,relay:d.relay!==false};return u.renew=()=>this.capability(t,i,r,n),u}async deviceCertificate(t,i,r,n,e){let a=this.authEpoch(t),o=a.devices.get(i)??{};if(a.devices.set(i,o),e&&o.current&&o.current.token!==e.token)return this.deviceCertificateResult(t,i,r,n,{...o.current,enrolled:false});if(!e&&o.current&&o.current.expiresAtMs>Date.now()+D)return this.deviceCertificateResult(t,i,r,n,{...o.current,enrolled:false});if(!o.inFlight){let d=a.generation;e&&(o.current=void 0,o.recoverRevokedEnrollment=true);let u=e?m(this.keyProvider,this.appTag,e.principalId,i,a.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(t,i,a.sessionKeyHash,n,true)):this.resolveAuthenticatedDevice(t,i,a,n,o.recoverRevokedEnrollment===true);o.inFlight=u.then(l=>{if(a.generation!==d)throw new Error("The OpenRTC authentication identity changed during enrollment.");return o.recoverRevokedEnrollment=false,o.current=l,l}).finally(()=>{o.inFlight=void 0;});}let c=await o.inFlight;return this.deviceCertificateResult(t,i,r,n,c)}async resolveAuthenticatedDevice(t,i,r,n,e=false){let a=await this.key();if(t.getSessionKey){let o=await t.getSessionKey();if(!o)throw new Error("The OpenRTC auth provider has no active principal.");let c=await K(this.appTag,a.thumbprint,o);r.sessionKeyHash=c;let d=await T(this.keyProvider,c,this.appTag,i,a.thumbprint);if(d)return d}return this.enrollAuthenticatedDevice(t,i,r.sessionKeyHash,n,e)}deviceCertificateResult(t,i,r,n,e){let a={type:"device-certificate",token:e.token,avenue:r??{kind:"user",id:e.principalId},expiresAtMs:e.expiresAtMs,relay:e.relay};return a.renew=async()=>(await this.deviceCertificate(t,i,r,n)).source,a.recoverRejectedCertificate=async()=>(await this.deviceCertificate(t,i,r,n,e)).source,{principalId:e.principalId,source:a,enrolled:e.enrolled}}async enrollAuthenticatedDevice(t,i,r,n,e=false){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let a=async(v,y)=>{let w=await t.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:v,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}:{}})},o;try{o=await a(!1);}catch(v){if(!(v instanceof g)||v.status!==401)throw v;o=await a(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let c=await this.key(),d=await x(this.keyProvider,this.appTag,o.principalId,i,c.thumbprint);if(d)return {...d,principalId:o.principalId,enrolled:false,relay:o.relay!==false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let{enrollDevice:u}=await import('./deviceEnrollment-VACC64CQ.js'),l=await u({apiKey:this.apiKey,appTag:this.appTag,auth:t,attestation:this.attestation,deviceId:i,identity:o,key:c,profile:n,recoverRevokedEnrollment:e||o.deviceRecoveryAuthorized===true,post:(v,y)=>this.post(v,y),recordAssertionExchange:()=>this.record("identity.assertion.exchange")});o=l.identity;let p=l.enrollment;this.record("device.enroll"),this.attestation&&this.record("security.attestation.verify");let h={principalId:o.principalId,token:p.deviceCertificate,expiresAtMs:p.expiresAt*1e3,signingPublicJwk:p.signingPublicJwk,enrolled:true,relay:o.relay!==false};return await M(this.keyProvider,this.appTag,o.principalId,i,{token:h.token,expiresAtMs:h.expiresAtMs,signingPublicJwk:h.signingPublicJwk}),r&&await G(this.keyProvider,this.appTag,r,i,h),h}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 n=await this.deviceCertificate(t,i);if(await this.deviceManagement(n.source,i,"revoke",r),r===i){let e=this.authEpoch(t);await m(this.keyProvider,this.appTag,n.principalId,i,e.sessionKeyHash),e.devices.delete(i),await this.deleteDeviceKey();}}async revokeAllDevices(t,i,r){let n=await this.deviceCertificate(t,i);await this.deviceManagement(n.source,i,"revoke-all",void 0,r);let e=this.authEpoch(t);await m(this.keyProvider,this.appTag,n.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,n,e=false){let a=r==="revoke"?"device.revoke":r==="revoke-all"?"identity.revoke-all":null;a&&this.before(a);let{manageDevice:o}=await import('./deviceManagement-SUMBRXXC.js'),c=await o({source:t,currentDeviceId:i,action:r,targetDeviceId:n,exceptCurrent:e,key:()=>this.key(),post:d=>this.post("/v2/devices/manage",d),isStale:C});return a&&this.record(a),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 n=b$1(t.token),e=String(n.jti??""),o=await(await this.key()).proof((c,d)=>["openrtc:v2:room-membership",e,r,i,c,d].join(":"));await this.post("/v2/rooms/memberships",{action:r,roomId:i,deviceCertificate:t.token,deviceProof:o}),this.record(r==="join"?"room.join":"room.leave");}grantProvider(t,i={}){let r=null,n=t;return async e=>{if(r)return r;let a=(async()=>{let o=false;n.expiresAtMs<=Date.now()+5*6e4&&n.renew&&(n=await n.renew(),o=true);let c=e.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),e.refreshGrant&&this.before("coordination.credential.refresh");let d=async l=>{let p=b$1(l.token),h=String(p.jti??""),y=await(await this.key()).proof((w,E)=>["openrtc:v2:gateway-grant",h,e.avenue.kind,e.avenue.id,e.runtimeInstanceId,w,E].join(":"));return this.post("/v2/gateway/grants",{credentialType:l.type,credential:l.token,avenue:e.avenue,runtimeInstanceId:e.runtimeInstanceId,ticketFingerprint:e.ticketFingerprint,deviceProof:y,...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},...i.maxPeers?{maxPeers:i.maxPeers}:{},...i.features?{features:i.features}:{},...l.type==="device-certificate"&&i.deviceProfile?{deviceProfile:i.deviceProfile}:{}})},u;try{u=await d(n);}catch(l){if(!C(l))throw l;let p=await n.recoverRejectedCertificate?.();if(!p)throw l;n=p,o=true,u=await d(n);}return this.record(c),e.refreshGrant&&this.record("coordination.credential.refresh"),o&&await i.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),u})();r=a;try{return await a}finally{r===a&&(r=null);}}}turnProvider(t){let i=S("relay"),r=null,n=null;return async()=>{if(r&&r.expiresAtMs>Date.now()+5*6e4)return r;if(n)return n;let e=(async()=>{let a=t(),o=b$1(a.token),c=String(o.jti??""),u=await(await this.key()).proof((p,h)=>["openrtc:v2:relay-turn",c,i,p,h].join(":")),l=await this.post("/v2/relay/turn",{credentialType:a.type,credential:a.token,sessionId:i,deviceProof:u});return r=l,l})();n=e;try{return await e}finally{n===e&&(n=null);}}}};
2
+ export{A as a};
@@ -1 +1 @@
1
- import {v}from'./chunk-OUFHVLDQ.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 stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}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 listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}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 resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(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)}forceReconnect(){this.backend.forceReconnect();}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 updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let n=this.backend;if(typeof n.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return n.startNativeSession(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 startPresence(e,n,t,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(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 getTicketWithToken(e,n){let t=this.backend;return typeof t.getTicketWithToken!="function"?null:t.getTicketWithToken(e,n)}async registerSessionToken(e,n,t,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,n,t,i);}async revokeTokens(e){let n=this.backend;return typeof n.revokeTokens!="function"?[]:n.revokeTokens(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 isCurrentTransport(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 openPeerBiRaw(e,n){let t=this.backend;return typeof t.openPeerBiRaw=="function"?t.openPeerBiRaw(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 excludeAutoConnect(e,n){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,n)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(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)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():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};
1
+ import {v}from'./chunk-Z2IS6NH2.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 stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}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 listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}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 resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(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)}forceReconnect(){this.backend.forceReconnect();}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 updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let n=this.backend;if(typeof n.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return n.startNativeSession(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 startPresence(e,n,t,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(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 getTicketWithToken(e,n){let t=this.backend;return typeof t.getTicketWithToken!="function"?null:t.getTicketWithToken(e,n)}async registerSessionToken(e,n,t,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,n,t,i);}async revokeTokens(e){let n=this.backend;return typeof n.revokeTokens!="function"?[]:n.revokeTokens(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 isCurrentTransport(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 openPeerBiRaw(e,n){let t=this.backend;return typeof t.openPeerBiRaw=="function"?t.openPeerBiRaw(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 excludeAutoConnect(e,n){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,n)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(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)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():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 @@
1
+ import {a,b as b$1}from'./chunk-ZA44REGI.js';import {a as a$1}from'./chunk-DUY34MGT.js';import {c}from'./chunk-HEAJ7ZUR.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 b=new WeakMap;function B(o){let e=b.get(o);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function K(o){let e=o?.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 f(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var N=/^[A-Za-z0-9_.:@-]{1,160}$/,$=/^[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 j(o){let e=typeof o=="string"?o.trim():"";if(!N.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return $.test(t)?t:e}function W(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,j(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function U(o){let e=typeof o=="string"?o.trim():"";if(!N.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function k(o){let e=b$1(o.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 D=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,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});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 i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},R=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 i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let s={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(s),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let s=this.options?.warnAtSessionCreditsUsd;!this.warned&&s!==void 0&&this.total>=s&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:s,kind:"warning"}));}},G=32,q=4096;function _(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}function P(o,e,t,i){let n=JSON.stringify({__openrtc:2,kind:o,name:e,value:t,...i?{gossip:i}:{}});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function z(o){if(!o||typeof o!="object"||o instanceof Uint8Array)return null;let e=o,t=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;if(!t?.gossip)return t;let{gossip:i}=t;return typeof i.id=="string"&&i.id.length>0&&i.id.length<=384&&typeof i.originPeerId=="string"&&i.originPeerId.length>0&&i.originPeerId.length<=256&&(i.targetPeerId===void 0||typeof i.targetPeerId=="string"&&i.targetPeerId.length>0&&i.targetPeerId.length<=256)&&Number.isSafeInteger(i.hops)&&i.hops>=0&&i.hops<=G?t:null}var T=class{constructor(e,t=false){this.client=e;this.gossipFanout=t;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.seenGossipMessages=new Set;this.seenGossipOrder=[];this.stopMessage=e.onMessage((i,n)=>this.receive(i,n)),this.stopConnection=e.onConnection(i=>this.add(i)),this.stopDisconnection=e.onDisconnection(i=>this.remove(i)),e.getConnections().forEach(i=>this.add(i));}state(e){if(this.gossipFanout)throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=_(e);return {set:i=>{let n=P("state",t,i);this.localState.set(t,n);for(let{raw:s}of this.connections.values())this.sendState(s,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let s=(r,a)=>i({peerId:r,value:a});n.add(s);for(let[r,a]of this.remoteState)a.has(t)&&i({peerId:r,value:a.get(t)});return ()=>n?.delete(s)}}}channel(e){let t=_(e),i=n=>P("channel",t,n);return {send:async n=>{let s=i(n);if(!this.gossipFanout){await Promise.all([...this.connections.values()].map(({raw:r})=>r.send(s)));return}await this.sendGossip("channel",t,n);},sendTo:async(n,s)=>{let r=[...this.connections.values()].find(a=>a.view.peerId===n);if(r){await r.raw.send(i(s));return}if(!this.gossipFanout)throw new Error(`[OpenRTC] Peer '${n}' is not connected.`);await this.sendGossip("channel",t,s,n);},onMessage:n=>{let s=this.channelListeners.get(t);s||this.channelListeners.set(t,s=new Set);let r=(a,c)=>n({peerId:a,message:c});return s.add(r),()=>s?.delete(r)}}}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(),this.seenGossipMessages.clear(),this.seenGossipOrder.splice(0,this.seenGossipOrder.length);}add(e){if(this.connections.has(e.id))return;let t=e.remoteNodeId||e.id,i={id:e.id,peerId:t,send:n=>e.send(n),onMessage:n=>{let s=this.rawListeners.get(e.id);s||this.rawListeners.set(e.id,s=new Set);let r=n;return s.add(r),()=>s?.delete(r)},onClose:n=>{let s=this.closeListeners.get(e.id);return s||this.closeListeners.set(e.id,s=new Set),s.add(n),()=>s?.delete(n)}};this.connections.set(e.id,{raw:e,view:i});for(let n of this.connectionListeners)n(i);for(let[n,s]of this.localState)this.sendState(e,n,s);}remove(e){let t=this.connections.get(e.id);if(!t)return;this.connections.delete(e.id);let i=this.stateSenders.get(e);if(i){for(let s of i.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 n=this.remoteState.get(t.view.peerId);if(n){for(let s of n.keys())for(let r of this.stateListeners.get(s)??[])r(t.view.peerId,null);this.remoteState.delete(t.view.peerId);}}receive(e,t){this.add(e);let i=z(t);if(!i){for(let r of this.rawListeners.get(e.id)??[])r(t);return}if(i.gossip){if(!this.rememberGossipMessage(i.gossip.id))return;let r=!i.gossip.targetPeerId||i.gossip.targetPeerId===e.localNodeId;if(i.gossip.hops<G){let a=P(i.kind,i.name,i.value,{...i.gossip,hops:i.gossip.hops+1});Promise.allSettled([...this.connections.values()].filter(({raw:c})=>c.id!==e.id).map(({raw:c})=>c.send(a)));}if(!r)return}let n=i.gossip?.originPeerId??this.connections.get(e.id)?.view.peerId??e.remoteNodeId??e.id;if(i.kind==="channel"){for(let r of this.channelListeners.get(i.name)??[])r(n,i.value);return}let s=this.remoteState.get(n);s||this.remoteState.set(n,s=new Map),s.set(i.name,i.value);for(let r of this.stateListeners.get(i.name)??[])r(n,i.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let s=n.get(t);s||(s=new a$1(r=>e.send(r)),n.set(t,s)),s.send(i).catch(()=>{});}async sendGossip(e,t,i,n){let s=[...this.connections.values()];if(s.length===0)return;let r=s[0].raw.localNodeId,a=`${r}:${crypto.randomUUID()}`;this.rememberGossipMessage(a);let c=P(e,t,i,{id:a,originPeerId:r,...n?{targetPeerId:n}:{},hops:0});await Promise.all(s.map(({raw:d})=>d.send(c)));}rememberGossipMessage(e){if(this.seenGossipMessages.has(e))return false;if(this.seenGossipMessages.add(e),this.seenGossipOrder.push(e),this.seenGossipOrder.length>q){let t=this.seenGossipOrder.shift();t&&this.seenGossipMessages.delete(t);}return true}},w=class{constructor(e,t,i,n,s=false){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.gossipFanout=s;this.closed=false;b.set(this,i);}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{b.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new T(this.client,this.gossipFanout))}},g=class extends w{constructor(t,i,n,s){super("devices",t,i,n);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(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let r=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,d=i.devices.watchWithStatus,h=v=>(this.roster.reconcileLiveSnapshot(v),v),l=async()=>this.roster.mergeDevices(h(await r())),p=async()=>this.roster.mergeStatus(await a()),u=v=>c(I=>v(this.roster.mergeDevices(h(I)))),y=v=>d(I=>v(this.roster.mergeStatus(I))),m=Object.create(i);Object.defineProperties(m,{listDevices:{value:l,enumerable:false},listDeviceStatus:{value:p,enumerable:false},watchDevices:{value:u,enumerable:false},watchDeviceStatus:{value:y,enumerable:false},devices:{value:{...i.devices,list:l,listWithStatus:p,watch:u,watchWithStatus:y},enumerable:true}}),b.set(this,m),this.stopRosterSync=c(h);}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();}},A=class extends w{constructor(t,i,n,s){super("space",t,i,n);this.delivery=s;this.kind="space";this.leave=()=>this.close();}},S=class extends w{constructor(t,i,n,s,r,a=false){super("room",t,i,n,a);this.membership=s;this.onLeave=r;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},E=class extends w{constructor(t,i,n,s){super("ticket",t,i,n);this.token=s;this.kind="ticket";}},M=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new D;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 i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof g&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=U(e),s=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,s,n);for(let r of this.handles)r instanceof g&&r.removeEnrolledDevice(n);n===s&&this.retireAuthCapabilities(i);},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 i=await this.deviceId();for(let n of this.handles)n instanceof g&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${f(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let i=t.access??"capability";return this.activateOnce(`room:${f(e)}`,JSON.stringify({access:i,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),i==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${f(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,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=K(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new R(e.usage);}makeControlPlane(e){return Promise.all([import('./controlPlane-KVFZ7BR5.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a,i,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))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-Y35WSEQQ.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-Y35WSEQQ.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let s=this.activations.get(e);if(s){if(s.fingerprint!==t||s.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return s.promise}let r={fingerprint:t,auth:i},a=n().then(c=>(r.handle=c,c)).catch(c=>{throw this.activations.get(e)===r&&this.activations.delete(e),c});return r.promise=a,this.activations.set(e,r),a}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):W(this.appTag);return U(e)}runtimeOptions(e){let t=this.options.transports,i=e.relay&&t?.relay!==false,n=t?.privacy==="relay-only";if(n&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let s=n?c(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,nativeStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationGateway:{endpoint:(this.internals.endpoints??a).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:e.turnProvider,transports:{relay:i,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:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:s},transportPriority:s}}async activate(e){let t=e.controlPlane??await this.controlPlane(),i=e.source.relay&&this.options.transports?.relay!==false,n={relay:i,moq:i&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},s=e.source,r=null,a=()=>({userId:e.principalId,token:s.token,tokenProvider:async()=>s.token,expiresAtMs:s.expiresAtMs}),c=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=>{s={...s,...l},await r?.setAuth(a());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:e.kind==="room"&&e.advancedFanout===true,relay:e.source.relay,turnProvider:i?t.turnProvider(()=>s):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform}),[d,{wrapAssembly:h}]=await Promise.all([this.internals.runtimeFactory(c),import('./coreClient.js')]);r=h(d,this.internals.platform==="native"?"native":"web"),await r.setAuth(a()),this.channels.attach(r,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await r.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(r),await r.advanced.runtime.shutdown().catch(()=>{}),l}return this.usage.record("coordination.connection.open"),r}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 i=await this.deviceId(),{resolveDeviceProfile:n}=await import('./deviceProfile-CR2C7OYR.js'),s=n(e.profile,this.internals.platform==="native"?"native":"web"),r=await this.controlPlane(),a=await r.deviceCertificate(t,i,void 0,s),c=await this.activate({kind:"devices",id:a.principalId,source:a.source,principalId:a.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:s.name,devicePlatform:s.platform,deviceMetadata:s.metadata}),d;try{d=await r.listEnrolledDevices(t,i);}catch(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}let{AuthenticatedDeviceRoster:h}=await import('./deviceRoster-EUF6BBF5.js'),l;return l=new g(a.principalId,c,()=>{this.channels.detach(c),this.onClosed(l);},new h(d)),this.handles.add(l),l}async joinSpace(e,t={}){this.assertOpen();let i=f(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),s=await n.capability("space",i,t.maxPeers,t.advancedFanout),r=String(b$1(s.token).principalId),a=await this.activate({kind:"space",id:i,source:s,principalId:r,deviceId:k(s),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new A(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async joinRoom(e,t={}){this.assertOpen();let i=f(e),n=t.membership??"ephemeral",s=t.access??"capability";if(n==="durable"&&s!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(s==="authenticated"){let h=t.auth??this.options.auth;if(!h)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let l=await this.deviceId(),p=await this.controlPlane(),u=await p.deviceCertificate(h,l,{kind:"room",id:i});n==="durable"&&await p.durableRoomMembership(u.source,i,"join");let y;try{y=await this.activate({kind:"room",id:i,source:u.source,principalId:u.principalId,deviceId:l,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(v){throw n==="durable"&&await p.durableRoomMembership(u.source,i,"leave").catch(()=>{}),v}let m;return m=new S(i,y,()=>{this.channels.detach(y),this.onClosed(m);},n,n==="durable"?async()=>{await p.durableRoomMembership(u.source,i,"leave");}:void 0,t.advancedFanout===true),this.handles.add(m),m}let r=await(await this.controlPlane()).capability("room",i,t.maxPeers,t.advancedFanout),a=String(b$1(r.token).principalId),c=await this.activate({kind:"room",id:i,source:r,principalId:a,deviceId:k(r),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),d;return d=new S(i,c,()=>{this.channels.detach(c),this.onClosed(d);},"ephemeral",void 0,t.advancedFanout===true),this.handles.add(d),d}async issueTicket(e,t={}){this.assertOpen();let i=f(e),n=await(await this.controlPlane()).capability("ticket",i,t.maxPeers,t.advancedFanout),s=String(b$1(n.token).principalId),r=await this.activate({kind:"ticket",id:i,source:n,principalId:s,deviceId:k(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),a;return a=new E(i,r,()=>{this.channels.detach(r),this.onClosed(a);},n.token),this.handles.add(a),a}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear();}}}};function Q(o,e){return new M(o,e)}export{B as a,Q as b};
@@ -0,0 +1,2 @@
1
+ import {a as a$1,c as c$1,b}from'./chunk-HEAJ7ZUR.js';import {c}from'./chunk-2SUSPEC4.js';var v=new Set;function p(e,t){v.has(e)||(v.add(e),console.warn(t));}function R(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function F(e,t){let r=`${e}:${t}`,o=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s)).map(T=>T.toString(16).padStart(2,"0")).join("")}function u(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return R(t)||p(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function a(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||p("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function j(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(p("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),i)}function P(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function K(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?P(e.storagePrefix):"";return t||P(u(e))||"default"}var x={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:250,maxPersonalDevices:25e3},H=x;var M=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],f={iceServers:M},G={};var A=/^[A-Za-z0-9._-]+$/,w="[redacted]";function I(e){let t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(t.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(t.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(t.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return t}function m(e){return I(e.trim()).toString()}function W(e,t){let r=I(e.trim());if(t!==void 0){let n=t.trim();if(!n)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(n).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!A.test(n))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");r.searchParams.append("jwt",n);}return r.toString()}function z(e){try{let t=new URL(e);return t.search="",t.hash="",t.toString()}catch{return "invalid-moq-relay-url"}}function Y(e,t){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e),n=t?.trim();return n?r.split(n).join(w):r}var C=[...c];function g(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function S(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function O(e){return {...e}}function D(e){return {...e}}function k(e){if(e)return {iroh:typeof e.iroh=="object"?D(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?S(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?O(e.moq):e.moq,privacy:e.privacy,optimizeFor:e.optimizeFor,priority:a$1(e.priority)}}function N(e){if(e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),!!e.transports){if(e.transports.webrtc===true?e.transports.webrtc=S(f):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(e.transports.moq===false)e.transports.moq=void 0;else if(e.transports.moq&&typeof e.transports.moq=="object"){let t=e.transports.moq,r=t.relayUrl?.trim(),n=t.accessToken;if(n!==void 0&&!n.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");e.transports.moq={...t,...r?{relayUrl:m(r)}:{},...n!==void 0?{accessToken:n.trim()}:{}};}if(e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0),e.transports.privacy==="relay-only"){let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:b(r.iceServers)??[],iceTransportPolicy:"relay"}),e.transports.priority=c$1(e.transports.priority,!!e.transports.webrtc);}}}function E(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},e.transports.privacy="relay-only",e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:b(r.iceServers)??[],iceTransportPolicy:"relay"});let n=e.transports.moq;if(n&&typeof n=="object"){let o=n.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");e.transports.moq={...n,relayUrl:m(o)};}}function te(e){let t=g(e),r=u(t),n=a(t),o={strictMode:false,disableIrohFallback:false,transportPriority:[...C],...t,authMode:n,transports:k(t.transports)};N(o),E(o),o.transportPriority=a$1(t.transportPriority??o.transports?.priority)??[...C],(o.strictMode||o.transports?.privacy==="relay-only")&&(o.transportPriority=c$1(t.transportPriority??o.transports?.priority,!!o.transports?.webrtc));let s=h(o),b=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:r,authMode:n,configuredPersistenceMode:s,options:o,roomCreationMode:b}}function h(e){let t=e.transports?.iroh;return e.endpointIdPersistence??e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"ephemeral"}function re(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:a(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:a(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:h(e)}}function ne(e,t){t&&(e.transports={...e.transports||{},...t});}var i="pluto-rtc-prod",U="https://api.openrtc.app",_="https://gateway.openrtc.app";function ae(e){let t=g(e),n=(typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():void 0)??i,o=n===i;return {...t,projectId:n,coordinationGateway:t.coordinationGateway??(o?{endpoint:_,controlPlaneEndpoint:U,environment:"production"}:void 0)}}
2
+ export{ae as a,F as b,u as c,a as d,j as e,K as f,H as g,M as h,f as i,G as j,W as k,z as l,Y as m,g as n,te as o,re as p,ne as q};