openrtc 2.8.10 → 2.9.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 (30) hide show
  1. package/dist/BrowserManagedBroadcastHost-FTKYCKLF.js +1 -0
  2. package/dist/{NativeManagedBroadcastHost-WCQ6TPUU.js → NativeManagedBroadcastHost-6A2QP3A7.js} +1 -1
  3. package/dist/{WasmBridge-BPNNHEFW.js → WasmBridge-QUACJ7JY.js} +1 -1
  4. package/dist/{chunk-GSSORRBR.js → chunk-6CHYSTXL.js} +1 -1
  5. package/dist/{chunk-LLZT3MR6.js → chunk-FKAQDDUM.js} +1 -1
  6. package/dist/{chunk-YZ5LN36Y.js → chunk-Q7ZKAI5S.js} +1 -1
  7. package/dist/{chunk-RE2LBIIA.js → chunk-ZFSJ2LEF.js} +1 -1
  8. package/dist/{deviceHandle-EEOA7VQW.js → deviceHandle-R7WWNAG7.js} +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/native.js +1 -1
  11. package/dist/node.js +2 -2
  12. package/dist/{openrtc-H2DETG65.js → openrtc-K6B3ZZIG.js} +1 -1
  13. package/dist/openrtc_bg.wasm +0 -0
  14. package/dist/{room-YU3N75H3.js → room-QWTKWEAZ.js} +1 -1
  15. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  16. package/dist/runtime/factories.js +1 -1
  17. package/dist/runtime/index.js +1 -1
  18. package/dist/server.js +1 -1
  19. package/dist/service-node.js +1 -1
  20. package/dist/testing/native.js +1 -1
  21. package/dist/testing.d.ts +20 -1
  22. package/dist/testing.js +1 -1
  23. package/native/darwin-arm64/openrtc-node-host +0 -0
  24. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  25. package/native/darwin-x64/openrtc-node-host +0 -0
  26. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  27. package/native/linux-x64/openrtc-node-host +0 -0
  28. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  29. package/package.json +1 -1
  30. package/dist/BrowserManagedBroadcastHost-ARCP5MGJ.js +0 -1
@@ -0,0 +1 @@
1
+ import {b,a as a$2}from'./chunk-BGWJHPBC.js';import {a}from'./chunk-AYHD4X2R.js';import {b as b$1,a as a$1}from'./chunk-FKAQDDUM.js';import'./chunk-JPBW67B3.js';var g=class{constructor(e){this.deps=e;this.active=null;this.opening=null;this.commands=Promise.resolve();}apply(e){let t=this.commands.then(()=>this.applyOrdered(e));return this.commands=t.catch(()=>{}),t}dispose(){this.opening=null,this.retire();}async applyOrdered(e){if(e.type==="open"){await this.open(e);return}if(this.isCurrent(e)){if(e.type==="publish"){if(!this.active||!["owner","publisher","processor"].includes(this.active.role))throw new Error("broadcast role cannot publish");let t=await this.duplex(e.sourceSlot,true),r=this.active.writers.get(e.sourceSlot);r||(r=t.writable.getWriter(),this.active.writers.set(e.sourceSlot,r)),await b(r.write(e.object),6e4,"broadcast object write");return}if(e.type==="subscribe"){if(!this.active||!["owner","subscriber","processor"].includes(this.active.role))throw new Error("broadcast role cannot subscribe");await Promise.all(e.sourceSlots.map(async t=>{let r=await this.duplex(t,false),a=this.active;this.readObjects(a,t,r.readable).catch(async()=>{if(!(this.active!==a||a.closed))try{await this.deps.observe({type:"failed",broadcastGeneration:a.broadcastGeneration,grantGeneration:a.grantGeneration,retryable:!1,code:"relay-object-rejected"});}catch{}});}));return}this.retire(),await this.deps.observe({type:"closed",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,code:e.reason});}}async open(e){this.retire(),this.opening=e;try{if(e.relay.kind==="sfu")throw new Error("SFU relay passed to MoQ adapter");let t=this.deps.openSession?await this.deps.openSession(e.relay.relayUrl,e.relay.token):await E(e.relay.relayUrl,e.relay.token,e.relay.serverCertificateHash),r={broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,role:e.role,namespace:e.relay.namespace,controlNamespace:`${e.relay.namespace}/control/${crypto.randomUUID()}`,session:t,duplexes:new Map,writers:new Map,closed:!1};if(this.active=r,t.onClose(()=>{this.active!==r||r.closed||this.deps.observe({type:"failed",broadcastGeneration:r.broadcastGeneration,grantGeneration:r.grantGeneration,retryable:!0,code:"relay-session-closed"});}),await b(t.init(),1e4,"broadcast MoQ Draft 14 setup"),await b(t.waitForSetup(),5e3,"broadcast MoQ Draft 14 setup"),this.active!==r||this.opening!==e)return;await this.deps.observe({type:"opened",broadcastGeneration:r.broadcastGeneration,grantGeneration:r.grantGeneration});}catch{this.opening===e&&(this.retire(),await this.deps.observe({type:"failed",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,retryable:true,code:"relay-open-failed"}));}finally{this.opening===e&&(this.opening=null);}}async duplex(e,t){let r=this.active;if(!r)throw new Error("broadcast session is unavailable");let a=`${t?"pub":"sub"}:${e}`,o=r.duplexes.get(a);if(o)return o;let n=`${r.namespace}/source/${e}`,c=`${r.controlNamespace}/${e}`,i=await b(r.session.openObjectStreamDuplex(t?n:c,t?c:n,"openrtc-broadcast-1"),12e3,"broadcast MoQ Draft 14 object stream");if(this.active!==r)throw i.close(),new Error("broadcast generation retired during setup");return r.duplexes.set(a,i),i}async readObjects(e,t,r){let a=r.getReader();try{for(;this.active===e;){let o=await a.read();if(o.done)break;await this.deps.onObject({broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,sourceSlot:t,object:o.value})&&await this.deps.observe({type:"usage",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,deliveredBytes:o.value.byteLength});}}finally{a.releaseLock();}}isCurrent(e){return this.matches(e)&&this.active?.closed===false}matches(e){return this.active?.broadcastGeneration===e.broadcastGeneration&&this.active.grantGeneration===e.grantGeneration}retire(){let e=this.active;if(this.active=null,!!e){e.closed=true;for(let t of e.writers.values())try{t.releaseLock();}catch{}for(let t of e.duplexes.values())try{t.close();}catch{}e.session.close();}}};async function E(b$1,e,t){let r=new URL(b$1);if(r.protocol!=="https:"||r.search||r.hash||!/^[A-Za-z0-9._-]{16,16384}$/.test(e))throw new Error("broadcast relay access is invalid");let a=new URL(r.toString());if(a.pathname=`${a.pathname.replace(/\/+$/,"")}/${encodeURIComponent(e)}`,t&&t.byteLength!==32)throw new Error("broadcast relay certificate hash is invalid");let o=new WebTransport(a.toString(),t?{serverCertificateHashes:[{algorithm:"sha-256",value:t}]}:void 0);return await b(o.ready,15e3,"broadcast relay connection"),new a$2(o,r)}var y=class{constructor(e){this.deps=e;this.active=null;this.commands=Promise.resolve();}apply(e){let t=this.commands.then(()=>this.applyOrdered(e));return this.commands=t.catch(()=>{}),t}dispose(){this.retire();}async call(e,t,r={}){let a=await fetch(`${e.controlUrl}/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant:e.grant,bindingPublicJwk:e.bindingPublicJwk,publicationVerifyingKey:e.publicationVerifyingKey,...r})}),o=await a.json();if(!a.ok)throw new Error(o.error||`SFU ${t} failed (${a.status})`);return o}async applyOrdered(e){if(e.type==="open"){await this.open(e);return}let t=this.active;if(!(!t||t.closed||t.broadcastGeneration!==e.broadcastGeneration||t.grantGeneration!==e.grantGeneration))if(e.type==="publish"){if(!["owner","publisher","processor"].includes(t.role))throw new Error("SFU role cannot publish");let r=await this.channel(t,e.sourceSlot);await this.send(r,t,e.object);}else if(e.type==="subscribe"){if(!["owner","subscriber","processor"].includes(t.role))throw new Error("SFU role cannot subscribe");for(let r of e.sourceSlots)await this.channel(t,r);}else await this.retire(),await this.deps.observe({type:"closed",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,code:e.reason});}async open(e){if(await this.retire(),e.relay.kind!=="sfu")throw new Error("MoQ relay passed to SFU adapter");let t=null,r=null;try{let a=e.relay;if({sessionId:r}=await this.call(a,"session"),!r)throw new Error("SFU session is missing");t=new RTCPeerConnection,t.addEventListener("datachannel",c=>{c.channel.label!=="server-events"&&c.channel.close();});let o=await this.call(a,"establish",{sessionId:r});await t.setRemoteDescription(o.sessionDescription),await t.setLocalDescription(await t.createAnswer()),await this.waitIce(t),await this.call(a,"answer",{sessionId:r,sessionDescription:t.localDescription}),await this.waitConnected(t);let n={broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,role:e.role,access:a,sessionId:r,pc:t,channels:new Map,nextObjectId:0,receiving:Promise.resolve(),fragments:new Map,closed:!1};this.active=n,t.addEventListener("connectionstatechange",()=>{this.active!==n||n.closed||["failed","closed","disconnected"].includes(t.connectionState)&&this.deps.observe({type:"failed",broadcastGeneration:n.broadcastGeneration,grantGeneration:n.grantGeneration,retryable:!0,code:"sfu-connection-lost"});}),await this.deps.observe({type:"opened",broadcastGeneration:n.broadcastGeneration,grantGeneration:n.grantGeneration});}catch{t?.close(),r&&await this.call(e.relay,"close",{sessionId:r}).catch(()=>{}),await this.deps.observe({type:"failed",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,retryable:true,code:"sfu-open-failed"});}}async channel(e,t){let r=e.channels.get(t);if(r)return r;let{channelId:a}=await this.call(e.access,"channel",{sessionId:e.sessionId,sourceSlot:t});if(!Number.isInteger(a))throw new Error("SFU channel ID is invalid");let o=e.pc.createDataChannel(`openrtc-${t}`,{negotiated:true,id:a});return o.binaryType="arraybuffer",["owner","subscriber","processor"].includes(e.role)&&o.addEventListener("message",n=>{this.active!==e||e.closed||!(n.data instanceof ArrayBuffer)||(e.receiving=e.receiving.then(()=>this.receive(e,t,new Uint8Array(n.data))).catch(()=>{this.deps.observe({type:"failed",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,retryable:false,code:"sfu-object-rejected"});}));}),e.channels.set(t,o),await new Promise((n,c)=>{if(o.readyState==="open")return n();let i=setTimeout(()=>c(new Error("SFU channel timed out")),15e3);o.addEventListener("open",()=>{clearTimeout(i),n();},{once:true}),o.addEventListener("error",()=>{clearTimeout(i),c(new Error("SFU channel failed"));},{once:true});}),o}async send(e,t,r){let a=r instanceof Uint8Array?r:Uint8Array.from(r);if(!a.length||a.length>1e6)throw new Error("SFU object exceeds bound");let o=Math.ceil(a.length/8e3),n=t.nextObjectId++>>>0;for(let c=0;c<o;c++){let i=a.subarray(c*8e3,(c+1)*8e3),s=new Uint8Array(12+i.length),d=new DataView(s.buffer);d.setUint32(0,1330795587),d.setUint32(4,n),d.setUint16(8,c),d.setUint16(10,o),s.set(i,12);let p=Date.now()+1e4;for(;e.bufferedAmount>128e3;){if(Date.now()>p||e.readyState!=="open")throw new Error("SFU send stalled");await new Promise(u=>setTimeout(u,10));}e.send(s);}}async receive(e,t,r){if(r.length<=12||r.length>8012)throw new Error("SFU fragment bound");let a=new DataView(r.buffer,r.byteOffset,r.byteLength);if(a.getUint32(0)!==1330795587)throw new Error("SFU fragment magic");let o=a.getUint32(4),n=a.getUint16(8),c=a.getUint16(10);if(!c||c>Math.ceil(1e6/8e3)||n>=c)throw new Error("SFU fragment count");let i=e.fragments.get(t);if(n===0&&(i={id:o,count:c,parts:[],bytes:0,started:Date.now()},e.fragments.set(t,i)),!i||i.id!==o||i.count!==c||i.parts.length!==n||Date.now()-i.started>5e3){e.fragments.delete(t);return}let s=r.slice(12);if(i.bytes+=s.length,i.bytes>1e6)throw new Error("SFU object bound");if(i.parts.push(s),i.parts.length!==c)return;e.fragments.delete(t);let d=new Uint8Array(i.bytes),p=0;for(let m of i.parts)d.set(m,p),p+=m.length;await this.deps.onObject({broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,sourceSlot:t,object:d})&&await this.deps.observe({type:"usage",broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration,deliveredBytes:d.length});}async retire(){let e=this.active;if(this.active=null,!!e){e.closed=true;for(let t of e.channels.values())t.close();e.pc.close(),await this.call(e.access,"close",{sessionId:e.sessionId}).catch(()=>{});}}async waitIce(e){e.iceGatheringState!=="complete"&&await new Promise((t,r)=>{let a=setTimeout(()=>r(new Error("SFU ICE gathering timed out")),15e3);e.addEventListener("icegatheringstatechange",()=>{e.iceGatheringState==="complete"&&(clearTimeout(a),t());});});}async waitConnected(e){e.connectionState!=="connected"&&await new Promise((t,r)=>{let a=setTimeout(()=>r(new Error("SFU connection timed out")),15e3);e.addEventListener("connectionstatechange",()=>{e.connectionState==="connected"&&(clearTimeout(a),t()),e.connectionState==="failed"&&(clearTimeout(a),r(new Error("SFU connection failed")));});});}};var f=class{constructor(e,t,r,a,o){this.wasm=e;this.handleId=t;this.drain=o;this.incoming=null;this.incomingWriters=new Map;this.sources=new Map;this.closed=false;let n=a[0]??"",c={beginOpenRtcMediaPublication:async s=>{let d=this.wasm.__beginOpenRtcBroadcastPublication(this.handleId,n,s.publicationId||void 0,s.kind,s.codec,s.clockRate,s.codedWidth,s.codedHeight,s.channels);return await this.drain(),{...d,control:new Uint8Array(d.control??[])}},encodeOpenRtcMediaSample:async s=>(this.wasm.__publishOpenRtcBroadcastSample(this.handleId,s.publicationId,s.timestampUs,s.durationUs,s.keyframe,s.discardable,s.payload),await this.drain(),new Uint8Array),pauseOpenRtcMediaPublication:async s=>{this.wasm.__pauseOpenRtcBroadcastPublication(this.handleId,s);},retireOpenRtcMediaPublication:async s=>{this.wasm.__retireOpenRtcBroadcastPublication(this.handleId,s);},retireOpenRtcMediaReceiver:async(s,d)=>{this.wasm.__retireOpenRtcMediaReceiver(s,d);},decodeOpenRtcMediaControl:async s=>this.wasm.__decodeOpenRtcMediaControl(s),decodeOpenRtcMediaChunk:async s=>{let d=this.wasm.__decodeOpenRtcMediaChunk(s);return {...d,payload:new Uint8Array(d.payload)}}},i={createBidirectionalStream:async()=>({protocol:"openrtc-media/1",readable:new ReadableStream({start(s){s.close();}}),writable:new WritableStream})};if(this.media=new b$1(i,c,(s,d)=>(this.incoming=d,()=>{this.incoming=null;})),["owner","publisher","processor"].includes(r)&&!n)throw new Error("[OpenRTC] Broadcast publisher grant has no source slot.")}addTrack(e,t){return this.media.addTrack(e,t)}removeTrack(e){return this.media.removeTrack(e)}onTrack(e){return this.media.onTrack(t=>e({...t,source:{id:this.sources.get(t.receiver.id)??"unknown"}}))}senders(){return this.media.senders()}receivers(){return this.media.receivers()}async accept(e,t){if(this.closed)return false;let r=this.wasm.__acceptOpenRtcBroadcastObject(this.handleId,e,t);if(!r)return false;let a=r.publicationId;if(this.sources.set(a,r.sourceSlot),r.control){let n=this.incomingWriters.get(a);if(r.controlType==="stop")return n?.generation===r.mediaGeneration&&(this.incomingWriters.delete(a),await n.writer.close().catch(()=>{})),this.sources.delete(a),true;if(r.controlType!=="publish"||n&&n.generation>=r.mediaGeneration)return true;n&&await n.writer.close().catch(()=>{});let c=new TransformStream,i=c.writable.getWriter();return this.incomingWriters.set(a,{generation:r.mediaGeneration,writer:i}),this.incoming?.({peerId:r.sourceSlot,protocol:"openrtc-media/1",readable:c.readable,writable:new WritableStream}),await i.write(a$1(new Uint8Array(r.control))),true}if(!r.media)return true;let o=this.incomingWriters.get(a);return !o||o.generation!==r.mediaGeneration||await o.writer.write(a$1(new Uint8Array(r.media))),true}async close(){this.closed||(this.closed=true,await Promise.all([...this.incomingWriters.values()].map(({writer:e})=>e.close().catch(()=>{}))),this.incomingWriters.clear(),this.sources.clear(),await this.media.close());}};var _=class{constructor(e){this.deps=e;this.wasmPromise=null;this.sessions=new Set;this.publishers=new Set;}async open(e){return this.openResolved(e)}async create(e){let t=e.auth??this.deps.defaultAuth;if(!t||!this.deps.manage||!this.deps.deviceId)throw new Error("Managed broadcast creation requires authenticated control-plane access.");let r=await this.deps.manage({action:"create",deviceId:await this.deps.deviceId(),auth:t,create:e});if(!r)throw new Error("Managed broadcast creation returned no grant.");return r}async renew(e,t){let r=await this.manageGrant("renew",e,t);if(!r)throw new Error("Managed broadcast renewal returned no grant.");return r}async invite(e,t,r){let a=await this.manage("invite",r,{grant:e,invitation:t});if(!a)throw new Error("Managed broadcast invitation returned no token.");return a}async accept(e,t){let r=await this.manage("accept",t,{invite:e});if(!r)throw new Error("Managed broadcast invitation acceptance returned no grant.");return r}async revoke(e,t,r){await this.manage("revoke",r,{grant:e,invite:t});}async leave(e,t){await this.manageGrant("leave",e,t);}async closeGrant(e,t){await this.manageGrant("close",e,t);}async preparePublisher(){let e=await this.wasm(),t=a.create(e);this.publishers.add(t);let r=false;return {verificationKey:t.verificationKey.slice(),open:a=>{if(r)throw new Error("broadcast publisher signer is closed");return this.openResolved(a,t)},close:async()=>{r||(r=true,t.close(),this.publishers.delete(t));}}}async close(){await Promise.all([...this.sessions].map(e=>e.close()));for(let e of this.publishers)e.close();this.publishers.clear();}wasm(){return this.wasmPromise??(this.wasmPromise=this.deps.loadWasm())}async manageGrant(e,t,r){return this.manage(e,r,{grant:t})}async manage(e,t,r){let a=t??this.deps.defaultAuth;if(!a||!this.deps.manage||!this.deps.deviceId)throw new Error(`Managed broadcast ${e} requires authenticated control-plane access.`);return this.deps.manage({action:e,deviceId:await this.deps.deviceId(),auth:a,...r})}async openResolved(e,t){let[r,a]=await Promise.all([this.wasm(),this.deps.resolve(e,t?.verificationKey)]),o=Date.now(),n;if(t)n=await t.open(a,o);else {let l=r.__prepareOpenRtcBroadcastGrant(a.token,a.issuerPublicKey,o),B=await a.signBindingChallenge(l.signingBytes);n=r.__openOpenRtcBroadcast(a.token,a.issuerPublicKey,l.handle,B,void 0,o);}let c={...a.relay},i=n.state,s=false,d=false,p=false,u=null,m={openSession:this.deps.openSession,observe:async l=>{if(!s){l.type==="opened"&&(i="live"),l.type==="failed"&&(i="retrying"),l.type==="closed"&&(i="closed");try{r.__observeOpenRtcBroadcastAdapter(n.handleId,l);}finally{await v();}}},onObject:async l=>s||!u?false:u.accept(l.sourceSlot,l.object)},S=c.kind==="sfu"?new y(m):new g(m),v=async()=>{if(!s){if(d){p=true;return}d=true;try{do{p=!1;let l=r.__takeOpenRtcBroadcastActions(n.handleId,32);for(let B of l)await S.apply(this.adapterAction(B,c));l.length===32&&(p=!0);}while(p)}finally{d=false;}}};u=new f(r,n.handleId,n.role,n.sourceSlots??[],v);let w={id:n.id,role:n.role,get state(){return i},media:u,getStats:async()=>({...r.__getOpenRtcBroadcastStats(n.handleId)}),close:async()=>{s||(s=true,S.dispose(),await u?.close(),r.__closeOpenRtcBroadcast(n.handleId),this.sessions.delete(w));}};this.sessions.add(w);try{return await v(),w}catch(l){throw await w.close(),l}}adapterAction(e,t){let r={broadcastGeneration:e.broadcastGeneration,grantGeneration:e.grantGeneration};if(e.type==="open"&&e.role)return {type:"open",role:e.role,relay:t,...r};if(e.type==="publish"&&e.sourceSlot&&e.object)return {type:"publish",sourceSlot:e.sourceSlot,object:e.object,discardable:e.discardable===true,control:e.control===true,...r};if(e.type==="subscribe"&&e.sourceSlots)return {type:"subscribe",sourceSlots:e.sourceSlots,...r};if(e.type==="close"&&e.reason)return {type:"close",reason:e.reason,...r};throw new Error("Rust returned an invalid broadcast adapter action")}};export{_ as BrowserManagedBroadcastHost};
@@ -1 +1 @@
1
- import {b as b$1,a}from'./chunk-LLZT3MR6.js';import'./chunk-JPBW67B3.js';var p=64,w=50;function l(n,e){if(n instanceof Uint8Array)return n.slice();if(n instanceof ArrayBuffer)return new Uint8Array(n.slice(0));if(Array.isArray(n)&&n.every(r=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(n);throw new Error(`[OpenRTC] ${e} returned invalid binary data.`)}var u=class{constructor(e,r,t,i,o){this.bridge=e;this.handleId=r;this.onFailure=o;this.incoming=null;this.incomingWriters=new Map;this.sources=new Map;this.timer=null;this.closed=false;let s=i[0]??"",c={beginOpenRtcMediaPublication:async a=>{let d=await this.bridge.invoke("begin_openrtc_broadcast_publication",{handleId:this.handleId,sourceSlot:s,publicationId:a.publicationId||null,kind:a.kind,codec:a.codec,clockRate:a.clockRate,codedWidth:a.codedWidth??null,codedHeight:a.codedHeight??null,channels:a.channels??null});return {...d,control:l(d.control??[],"broadcast publication")}},encodeOpenRtcMediaSample:async a=>{if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");return await this.bridge.invokeRaw("publish_openrtc_broadcast_sample",a.payload,{"x-openrtc-broadcast-handle-id":this.handleId,"x-openrtc-publication-id":a.publicationId,"x-openrtc-timestamp-us":String(a.timestampUs),"x-openrtc-duration-us":String(a.durationUs),"x-openrtc-keyframe":String(a.keyframe),"x-openrtc-discardable":String(a.discardable)}),new Uint8Array},pauseOpenRtcMediaPublication:async a=>{await this.bridge.invoke("pause_openrtc_broadcast_publication",{handleId:this.handleId,publicationId:a});},retireOpenRtcMediaPublication:async a=>{await this.bridge.invoke("retire_openrtc_broadcast_publication",{handleId:this.handleId,publicationId:a});},retireOpenRtcMediaReceiver:async(a,d)=>{await this.bridge.invoke("retire_openrtc_broadcast_receiver",{handleId:this.handleId,publicationId:a,mediaGeneration:d});},decodeOpenRtcMediaControl:a=>this.decodeControl(a),decodeOpenRtcMediaChunk:a=>this.decodeChunk(a)},v={createBidirectionalStream:async()=>({protocol:"openrtc-media/1",readable:new ReadableStream({start(a){a.close();}}),writable:new WritableStream})};if(this.media=new b$1(v,c,(a,d)=>(this.incoming=d,()=>{this.incoming=null;})),["owner","publisher","processor"].includes(t)&&!s)throw new Error("[OpenRTC] Broadcast publisher grant has no source slot.");this.scheduleReceive(0);}addTrack(e,r){return this.media.addTrack(e,r)}removeTrack(e){return this.media.removeTrack(e)}onTrack(e){return this.media.onTrack(r=>e({...r,source:{id:this.sources.get(r.receiver.id)??"unknown"}}))}senders(){return this.media.senders()}receivers(){return this.media.receivers()}async close(){this.closed||(this.closed=true,this.timer&&clearTimeout(this.timer),this.timer=null,await Promise.all([...this.incomingWriters.values()].map(({writer:e})=>e.close().catch(()=>{}))),this.incomingWriters.clear(),this.sources.clear(),await this.media.close());}scheduleReceive(e){this.closed||(this.timer=setTimeout(()=>{this.receive();},e));}async receive(){if(!this.closed)try{let e=await this.bridge.invoke("receive_openrtc_broadcast_media",{handleId:this.handleId,max:p});for(let r of e)await this.accept(r);this.scheduleReceive(e.length===p?0:w);}catch(e){this.closed||this.onFailure(e);}}async accept(e){let r=e.publicationId;if(this.sources.set(r,e.sourceSlot),e.control){let i=this.incomingWriters.get(r);if(e.controlType==="stop"){i?.generation===e.mediaGeneration&&(this.incomingWriters.delete(r),await i.writer.close().catch(()=>{})),this.sources.delete(r);return}if(e.controlType!=="publish"||i&&i.generation>=e.mediaGeneration)return;i&&await i.writer.close().catch(()=>{});let o=new TransformStream,s=o.writable.getWriter();this.incomingWriters.set(r,{generation:e.mediaGeneration,writer:s}),this.incoming?.({peerId:e.sourceSlot,protocol:"openrtc-media/1",readable:o.readable,writable:new WritableStream}),await s.write(a(l(e.control,"broadcast control")));return}if(!e.media)return;let t=this.incomingWriters.get(r);!t||t.generation!==e.mediaGeneration||await t.writer.write(a(l(e.media,"broadcast media")));}async decodeControl(e){if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");return this.bridge.invokeRaw("decode_openrtc_media_control",e,{})}async decodeChunk(e){if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");let r=l(await this.bridge.invokeRaw("decode_openrtc_media_chunk",e,{}),"decode_openrtc_media_chunk");if(r.byteLength<4)throw new Error("[OpenRTC] Native media metadata is truncated.");let i=4+new DataView(r.buffer,r.byteOffset,4).getUint32(0,false);if(i>r.byteLength)throw new Error("[OpenRTC] Native media metadata is invalid.");return {...JSON.parse(new TextDecoder().decode(r.subarray(4,i))),payload:r.slice(i)}}},b=class{constructor(e,r){this.bridge=e;this.context=r;this.sessions=new Set;this.publishers=new Set;}open(e){return this.openNative(e)}async create(e){let r=e.auth??this.context.defaultAuth;if(!r)throw new Error("Managed broadcast creation requires authenticated control-plane access.");let t=await this.context.manage({action:"create",deviceId:await this.context.deviceId(),auth:r,create:e});if(!t)throw new Error("Managed broadcast creation returned no grant.");return t}async preparePublisher(){let e=await this.bridge.invoke("prepare_openrtc_broadcast_publisher"),r=l(e.verificationKey,"broadcast publisher");if(!e.handle||r.byteLength!==32)throw e.handle&&await this.bridge.invoke("release_openrtc_broadcast_publisher",{handle:e.handle}).catch(()=>{}),new Error("[OpenRTC] Native broadcast publisher is invalid.");let t=false,i={verificationKey:r,open:o=>{if(t)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.openNative(o,e.handle)},close:async()=>{t||(t=true,this.publishers.delete(i),await this.bridge.invoke("release_openrtc_broadcast_publisher",{handle:e.handle}));}};return this.publishers.add(i),i}renew(e,r){return this.manage("renew",r,{grant:e})}invite(e,r,t){return this.manage("invite",t,{grant:e,invitation:r})}accept(e,r){return this.manage("accept",r,{invite:e})}async revoke(e,r,t){await this.manage("revoke",t,{grant:e,invite:r});}async leave(e,r){await this.manage("leave",r,{grant:e});}async closeGrant(e,r){await this.manage("close",r,{grant:e});}async close(){await Promise.all([...this.sessions].map(e=>e.close())),await Promise.all([...this.publishers].map(e=>e.close()));}async manage(e,r,t){let i=r??this.context.defaultAuth;if(!i)throw new Error(`Managed broadcast ${e} requires authenticated control-plane access.`);return this.context.manage({action:e,deviceId:await this.context.deviceId(),auth:i,...t})}async openNative(e,r){let t=await this.bridge.invoke("open_openrtc_broadcast",{grantToken:e,issuerPublicKey:null,publisherSignerHandle:r??null,nowMs:Date.now()}),i=t.state,o=false,s=new u(this.bridge,t.handleId,t.role,t.sourceSlots??[],()=>{i="failed";}),c={id:t.id,role:t.role,get state(){return i},media:s,getStats:()=>this.bridge.invoke("get_openrtc_broadcast_stats",{handleId:t.handleId}),close:async()=>{o||(o=true,i="closed",await s.close(),await this.bridge.invoke("close_openrtc_broadcast",{handleId:t.handleId}),this.sessions.delete(c));}};return this.sessions.add(c),c}};export{b as NativeManagedBroadcastHost};
1
+ import {b as b$1,a}from'./chunk-FKAQDDUM.js';import'./chunk-JPBW67B3.js';var p=64,w=50;function l(n,e){if(n instanceof Uint8Array)return n.slice();if(n instanceof ArrayBuffer)return new Uint8Array(n.slice(0));if(Array.isArray(n)&&n.every(r=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(n);throw new Error(`[OpenRTC] ${e} returned invalid binary data.`)}var u=class{constructor(e,r,t,i,o){this.bridge=e;this.handleId=r;this.onFailure=o;this.incoming=null;this.incomingWriters=new Map;this.sources=new Map;this.timer=null;this.closed=false;let s=i[0]??"",c={beginOpenRtcMediaPublication:async a=>{let d=await this.bridge.invoke("begin_openrtc_broadcast_publication",{handleId:this.handleId,sourceSlot:s,publicationId:a.publicationId||null,kind:a.kind,codec:a.codec,clockRate:a.clockRate,codedWidth:a.codedWidth??null,codedHeight:a.codedHeight??null,channels:a.channels??null});return {...d,control:l(d.control??[],"broadcast publication")}},encodeOpenRtcMediaSample:async a=>{if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");return await this.bridge.invokeRaw("publish_openrtc_broadcast_sample",a.payload,{"x-openrtc-broadcast-handle-id":this.handleId,"x-openrtc-publication-id":a.publicationId,"x-openrtc-timestamp-us":String(a.timestampUs),"x-openrtc-duration-us":String(a.durationUs),"x-openrtc-keyframe":String(a.keyframe),"x-openrtc-discardable":String(a.discardable)}),new Uint8Array},pauseOpenRtcMediaPublication:async a=>{await this.bridge.invoke("pause_openrtc_broadcast_publication",{handleId:this.handleId,publicationId:a});},retireOpenRtcMediaPublication:async a=>{await this.bridge.invoke("retire_openrtc_broadcast_publication",{handleId:this.handleId,publicationId:a});},retireOpenRtcMediaReceiver:async(a,d)=>{await this.bridge.invoke("retire_openrtc_broadcast_receiver",{handleId:this.handleId,publicationId:a,mediaGeneration:d});},decodeOpenRtcMediaControl:a=>this.decodeControl(a),decodeOpenRtcMediaChunk:a=>this.decodeChunk(a)},v={createBidirectionalStream:async()=>({protocol:"openrtc-media/1",readable:new ReadableStream({start(a){a.close();}}),writable:new WritableStream})};if(this.media=new b$1(v,c,(a,d)=>(this.incoming=d,()=>{this.incoming=null;})),["owner","publisher","processor"].includes(t)&&!s)throw new Error("[OpenRTC] Broadcast publisher grant has no source slot.");this.scheduleReceive(0);}addTrack(e,r){return this.media.addTrack(e,r)}removeTrack(e){return this.media.removeTrack(e)}onTrack(e){return this.media.onTrack(r=>e({...r,source:{id:this.sources.get(r.receiver.id)??"unknown"}}))}senders(){return this.media.senders()}receivers(){return this.media.receivers()}async close(){this.closed||(this.closed=true,this.timer&&clearTimeout(this.timer),this.timer=null,await Promise.all([...this.incomingWriters.values()].map(({writer:e})=>e.close().catch(()=>{}))),this.incomingWriters.clear(),this.sources.clear(),await this.media.close());}scheduleReceive(e){this.closed||(this.timer=setTimeout(()=>{this.receive();},e));}async receive(){if(!this.closed)try{let e=await this.bridge.invoke("receive_openrtc_broadcast_media",{handleId:this.handleId,max:p});for(let r of e)await this.accept(r);this.scheduleReceive(e.length===p?0:w);}catch(e){this.closed||this.onFailure(e);}}async accept(e){let r=e.publicationId;if(this.sources.set(r,e.sourceSlot),e.control){let i=this.incomingWriters.get(r);if(e.controlType==="stop"){i?.generation===e.mediaGeneration&&(this.incomingWriters.delete(r),await i.writer.close().catch(()=>{})),this.sources.delete(r);return}if(e.controlType!=="publish"||i&&i.generation>=e.mediaGeneration)return;i&&await i.writer.close().catch(()=>{});let o=new TransformStream,s=o.writable.getWriter();this.incomingWriters.set(r,{generation:e.mediaGeneration,writer:s}),this.incoming?.({peerId:e.sourceSlot,protocol:"openrtc-media/1",readable:o.readable,writable:new WritableStream}),await s.write(a(l(e.control,"broadcast control")));return}if(!e.media)return;let t=this.incomingWriters.get(r);!t||t.generation!==e.mediaGeneration||await t.writer.write(a(l(e.media,"broadcast media")));}async decodeControl(e){if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");return this.bridge.invokeRaw("decode_openrtc_media_control",e,{})}async decodeChunk(e){if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");let r=l(await this.bridge.invokeRaw("decode_openrtc_media_chunk",e,{}),"decode_openrtc_media_chunk");if(r.byteLength<4)throw new Error("[OpenRTC] Native media metadata is truncated.");let i=4+new DataView(r.buffer,r.byteOffset,4).getUint32(0,false);if(i>r.byteLength)throw new Error("[OpenRTC] Native media metadata is invalid.");return {...JSON.parse(new TextDecoder().decode(r.subarray(4,i))),payload:r.slice(i)}}},b=class{constructor(e,r){this.bridge=e;this.context=r;this.sessions=new Set;this.publishers=new Set;}open(e){return this.openNative(e)}async create(e){let r=e.auth??this.context.defaultAuth;if(!r)throw new Error("Managed broadcast creation requires authenticated control-plane access.");let t=await this.context.manage({action:"create",deviceId:await this.context.deviceId(),auth:r,create:e});if(!t)throw new Error("Managed broadcast creation returned no grant.");return t}async preparePublisher(){let e=await this.bridge.invoke("prepare_openrtc_broadcast_publisher"),r=l(e.verificationKey,"broadcast publisher");if(!e.handle||r.byteLength!==32)throw e.handle&&await this.bridge.invoke("release_openrtc_broadcast_publisher",{handle:e.handle}).catch(()=>{}),new Error("[OpenRTC] Native broadcast publisher is invalid.");let t=false,i={verificationKey:r,open:o=>{if(t)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.openNative(o,e.handle)},close:async()=>{t||(t=true,this.publishers.delete(i),await this.bridge.invoke("release_openrtc_broadcast_publisher",{handle:e.handle}));}};return this.publishers.add(i),i}renew(e,r){return this.manage("renew",r,{grant:e})}invite(e,r,t){return this.manage("invite",t,{grant:e,invitation:r})}accept(e,r){return this.manage("accept",r,{invite:e})}async revoke(e,r,t){await this.manage("revoke",t,{grant:e,invite:r});}async leave(e,r){await this.manage("leave",r,{grant:e});}async closeGrant(e,r){await this.manage("close",r,{grant:e});}async close(){await Promise.all([...this.sessions].map(e=>e.close())),await Promise.all([...this.publishers].map(e=>e.close()));}async manage(e,r,t){let i=r??this.context.defaultAuth;if(!i)throw new Error(`Managed broadcast ${e} requires authenticated control-plane access.`);return this.context.manage({action:e,deviceId:await this.context.deviceId(),auth:i,...t})}async openNative(e,r){let t=await this.bridge.invoke("open_openrtc_broadcast",{grantToken:e,issuerPublicKey:null,publisherSignerHandle:r??null,nowMs:Date.now()}),i=t.state,o=false,s=new u(this.bridge,t.handleId,t.role,t.sourceSlots??[],()=>{i="failed";}),c={id:t.id,role:t.role,get state(){return i},media:s,getStats:()=>this.bridge.invoke("get_openrtc_broadcast_stats",{handleId:t.handleId}),close:async()=>{o||(o=true,i="closed",await s.close(),await this.bridge.invoke("close_openrtc_broadcast",{handleId:t.handleId}),this.sessions.delete(c));}};return this.sessions.add(c),c}};export{b as NativeManagedBroadcastHost};
@@ -1 +1 @@
1
- export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-YZ5LN36Y.js';import'./chunk-AYHD4X2R.js';import'./chunk-XK2JESZY.js';import'./chunk-XMYBBLYK.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import'./chunk-COXQYBTI.js';import'./chunk-CNAW5BZ3.js';import'./chunk-CCCYE3XN.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';
1
+ export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-Q7ZKAI5S.js';import'./chunk-AYHD4X2R.js';import'./chunk-XK2JESZY.js';import'./chunk-XMYBBLYK.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import'./chunk-COXQYBTI.js';import'./chunk-CNAW5BZ3.js';import'./chunk-CCCYE3XN.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';
@@ -1,2 +1,2 @@
1
- import {j,d as d$1,c}from'./chunk-RE2LBIIA.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
1
+ import {j,d as d$1,c}from'./chunk-ZFSJ2LEF.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
2
2
  export{p as a,S as b};
@@ -115,4 +115,4 @@ class OpenRtcAudioCaptureProcessor extends AudioWorkletProcessor {
115
115
  }
116
116
  }
117
117
  registerProcessor('openrtc-audio-capture', OpenRtcAudioCaptureProcessor);
118
- `;function ne(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))}function ie(i){if(typeof Worker!="function")throw new Error("[OpenRTC] Dedicated workers are unavailable for the browser video edge.");let e=ne(i);try{return {worker:new Worker(e),url:e}}catch(t){throw URL.revokeObjectURL(e),t}}async function we(i){if(typeof i.clone!="function")throw new Error("[OpenRTC] The browser cannot clone a video track for its worker media edge.");let{worker:e,url:t}=ie(fe),r=null,l,s,a=new Promise((o,c)=>{l=o,s=c;}),n=new ReadableStream({start(o){r=o;},pull(){e.postMessage({type:"read"});},cancel(o){e.postMessage({type:"cancel",reason:String(o??"")}),e.terminate();}},{highWaterMark:0});e.onmessage=({data:o})=>{if(o?.type==="ready")l();else if(o?.type==="frame")r?.enqueue(o.frame);else if(o?.type==="done")r?.close(),e.terminate();else if(o?.type==="error"){let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();}},e.onerror=o=>{let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();};let d=i.clone();e.postMessage({type:"start",track:d},[d]);try{await a;}finally{URL.revokeObjectURL(t);}return {readable:n}}async function ve(i){let e=globalThis,t=e.AudioContext??e.webkitAudioContext,r=e.AudioData;if(typeof t!="function"||typeof r!="function")throw new Error("[OpenRTC] Web Audio and AudioData are required for browser audio capture.");let l=i.getSettings?.()??{},s=Number(l.sampleRate??48e3),a=Math.max(1,Math.min(2,Number(l.channelCount??1))),n=new t({sampleRate:s}),d=Number(n.sampleRate??s),o=ne(ye);try{await n.audioWorklet.addModule(o);}catch(f){throw await n.close(),f}finally{URL.revokeObjectURL(o);}await n.resume();let c=n.createMediaStreamSource(new MediaStream([i])),m=new AudioWorkletNode(n,"openrtc-audio-capture",{numberOfInputs:1,numberOfOutputs:1,channelCount:a,channelCountMode:"explicit",channelInterpretation:"speakers",outputChannelCount:[a],processorOptions:{channels:a,framesPerChunk:Math.max(1,Math.round(d/50))}}),y=n.createGain();y.gain.value=0,c.connect(m).connect(y).connect(n.destination);let k=false,w=async()=>{k||(k=true,m.port.onmessage=null,c.disconnect(),m.disconnect(),y.disconnect(),i.removeEventListener?.("ended",v),await n.close());},A=null,v=()=>{A?.close(),w();};return i.addEventListener?.("ended",v,{once:true}),{readable:new ReadableStream({start(f){A=f,m.port.onmessage=({data:u})=>{if(!(f.desiredSize!==null&&f.desiredSize<=0))try{f.enqueue(new r({format:"f32-planar",sampleRate:d,numberOfFrames:u.frames,numberOfChannels:a,timestamp:Math.round(u.timestampFrames*1e6/d),data:u.planar}));}catch(O){f.error(O);}};},cancel:w},{highWaterMark:2})}}async function ae(i){let e=globalThis.MediaStreamTrackProcessor;return typeof e=="function"?he(i,e):i.kind==="video"?we(i):ve(i)}async function ge(){let{worker:i,url:e}=ie(be),t,r,l=new Promise((c,m)=>{t=c,r=m;}),s=0,a=new Map,n=null;i.onmessage=({data:c})=>{if(c?.type==="ready"){t(c.track);return}if(c?.type==="written"){a.get(c.id)?.resolve(),a.delete(c.id);return}if(c?.type==="closed"||c?.type==="aborted"){n?.resolve(),n=null,i.terminate();return}if(c?.type==="error"){let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m),a.get(c.id)?.reject(m),a.delete(c.id),n?.reject(m),n=null,i.terminate();}},i.onerror=c=>{let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m);for(let y of a.values())y.reject(m);a.clear(),n?.reject(m),n=null,i.terminate();},i.postMessage({type:"start"});let d;try{d=await l;}finally{URL.revokeObjectURL(e);}let o=(c,m)=>new Promise((y,k)=>{n={resolve:y,reject:k},i.postMessage({type:c,reason:String(m??"")});});return {track:d,writable:new WritableStream({write(c){let m=++s;return new Promise((y,k)=>{a.set(m,{resolve:y,reject:k}),i.postMessage({type:"write",id:m,frame:c},[c]);})},close:()=>o("close"),abort:c=>o("abort",c)},{highWaterMark:1})}}async function Me(i,e,t){let r=globalThis,l=r.AudioContext??r.webkitAudioContext;if(typeof l!="function")throw new Error("[OpenRTC] Web Audio is required for browser audio rendering.");let s=new l({sampleRate:i});await s.resume();let a=s.createMediaStreamDestination(),n=a.stream.getAudioTracks()[0];if(!n)throw await s.close(),new Error("[OpenRTC] Web Audio did not create a renderable media track.");let d=new Set,o=s.currentTime,c=async()=>{for(let m of d)try{m.stop();}catch{}d.clear(),n.stop(),await s.close();};return {track:n,writable:new WritableStream({async write(m){for(;o-s.currentTime>.5;){if(t?.aborted)throw new Error("[OpenRTC] browser audio rendering was cancelled.");await new Promise(f=>{let u,O=()=>{clearTimeout(u),t?.removeEventListener("abort",O),f();};u=setTimeout(()=>{t?.removeEventListener("abort",O),f();},10),t?.addEventListener("abort",O,{once:true});});}let y=Number(m.numberOfChannels??e),k=Number(m.sampleRate??i),w=Number(m.numberOfFrames??0),A=s.createBuffer(y,w,k);for(let f=0;f<y;f+=1){let u=new Float32Array(w);m.copyTo(u,{planeIndex:f,format:"f32-planar"}),A.copyToChannel(u,f);}let v=s.createBufferSource();v.buffer=A,v.connect(a),v.onended=()=>d.delete(v),d.add(v),o<s.currentTime-.05&&(o=s.currentTime),v.start(o),o+=A.duration;},close:c,abort:c},{highWaterMark:2})}}async function oe(i){let e=globalThis.MediaStreamTrackGenerator;if(typeof e=="function"){let t=new e({kind:i.kind});return {track:t.track??t,writable:t.writable}}return i.kind==="video"?ge():Me(i.sampleRate,i.channels,i.signal)}var ce="openrtc-media/1",le=2*1024*1024+72,Re=32,ke=8,Se=2*1024*1024,Te=8*1024*1024,J=1e3,Pe=30,Ee=32,Ce=8,Ae=8,Oe=16,ue=1e4,Le=512;function We(i){if(!i||typeof i!="object")return false;let e=i;return e.name==="OpenRtcPeerStreamStopped"&&e.openrtcPeerStopCode===0}function Ie(i){if(!Number.isSafeInteger(i.transportStableId)||i.transportStableId<=0||!Number.isSafeInteger(i.transportGeneration)||i.transportGeneration<=0||!Number.isSafeInteger(i.routeGeneration)||i.routeGeneration<0)throw new RangeError("[OpenRTC] media physical generation requires a safe positive transport identity and generation.")}function C(){return globalThis.performance?.now?.()??Date.now()}var B=class{constructor(){this.values=[];}observe(e){!Number.isFinite(e)||e<0||(this.values.length===Le&&this.values.shift(),this.values.push(e));}snapshot(){if(this.values.length===0)return {samples:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let e=[...this.values].sort((r,l)=>r-l),t=r=>e[Math.ceil(r*e.length)-1]??0;return {samples:e.length,p50Ms:t(.5),p95Ms:t(.95),p99Ms:t(.99),maxMs:e[e.length-1]}}};function se(i){if(i.byteLength>le)throw new Error("[OpenRTC] encoded media frame exceeds the portable media limit.");let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer).setUint32(0,i.byteLength,false),e.set(i,4),e}async function*xe(i,e){let t=i.getReader(),r=()=>{t.cancel("media-publication-cancelled");};e?.addEventListener("abort",r,{once:true});let l=new Uint8Array(4),s=0,a=null,n=0;try{for(;;){let d=await t.read();if(d.done)break;if(!d.value?.byteLength)continue;let o=0;for(;o<d.value.byteLength;){if(!a){let m=Math.min(l.byteLength-s,d.value.byteLength-o);if(l.set(d.value.subarray(o,o+m),s),s+=m,o+=m,s<l.byteLength)continue;let y=new DataView(l.buffer).getUint32(0,!1);if(y>le)throw new Error("[OpenRTC] incoming media frame exceeds the portable media limit.");s=0,a=new Uint8Array(y),n=0,y===0&&(yield a,a=null);continue}let c=Math.min(a.byteLength-n,d.value.byteLength-o);a.set(d.value.subarray(o,o+c),n),n+=c,o+=c,n===a.byteLength&&(yield a,a=null,n=0);}}if(s!==0||a!==null)throw new Error("[OpenRTC] incoming media stream ended with a truncated frame.")}finally{e?.removeEventListener("abort",r),t.releaseLock();}}function H(i){switch(i){case "h264":return "avc1.42001e";case "av1":return "av01.0.04M.08";default:return i}}function Ge(i){let e=Number(i.numberOfFrames),t=Number(i.numberOfChannels);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(t)||t<1||typeof i.copyTo!="function")throw new Error("[OpenRTC] PCM audio requires copyable AudioData frames.");let r=new Uint8Array(e*t*2),l=new DataView(r.buffer),s=new Float32Array(e);for(let a=0;a<t;a+=1){s.fill(0),i.copyTo(s,{planeIndex:a,format:"f32-planar"});for(let n=0;n<e;n+=1){let d=Math.max(-1,Math.min(1,s[n])),o=d<0?Math.round(d*32768):Math.round(d*32767);l.setInt16((a*e+n)*2,o,true);}}return r}var Z=class{constructor(e,t,r,l){this.options=t;this.streams=r;this.runtime=l;this.publicationId="";this.stopped=false;this.abort=null;this.run=null;this.encodeLatency=new B;this.protectedWriteLatency=new B;this.pendingWrites=new Map;this.nextPendingWriteId=0;this.currentTrack=e,this.stats={publicationId:"",mediaGeneration:0,accepted:0,queued:0,queuedBytes:0,queuedAgeMs:0,transmitted:0,dropped:0,bytes:0,maxQueued:0,maxQueuedBytes:0,maxQueuedAgeMs:0,lastError:void 0,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()};}get id(){return this.publicationId}get track(){return this.currentTrack}async start(){if(!this.currentTrack)return;this.stats.lastError=void 0;let e=new AbortController;this.abort=e;let t,r,l=new Promise((s,a)=>{t=s,r=a;});this.run=this.encode(this.currentTrack,e.signal,t).catch(s=>{throw e.signal.aborted||(this.stats.lastError=s instanceof Error?s.message:String(s)),r(s),s}),this.run.catch(()=>{});try{await l;}catch(s){throw e.abort(),await this.run.catch(()=>{}),s}}async replaceTrack(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),this.currentTrack=e,e&&await this.start();}async setEnabled(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.currentTrack&&(this.currentTrack.enabled=e);}async stop(){this.stopped||(this.stopped=true,this.abort?.abort(),await this.run?.catch(()=>{}),this.currentTrack=null,this.publicationId&&await this.runtime.retireOpenRtcMediaPublication(this.publicationId));}async restartForPhysicalGeneration(){this.stopped||!this.currentTrack||(this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),!this.stopped&&this.currentTrack&&await this.start());}async getStats(){return this.updatePendingWriteStats(),{...this.stats,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()}}updatePendingWriteStats(e=C()){for(let[r,l]of this.pendingWrites)e-l.acceptedAtMs<=J||(this.pendingWrites.delete(r),this.stats.dropped+=1);this.stats.queued=this.pendingWrites.size,this.stats.queuedBytes=[...this.pendingWrites.values()].reduce((r,l)=>r+l.bytes,0);let t=[...this.pendingWrites.values()].reduce((r,l)=>r===null||l.acceptedAtMs<r?l.acceptedAtMs:r,null);this.stats.queuedAgeMs=t===null?0:Math.max(0,e-t),this.stats.maxQueued=Math.max(this.stats.maxQueued,this.stats.queued),this.stats.maxQueuedBytes=Math.max(this.stats.maxQueuedBytes,this.stats.queuedBytes),this.stats.maxQueuedAgeMs=Math.max(this.stats.maxQueuedAgeMs,this.stats.queuedAgeMs);}async encode(e,t,r){let l=globalThis;if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let s=await ae(e),a=s.readable.getReader(),n=async()=>{await s.close?.();},d=()=>{a.cancel("media-generation-replaced");},o,c=new Promise(h=>{o=h;}),m=()=>o();t.addEventListener("abort",d,{once:true}),t.addEventListener("abort",m,{once:true});let y=null,k;try{k=await Promise.race([a.read(),new Promise((h,E)=>{y=setTimeout(()=>{E(new Error("[OpenRTC] media encoder startup timed out."));},ue);})]);}catch(h){throw await a.cancel("media-encoder-startup-failed").catch(()=>{}),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),h}finally{y&&clearTimeout(y);}if(k.done||!k.value||t.aborted)throw a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),new Error("[OpenRTC] media track ended before its encoder became ready.");let w=k.value,A=e.kind==="video"?"vp8":typeof l.AudioEncoder=="function"?"opus":"pcm",v=(this.options.codec??A).toLowerCase(),f=v.startsWith("avc1")?"h264":v.startsWith("av01")?"av1":v,u=e.kind==="audio"&&f==="pcm";if(f==="pcm"&&e.kind!=="audio")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] PCM is supported only for audio tracks.");let O=e.kind==="video"?l.VideoEncoder:l.AudioEncoder;if(!u&&typeof O!="function")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] WebCodecs encode support is required for compressed browser media.");let D={publicationId:this.publicationId,kind:e.kind,codec:f,clockRate:e.kind==="audio"?Number(w.sampleRate??48e3):1e6,codedWidth:e.kind==="video"?Number(w.displayWidth??w.codedWidth):void 0,codedHeight:e.kind==="video"?Number(w.displayHeight??w.codedHeight):void 0,channels:e.kind==="audio"?Number(w.numberOfChannels??2):void 0},G=Promise.resolve(),S=null,L=false,I=null,N=null,F=null,q=0,V=false,W=false,z=false,_=new Map,U=h=>N?(F??(F=N(h)),F):Promise.resolve(),Q=()=>{U("media-generation-replaced").catch(()=>{});},x=h=>{S===null&&(S=h),o(),a.cancel("media-sender-failed").catch(()=>{}),U("media-sender-failed").catch(()=>{});},K=()=>{L=true,o(),a.cancel("media-peer-receiver-stopped").catch(()=>{});},X=h=>{try{if(t.aborted||S){this.stats.dropped+=1;return}let E=Number(h.timestamp??0),T=_.get(E);T!==void 0&&(this.encodeLatency.observe(C()-T),_.delete(E));let b=e.kind==="video"?ke:Re,P=e.kind==="video"?Te:Se,M=new Uint8Array(h.byteLength);if(this.pendingWrites.size>=b||this.stats.queuedBytes+M.byteLength>P||!I){this.stats.dropped+=1;return}h.copyTo(M),this.stats.accepted+=1;let R=++this.nextPendingWriteId,te=C();this.pendingWrites.set(R,{bytes:M.byteLength,acceptedAtMs:te}),this.updatePendingWriteStats(te),G=G.then(async()=>{let $=this.pendingWrites.get(R);if(!$||t.aborted)return;if(C()-$.acceptedAtMs>J){this.pendingWrites.delete(R),this.stats.dropped+=1;return}if(this.updatePendingWriteStats(),!this.pendingWrites.has(R))return;let pe=await this.runtime.encodeOpenRtcMediaSample({publicationId:this.id,timestampUs:Number(h.timestamp??0),durationUs:Number(h.duration??0),keyframe:h.type==="key",discardable:e.kind==="video"&&h.type!=="key",payload:M});if(t.aborted||S)return;let Y=this.pendingWrites.get(R);if(!Y||C()-Y.acceptedAtMs>J){Y&&(this.pendingWrites.delete(R),this.stats.dropped+=1);return}this.pendingWrites.delete(R),this.updatePendingWriteStats();let me=C();await I.write(se(pe)),!(t.aborted||S)&&(this.protectedWriteLatency.observe(C()-me),this.stats.transmitted+=1,this.stats.bytes+=M.byteLength);}).catch($=>{We($)?K():x($);}).finally(()=>{this.pendingWrites.delete(R),this.updatePendingWriteStats();});}catch(E){x(E),this.stats.dropped+=1;}},g=u?null:new O({output:X,error:h=>{x(h);}}),j=e.kind==="video"?{codec:H(f),width:D.codedWidth,height:D.codedHeight,bitrate:this.options.bitrate??15e5,framerate:30,latencyMode:"realtime"}:{codec:H(f),sampleRate:D.clockRate,numberOfChannels:D.channels,bitrate:this.options.bitrate??96e3},p=h=>{try{if(t.aborted)return;if(u){let P=Number(h.timestamp??0);_.set(P,C());let M=Ge(h);X({timestamp:P,duration:Number(h.duration??0),type:"key",byteLength:M.byteLength,copyTo(R){R.set(M);}});return}let E=e.kind==="video"?4:8;if(g.encodeQueueSize>=E){this.stats.dropped+=1;return}let T=e.kind==="video"&&q%Pe===0;q+=1;let b=Number(h.timestamp??0);if(_.size>=64){let P=_.keys().next().value;P!==void 0&&_.delete(P);}_.set(b,C()),g.encode(h,e.kind==="video"?{keyFrame:T}:void 0);}finally{h.close?.();}};try{if(!u&&typeof O.isConfigSupported!="function")throw new Error("[OpenRTC] The browser cannot verify WebCodecs encoder support.");let h=u?null:await O.isConfigSupported(j);if(!u&&!h?.supported)throw new Error(`[OpenRTC] The browser cannot encode '${f}' for this track.`);let E=h?.config??j,T=await this.runtime.beginOpenRtcMediaPublication(D);V=!0,this.publicationId=T.publicationId,this.stats.publicationId=T.publicationId,this.stats.mediaGeneration=T.mediaGeneration;let b$1=await this.streams.createBidirectionalStream({protocol:ce});for(N=b(b$1.writable),I=b$1.writable.getWriter(),t.addEventListener("abort",Q,{once:!0}),t.aborted&&Q(),b$1.readable.cancel("media-v1-has-no-reverse-control").catch(()=>{}),await I.write(se(T.control)),g?.configure(E),r(),z=!0,p(w);!t.aborted&&!S&&!L;){let P=await a.read();if(P.done)break;P.value&&p(P.value);}if(!t.aborted&&!S&&!L&&(g&&await Promise.race([g.flush(),c]),!t.aborted&&!S&&!L&&await Promise.race([G,c])),S)throw S;if(L)await this.runtime.pauseOpenRtcMediaPublication(this.publicationId);else if(!t.aborted){let P=I.close();await Promise.race([P,c]),W=!t.aborted&&!S;}}catch(h){throw V&&!t.aborted&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),h}finally{if(t.removeEventListener("abort",d),t.removeEventListener("abort",m),t.removeEventListener("abort",Q),z||w.close?.(),a.releaseLock(),await n().catch(()=>{}),g&&g.state!=="closed")try{g.close?.();}catch{}if(I&&!W){let h=t.aborted?"media-generation-replaced":L?"media-peer-receiver-stopped":"media-sender-failed";await U(h).catch(()=>{}),await I.abort(h).catch(()=>{});}await G.catch(()=>{});try{I?.releaseLock();}catch{}}}},ee=class{constructor(e,t,r,l,s){this.id=e;this.track=t;this.stats=r;this.receiveToDecodeLatency=l;this.renderWriteLatency=s;}async getStats(){return {...this.stats,receiveToDecodeLatency:this.receiveToDecodeLatency.snapshot(),renderWriteLatency:this.renderWriteLatency.snapshot()}}},de=class{constructor(e,t,r,l=()=>({registered:true,peers:1,boundConnections:0,observed:0,accepted:0,declined:0,lastResolution:"none"})){this.streams=e;this.runtime=t;this.incomingDemux=l;this.senderMap=new Map;this.receiverMap=new Map;this.listeners=new Set;this.incomingRuns=new Map;this.receiverRuns=new Map;this.incomingFailures=[];this.incomingProtocolStreams=0;this.stopped=false;this.physicalGeneration=null;this.recoveryTail=Promise.resolve();this.stopIncoming=r(ce,s=>{if(this.incomingProtocolStreams+=1,this.stopped||this.incomingRuns.size>=Ae){s.readable.cancel("incoming-media-publication-limit").catch(()=>{}),s.writable.abort("incoming-media-publication-limit").catch(()=>{});return}let a=new AbortController,n=this.receivePublication(s.readable,s.writable,a);this.incomingRuns.set(a,n),n.catch(d=>{let o=d instanceof Error?d.message:String(d);this.incomingFailures.length===Oe&&this.incomingFailures.shift(),this.incomingFailures.push(o),console.error("[OpenRTC][media] incoming publication failed",{message:o});}).finally(()=>this.incomingRuns.delete(a));});}async addTrack(e,t={}){if(this.stopped)throw new Error("[OpenRTC] media connection is closed.");if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let r=new Z(e,t,this.streams,this.runtime);try{return await r.start(),this.senderMap.set(r.id,r),r}catch(l){throw await r.stop().catch(()=>{}),l}}async removeTrack(e){let t=this.senderMap.get(e.id);!t||t!==e||(this.senderMap.delete(e.id),await t.stop());}onTrack(e){return this.listeners.add(e),()=>this.listeners.delete(e)}senders(){return [...this.senderMap.values()]}receivers(){return [...this.receiverMap.values()]}async getStats(){return {senders:await Promise.all([...this.senderMap.values()].map(e=>e.getStats())),receivers:await Promise.all([...this.receiverMap.values()].map(e=>e.getStats())),incomingFailures:[...this.incomingFailures],incomingProtocolStreams:this.incomingProtocolStreams,incomingDemux:this.incomingDemux()}}async observePhysicalGeneration(e){if(this.stopped)return;if(Ie(e),this.physicalGeneration===null){this.physicalGeneration={...e};return}let t=this.physicalGeneration;if(!(e.transportGeneration<t.transportGeneration)){if(e.transportGeneration===t.transportGeneration){if(e.transportStableId!==t.transportStableId)throw new Error("[OpenRTC] media rejected an inconsistent physical generation tuple.");e.routeGeneration>t.routeGeneration&&(this.physicalGeneration={...e});return}if(e.transportStableId===t.transportStableId)throw new Error("[OpenRTC] media rejected a reused physical transport identity.");this.physicalGeneration={...e},this.recoveryTail=this.recoveryTail.catch(()=>{}).then(async()=>{if(!this.stopped)for(let r of this.senderMap.values())await r.restartForPhysicalGeneration();}),await this.recoveryTail;}}async close(){if(this.stopped)return;this.stopped=true,this.stopIncoming(),await this.recoveryTail.catch(()=>{}),await Promise.all([...this.senderMap.values()].map(t=>t.stop())),this.senderMap.clear(),this.listeners.clear();let e=[...this.incomingRuns.entries()];for(let[t]of e)t.abort();await Promise.allSettled(e.map(([,t])=>t)),this.incomingRuns.clear(),this.receiverRuns.clear();for(let t of this.receiverMap.values())t.track.stop();this.receiverMap.clear(),this.incomingFailures.splice(0);}async receivePublication(e,t,r){if(this.stopped){await e.cancel("media-connection-closed").catch(()=>{}),await t.abort("media-connection-closed").catch(()=>{});return}let l=xe(e,r.signal),s=null,a;try{a=await Promise.race([l.next(),new Promise((p,h)=>{s=setTimeout(()=>{h(new Error("[OpenRTC] incoming media control timed out."));},ue);})]);}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-failed").catch(()=>{}),await t.abort("incoming-media-control-failed").catch(()=>{}),p}finally{s&&clearTimeout(s);}if(a.done){await t.close().catch(()=>{});return}let n;try{let p=await this.runtime.decodeOpenRtcMediaControl(a.value);if(p.type!=="publish")throw new Error("[OpenRTC] media stream did not begin with publish control.");n=p;}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-invalid").catch(()=>{}),await t.abort("incoming-media-control-invalid").catch(()=>{}),p}let d=n.publicationId,o=async(p,h)=>{throw r.abort(),await l.return(void 0).catch(()=>{}),await this.runtime.retireOpenRtcMediaReceiver(d,n.mediaGeneration),await t.abort(p).catch(()=>{}),h},c=globalThis,m=n.kind==="audio"&&n.codec==="pcm",y=n.kind==="video"?c.VideoDecoder:c.AudioDecoder,k=n.kind==="video"?c.EncodedVideoChunk:c.EncodedAudioChunk;if(!m&&(typeof y!="function"||typeof k!="function"))return o("media-decoder-api-unavailable",new Error("[OpenRTC] WebCodecs decode support is required for browser media."));if(m&&typeof c.AudioData!="function")return o("media-pcm-api-unavailable",new Error("[OpenRTC] AudioData is required for PCM browser media."));let w=n.kind==="video"?{codec:H(n.codec),codedWidth:n.codedWidth,codedHeight:n.codedHeight,optimizeForLatency:true}:{codec:H(n.codec),sampleRate:n.clockRate,numberOfChannels:n.channels??2};if(!m&&typeof y.isConfigSupported!="function")return o("media-decoder-support-unverifiable",new Error("[OpenRTC] The browser cannot verify WebCodecs decoder support."));let A=null;try{m||(A=await y.isConfigSupported(w));}catch(p){return o("media-decoder-support-check-failed",p)}if(!m&&!A?.supported)return o("media-decoder-unsupported",new Error(`[OpenRTC] The browser cannot decode '${n.codec}'.`));let v,f;try{let p=await oe({kind:n.kind,sampleRate:n.clockRate,channels:n.channels??2,signal:r.signal});v=p.track,f=p.writable.getWriter();}catch(p){return o("media-renderer-setup-failed",p)}let u={publicationId:d,mediaGeneration:n.mediaGeneration,received:0,decoded:0,rendered:0,dropped:0,integrityFailures:0,malformedFrames:0,replayDrops:0,videoRecoveries:0,awaitingKeyframe:n.kind==="video",maxVideoRecoveryMs:0,bytes:0,decoderQueued:0,maxDecoderQueued:0,renderQueued:0,maxRenderQueued:0,receiveToDecodeLatency:new B().snapshot(),renderWriteLatency:new B().snapshot()},O=new B,D=new B,G=new Map,S=[],L=n.kind==="video",I=L,N=null,F=null,q=()=>{L&&(I=true,u.awaitingKeyframe=true,N===null&&(N=C()));},V=Promise.resolve(),W=null,z,_=new Promise(p=>{z=p;}),U=()=>{z(),f.abort("media-receiver-cancelled").catch(()=>{});};r.signal.addEventListener("abort",U,{once:true}),r.signal.aborted&&U();let Q=p=>{W===null&&(W=p),r.abort();},x=0,K=n.kind==="video"?Ce:Ee,X=(p,h=0)=>{if(r.signal.aborted||W){p.close?.();return}u.decoderQueued=h;let E=Number(p.timestamp??0),T=L?G.get(E):S.shift();if(T!==void 0&&(O.observe(C()-T),L&&G.delete(E)),x>=K){u.dropped+=1,p.close?.();return}x+=1,u.renderQueued=x,u.maxRenderQueued=Math.max(u.maxRenderQueued,x),V=V.then(async()=>{if(r.signal.aborted)return;let b=C();await f.write(p),D.observe(C()-b),u.decoded+=1,u.rendered+=1;}).catch(b=>{r.signal.aborted||Q(b);}).finally(()=>{p.close?.(),x-=1,u.renderQueued=x;});},g=null;try{m||(g=new y({output:p=>{X(p,Number(g?.decodeQueueSize??0));},error:p=>{r.signal.aborted||Q(p);}})),g?.configure(A?.config??w);}catch(p){r.signal.removeEventListener("abort",U),f.abort("media-decoder-setup-failed").catch(()=>{});try{f.releaseLock();}catch{}return v.stop(),o("media-decoder-setup-failed",p)}let j=new ee(d,v,u,O,D);try{let p=this.receiverRuns.get(d);if(p&&p.abort!==r&&p.mediaGeneration>=n.mediaGeneration)throw new Error(`[OpenRTC] stale media generation ${n.mediaGeneration} cannot replace ${p.mediaGeneration} for '${d}'.`);if(this.receiverRuns.set(d,{mediaGeneration:n.mediaGeneration,abort:r}),p&&p.abort!==r&&(p.abort.abort(),await this.incomingRuns.get(p.abort)?.catch(()=>{})),this.stopped||r.signal.aborted)return;let h=this.receiverMap.get(d);h&&h.track.stop(),this.receiverMap.set(d,j);let E=new MediaStream([v]);for(let T of this.listeners)try{T({track:v,receiver:j,streams:[E]});}catch{}for await(let T of l){if(r.signal.aborted||W||this.stopped)break;let b;try{b=await this.runtime.decodeOpenRtcMediaChunk(T);}catch(M){let R=String(M);/integrity/i.test(R)?(u.integrityFailures+=1,q()):/replay|retired/i.test(R)?u.replayDrops+=1:/truncated|invalidmagic|unsupported|chunktoolarge|too large|lengthmismatch/i.test(R)?(u.malformedFrames+=1,q()):u.dropped+=1;continue}if(r.signal.aborted||this.stopped)break;if(b.publicationId!==d||b.mediaGeneration!==n.mediaGeneration){u.dropped+=1;continue}if(F!==null&&b.sequence>F+1&&q(),F=F===null?b.sequence:Math.max(F,b.sequence),u.received+=1,u.bytes+=b.payload.byteLength,L&&I){if(!b.keyframe){u.dropped+=1;continue}if(N!==null){let M=C()-N;u.videoRecoveries+=1,u.maxVideoRecoveryMs=Math.max(u.maxVideoRecoveryMs,M),g?.reset?.(),g?.configure(A?.config??w);}I=!1,N=null,u.awaitingKeyframe=!1;}if((g?.decodeQueueSize??x)>=K){u.dropped+=1;continue}let P=C();if(L){if(G.size>=64){let M=G.keys().next().value;M!==void 0&&G.delete(M);}G.set(b.timestampUs,P);}else S.length>=64&&S.shift(),S.push(P);if(m){let M=n.channels??2,R=M*2;if(b.payload.byteLength===0||b.payload.byteLength%R!==0){u.dropped+=1;continue}X(new c.AudioData({format:"s16-planar",sampleRate:n.clockRate,numberOfFrames:b.payload.byteLength/R,numberOfChannels:M,timestamp:b.timestampUs,data:b.payload}));}else try{g.decode(new k({type:b.keyframe?"key":"delta",timestamp:b.timestampUs,duration:b.durationUs||void 0,data:b.payload}));}catch(M){Q(M);break}u.decoderQueued=Number(g?.decodeQueueSize??x),u.maxDecoderQueued=Math.max(u.maxDecoderQueued,u.decoderQueued);}if(!r.signal.aborted&&!W&&g&&await Promise.race([g.flush(),_]),!r.signal.aborted&&!W&&await Promise.race([V,_]),W)throw W}finally{r.signal.removeEventListener("abort",U);try{g?.close?.();}catch{}r.signal.aborted||W?f.abort("media-receiver-finished").catch(()=>{}):f.close().catch(()=>{});try{f.releaseLock();}catch{}this.receiverRuns.get(d)?.abort===r&&this.receiverRuns.delete(d),this.receiverMap.get(d)===j&&this.receiverMap.delete(d),await this.runtime.retireOpenRtcMediaReceiver(d,u.mediaGeneration),v.stop(),r.signal.aborted||W?t.abort("media-receiver-finished").catch(()=>{}):t.close().catch(()=>{});}}};export{se as a,de as b};
118
+ `;function ne(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))}function ie(i){if(typeof Worker!="function")throw new Error("[OpenRTC] Dedicated workers are unavailable for the browser video edge.");let e=ne(i);try{return {worker:new Worker(e),url:e}}catch(t){throw URL.revokeObjectURL(e),t}}async function we(i){if(typeof i.clone!="function")throw new Error("[OpenRTC] The browser cannot clone a video track for its worker media edge.");let{worker:e,url:t}=ie(fe),r=null,l,s,a=new Promise((o,c)=>{l=o,s=c;}),n=new ReadableStream({start(o){r=o;},pull(){e.postMessage({type:"read"});},cancel(o){e.postMessage({type:"cancel",reason:String(o??"")}),e.terminate();}},{highWaterMark:0});e.onmessage=({data:o})=>{if(o?.type==="ready")l();else if(o?.type==="frame")r?.enqueue(o.frame);else if(o?.type==="done")r?.close(),e.terminate();else if(o?.type==="error"){let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();}},e.onerror=o=>{let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();};let d=i.clone();e.postMessage({type:"start",track:d},[d]);try{await a;}finally{URL.revokeObjectURL(t);}return {readable:n}}async function ve(i){let e=globalThis,t=e.AudioContext??e.webkitAudioContext,r=e.AudioData;if(typeof t!="function"||typeof r!="function")throw new Error("[OpenRTC] Web Audio and AudioData are required for browser audio capture.");let l=i.getSettings?.()??{},s=Number(l.sampleRate??48e3),a=Math.max(1,Math.min(2,Number(l.channelCount??1))),n=new t({sampleRate:s}),d=Number(n.sampleRate??s),o=ne(ye);try{await n.audioWorklet.addModule(o);}catch(f){throw await n.close(),f}finally{URL.revokeObjectURL(o);}await n.resume();let c=n.createMediaStreamSource(new MediaStream([i])),m=new AudioWorkletNode(n,"openrtc-audio-capture",{numberOfInputs:1,numberOfOutputs:1,channelCount:a,channelCountMode:"explicit",channelInterpretation:"speakers",outputChannelCount:[a],processorOptions:{channels:a,framesPerChunk:Math.max(1,Math.round(d/50))}}),y=n.createGain();y.gain.value=0,c.connect(m).connect(y).connect(n.destination);let k=false,w=async()=>{k||(k=true,m.port.onmessage=null,c.disconnect(),m.disconnect(),y.disconnect(),i.removeEventListener?.("ended",v),await n.close());},A=null,v=()=>{A?.close(),w();};return i.addEventListener?.("ended",v,{once:true}),{readable:new ReadableStream({start(f){A=f,m.port.onmessage=({data:u})=>{if(!(f.desiredSize!==null&&f.desiredSize<=0))try{f.enqueue(new r({format:"f32-planar",sampleRate:d,numberOfFrames:u.frames,numberOfChannels:a,timestamp:Math.round(u.timestampFrames*1e6/d),data:u.planar}));}catch(O){f.error(O);}};},cancel:w},{highWaterMark:2})}}async function ae(i){let e=globalThis.MediaStreamTrackProcessor;return typeof e=="function"?he(i,e):i.kind==="video"?we(i):ve(i)}async function ge(){let{worker:i,url:e}=ie(be),t,r,l=new Promise((c,m)=>{t=c,r=m;}),s=0,a=new Map,n=null;i.onmessage=({data:c})=>{if(c?.type==="ready"){t(c.track);return}if(c?.type==="written"){a.get(c.id)?.resolve(),a.delete(c.id);return}if(c?.type==="closed"||c?.type==="aborted"){n?.resolve(),n=null,i.terminate();return}if(c?.type==="error"){let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m),a.get(c.id)?.reject(m),a.delete(c.id),n?.reject(m),n=null,i.terminate();}},i.onerror=c=>{let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m);for(let y of a.values())y.reject(m);a.clear(),n?.reject(m),n=null,i.terminate();},i.postMessage({type:"start"});let d;try{d=await l;}finally{URL.revokeObjectURL(e);}let o=(c,m)=>new Promise((y,k)=>{n={resolve:y,reject:k},i.postMessage({type:c,reason:String(m??"")});});return {track:d,writable:new WritableStream({write(c){let m=++s;return new Promise((y,k)=>{a.set(m,{resolve:y,reject:k}),i.postMessage({type:"write",id:m,frame:c},[c]);})},close:()=>o("close"),abort:c=>o("abort",c)},{highWaterMark:1})}}async function Me(i,e,t){let r=globalThis,l=r.AudioContext??r.webkitAudioContext;if(typeof l!="function")throw new Error("[OpenRTC] Web Audio is required for browser audio rendering.");let s=new l({sampleRate:i});await s.resume();let a=s.createMediaStreamDestination(),n=a.stream.getAudioTracks()[0];if(!n)throw await s.close(),new Error("[OpenRTC] Web Audio did not create a renderable media track.");let d=new Set,o=s.currentTime,c=async()=>{for(let m of d)try{m.stop();}catch{}d.clear(),n.stop(),await s.close();};return {track:n,writable:new WritableStream({async write(m){for(;o-s.currentTime>.5;){if(t?.aborted)throw new Error("[OpenRTC] browser audio rendering was cancelled.");await new Promise(f=>{let u,O=()=>{clearTimeout(u),t?.removeEventListener("abort",O),f();};u=setTimeout(()=>{t?.removeEventListener("abort",O),f();},10),t?.addEventListener("abort",O,{once:true});});}let y=Number(m.numberOfChannels??e),k=Number(m.sampleRate??i),w=Number(m.numberOfFrames??0),A=s.createBuffer(y,w,k);for(let f=0;f<y;f+=1){let u=new Float32Array(w);m.copyTo(u,{planeIndex:f,format:"f32-planar"}),A.copyToChannel(u,f);}let v=s.createBufferSource();v.buffer=A,v.connect(a),v.onended=()=>d.delete(v),d.add(v),o<s.currentTime-.05&&(o=s.currentTime),v.start(o),o+=A.duration;},close:c,abort:c},{highWaterMark:2})}}async function oe(i){let e=globalThis.MediaStreamTrackGenerator;if(typeof e=="function"){let t=new e({kind:i.kind});return {track:t.track??t,writable:t.writable}}return i.kind==="video"?ge():Me(i.sampleRate,i.channels,i.signal)}var ce="openrtc-media/1",le=2*1024*1024+72,Re=32,ke=8,Se=2*1024*1024,Te=8*1024*1024,J=1e3,Pe=30,Ee=32,Ce=8,Ae=8,Oe=16,ue=1e4,Le=512;function We(i){if(!i||typeof i!="object")return false;let e=i;return e.name==="OpenRtcPeerStreamStopped"&&e.openrtcPeerStopCode===0}function Ie(i){if(!Number.isSafeInteger(i.transportStableId)||i.transportStableId<=0||!Number.isSafeInteger(i.transportGeneration)||i.transportGeneration<=0||!Number.isSafeInteger(i.routeGeneration)||i.routeGeneration<0)throw new RangeError("[OpenRTC] media physical generation requires a safe positive transport identity and generation.")}function C(){return globalThis.performance?.now?.()??Date.now()}var B=class{constructor(){this.values=[];}observe(e){!Number.isFinite(e)||e<0||(this.values.length===Le&&this.values.shift(),this.values.push(e));}snapshot(){if(this.values.length===0)return {samples:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let e=[...this.values].sort((r,l)=>r-l),t=r=>e[Math.ceil(r*e.length)-1]??0;return {samples:e.length,p50Ms:t(.5),p95Ms:t(.95),p99Ms:t(.99),maxMs:e[e.length-1]}}};function se(i){if(i.byteLength>le)throw new Error("[OpenRTC] encoded media frame exceeds the portable media limit.");let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer).setUint32(0,i.byteLength,false),e.set(i,4),e}async function*xe(i,e){let t=i.getReader(),r=()=>{t.cancel("media-publication-cancelled");};e?.addEventListener("abort",r,{once:true});let l=new Uint8Array(4),s=0,a=null,n=0;try{for(;;){let d=await t.read();if(d.done)break;if(!d.value?.byteLength)continue;let o=0;for(;o<d.value.byteLength;){if(!a){let m=Math.min(l.byteLength-s,d.value.byteLength-o);if(l.set(d.value.subarray(o,o+m),s),s+=m,o+=m,s<l.byteLength)continue;let y=new DataView(l.buffer).getUint32(0,!1);if(y>le)throw new Error("[OpenRTC] incoming media frame exceeds the portable media limit.");s=0,a=new Uint8Array(y),n=0,y===0&&(yield a,a=null);continue}let c=Math.min(a.byteLength-n,d.value.byteLength-o);a.set(d.value.subarray(o,o+c),n),n+=c,o+=c,n===a.byteLength&&(yield a,a=null,n=0);}}if(s!==0||a!==null)throw new Error("[OpenRTC] incoming media stream ended with a truncated frame.")}finally{e?.removeEventListener("abort",r),t.releaseLock();}}function H(i){switch(i){case "h264":return "avc1.42e01f";case "av1":return "av01.0.04M.08";default:return i}}function Ge(i){let e=Number(i.numberOfFrames),t=Number(i.numberOfChannels);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(t)||t<1||typeof i.copyTo!="function")throw new Error("[OpenRTC] PCM audio requires copyable AudioData frames.");let r=new Uint8Array(e*t*2),l=new DataView(r.buffer),s=new Float32Array(e);for(let a=0;a<t;a+=1){s.fill(0),i.copyTo(s,{planeIndex:a,format:"f32-planar"});for(let n=0;n<e;n+=1){let d=Math.max(-1,Math.min(1,s[n])),o=d<0?Math.round(d*32768):Math.round(d*32767);l.setInt16((a*e+n)*2,o,true);}}return r}var Z=class{constructor(e,t,r,l){this.options=t;this.streams=r;this.runtime=l;this.publicationId="";this.stopped=false;this.abort=null;this.run=null;this.encodeLatency=new B;this.protectedWriteLatency=new B;this.pendingWrites=new Map;this.nextPendingWriteId=0;this.currentTrack=e,this.stats={publicationId:"",mediaGeneration:0,accepted:0,queued:0,queuedBytes:0,queuedAgeMs:0,transmitted:0,dropped:0,bytes:0,maxQueued:0,maxQueuedBytes:0,maxQueuedAgeMs:0,lastError:void 0,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()};}get id(){return this.publicationId}get track(){return this.currentTrack}async start(){if(!this.currentTrack)return;this.stats.lastError=void 0;let e=new AbortController;this.abort=e;let t,r,l=new Promise((s,a)=>{t=s,r=a;});this.run=this.encode(this.currentTrack,e.signal,t).catch(s=>{throw e.signal.aborted||(this.stats.lastError=s instanceof Error?s.message:String(s)),r(s),s}),this.run.catch(()=>{});try{await l;}catch(s){throw e.abort(),await this.run.catch(()=>{}),s}}async replaceTrack(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),this.currentTrack=e,e&&await this.start();}async setEnabled(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.currentTrack&&(this.currentTrack.enabled=e);}async stop(){this.stopped||(this.stopped=true,this.abort?.abort(),await this.run?.catch(()=>{}),this.currentTrack=null,this.publicationId&&await this.runtime.retireOpenRtcMediaPublication(this.publicationId));}async restartForPhysicalGeneration(){this.stopped||!this.currentTrack||(this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),!this.stopped&&this.currentTrack&&await this.start());}async getStats(){return this.updatePendingWriteStats(),{...this.stats,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()}}updatePendingWriteStats(e=C()){for(let[r,l]of this.pendingWrites)e-l.acceptedAtMs<=J||(this.pendingWrites.delete(r),this.stats.dropped+=1);this.stats.queued=this.pendingWrites.size,this.stats.queuedBytes=[...this.pendingWrites.values()].reduce((r,l)=>r+l.bytes,0);let t=[...this.pendingWrites.values()].reduce((r,l)=>r===null||l.acceptedAtMs<r?l.acceptedAtMs:r,null);this.stats.queuedAgeMs=t===null?0:Math.max(0,e-t),this.stats.maxQueued=Math.max(this.stats.maxQueued,this.stats.queued),this.stats.maxQueuedBytes=Math.max(this.stats.maxQueuedBytes,this.stats.queuedBytes),this.stats.maxQueuedAgeMs=Math.max(this.stats.maxQueuedAgeMs,this.stats.queuedAgeMs);}async encode(e,t,r){let l=globalThis;if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let s=await ae(e),a=s.readable.getReader(),n=async()=>{await s.close?.();},d=()=>{a.cancel("media-generation-replaced");},o,c=new Promise(h=>{o=h;}),m=()=>o();t.addEventListener("abort",d,{once:true}),t.addEventListener("abort",m,{once:true});let y=null,k;try{k=await Promise.race([a.read(),new Promise((h,E)=>{y=setTimeout(()=>{E(new Error("[OpenRTC] media encoder startup timed out."));},ue);})]);}catch(h){throw await a.cancel("media-encoder-startup-failed").catch(()=>{}),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),h}finally{y&&clearTimeout(y);}if(k.done||!k.value||t.aborted)throw a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),new Error("[OpenRTC] media track ended before its encoder became ready.");let w=k.value,A=e.kind==="video"?"vp8":typeof l.AudioEncoder=="function"?"opus":"pcm",v=(this.options.codec??A).toLowerCase(),f=v.startsWith("avc1")?"h264":v.startsWith("av01")?"av1":v,u=e.kind==="audio"&&f==="pcm";if(f==="pcm"&&e.kind!=="audio")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] PCM is supported only for audio tracks.");let O=e.kind==="video"?l.VideoEncoder:l.AudioEncoder;if(!u&&typeof O!="function")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] WebCodecs encode support is required for compressed browser media.");let D={publicationId:this.publicationId,kind:e.kind,codec:f,clockRate:e.kind==="audio"?Number(w.sampleRate??48e3):1e6,codedWidth:e.kind==="video"?Number(w.displayWidth??w.codedWidth):void 0,codedHeight:e.kind==="video"?Number(w.displayHeight??w.codedHeight):void 0,channels:e.kind==="audio"?Number(w.numberOfChannels??2):void 0},G=Promise.resolve(),S=null,L=false,I=null,N=null,F=null,q=0,V=false,W=false,z=false,_=new Map,U=h=>N?(F??(F=N(h)),F):Promise.resolve(),Q=()=>{U("media-generation-replaced").catch(()=>{});},x=h=>{S===null&&(S=h),o(),a.cancel("media-sender-failed").catch(()=>{}),U("media-sender-failed").catch(()=>{});},K=()=>{L=true,o(),a.cancel("media-peer-receiver-stopped").catch(()=>{});},X=h=>{try{if(t.aborted||S){this.stats.dropped+=1;return}let E=Number(h.timestamp??0),T=_.get(E);T!==void 0&&(this.encodeLatency.observe(C()-T),_.delete(E));let b=e.kind==="video"?ke:Re,P=e.kind==="video"?Te:Se,M=new Uint8Array(h.byteLength);if(this.pendingWrites.size>=b||this.stats.queuedBytes+M.byteLength>P||!I){this.stats.dropped+=1;return}h.copyTo(M),this.stats.accepted+=1;let R=++this.nextPendingWriteId,te=C();this.pendingWrites.set(R,{bytes:M.byteLength,acceptedAtMs:te}),this.updatePendingWriteStats(te),G=G.then(async()=>{let $=this.pendingWrites.get(R);if(!$||t.aborted)return;if(C()-$.acceptedAtMs>J){this.pendingWrites.delete(R),this.stats.dropped+=1;return}if(this.updatePendingWriteStats(),!this.pendingWrites.has(R))return;let pe=await this.runtime.encodeOpenRtcMediaSample({publicationId:this.id,timestampUs:Number(h.timestamp??0),durationUs:Number(h.duration??0),keyframe:h.type==="key",discardable:e.kind==="video"&&h.type!=="key",payload:M});if(t.aborted||S)return;let Y=this.pendingWrites.get(R);if(!Y||C()-Y.acceptedAtMs>J){Y&&(this.pendingWrites.delete(R),this.stats.dropped+=1);return}this.pendingWrites.delete(R),this.updatePendingWriteStats();let me=C();await I.write(se(pe)),!(t.aborted||S)&&(this.protectedWriteLatency.observe(C()-me),this.stats.transmitted+=1,this.stats.bytes+=M.byteLength);}).catch($=>{We($)?K():x($);}).finally(()=>{this.pendingWrites.delete(R),this.updatePendingWriteStats();});}catch(E){x(E),this.stats.dropped+=1;}},g=u?null:new O({output:X,error:h=>{x(h);}}),j=e.kind==="video"?{codec:H(f),width:D.codedWidth,height:D.codedHeight,bitrate:this.options.bitrate??15e5,framerate:30,latencyMode:"realtime"}:{codec:H(f),sampleRate:D.clockRate,numberOfChannels:D.channels,bitrate:this.options.bitrate??96e3},p=h=>{try{if(t.aborted)return;if(u){let P=Number(h.timestamp??0);_.set(P,C());let M=Ge(h);X({timestamp:P,duration:Number(h.duration??0),type:"key",byteLength:M.byteLength,copyTo(R){R.set(M);}});return}let E=e.kind==="video"?4:8;if(g.encodeQueueSize>=E){this.stats.dropped+=1;return}let T=e.kind==="video"&&q%Pe===0;q+=1;let b=Number(h.timestamp??0);if(_.size>=64){let P=_.keys().next().value;P!==void 0&&_.delete(P);}_.set(b,C()),g.encode(h,e.kind==="video"?{keyFrame:T}:void 0);}finally{h.close?.();}};try{if(!u&&typeof O.isConfigSupported!="function")throw new Error("[OpenRTC] The browser cannot verify WebCodecs encoder support.");let h=u?null:await O.isConfigSupported(j);if(!u&&!h?.supported)throw new Error(`[OpenRTC] The browser cannot encode '${f}' for this track.`);let E=h?.config??j,T=await this.runtime.beginOpenRtcMediaPublication(D);V=!0,this.publicationId=T.publicationId,this.stats.publicationId=T.publicationId,this.stats.mediaGeneration=T.mediaGeneration;let b$1=await this.streams.createBidirectionalStream({protocol:ce});for(N=b(b$1.writable),I=b$1.writable.getWriter(),t.addEventListener("abort",Q,{once:!0}),t.aborted&&Q(),b$1.readable.cancel("media-v1-has-no-reverse-control").catch(()=>{}),await I.write(se(T.control)),g?.configure(E),r(),z=!0,p(w);!t.aborted&&!S&&!L;){let P=await a.read();if(P.done)break;P.value&&p(P.value);}if(!t.aborted&&!S&&!L&&(g&&await Promise.race([g.flush(),c]),!t.aborted&&!S&&!L&&await Promise.race([G,c])),S)throw S;if(L)await this.runtime.pauseOpenRtcMediaPublication(this.publicationId);else if(!t.aborted){let P=I.close();await Promise.race([P,c]),W=!t.aborted&&!S;}}catch(h){throw V&&!t.aborted&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),h}finally{if(t.removeEventListener("abort",d),t.removeEventListener("abort",m),t.removeEventListener("abort",Q),z||w.close?.(),a.releaseLock(),await n().catch(()=>{}),g&&g.state!=="closed")try{g.close?.();}catch{}if(I&&!W){let h=t.aborted?"media-generation-replaced":L?"media-peer-receiver-stopped":"media-sender-failed";await U(h).catch(()=>{}),await I.abort(h).catch(()=>{});}await G.catch(()=>{});try{I?.releaseLock();}catch{}}}},ee=class{constructor(e,t,r,l,s){this.id=e;this.track=t;this.stats=r;this.receiveToDecodeLatency=l;this.renderWriteLatency=s;}async getStats(){return {...this.stats,receiveToDecodeLatency:this.receiveToDecodeLatency.snapshot(),renderWriteLatency:this.renderWriteLatency.snapshot()}}},de=class{constructor(e,t,r,l=()=>({registered:true,peers:1,boundConnections:0,observed:0,accepted:0,declined:0,lastResolution:"none"})){this.streams=e;this.runtime=t;this.incomingDemux=l;this.senderMap=new Map;this.receiverMap=new Map;this.listeners=new Set;this.incomingRuns=new Map;this.receiverRuns=new Map;this.incomingFailures=[];this.incomingProtocolStreams=0;this.stopped=false;this.physicalGeneration=null;this.recoveryTail=Promise.resolve();this.stopIncoming=r(ce,s=>{if(this.incomingProtocolStreams+=1,this.stopped||this.incomingRuns.size>=Ae){s.readable.cancel("incoming-media-publication-limit").catch(()=>{}),s.writable.abort("incoming-media-publication-limit").catch(()=>{});return}let a=new AbortController,n=this.receivePublication(s.readable,s.writable,a);this.incomingRuns.set(a,n),n.catch(d=>{let o=d instanceof Error?d.message:String(d);this.incomingFailures.length===Oe&&this.incomingFailures.shift(),this.incomingFailures.push(o),console.error("[OpenRTC][media] incoming publication failed",{message:o});}).finally(()=>this.incomingRuns.delete(a));});}async addTrack(e,t={}){if(this.stopped)throw new Error("[OpenRTC] media connection is closed.");if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let r=new Z(e,t,this.streams,this.runtime);try{return await r.start(),this.senderMap.set(r.id,r),r}catch(l){throw await r.stop().catch(()=>{}),l}}async removeTrack(e){let t=this.senderMap.get(e.id);!t||t!==e||(this.senderMap.delete(e.id),await t.stop());}onTrack(e){return this.listeners.add(e),()=>this.listeners.delete(e)}senders(){return [...this.senderMap.values()]}receivers(){return [...this.receiverMap.values()]}async getStats(){return {senders:await Promise.all([...this.senderMap.values()].map(e=>e.getStats())),receivers:await Promise.all([...this.receiverMap.values()].map(e=>e.getStats())),incomingFailures:[...this.incomingFailures],incomingProtocolStreams:this.incomingProtocolStreams,incomingDemux:this.incomingDemux()}}async observePhysicalGeneration(e){if(this.stopped)return;if(Ie(e),this.physicalGeneration===null){this.physicalGeneration={...e};return}let t=this.physicalGeneration;if(!(e.transportGeneration<t.transportGeneration)){if(e.transportGeneration===t.transportGeneration){if(e.transportStableId!==t.transportStableId)throw new Error("[OpenRTC] media rejected an inconsistent physical generation tuple.");e.routeGeneration>t.routeGeneration&&(this.physicalGeneration={...e});return}if(e.transportStableId===t.transportStableId)throw new Error("[OpenRTC] media rejected a reused physical transport identity.");this.physicalGeneration={...e},this.recoveryTail=this.recoveryTail.catch(()=>{}).then(async()=>{if(!this.stopped)for(let r of this.senderMap.values())await r.restartForPhysicalGeneration();}),await this.recoveryTail;}}async close(){if(this.stopped)return;this.stopped=true,this.stopIncoming(),await this.recoveryTail.catch(()=>{}),await Promise.all([...this.senderMap.values()].map(t=>t.stop())),this.senderMap.clear(),this.listeners.clear();let e=[...this.incomingRuns.entries()];for(let[t]of e)t.abort();await Promise.allSettled(e.map(([,t])=>t)),this.incomingRuns.clear(),this.receiverRuns.clear();for(let t of this.receiverMap.values())t.track.stop();this.receiverMap.clear(),this.incomingFailures.splice(0);}async receivePublication(e,t,r){if(this.stopped){await e.cancel("media-connection-closed").catch(()=>{}),await t.abort("media-connection-closed").catch(()=>{});return}let l=xe(e,r.signal),s=null,a;try{a=await Promise.race([l.next(),new Promise((p,h)=>{s=setTimeout(()=>{h(new Error("[OpenRTC] incoming media control timed out."));},ue);})]);}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-failed").catch(()=>{}),await t.abort("incoming-media-control-failed").catch(()=>{}),p}finally{s&&clearTimeout(s);}if(a.done){await t.close().catch(()=>{});return}let n;try{let p=await this.runtime.decodeOpenRtcMediaControl(a.value);if(p.type!=="publish")throw new Error("[OpenRTC] media stream did not begin with publish control.");n=p;}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-invalid").catch(()=>{}),await t.abort("incoming-media-control-invalid").catch(()=>{}),p}let d=n.publicationId,o=async(p,h)=>{throw r.abort(),await l.return(void 0).catch(()=>{}),await this.runtime.retireOpenRtcMediaReceiver(d,n.mediaGeneration),await t.abort(p).catch(()=>{}),h},c=globalThis,m=n.kind==="audio"&&n.codec==="pcm",y=n.kind==="video"?c.VideoDecoder:c.AudioDecoder,k=n.kind==="video"?c.EncodedVideoChunk:c.EncodedAudioChunk;if(!m&&(typeof y!="function"||typeof k!="function"))return o("media-decoder-api-unavailable",new Error("[OpenRTC] WebCodecs decode support is required for browser media."));if(m&&typeof c.AudioData!="function")return o("media-pcm-api-unavailable",new Error("[OpenRTC] AudioData is required for PCM browser media."));let w=n.kind==="video"?{codec:H(n.codec),codedWidth:n.codedWidth,codedHeight:n.codedHeight,optimizeForLatency:true}:{codec:H(n.codec),sampleRate:n.clockRate,numberOfChannels:n.channels??2};if(!m&&typeof y.isConfigSupported!="function")return o("media-decoder-support-unverifiable",new Error("[OpenRTC] The browser cannot verify WebCodecs decoder support."));let A=null;try{m||(A=await y.isConfigSupported(w));}catch(p){return o("media-decoder-support-check-failed",p)}if(!m&&!A?.supported)return o("media-decoder-unsupported",new Error(`[OpenRTC] The browser cannot decode '${n.codec}'.`));let v,f;try{let p=await oe({kind:n.kind,sampleRate:n.clockRate,channels:n.channels??2,signal:r.signal});v=p.track,f=p.writable.getWriter();}catch(p){return o("media-renderer-setup-failed",p)}let u={publicationId:d,mediaGeneration:n.mediaGeneration,received:0,decoded:0,rendered:0,dropped:0,integrityFailures:0,malformedFrames:0,replayDrops:0,videoRecoveries:0,awaitingKeyframe:n.kind==="video",maxVideoRecoveryMs:0,bytes:0,decoderQueued:0,maxDecoderQueued:0,renderQueued:0,maxRenderQueued:0,receiveToDecodeLatency:new B().snapshot(),renderWriteLatency:new B().snapshot()},O=new B,D=new B,G=new Map,S=[],L=n.kind==="video",I=L,N=null,F=null,q=()=>{L&&(I=true,u.awaitingKeyframe=true,N===null&&(N=C()));},V=Promise.resolve(),W=null,z,_=new Promise(p=>{z=p;}),U=()=>{z(),f.abort("media-receiver-cancelled").catch(()=>{});};r.signal.addEventListener("abort",U,{once:true}),r.signal.aborted&&U();let Q=p=>{W===null&&(W=p),r.abort();},x=0,K=n.kind==="video"?Ce:Ee,X=(p,h=0)=>{if(r.signal.aborted||W){p.close?.();return}u.decoderQueued=h;let E=Number(p.timestamp??0),T=L?G.get(E):S.shift();if(T!==void 0&&(O.observe(C()-T),L&&G.delete(E)),x>=K){u.dropped+=1,p.close?.();return}x+=1,u.renderQueued=x,u.maxRenderQueued=Math.max(u.maxRenderQueued,x),V=V.then(async()=>{if(r.signal.aborted)return;let b=C();await f.write(p),D.observe(C()-b),u.decoded+=1,u.rendered+=1;}).catch(b=>{r.signal.aborted||Q(b);}).finally(()=>{p.close?.(),x-=1,u.renderQueued=x;});},g=null;try{m||(g=new y({output:p=>{X(p,Number(g?.decodeQueueSize??0));},error:p=>{r.signal.aborted||Q(p);}})),g?.configure(A?.config??w);}catch(p){r.signal.removeEventListener("abort",U),f.abort("media-decoder-setup-failed").catch(()=>{});try{f.releaseLock();}catch{}return v.stop(),o("media-decoder-setup-failed",p)}let j=new ee(d,v,u,O,D);try{let p=this.receiverRuns.get(d);if(p&&p.abort!==r&&p.mediaGeneration>=n.mediaGeneration)throw new Error(`[OpenRTC] stale media generation ${n.mediaGeneration} cannot replace ${p.mediaGeneration} for '${d}'.`);if(this.receiverRuns.set(d,{mediaGeneration:n.mediaGeneration,abort:r}),p&&p.abort!==r&&(p.abort.abort(),await this.incomingRuns.get(p.abort)?.catch(()=>{})),this.stopped||r.signal.aborted)return;let h=this.receiverMap.get(d);h&&h.track.stop(),this.receiverMap.set(d,j);let E=new MediaStream([v]);for(let T of this.listeners)try{T({track:v,receiver:j,streams:[E]});}catch{}for await(let T of l){if(r.signal.aborted||W||this.stopped)break;let b;try{b=await this.runtime.decodeOpenRtcMediaChunk(T);}catch(M){let R=String(M);/integrity/i.test(R)?(u.integrityFailures+=1,q()):/replay|retired/i.test(R)?u.replayDrops+=1:/truncated|invalidmagic|unsupported|chunktoolarge|too large|lengthmismatch/i.test(R)?(u.malformedFrames+=1,q()):u.dropped+=1;continue}if(r.signal.aborted||this.stopped)break;if(b.publicationId!==d||b.mediaGeneration!==n.mediaGeneration){u.dropped+=1;continue}if(F!==null&&b.sequence>F+1&&q(),F=F===null?b.sequence:Math.max(F,b.sequence),u.received+=1,u.bytes+=b.payload.byteLength,L&&I){if(!b.keyframe){u.dropped+=1;continue}if(N!==null){let M=C()-N;u.videoRecoveries+=1,u.maxVideoRecoveryMs=Math.max(u.maxVideoRecoveryMs,M),g?.reset?.(),g?.configure(A?.config??w);}I=!1,N=null,u.awaitingKeyframe=!1;}if((g?.decodeQueueSize??x)>=K){u.dropped+=1;continue}let P=C();if(L){if(G.size>=64){let M=G.keys().next().value;M!==void 0&&G.delete(M);}G.set(b.timestampUs,P);}else S.length>=64&&S.shift(),S.push(P);if(m){let M=n.channels??2,R=M*2;if(b.payload.byteLength===0||b.payload.byteLength%R!==0){u.dropped+=1;continue}X(new c.AudioData({format:"s16-planar",sampleRate:n.clockRate,numberOfFrames:b.payload.byteLength/R,numberOfChannels:M,timestamp:b.timestampUs,data:b.payload}));}else try{g.decode(new k({type:b.keyframe?"key":"delta",timestamp:b.timestampUs,duration:b.durationUs||void 0,data:b.payload}));}catch(M){Q(M);break}u.decoderQueued=Number(g?.decodeQueueSize??x),u.maxDecoderQueued=Math.max(u.maxDecoderQueued,u.decoderQueued);}if(!r.signal.aborted&&!W&&g&&await Promise.race([g.flush(),_]),!r.signal.aborted&&!W&&await Promise.race([V,_]),W)throw W}finally{r.signal.removeEventListener("abort",U);try{g?.close?.();}catch{}r.signal.aborted||W?f.abort("media-receiver-finished").catch(()=>{}):f.close().catch(()=>{});try{f.releaseLock();}catch{}this.receiverRuns.get(d)?.abort===r&&this.receiverRuns.delete(d),this.receiverMap.get(d)===j&&this.receiverMap.delete(d),await this.runtime.retireOpenRtcMediaReceiver(d,u.mediaGeneration),v.stop(),r.signal.aborted||W?t.abort("media-receiver-finished").catch(()=>{}):t.close().catch(()=>{});}}};export{se as a,de as b};
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-XK2JESZY.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function _(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var R=class R{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,R.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};R.PRESENCE_LEASE_MS=15*6e4;var M=R;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-H2DETG65.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:_(i),tokenFingerprint:_(r),tokenSuffixFingerprint:_(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new M({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async issueTicketMesh(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.issue_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return n.issue_ticket_mesh(e,t,i)}async joinTicketMesh(e,t){let i=await this.waitForWasmClient();if(typeof i?.join_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return i.join_ticket_mesh(e,t)}async receiveTicketMeshFrame(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.receive_ticket_mesh_frame!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");n.receive_ticket_mesh_frame(e,t,i);}async ticketMeshIssuerNode(e){let t=await this.waitForWasmClient();if(typeof t?.ticket_mesh_issuer_node!="function")throw new Error("WASM ticket mesh issuer projection is unavailable.");return t.ticket_mesh_issuer_node(e)}async closeTicketMesh(e){let t=await this.waitForWasmClient();if(typeof t?.close_ticket_mesh!="function")throw new Error("WASM runtime does not support closing Rust-owned ticket meshes.");await t.close_ticket_mesh(e);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i,e.timeoutMs??null);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,o)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let P=E(w,S,{requireFinish:true}).getWriter(),D=false;try{await P.write(y);let C=new Uint8Array(await i.arrayBuffer());for(let b=0;b<C.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=C.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await P.write(ie);}}catch(C){throw D=true,C}finally{try{await P.close();}catch(C){if(!D)throw C}finally{P.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
1
+ import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-XK2JESZY.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function _(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var R=class R{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,R.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};R.PRESENCE_LEASE_MS=15*6e4;var M=R;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-K6B3ZZIG.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:_(i),tokenFingerprint:_(r),tokenSuffixFingerprint:_(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new M({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async issueTicketMesh(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.issue_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return n.issue_ticket_mesh(e,t,i)}async joinTicketMesh(e,t){let i=await this.waitForWasmClient();if(typeof i?.join_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return i.join_ticket_mesh(e,t)}async receiveTicketMeshFrame(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.receive_ticket_mesh_frame!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");n.receive_ticket_mesh_frame(e,t,i);}async ticketMeshIssuerNode(e){let t=await this.waitForWasmClient();if(typeof t?.ticket_mesh_issuer_node!="function")throw new Error("WASM ticket mesh issuer projection is unavailable.");return t.ticket_mesh_issuer_node(e)}async closeTicketMesh(e){let t=await this.waitForWasmClient();if(typeof t?.close_ticket_mesh!="function")throw new Error("WASM runtime does not support closing Rust-owned ticket meshes.");await t.close_ticket_mesh(e);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i,e.timeoutMs??null);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,o)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let P=E(w,S,{requireFinish:true}).getWriter(),D=false;try{await P.write(y);let C=new Uint8Array(await i.arrayBuffer());for(let b=0;b<C.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=C.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await P.write(ie);}}catch(C){throw D=true,C}finally{try{await P.close();}catch(C){if(!D)throw C}finally{P.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};