openrtc 2.8.9 → 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 (61) hide show
  1. package/dist/BrowserManagedBroadcastHost-FTKYCKLF.js +1 -0
  2. package/dist/{IpcRuntimeAdapter-Cp2QsHX2.d.ts → IpcRuntimeAdapter-BVTYrfIe.d.ts} +2 -0
  3. package/dist/{NativeManagedBroadcastHost-WCQ6TPUU.js → NativeManagedBroadcastHost-6A2QP3A7.js} +1 -1
  4. package/dist/NativeProjectionBroker-2OH2SCPF.js +1 -0
  5. package/dist/WasmBridge-QUACJ7JY.js +1 -0
  6. package/dist/chunk-3B4IDT2M.js +1 -0
  7. package/dist/{chunk-T3G55YPI.js → chunk-3PDMPSVP.js} +1 -1
  8. package/dist/{chunk-H4XCP4Z4.js → chunk-6CHYSTXL.js} +1 -1
  9. package/dist/chunk-7KWWA3M6.js +2 -0
  10. package/dist/{chunk-EUVLZSGT.js → chunk-BG7VCJ5V.js} +1 -1
  11. package/dist/chunk-COXQYBTI.js +1 -0
  12. package/dist/chunk-FIWTJQJA.js +2 -0
  13. package/dist/{chunk-LLZT3MR6.js → chunk-FKAQDDUM.js} +1 -1
  14. package/dist/chunk-ONV44QWS.js +1 -0
  15. package/dist/{chunk-RCQ6MLBL.js → chunk-Q7ZKAI5S.js} +1 -1
  16. package/dist/chunk-RT7YTAXU.js +1 -0
  17. package/dist/chunk-WALOTASO.js +2 -0
  18. package/dist/chunk-XK2JESZY.js +2 -0
  19. package/dist/chunk-ZFSJ2LEF.js +1 -0
  20. package/dist/controlPlane-HPGXZDDD.js +1 -0
  21. package/dist/deviceEnrollment-ZRMFBH5R.js +2 -0
  22. package/dist/deviceHandle-R7WWNAG7.js +1 -0
  23. package/dist/index.js +1 -1
  24. package/dist/ipcFactory-FYLQKIJ2.js +1 -0
  25. package/dist/native.js +1 -1
  26. package/dist/node.js +2 -2
  27. package/dist/{openrtc-H2DETG65.js → openrtc-K6B3ZZIG.js} +1 -1
  28. package/dist/openrtc_bg.wasm +0 -0
  29. package/dist/room-QWTKWEAZ.js +1 -0
  30. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  31. package/dist/runtime/factories.d.ts +1 -1
  32. package/dist/runtime/factories.js +1 -1
  33. package/dist/runtime/index.d.ts +1 -1
  34. package/dist/runtime/index.js +1 -1
  35. package/dist/server.js +1 -1
  36. package/dist/service-node.js +1 -1
  37. package/dist/testing/native.js +1 -1
  38. package/dist/testing.d.ts +20 -1
  39. package/dist/testing.js +1 -1
  40. package/native/darwin-arm64/openrtc-node-host +0 -0
  41. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  42. package/native/darwin-x64/openrtc-node-host +0 -0
  43. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  44. package/native/linux-x64/openrtc-node-host +0 -0
  45. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  46. package/package.json +1 -1
  47. package/dist/BrowserManagedBroadcastHost-ARCP5MGJ.js +0 -1
  48. package/dist/WasmBridge-QNS6SWNZ.js +0 -1
  49. package/dist/chunk-577A77JB.js +0 -2
  50. package/dist/chunk-67RYEH6T.js +0 -1
  51. package/dist/chunk-ESBROG6S.js +0 -2
  52. package/dist/chunk-IR5VXG3N.js +0 -1
  53. package/dist/chunk-LAL63F6X.js +0 -2
  54. package/dist/chunk-OC4VXLX7.js +0 -1
  55. package/dist/chunk-WD2FZUOM.js +0 -1
  56. package/dist/chunk-WD47V4PK.js +0 -2
  57. package/dist/controlPlane-C5RUPLAM.js +0 -1
  58. package/dist/deviceEnrollment-27EVK3E3.js +0 -2
  59. package/dist/deviceHandle-2T6HQ253.js +0 -1
  60. package/dist/ipcFactory-DOEPQPOP.js +0 -1
  61. package/dist/room-JIU2XJZX.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};
@@ -69,6 +69,8 @@ declare class NativeProjectionBroker {
69
69
  private hostPump;
70
70
  private consecutiveEstablishedFaults;
71
71
  private closed;
72
+ private failedHostRelease;
73
+ private closeAttempt;
72
74
  register(capabilityKey: string, host: NativeProjectionHost): NativeProjectedStreamSource;
73
75
  unregister(capabilityKey: string): void;
74
76
  private subscribeState;
@@ -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};
@@ -0,0 +1 @@
1
+ export{a as NativeProjectionBroker}from'./chunk-RT7YTAXU.js';import'./chunk-COXQYBTI.js';import'./chunk-WALOTASO.js';
@@ -0,0 +1 @@
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';
@@ -0,0 +1 @@
1
+ import {a as a$1,d as d$1,e,c}from'./chunk-WALOTASO.js';var o={...a$1,AUTH_NOT_READY:"auth/not-ready",AUTH_DENIED:"auth/denied",AUTH_EXPIRED:"auth/expired",AUTH_DEVICE_REENROLLMENT_REQUIRED:"auth/device-reenrollment-required",ADMISSION_DENIED:"admission/denied",ADMISSION_SCOPE_MISMATCH:"admission/scope-mismatch",TICKET_INVITE_INVALID:"admission/ticket-invite-invalid",TICKET_MESH_INVALID_OPTIONS:"admission/ticket-mesh-invalid-options",TICKET_MESH_CAPACITY_EXCEEDED:"admission/ticket-mesh-capacity-exceeded",TICKET_MESH_ALREADY_ACTIVE:"admission/ticket-mesh-already-active",ROOM_ARCHITECTURE_UNAVAILABLE:"room-architecture-unavailable",BUDGET_EXCEEDED:"budget/exceeded",BUDGET_STALE:"budget/stale",BUDGET_RENEWAL_REQUIRED:"budget/renewal-required",COORDINATION_DISCONNECTED:"coordination/disconnected",COORDINATION_PROTOCOL:"coordination/protocol",COORDINATION_RATE_LIMITED:"coordination/rate-limited",COORDINATION_SERVICE_UNAVAILABLE:"coordination/service-unavailable",TICKET_MESH_UNAVAILABLE:"coordination/ticket-mesh-unavailable",TRANSPORT_DIAL_EXHAUSTED:"transport/dial-exhausted",TRANSPORT_UNAVAILABLE:"transport/unavailable",TRANSPORT_TICKET_MISSING:"transport/ticket-missing",DELIVERY_NOT_READY:"delivery/not-ready",INTERNAL:"internal/error"},a=class e$1 extends Error{constructor(r){super(r.message);this.name="RTCError";r.cause!==void 0&&(this.cause=r.cause),this.code=r.code,this.retryable=r.retryable,this.plane=r.plane,this.generation=r.generation,this.transportGeneration=r.transportGeneration,this.routeGeneration=r.routeGeneration,this.revision=r.revision,d$1(r.code)&&Object.assign(this,e(r));}static is(r){return r instanceof e$1||typeof r=="object"&&r!==null&&r.name==="RTCError"&&typeof r.code=="string"&&typeof r.retryable=="boolean"&&typeof r.plane=="string"}static shouldAppRetry(r){let t=O(r);return t.retryable?t.plane==="coordination"||t.plane==="transport"||t.plane==="auth":false}toJSON(){return {name:this.name,code:this.code,message:this.message,retryable:this.retryable,plane:this.plane,generation:this.generation??null,transportGeneration:this.transportGeneration??null,routeGeneration:this.routeGeneration??null,revision:this.revision??null,...d$1(this.code)?e(this):{}}}};function S(e$1){let n=O(e$1);return {errorCode:n.code,retryable:n.retryable,errorPlane:n.plane,...d$1(n.code)?e(n):{}}}function d(e$1,n,r){let t=C(e$1);return new a({code:e$1,message:n,retryable:r.retryable??t.retryable,plane:r.plane??t.plane,cause:r.cause,generation:r.generation,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,revision:r.revision,...e(r)})}function C(e){if(String(e).endsWith("-rate-limited"))return {retryable:true,plane:"coordination"};if(e===o.ROOM_CAPACITY_EXCEEDED||e===o.ROOM_ARCHITECTURE_UNAVAILABLE)return {retryable:false,plane:"admission"};let n=String(e).split("/",1)[0],r=d$1(e)?"budget":["auth","admission","budget","coordination","transport","delivery"].includes(n)?n:"internal";return {retryable:r==="transport"||r==="delivery"||r==="auth"&&e!==o.AUTH_DENIED||r==="coordination"&&e!==o.COORDINATION_PROTOCOL||r==="budget"&&[o.USAGE_PRICE_STALE,o.BUDGET_STALE,o.BUDGET_RENEWAL_REQUIRED].includes(e),plane:r}}function i(e,n,r){return new a({code:e,message:n,...C(e),cause:r})}function O(e$1){if(a.is(e$1))return e$1 instanceof a?e$1:new a({code:e$1.code,message:e$1.message||String(e$1),retryable:e$1.retryable,plane:e$1.plane,cause:e$1,generation:e$1.generation,transportGeneration:e$1.transportGeneration,routeGeneration:e$1.routeGeneration,revision:e$1.revision,...e(e$1)});if(typeof e$1=="object"&&e$1!==null){let r=e$1,t=typeof r.code=="string"?r.code:"",u=typeof r.message=="string"?r.message:typeof r.error=="string"?r.error:e$1 instanceof Error?e$1.message:String(e$1),T=typeof r.retryable=="boolean"?r.retryable:void 0,p=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:null,I=p&&c(p.code),y=c(t),c$1=I?p:y?e$1:null,l=I||y;if(c$1&&l)return new a({...C(l.code),code:l.code,message:u,cause:e$1,retryable:typeof c$1.retryable=="boolean"?c$1.retryable:!!l.scope,...e(c$1),...l.scope?{scope:l.scope}:{}});if(t){let b=f(t,u,T);if(b)return b}if(typeof r.name=="string"&&r.name==="CoordinationConnectError")return d(o.COORDINATION_DISCONNECTED,u,{retryable:T??true,plane:"coordination",cause:e$1});if(typeof r.name=="string"&&r.name==="CoordinationGatewayProtocolError")return d(t||o.COORDINATION_PROTOCOL,u,{retryable:T??false,plane:_(t),cause:e$1})}let n=e$1 instanceof Error?e$1.message:String(e$1??"unknown error");return D(n,e$1)}function f(e,n,r){let t=e.trim().toLowerCase();return t===o.ROOM_ARCHITECTURE_UNAVAILABLE?i(o.ROOM_ARCHITECTURE_UNAVAILABLE,n):t==="unauthenticated"||t==="functions/unauthenticated"||t==="auth/unauthorized"||t.includes("permission-denied")?i(o.AUTH_DENIED,n):t==="budget-renewal-required"||t==="budget/renewal-required"?d(o.BUDGET_RENEWAL_REQUIRED,n,{retryable:r??true,plane:"budget"}):t.includes("resource-exhausted")||t.includes("budget")||t==="budget-exceeded"||t==="insufficient-budget"?t.includes("stale")||/stale-budget/i.test(n)?d(o.BUDGET_STALE,n,{retryable:r??true,plane:"budget"}):i(o.BUDGET_EXCEEDED,n):t.includes("rate-limit")||t==="rate_limited"||t==="too-many-requests"?d(o.COORDINATION_RATE_LIMITED,n,{retryable:r??true,plane:"coordination"}):t.includes("admission")||t==="permission-denied"||t==="session-token-denied"?i(o.ADMISSION_DENIED,n):t.includes("scope")?i(o.ADMISSION_SCOPE_MISMATCH,n):t.includes("disconnect")||t.includes("unavailable")||t==="aborted"?d(o.COORDINATION_DISCONNECTED,n,{retryable:r??true,plane:"coordination"}):t.startsWith("coordination/")||t.includes("protocol")?d(e,n,{retryable:r??false,plane:_(e)}):null}function _(e){let n=e.trim().toLowerCase();return n.includes("budget")?"budget":n.includes("auth")?"auth":n.includes("admission")||n.includes("scope")?"admission":"coordination"}function D(e,n){return /auth(?:entication)?\s*(?:not ready|pending|missing)/i.test(e)||/token\s*(?:not ready|pending|missing)/i.test(e)||/awaiting[- ]auth/i.test(e)?i(o.AUTH_NOT_READY,e,n):/missing endpoint ticket|ticket missing/i.test(e)?i(o.TRANSPORT_TICKET_MISSING,e,n):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(e)?i(o.TRANSPORT_DIAL_EXHAUSTED,e,n):/stale[- ]budget/i.test(e)?i(o.BUDGET_STALE,e,n):/budget|credit|quota|limit\s*exceeded/i.test(e)?i(o.BUDGET_EXCEEDED,e,n):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(e)?i(o.ADMISSION_DENIED,e,n):/not\s+application-routable|not[- ]ready|settledReady/i.test(e)?i(o.DELIVERY_NOT_READY,e,n):/gateway|coordination|websocket|signaling/i.test(e)?i(o.COORDINATION_DISCONNECTED,e,n):i(o.INTERNAL,e,n)}export{o as a,a as b,S as c,d,O as e};
@@ -1 +1 @@
1
- import {t}from'./chunk-WD47V4PK.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async issueTicketInvite(e,t,n){let i=this.backend;if(typeof i.issueTicketInvite!="function")throw new Error("Selected runtime adapter does not support ticket invitations.");return i.issueTicketInvite(e,t,n)}async issueTicketMesh(e,t,n){let i=this.backend;if(typeof i.issueTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return i.issueTicketMesh(e,t,n)}async joinTicketMesh(e,t){let n=this.backend;if(typeof n.joinTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return n.joinTicketMesh(e,t)}async onTicketMeshInvite(e,t){let n=this.backend;if(typeof n.onTicketMeshInvite!="function")throw new Error("Selected runtime adapter does not support ticket mesh invitation updates.");return n.onTicketMeshInvite(e,t)}async receiveTicketMeshFrame(e,t,n){let i=this.backend;if(typeof i.receiveTicketMeshFrame!="function")throw new Error("Selected runtime adapter does not support ticket mesh frames.");await i.receiveTicketMeshFrame(e,t,n);}async ticketMeshIssuerNode(e){let t=this.backend;if(typeof t.ticketMeshIssuerNode!="function")throw new Error("Selected runtime adapter does not support ticket mesh issuer lookup.");return t.ticketMeshIssuerNode(e)}async closeTicketMesh(e){let t=this.backend;if(typeof t.closeTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket mesh teardown.");await t.closeTicketMesh(e);}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
1
+ import {t}from'./chunk-XK2JESZY.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async issueTicketInvite(e,t,n){let i=this.backend;if(typeof i.issueTicketInvite!="function")throw new Error("Selected runtime adapter does not support ticket invitations.");return i.issueTicketInvite(e,t,n)}async issueTicketMesh(e,t,n){let i=this.backend;if(typeof i.issueTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return i.issueTicketMesh(e,t,n)}async joinTicketMesh(e,t){let n=this.backend;if(typeof n.joinTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return n.joinTicketMesh(e,t)}async onTicketMeshInvite(e,t){let n=this.backend;if(typeof n.onTicketMeshInvite!="function")throw new Error("Selected runtime adapter does not support ticket mesh invitation updates.");return n.onTicketMeshInvite(e,t)}async receiveTicketMeshFrame(e,t,n){let i=this.backend;if(typeof i.receiveTicketMeshFrame!="function")throw new Error("Selected runtime adapter does not support ticket mesh frames.");await i.receiveTicketMeshFrame(e,t,n);}async ticketMeshIssuerNode(e){let t=this.backend;if(typeof t.ticketMeshIssuerNode!="function")throw new Error("Selected runtime adapter does not support ticket mesh issuer lookup.");return t.ticketMeshIssuerNode(e)}async closeTicketMesh(e){let t=this.backend;if(typeof t.closeTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket mesh teardown.");await t.closeTicketMesh(e);}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
@@ -1,2 +1,2 @@
1
- import {j,d as d$1,c}from'./chunk-IR5VXG3N.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};
@@ -0,0 +1,2 @@
1
+ import {b as b$2}from'./chunk-ZA44REGI.js';import {e}from'./chunk-3B4IDT2M.js';import {d,b as b$1,e as e$1}from'./chunk-WALOTASO.js';function b(s){return {irohRelay:s.irohRelay===true||s.irohRelay===void 0&&s.relay!==false,managedTurn:s.managedTurn===true}}var M=1440*6e4,w=class extends Error{constructor(r,n,a){super(r);this.status=n;this.reason=a;this.name="RTCError";let t=[502,503,504].includes(n),o=a==="device-reenrollment-auth-required";this.code=o?"auth/device-reenrollment-required":t?"coordination/service-unavailable":n===429?"coordination/rate-limited":n===401?"auth/expired":n===403?"admission/denied":"internal/error",this.retryable=o||t,this.plane=o||n===401?"auth":t||n===429?"coordination":n===403?"admission":"internal";}};function T(s){return !(s instanceof w)||s.status!==403?false:s.reason==="device-certificate-stale"||s.reason==="device-certificate-revoked"?true:!s.reason&&s.message==="Device certificate is revoked or stale."}function P(s,e,r){return `openrtc:v2:device-certificate:${s}:${e}:${r}`}function C(s,e){return `openrtc:v2:device-session:${s}:${e}`}async function G(s,e,r){let n=new TextEncoder().encode(`openrtc:v2:session\0${s}\0${e}\0${r}`),a=new Uint8Array(await crypto.subtle.digest("SHA-256",n)),t="";for(let o of a)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function k(s){let e=s.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=atob(r);return Uint8Array.from(n,a=>a.charCodeAt(0))}function f(s){let e="";for(let r of s)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function B(s,e,r,n,a){if(typeof s.token!="string"||typeof s.expiresAtMs!="number"||s.expiresAtMs<=Date.now()+M||!s.signingPublicJwk||s.signingPublicJwk.kty!=="OKP"||s.signingPublicJwk.crv!=="Ed25519"||typeof s.signingPublicJwk.x!="string")return null;let t=s.token.split(".");if(t.length!==3)return null;let o,i;try{o=JSON.parse(new TextDecoder().decode(k(t[0]))),i=b$2(s.token);}catch{return null}if(o.alg!=="EdDSA"||s.signingPublicJwk.kid&&o.kid!==s.signingPublicJwk.kid)return null;try{let y=await crypto.subtle.importKey("jwk",s.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},y,k(t[2]),new TextEncoder().encode(`${t[0]}.${t[1]}`)))return null}catch{return null}let c=typeof i.principalId=="string"?i.principalId:"",l=Number(i.iat),u=Number(i.exp);if(i.iss!=="openrtc"||i.aud!=="openrtc:v2:gateway-grant"||i.typ!=="device-certificate"||i.appTag!==e||!c||a!==void 0&&c!==a||typeof i.principalKey!="string"||i.principalKey.length===0||i.deviceId!==r||i.deviceKeyThumbprint!==n||typeof i.jti!="string"||i.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||l>=u||u*1e3!==s.expiresAtMs)return null;let d=b(i);return {token:s.token,expiresAtMs:s.expiresAtMs,principalId:c,signingPublicJwk:s.signingPublicJwk,enrolled:false,...d}}async function J(s,e,r,n,a){try{let t=P(e,r,n),o=s.readSecureRecord?await s.readSecureRecord(e,t):globalThis.localStorage?.getItem(t);if(!o)return null;let i=JSON.parse(o),c=await B(i,e,n,a,r);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:r,signingPublicJwk:c.signingPublicJwk}:null}catch(t){if(s.readSecureRecord)throw t;return null}}async function O(s,e,r,n,a){try{let t=C(e,n),o=s.readSecureRecord?await s.readSecureRecord(r,t):globalThis.localStorage?.getItem(t);return o?await B(JSON.parse(o),r,n,a):null}catch(t){if(s.readSecureRecord)throw t;return null}}async function _(s,e,r,n,a){try{let t=P(e,r,n),o=JSON.stringify(a);s.writeSecureRecord?await s.writeSecureRecord(e,t,o):globalThis.localStorage?.setItem(t,o);}catch(t){if(s.writeSecureRecord)throw t}}async function $(s,e,r,n,a){try{let t=C(r,n),o=JSON.stringify({token:a.token,expiresAtMs:a.expiresAtMs,principalId:a.principalId,signingPublicJwk:a.signingPublicJwk});s.writeSecureRecord?await s.writeSecureRecord(e,t,o):globalThis.localStorage?.setItem(t,o);}catch(t){if(s.writeSecureRecord)throw t}}async function A(s,e,r,n,a){try{let t=P(e,r,n);if(s.deleteSecureRecord?await s.deleteSecureRecord(e,t):globalThis.localStorage?.removeItem(t),a){let o=C(a,n);s.deleteSecureRecord?await s.deleteSecureRecord(e,o):globalThis.localStorage?.removeItem(o);}}catch(t){if(s.deleteSecureRecord)throw t}}function x(s){return `${s}_${crypto.randomUUID()}`}function U(s){if(s instanceof TypeError)return true;if(!s||typeof s!="object")return false;let e=Reflect.get(s,"name");return e==="TimeoutError"||e==="AbortError"}async function j(s,e){let r=new TextEncoder().encode(`${s}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",r))].map(a=>a.toString(16).padStart(2,"0")).join("")}var K=class{constructor(e,r,n,a,t={},o){this.apiKey=e;this.endpoints=r;this.keyProvider=n;this.attestation=a;this.events=t;this.botVerification=o;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let r=this.authEpochs.get(e);if(r)return r;let n={generation:0,devices:new Map};return this.authEpochs.set(e,n),e.subscribe&&(n.unsubscribe=e.subscribe(a=>{a?.type==="principal-changed"&&(n.generation+=1,n.devices.clear(),n.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),n}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async deviceSigningPublicKey(){return (await this.key()).publicKeyJwk}async signDeviceBytes(e){return (await this.key()).sign(e)}async resolveBroadcastAccess(e,r){if(!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e)||e.length>32768)throw new Error("Broadcast grant is invalid.");if(r&&r.byteLength!==32)throw new Error("Broadcast publisher verification key is invalid.");let n=await this.key(),a=f(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))),t=r?f(r):"",o=await n.proof((u,d)=>["openrtc:v2:broadcast-access",this.apiKey,a,t,u,d].join(":")),i=await this.post("/v2/broadcasts",{action:"access",grant:e,...t?{publicationVerifyingKey:t}:{},deviceProof:o});if(i.grant!==e)throw new Error("Broadcast access grant mismatch.");let c=k(i.issuerPublicKey);if(c.byteLength!==32)throw new Error("Broadcast issuer key is invalid.");let l=new URL(i.relay?.relayUrl);if(l.protocol!=="https:"||l.username||l.password)throw new Error("Broadcast relay URL is invalid.");if(typeof i.relay.token!="string"||!/^[A-Za-z0-9._-]{16,16384}$/.test(i.relay.token)||typeof i.relay.namespace!="string"||!/^[A-Za-z0-9._/-]{1,512}$/.test(i.relay.namespace))throw new Error("Broadcast relay allocation is invalid.");return {token:e,issuerPublicKey:c,signBindingChallenge:async u=>{if(!(u instanceof Uint8Array)||u.byteLength>2048)throw new Error("Broadcast binding challenge is invalid.");return k(await n.sign(u))},relay:{relayUrl:l.toString(),token:i.relay.token,namespace:i.relay.namespace}}}async manageBroadcast(e){let r=await this.deviceCertificate(e.auth,e.deviceId),n=e.grant??"",a=e.invite??"",t=e.create,o=e.invitation,i=t?f(t.publisher.verificationKey):o?.publicationVerificationKey?f(o.publicationVerificationKey):"",c=t?{maxPublishers:t.maxPublishers,maxSubscribers:t.maxSubscribers,maxBitrateBps:t.maxBitrateBps,maxDurationSeconds:t.maxDurationSeconds,maxEgressBytes:t.maxEgressBytes}:void 0,l=t?{bitrateBps:t.publisherBitrateBps,durationSeconds:t.maxDurationSeconds,reservedEgressBytes:t.reservedEgressBytes}:o?{role:o.role,sourceSlot:o.sourceSlot??"",bitrateBps:o.bitrateBps,durationSeconds:o.durationSeconds,reservedEgressBytes:o.reservedEgressBytes}:void 0,u=f(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({action:e.action,grant:n,invite:a,publicationKey:i,sourceSlot:t?.sourceSlot??o?.sourceSlot??"host-a",limits:c,reservation:l}))))),y=await(await this.key()).proof((v,g)=>["openrtc:v2:broadcast-manage",r.source.token,e.action,u,v,g].join(":")),p=await this.post("/v2/broadcasts",{action:e.action,deviceId:e.deviceId,deviceCertificate:r.source.token,deviceProof:y,...n?{grant:n}:{},...a?{invite:a}:{},...i?{publicationVerifyingKey:i}:{},...t?{sourceSlot:t.sourceSlot??"host-a",limits:c,reservation:l}:{},...o?{invitation:{...l,publicationVerifyingKey:i}}:{}});if(e.action==="create"||e.action==="renew"){if(typeof p.grant!="string"||!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.grant))throw new Error("Managed broadcast grant is invalid.");return p.grant}if(e.action==="invite"){if(typeof p.invite!="string"||!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.invite))throw new Error("Managed broadcast invitation is invalid.");return p.invite}if(e.action==="accept"){if(typeof p.grant!="string"||!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.grant))throw new Error("Managed broadcast accepted grant is invalid.");return p.grant}}async post(e$2,r){let n=x("request"),a=JSON.stringify({apiKey:this.apiKey,...r}),t=null;for(let o=0;o<2;o+=1)try{let i=await fetch(`${this.endpoints.controlPlane}${e$2}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":n},body:a,signal:AbortSignal.timeout(15e3)});if(i.ok)return i.json();let c=`OpenRTC request failed (${i.status}).`,l,u;try{let y=await i.json();typeof y.error=="string"&&(c=y.error.slice(0,256)),typeof y.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(y.reason)&&(l=y.reason),(d(y.code)||b$1(y.code))&&(u=e({...e$1(y),code:y.code,message:c,retryable:y.retryable}));}catch{}let d$1=u?Object.assign(u,{status:i.status,reason:l}):new w(c,i.status,l);if(t=d$1,!u&&o===0&&[502,503,504].includes(i.status))continue;throw d$1}catch(i){if(t=i,o===0&&U(i))continue;throw i}throw t instanceof Error?t:new Error("OpenRTC request failed.")}async capability(e,r,n,a=false,t,o){this.before("capability.issue");let i=e==="space"?await j(this.apiKey,r):r,l=await(await this.key()).proof((p,v)=>["openrtc:v2:capability",this.apiKey,e,i,p,v].join(":")),u=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,d=await this.post("/v2/capabilities",{avenue:{kind:e,id:i},deviceProof:l,...n?{maxPeers:n}:{},...a?{advancedFanout:true}:{},...e==="room"&&t?{architecture:t}:{},...e==="room"&&o?{roomDelivery:o}:{},...u?{turnstileToken:u}:{}});this.record("capability.issue");let y={type:"capability",token:d.capability,avenue:e==="ticket"?{kind:"session",id:i}:d.avenue,expiresAtMs:d.expiresAt*1e3,...b(d)};return y.renew=()=>this.capability(e,r,n,a,t,o),y}async deviceCertificate(e,r,n,a,t){if(this.keyProvider.persistence==="session")throw new Error("[OpenRTC] Durable browser device enrollment requires trust.browserPersistence: persistent. Select it explicitly before creating the client; session keys cannot enroll retained devices.");let o=this.authEpoch(e),i=o.devices.get(r)??{};if(o.devices.set(r,i),t&&i.current&&i.current.token!==t.token)return this.deviceCertificateResult(e,r,n,a,{...i.current,enrolled:false});if(!t&&i.current&&i.current.expiresAtMs>Date.now()+M)return this.deviceCertificateResult(e,r,n,a,{...i.current,enrolled:false});if(!i.inFlight){let l=o.generation;t&&(i.current=void 0,i.recoverRevokedEnrollment=true);let u=t?A(this.keyProvider,this.appTag,t.principalId,r,o.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(e,r,o.sessionKeyHash,a,true)):this.resolveAuthenticatedDevice(e,r,o,a,i.recoverRevokedEnrollment===true);i.inFlight=u.then(d=>{if(o.generation!==l)throw new Error("The OpenRTC authentication identity changed during enrollment.");return i.recoverRevokedEnrollment=false,i.current=d,d}).finally(()=>{i.inFlight=void 0;});}let c=await i.inFlight;return this.deviceCertificateResult(e,r,n,a,c)}async resolveAuthenticatedDevice(e,r,n,a,t=false){let o=await this.key();if(e.getSessionKey){let i=await e.getSessionKey();if(!i)throw new Error("The OpenRTC auth provider has no active principal.");let c=await G(this.appTag,o.thumbprint,i);n.sessionKeyHash=c;let l=await O(this.keyProvider,c,this.appTag,r,o.thumbprint);if(l)return l}return this.enrollAuthenticatedDevice(e,r,n.sessionKeyHash,a,t)}deviceCertificateResult(e,r,n,a,t){let o={type:"device-certificate",token:t.token,avenue:n??{kind:"user",id:t.principalId},expiresAtMs:t.expiresAtMs,irohRelay:t.irohRelay,managedTurn:t.managedTurn};return o.renew=async()=>(await this.deviceCertificate(e,r,n,a)).source,o.recoverRejectedCertificate=async()=>(await this.deviceCertificate(e,r,n,a,t)).source,{principalId:t.principalId,source:o,enrolled:t.enrolled}}async enrollAuthenticatedDevice(e,r,n,a,t=false){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let o=async(v,g)=>{let m=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:v,deviceId:r,...{}});if(!m)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:m,deviceId:r,...e.providerId?{providerId:e.providerId}:{}})},i;try{i=await o(!1);}catch(v){if(!(v instanceof w)||v.status!==401)throw v;i=await o(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let c=await this.key(),l=await J(this.keyProvider,this.appTag,i.principalId,r,c.thumbprint);if(l)return {...l,principalId:i.principalId,enrolled:false,...b(i)};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let{enrollDevice:u}=await import('./deviceEnrollment-ZRMFBH5R.js'),d=await u({apiKey:this.apiKey,appTag:this.appTag,auth:e,attestation:this.attestation,deviceId:r,identity:i,key:c,profile:a,recoverRevokedEnrollment:t||i.deviceRecoveryAuthorized===true,post:(v,g)=>this.post(v,g),recordAssertionExchange:()=>this.record("identity.assertion.exchange")});i=d.identity;let y=d.enrollment;this.record("device.enroll"),this.attestation&&this.record("security.attestation.verify");let p={principalId:i.principalId,token:y.deviceCertificate,expiresAtMs:y.expiresAt*1e3,signingPublicJwk:y.signingPublicJwk,enrolled:true,...b(i)};return await _(this.keyProvider,this.appTag,i.principalId,r,{token:p.token,expiresAtMs:p.expiresAtMs,signingPublicJwk:p.signingPublicJwk}),n&&await $(this.keyProvider,this.appTag,n,r,p),p}async listEnrolledDevices(e,r){let n=await this.deviceCertificate(e,r);return (await this.deviceManagement(n.source,r,"list")).devices??[]}async revokeDevice(e,r,n){let a=await this.deviceCertificate(e,r);if(await this.deviceManagement(a.source,r,"revoke",n),n===r){let t=this.authEpoch(e);await A(this.keyProvider,this.appTag,a.principalId,r,t.sessionKeyHash),t.devices.delete(r),await this.deleteDeviceKey();}}async revokeAllDevices(e,r,n){let a=await this.deviceCertificate(e,r);await this.deviceManagement(a.source,r,"revoke-all",void 0,n);let t=this.authEpoch(e);await A(this.keyProvider,this.appTag,a.principalId,r,t.sessionKeyHash),t.devices.delete(r),n?await this.deviceCertificate(e,r):(t.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,r,n,a,t=false){let o=n==="revoke"?"device.revoke":n==="revoke-all"?"identity.revoke-all":null;o&&this.before(o);let{manageDevice:i}=await import('./deviceManagement-SUMBRXXC.js'),c=await i({source:e,currentDeviceId:r,action:n,targetDeviceId:a,exceptCurrent:t,key:()=>this.key(),post:l=>this.post("/v2/devices/manage",l),isStale:T});return o&&this.record(o),c}async durableRoomMembership(e,r,n){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(n==="join"?"room.join":"room.leave");let a=b$2(e.token),t=String(a.jti??""),i=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",t,n,r,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:n,roomId:r,deviceCertificate:e.token,deviceProof:i}),this.record(n==="join"?"room.join":"room.leave");}grantProvider(e,r={}){let n=Promise.resolve(),a=e;return t=>{let o=n.then(async()=>{let i=false;a.expiresAtMs<=Date.now()+3e5&&a.renew&&(a=await a.renew(),i=true);let c=t.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),t.refreshGrant&&this.before("coordination.credential.refresh");let l=async d=>{let y=b$2(d.token),p=String(y.jti??""),g=await(await this.key()).proof((m,I)=>["openrtc:v2:gateway-grant",p,t.avenue.kind,t.avenue.id,t.runtimeInstanceId,m,I].join(":"));return this.post("/v2/gateway/grants",{credentialType:d.type,credential:d.token,avenue:t.avenue,runtimeInstanceId:t.runtimeInstanceId,ticketFingerprint:t.ticketFingerprint,deviceProof:g,...t.refreshGrant?{refreshGrant:t.refreshGrant}:{},...r.maxPeers?{maxPeers:r.maxPeers}:{},...r.features?{features:r.features}:{},...t.avenue.kind==="room"&&r.architecture?{architecture:r.architecture}:{},...t.avenue.kind==="room"&&r.roomDelivery?{roomDelivery:r.roomDelivery}:{},...d.type==="device-certificate"&&r.deviceProfile?{deviceProfile:r.deviceProfile}:{}})},u;try{u=await l(a);}catch(d){if(!T(d))throw d;let y=await a.recoverRejectedCertificate?.();if(!y)throw d;a=y,i=true,u=await l(a);}return this.record(c),t.refreshGrant&&this.record("coordination.credential.refresh"),i&&await r.onSourceRenewed?.({token:a.token,expiresAtMs:a.expiresAtMs}),u});return n=o.then(()=>{},()=>{}),o}}turnProvider(e){let r=x("relay"),n=null,a=null;return async()=>{if(n&&n.expiresAtMs>Date.now()+5*6e4)return n;if(a)return a;let t=(async()=>{let o=e(),i=b$2(o.token),c=String(i.jti??""),u=await(await this.key()).proof((y,p)=>["openrtc:v2:relay-turn",c,r,y,p].join(":")),d=await this.post("/v2/relay/turn",{credentialType:o.type,credential:o.token,sessionId:r,deviceProof:u});return n=d,d})();a=t;try{return await t}finally{a===t&&(a=null);}}}};
2
+ export{K as a};
@@ -1 +1 @@
1
- import {r}from'./chunk-LAL63F6X.js';import {a}from'./chunk-WD47V4PK.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
1
+ import {r}from'./chunk-FIWTJQJA.js';import {a}from'./chunk-XK2JESZY.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
@@ -0,0 +1 @@
1
+ import {c,e}from'./chunk-WALOTASO.js';function l(n,c$1){if(!n||typeof n!="object")return null;let r=n,t=r.details&&typeof r.details=="object"?r.details:null,i=t&&c(t.code),o=i?t:r,e$1=i||c(o.code);return e$1?Object.freeze({...e(o),...e$1.scope?{scope:e$1.scope}:{},code:e$1.code,retryable:typeof o.retryable=="boolean"?o.retryable:!!e$1.scope,avenue:Object.freeze({kind:c$1.kind,id:c$1.id})}):null}export{l as a};