openrtc 2.9.2 → 2.9.4

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 (73) hide show
  1. package/README.md +21 -0
  2. package/dist/{Connection-BU8g28lx.d.ts → Connection-gaN-X7kf.d.ts} +14 -1
  3. package/dist/{DelegatingRuntimeAdapter-DLrTF5Nr.d.ts → DelegatingRuntimeAdapter-Bh0rLvly.d.ts} +5 -3
  4. package/dist/{IpcRuntimeAdapter-BVTYrfIe.d.ts → IpcRuntimeAdapter-DZj7Rn-o.d.ts} +6 -2
  5. package/dist/NativeProjectionBroker-VFPBNUGH.js +1 -0
  6. package/dist/WasmBridge-42DIXTE6.js +1 -0
  7. package/dist/{assembly-CJjfcYrA.d.ts → assembly-DX6MlDlZ.d.ts} +12 -2
  8. package/dist/{capabilities-BOyxv_kT.d.ts → capabilities-wJO8ZWyF.d.ts} +1 -1
  9. package/dist/{chunk-ONV44QWS.js → chunk-2QE5HAPB.js} +1 -1
  10. package/dist/chunk-AZHDR5G7.js +2 -0
  11. package/dist/{chunk-XK2JESZY.js → chunk-DMCUS3TY.js} +1 -1
  12. package/dist/{chunk-3PDMPSVP.js → chunk-DZR5WWVW.js} +1 -1
  13. package/dist/chunk-F5ORG763.js +1 -0
  14. package/dist/{chunk-2MQS2BNY.js → chunk-FXVEX4SB.js} +1 -1
  15. package/dist/chunk-IJXTRVQS.js +2 -0
  16. package/dist/{chunk-CNAW5BZ3.js → chunk-L2ZZXECX.js} +1 -1
  17. package/dist/chunk-LJBVXWWV.js +1 -0
  18. package/dist/{chunk-5VCDW5BC.js → chunk-QO5WF4IG.js} +1 -1
  19. package/dist/chunk-TRUMV4SI.js +1 -0
  20. package/dist/chunk-US64VGDU.js +1 -0
  21. package/dist/controlPlane-U6XREYI4.js +1 -0
  22. package/dist/coreClient.d.ts +5 -3
  23. package/dist/coreClient.js +1 -1
  24. package/dist/{deviceEnrollment-ZRMFBH5R.js → deviceEnrollment-3AOGMX7C.js} +1 -1
  25. package/dist/{deviceHandle-OAF6XJPY.js → deviceHandle-2DLEXKFM.js} +1 -1
  26. package/dist/external-broadcast.d.ts +4 -4
  27. package/dist/external-broadcast.js +1 -1
  28. package/dist/index.d.ts +10 -6
  29. package/dist/index.js +1 -1
  30. package/dist/ipcFactory-7DTAMYUQ.js +1 -0
  31. package/dist/native.d.ts +5 -5
  32. package/dist/native.js +1 -1
  33. package/dist/node.d.ts +6 -6
  34. package/dist/node.js +2 -2
  35. package/dist/openrtc-4UMTYB7M.js +2 -0
  36. package/dist/openrtc_bg.wasm +0 -0
  37. package/dist/{room-52G6ONQZ.js → room-5FG5L44X.js} +1 -1
  38. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  39. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  40. package/dist/runtime/device-status.d.ts +1 -1
  41. package/dist/runtime/factories.d.ts +9 -7
  42. package/dist/runtime/factories.js +1 -1
  43. package/dist/runtime/index.d.ts +11 -9
  44. package/dist/runtime/index.js +1 -1
  45. package/dist/server-browser.d.ts +4 -4
  46. package/dist/server.d.ts +4 -4
  47. package/dist/server.js +1 -1
  48. package/dist/service-node.d.ts +4 -4
  49. package/dist/service-node.js +1 -1
  50. package/dist/testing/native.d.ts +4 -4
  51. package/dist/testing/native.js +1 -1
  52. package/dist/testing.d.ts +4 -4
  53. package/dist/testing.js +1 -1
  54. package/dist/transport/index.d.ts +2 -2
  55. package/dist/{types-ldAq2oqi.d.ts → types-CzogmfJl.d.ts} +1 -1
  56. package/native/darwin-arm64/openrtc-node-host +0 -0
  57. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  58. package/native/darwin-x64/openrtc-node-host +0 -0
  59. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  60. package/native/linux-x64/openrtc-node-host +0 -0
  61. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  62. package/package.json +1 -1
  63. package/dist/NativeProjectionBroker-2OH2SCPF.js +0 -1
  64. package/dist/WasmBridge-EWVV4DFE.js +0 -1
  65. package/dist/chunk-3B4IDT2M.js +0 -1
  66. package/dist/chunk-7KWWA3M6.js +0 -2
  67. package/dist/chunk-KXXQNKRK.js +0 -1
  68. package/dist/chunk-PEDATFS2.js +0 -2
  69. package/dist/chunk-PNPW22EQ.js +0 -1
  70. package/dist/chunk-RT7YTAXU.js +0 -1
  71. package/dist/controlPlane-HPGXZDDD.js +0 -1
  72. package/dist/ipcFactory-WNHLLXCB.js +0 -1
  73. package/dist/openrtc-SP4ISKSK.js +0 -2
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-5VCDW5BC.js';import'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function y(n){let e=new URL(n??"https://api.openrtc.app"),t=e.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(e.hostname.toLowerCase());if(e.protocol!=="https:"&&!t||e.username||e.password||e.search||e.hash)throw new TypeError("[OpenRTC] authority control-plane endpoint is invalid.");return e.toString().replace(/\/$/,"")}function h(){if(typeof document<"u"||typeof window<"u")throw new Error("[OpenRTC] openrtc/server is unavailable in browsers; use openrtc/service-node with a delegated grant.")}var c=class{constructor(e){h();let t=e.secretKey?.trim()??"";if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(t))throw new TypeError("[OpenRTC] secretKey is invalid.");let i=e.fetch??globalThis.fetch;if(typeof i!="function")throw new TypeError("[OpenRTC] a Fetch-compatible implementation is required.");let u=y(e.endpoint);this.authority=new a({apiKey:e.apiKey,serviceId:e.serviceId,generation:e.generation,shardIds:e.shardIds,deviceId:e.deviceId,deviceSigner:e.deviceSigner,assignmentSigner:e.assignmentSigner,grantIssuer:async s=>{let r=await i(`${u}/v2/developer/authority/grants`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json","x-openrtc-idempotency-key":s.idempotencyKey},body:JSON.stringify(s.body)});if(!r.ok){let o=await r.json().catch(()=>null),d=typeof o?.error=="string"?o.error.slice(0,256):`HTTP ${r.status}`;throw new Error(`[OpenRTC] authority service grant failed: ${d}`)}return r.json()}});}requestGrant(e){return this.authority.requestGrant(e)}signAssignment(e){return this.authority.signAssignment(e)}devicePublicKey(){return this.authority.devicePublicKey()}signDeviceBytes(e){return this.authority.signDeviceBytes(e)}grantIssuer(){return async e=>{let t=e.body;return this.requestGrant({roomId:String(t.avenue?.id??""),runtimeInstanceId:String(t.runtimeInstanceId??""),ticketFingerprint:String(t.ticketFingerprint??""),maxPeers:typeof t.maxPeers=="number"?t.maxPeers:void 0,refreshGrant:typeof t.refreshGrant=="string"?t.refreshGrant:void 0,features:typeof t.features=="object"&&t.features?t.features:void 0})}}};
1
+ import {a}from'./chunk-QO5WF4IG.js';import'./chunk-TRUMV4SI.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-2QE5HAPB.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-F5ORG763.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function y(n){let e=new URL(n??"https://api.openrtc.app"),t=e.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(e.hostname.toLowerCase());if(e.protocol!=="https:"&&!t||e.username||e.password||e.search||e.hash)throw new TypeError("[OpenRTC] authority control-plane endpoint is invalid.");return e.toString().replace(/\/$/,"")}function h(){if(typeof document<"u"||typeof window<"u")throw new Error("[OpenRTC] openrtc/server is unavailable in browsers; use openrtc/service-node with a delegated grant.")}var c=class{constructor(e){h();let t=e.secretKey?.trim()??"";if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(t))throw new TypeError("[OpenRTC] secretKey is invalid.");let i=e.fetch??globalThis.fetch;if(typeof i!="function")throw new TypeError("[OpenRTC] a Fetch-compatible implementation is required.");let u=y(e.endpoint);this.authority=new a({apiKey:e.apiKey,serviceId:e.serviceId,generation:e.generation,shardIds:e.shardIds,deviceId:e.deviceId,deviceSigner:e.deviceSigner,assignmentSigner:e.assignmentSigner,grantIssuer:async s=>{let r=await i(`${u}/v2/developer/authority/grants`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json","x-openrtc-idempotency-key":s.idempotencyKey},body:JSON.stringify(s.body)});if(!r.ok){let o=await r.json().catch(()=>null),d=typeof o?.error=="string"?o.error.slice(0,256):`HTTP ${r.status}`;throw new Error(`[OpenRTC] authority service grant failed: ${d}`)}return r.json()}});}requestGrant(e){return this.authority.requestGrant(e)}signAssignment(e){return this.authority.signAssignment(e)}devicePublicKey(){return this.authority.devicePublicKey()}signDeviceBytes(e){return this.authority.signDeviceBytes(e)}grantIssuer(){return async e=>{let t=e.body;return this.requestGrant({roomId:String(t.avenue?.id??""),runtimeInstanceId:String(t.runtimeInstanceId??""),ticketFingerprint:String(t.ticketFingerprint??""),maxPeers:typeof t.maxPeers=="number"?t.maxPeers:void 0,refreshGrant:typeof t.refreshGrant=="string"?t.refreshGrant:void 0,features:typeof t.features=="object"&&t.features?t.features:void 0})}}};
2
2
  export{c as AuthorityServiceControlPlane};
@@ -1,8 +1,8 @@
1
- import { C as Client, X as Room, r as Connection } from './types-ldAq2oqi.js';
1
+ import { C as Client, X as Room, r as Connection } from './types-CzogmfJl.js';
2
2
  import './coreClient.js';
3
- import './assembly-CJjfcYrA.js';
4
- import './Connection-BU8g28lx.js';
5
- import './capabilities-BOyxv_kT.js';
3
+ import './assembly-DX6MlDlZ.js';
4
+ import './Connection-gaN-X7kf.js';
5
+ import './capabilities-wJO8ZWyF.js';
6
6
 
7
7
  /** Browser-safe and Node-host-neutral developer service-node facade. */
8
8
 
@@ -1 +1 @@
1
- export{a as DelegatedAuthorityService,b as ServiceNode}from'./chunk-5VCDW5BC.js';import'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';
1
+ export{a as DelegatedAuthorityService,b as ServiceNode}from'./chunk-QO5WF4IG.js';import'./chunk-TRUMV4SI.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-2QE5HAPB.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-F5ORG763.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';
@@ -1,10 +1,10 @@
1
- import { O as Options, C as Client } from '../types-ldAq2oqi.js';
1
+ import { O as Options, C as Client } from '../types-CzogmfJl.js';
2
2
  import { E as Endpoints } from '../protocol-BSBjMb7p.js';
3
3
  import { P as PlutoIpcBridge } from '../ipc-DgzKqHH3.js';
4
4
  import '../coreClient.js';
5
- import '../assembly-CJjfcYrA.js';
6
- import '../Connection-BU8g28lx.js';
7
- import '../capabilities-BOyxv_kT.js';
5
+ import '../assembly-DX6MlDlZ.js';
6
+ import '../Connection-gaN-X7kf.js';
7
+ import '../capabilities-wJO8ZWyF.js';
8
8
 
9
9
  declare function OpenRTC(options: Options, endpoints: Endpoints, bridge: PlutoIpcBridge): Client;
10
10
 
@@ -1 +1 @@
1
- import {a}from'../chunk-RT7YTAXU.js';import'../chunk-COXQYBTI.js';import {a as a$1}from'../chunk-NS32P65Z.js';import'../chunk-GMPEZXPD.js';import {i}from'../chunk-KXXQNKRK.js';import'../chunk-FKAQDDUM.js';import'../chunk-ZA44REGI.js';import'../chunk-ONV44QWS.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-3B4IDT2M.js';import'../chunk-WALOTASO.js';import'../chunk-2GX6GB6L.js';function v(c,p,e){let o=new a;return i(c,{endpoints:p,testingAllowInsecureLoopback:true,platform:"native",close:()=>o.close(),deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:a}=await import('../ipcFactory-WNHLLXCB.js');return a(t,e,o)}})}export{v as OpenRTC};
1
+ import {a}from'../chunk-LJBVXWWV.js';import'../chunk-COXQYBTI.js';import {a as a$1}from'../chunk-NS32P65Z.js';import'../chunk-GMPEZXPD.js';import {i}from'../chunk-TRUMV4SI.js';import'../chunk-FKAQDDUM.js';import'../chunk-ZA44REGI.js';import'../chunk-2QE5HAPB.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-F5ORG763.js';import'../chunk-WALOTASO.js';import'../chunk-2GX6GB6L.js';function v(c,p,e){let o=new a;return i(c,{endpoints:p,testingAllowInsecureLoopback:true,platform:"native",close:()=>o.close(),deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:a}=await import('../ipcFactory-7DTAMYUQ.js');return a(t,e,o)}})}export{v as OpenRTC};
package/dist/testing.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { R as RoomArchitectureMode, ai as CoordinationGatewayGrantRequest, aj as CoordinationGatewayGrant } from './Connection-BU8g28lx.js';
2
- import { a as AttestationProvider, b as AuthProvider, B as BotVerificationProvider, e as BroadcastGrant, d as BroadcastCreateOptions, f as BroadcastInvite, g as BroadcastInviteOptions, D as Delivery, t as DeviceProfile, O as Options, C as Client } from './types-ldAq2oqi.js';
1
+ import { R as RoomArchitectureMode, aj as CoordinationGatewayGrantRequest, ak as CoordinationGatewayGrant } from './Connection-gaN-X7kf.js';
2
+ import { a as AttestationProvider, b as AuthProvider, B as BotVerificationProvider, e as BroadcastGrant, d as BroadcastCreateOptions, f as BroadcastInvite, g as BroadcastInviteOptions, D as Delivery, t as DeviceProfile, O as Options, C as Client } from './types-CzogmfJl.js';
3
3
  import { E as Endpoints } from './protocol-BSBjMb7p.js';
4
4
  import './coreClient.js';
5
- import './assembly-CJjfcYrA.js';
6
- import './capabilities-BOyxv_kT.js';
5
+ import './assembly-DX6MlDlZ.js';
6
+ import './capabilities-wJO8ZWyF.js';
7
7
 
8
8
  interface DeviceProof {
9
9
  publicKeyJwk: JsonWebKey;
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- import {a}from'./chunk-7KWWA3M6.js';import {a as a$1}from'./chunk-IAYQJZQQ.js';import {a as a$2,d,c}from'./chunk-CNAW5BZ3.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function v(i,o,e){let n=s=>{let t=new URL(s);return t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)&&Number(t.port)>0&&t.pathname==="/"&&!t.username&&!t.password&&!t.search&&!t.hash};if(i.apiKey!=="pk_test_0000000000000000000000000000000000000000"||!n(o.controlPlane)||!n(o.gateway)||!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace))throw new Error("Local broadcast testing requires the disposable loopback service lane")}function b(i){let o=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=");return Uint8Array.from(atob(o),e=>e.charCodeAt(0))}function A(i,o,e){return new a(i,o,a$1(e))}function R(i$1,o,e={}){if(e.localBroadcast&&v(i$1,o,e.localBroadcast),e.initialTicketLifetimeMs!==void 0){let t=(p,c)=>{let a=new URL(p);return a.protocol===c&&["127.0.0.1","[::1]"].includes(a.hostname)&&Number(a.port)>0&&a.pathname==="/"&&!a.username&&!a.password&&!a.search&&!a.hash};if(e.initialTicketLifetimeMs!==9e4||i$1.apiKey!=="pk_test_0000000000000000000000000000000000000000"||!t(o.controlPlane,"http:")||!t(o.gateway,"http:")||!e.irohTestRelayUrl||!t(e.irohTestRelayUrl,"https:"))throw new Error("Short initial tickets require the disposable local service lane")}let n=e.localBroadcast,s=n?a$1(n.keyNamespace):void 0;return i(i$1,{endpoints:o,testingAllowInsecureLoopback:true,platform:"web",...s?{deviceKeyProvider:s}:{},...n&&s?{broadcastHostFactory:async t=>{let[{BrowserManagedBroadcastHost:p},{loadBrowserWasmRuntimeModule:c}]=await Promise.all([import('./BrowserManagedBroadcastHost-GLSYJIOR.js'),import('./WasmBridge-EWVV4DFE.js')]),a=c().then(async r=>(await r.initWasm(),r.start(),new r.WasmClient(t.apiKey))),y=await s.getOrCreate(`app_${t.apiKey.slice(-16)}`);return new p({resolve:async(r,l)=>({token:r,...await n.resolve(r,l),signBindingChallenge:async m=>b(await y.sign(m))}),loadWasm:()=>a})}}:{},...e.deviceId?{deviceIdProvider:async()=>e.deviceId}:{},...e.irohTestRelayUrl?{irohTestRelayUrl:e.irohTestRelayUrl}:{},runtimeFactory:async t=>{let{createWasmClient:p}=await import('./runtime/factories.js'),c$1=await p(t);if(e.initialTicketLifetimeMs!==void 0){let a=c$1.runtime,y=a.getTicketWithToken.bind(a);a.getTicketWithToken=async(r,l=0)=>{if(a.getTicketWithToken=y,!r.startsWith("v2:room:"))throw new Error("Short initial ticket requires room scope");let{irohTicket:m,tokenSuffix:u}=a$2(await y(r,l)),d$1=u&&d(m,u);if(!d$1||!d$1.t||d$1.s!==r||d$1.m!==l)throw new Error("Invalid initial service ticket");let f=Date.now()+9e4;return await a.registerToken({token:d$1.t,scope:r,maxConnections:l,expiresAtMs:f}),c(m,d$1.t,r,l,f)};}return c$1}})}export{R as OpenRTC,A as controlPlane};
1
+ import {a}from'./chunk-IJXTRVQS.js';import {a as a$1}from'./chunk-IAYQJZQQ.js';import {a as a$2,d,c}from'./chunk-L2ZZXECX.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-TRUMV4SI.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-2QE5HAPB.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-F5ORG763.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function v(i,o,e){let n=s=>{let t=new URL(s);return t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)&&Number(t.port)>0&&t.pathname==="/"&&!t.username&&!t.password&&!t.search&&!t.hash};if(i.apiKey!=="pk_test_0000000000000000000000000000000000000000"||!n(o.controlPlane)||!n(o.gateway)||!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace))throw new Error("Local broadcast testing requires the disposable loopback service lane")}function b(i){let o=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=");return Uint8Array.from(atob(o),e=>e.charCodeAt(0))}function A(i,o,e){return new a(i,o,a$1(e))}function R(i$1,o,e={}){if(e.localBroadcast&&v(i$1,o,e.localBroadcast),e.initialTicketLifetimeMs!==void 0){let t=(p,c)=>{let a=new URL(p);return a.protocol===c&&["127.0.0.1","[::1]"].includes(a.hostname)&&Number(a.port)>0&&a.pathname==="/"&&!a.username&&!a.password&&!a.search&&!a.hash};if(e.initialTicketLifetimeMs!==9e4||i$1.apiKey!=="pk_test_0000000000000000000000000000000000000000"||!t(o.controlPlane,"http:")||!t(o.gateway,"http:")||!e.irohTestRelayUrl||!t(e.irohTestRelayUrl,"https:"))throw new Error("Short initial tickets require the disposable local service lane")}let n=e.localBroadcast,s=n?a$1(n.keyNamespace):void 0;return i(i$1,{endpoints:o,testingAllowInsecureLoopback:true,platform:"web",...s?{deviceKeyProvider:s}:{},...n&&s?{broadcastHostFactory:async t=>{let[{BrowserManagedBroadcastHost:p},{loadBrowserWasmRuntimeModule:c}]=await Promise.all([import('./BrowserManagedBroadcastHost-GLSYJIOR.js'),import('./WasmBridge-42DIXTE6.js')]),a=c().then(async r=>(await r.initWasm(),r.start(),new r.WasmClient(t.apiKey))),y=await s.getOrCreate(`app_${t.apiKey.slice(-16)}`);return new p({resolve:async(r,l)=>({token:r,...await n.resolve(r,l),signBindingChallenge:async m=>b(await y.sign(m))}),loadWasm:()=>a})}}:{},...e.deviceId?{deviceIdProvider:async()=>e.deviceId}:{},...e.irohTestRelayUrl?{irohTestRelayUrl:e.irohTestRelayUrl}:{},runtimeFactory:async t=>{let{createWasmClient:p}=await import('./runtime/factories.js'),c$1=await p(t);if(e.initialTicketLifetimeMs!==void 0){let a=c$1.runtime,y=a.getTicketWithToken.bind(a);a.getTicketWithToken=async(r,l=0)=>{if(a.getTicketWithToken=y,!r.startsWith("v2:room:"))throw new Error("Short initial ticket requires room scope");let{irohTicket:m,tokenSuffix:u}=a$2(await y(r,l)),d$1=u&&d(m,u);if(!d$1||!d$1.t||d$1.s!==r||d$1.m!==l)throw new Error("Invalid initial service ticket");let f=Date.now()+9e4;return await a.registerToken({token:d$1.t,scope:r,maxConnections:l,expiresAtMs:f}),c(m,d$1.t,r,l,f)};}return c$1}})}export{R as OpenRTC,A as controlPlane};
@@ -1,5 +1,5 @@
1
- import { g as ProtocolName, as as RouteDescriptor, at as PayloadCrypto, au as CryptoStreams } from '../Connection-BU8g28lx.js';
2
- export { av as CryptoBiStream, aw as RouteFamily, ax as RouteKind } from '../Connection-BU8g28lx.js';
1
+ import { g as ProtocolName, at as RouteDescriptor, au as PayloadCrypto, av as CryptoStreams } from '../Connection-gaN-X7kf.js';
2
+ export { aw as CryptoBiStream, ax as RouteFamily, ay as RouteKind } from '../Connection-gaN-X7kf.js';
3
3
 
4
4
  declare const TRANSPORT_LABELS: readonly ProtocolName[];
5
5
  declare function normalizeTransport(value: unknown): ProtocolName | undefined;
@@ -1,5 +1,5 @@
1
1
  import { PeerNamespace, ChannelNamespace, DiagnosticsNamespace, DeviceNamespace } from './coreClient.js';
2
- import { R as RoomArchitectureMode, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, C as ChannelDescriptor, S as ServiceErrorObservation, P as PlutoIrohConfiguration, d as PlutoRTCConfiguration, e as PlutoMoQConfiguration, f as RouteOptimization, g as ProtocolName } from './Connection-BU8g28lx.js';
2
+ import { R as RoomArchitectureMode, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, C as ChannelDescriptor, S as ServiceErrorObservation, P as PlutoIrohConfiguration, d as PlutoRTCConfiguration, e as PlutoMoQConfiguration, f as RouteOptimization, g as ProtocolName } from './Connection-gaN-X7kf.js';
3
3
 
4
4
  interface AuthProvider {
5
5
  /** Registered provider ID from the developer app capability manifest. */
@@ -4,9 +4,9 @@
4
4
  "platform": "darwin",
5
5
  "arch": "arm64",
6
6
  "rustTarget": "aarch64-apple-darwin",
7
- "sourceCommit": "133da570608c080c8ccfed64d96aeb31c275599a",
8
- "sourceDigest": "e4f5cca4c25f0a666c1255189d815783a00ae2cc45d353693eb90137137bcb8b",
9
- "binarySha256": "6d1dd0f3a12050a8823c1200e0f949d046e0a545644f0fb166010a54eb8ca499",
7
+ "sourceCommit": "3dc09762057f065c805a4e2d947482e82808c79d",
8
+ "sourceDigest": "70af51ee471ef7f1c05826e5115b8f061000a0359f3adf8faac3027966175d16",
9
+ "binarySha256": "e4499609311caa6bb9d9a9dd085938ec382463c2d83184e1c15e50614897788c",
10
10
  "protocol": {
11
11
  "lifecycleOwner": "rust-peer-session",
12
12
  "maxApplicationPayloadBytes": 65536,
@@ -16,5 +16,5 @@
16
16
  },
17
17
  "signingKeySha256": "0391c617f3df12611b419e129cace36fa792e73da03271649cbed9e9f9f155ef",
18
18
  "signatureAlgorithm": "ed25519",
19
- "signature": "5HOPRWoAmnhMUCt+ZoQ6xnHl/ZCI8VdTilRaOnJuo7GQcLL+QGWO0Dnhy3GOW4jz/58rCEp740sr1MbRC/iqBw=="
19
+ "signature": "6lYknhIWENURS/f9FTAIvl2ePp7JzBOaWwLshLaEowYxNUje8HEIA9VA0ZBztfQfMTWj5bQc3Cn257AxLh3VAw=="
20
20
  }
Binary file
@@ -4,9 +4,9 @@
4
4
  "platform": "darwin",
5
5
  "arch": "x64",
6
6
  "rustTarget": "x86_64-apple-darwin",
7
- "sourceCommit": "133da570608c080c8ccfed64d96aeb31c275599a",
8
- "sourceDigest": "e4f5cca4c25f0a666c1255189d815783a00ae2cc45d353693eb90137137bcb8b",
9
- "binarySha256": "a9ec91615c1ab571bd295a655f5fb8b84a2e6c19871294cd3074693e1e48a5db",
7
+ "sourceCommit": "3dc09762057f065c805a4e2d947482e82808c79d",
8
+ "sourceDigest": "70af51ee471ef7f1c05826e5115b8f061000a0359f3adf8faac3027966175d16",
9
+ "binarySha256": "47d9a1d4f63c382c134daa3e787705c9c3b588a39ce7963442fec16ecd8adcb7",
10
10
  "protocol": {
11
11
  "lifecycleOwner": "rust-peer-session",
12
12
  "maxApplicationPayloadBytes": 65536,
@@ -16,5 +16,5 @@
16
16
  },
17
17
  "signingKeySha256": "0391c617f3df12611b419e129cace36fa792e73da03271649cbed9e9f9f155ef",
18
18
  "signatureAlgorithm": "ed25519",
19
- "signature": "ReckMpRf+THfQd+6WqrDoA1B4rcLnjPGhzLMewR5t+GGaER/WNVyI1FMK0lNEmFPrr71r7Ihr0f9zhufSRKjCg=="
19
+ "signature": "+AwH2mj6Yj0Bm1RXKlvWxW0eX9PPI2yg+oHi4hht64nr4g0eNHXFX0Gfgafm5KDDZegHVzGSZoBiYwjUDLI8AQ=="
20
20
  }
Binary file
@@ -4,9 +4,9 @@
4
4
  "platform": "linux",
5
5
  "arch": "x64",
6
6
  "rustTarget": "x86_64-unknown-linux-gnu",
7
- "sourceCommit": "3d60241256f179e12f1c7aec9d064ca75af202bf",
8
- "sourceDigest": "e4f5cca4c25f0a666c1255189d815783a00ae2cc45d353693eb90137137bcb8b",
9
- "binarySha256": "0914866c9bf0ee73971858bf7757eddc4b879ef96dd6cd68fdf53324a64022d1",
7
+ "sourceCommit": "3dc09762057f065c805a4e2d947482e82808c79d",
8
+ "sourceDigest": "70af51ee471ef7f1c05826e5115b8f061000a0359f3adf8faac3027966175d16",
9
+ "binarySha256": "d6dedebd7be63be547906aafeb95b76e49699a414d9e341bc06e5934bbd1f4df",
10
10
  "protocol": {
11
11
  "lifecycleOwner": "rust-peer-session",
12
12
  "maxApplicationPayloadBytes": 65536,
@@ -16,5 +16,5 @@
16
16
  },
17
17
  "signingKeySha256": "0391c617f3df12611b419e129cace36fa792e73da03271649cbed9e9f9f155ef",
18
18
  "signatureAlgorithm": "ed25519",
19
- "signature": "bSJk9MSDagG4ddsCCf9PHkxlny4sC6TEwA5gaMiMFs1q2UDd9EV/gZAbV7msbqiRsvvgKwsBvlu521xHb0JlCw=="
19
+ "signature": "uERuJ9OSCnq4Kqo9Sm36JPwugtZbn1y7sngGbrn8/zn8dFzEu8rzkdsEP/8MCzzz7doZq6w4CeXcbTh9OJxaBg=="
20
20
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openrtc",
3
- "version": "2.9.2",
3
+ "version": "2.9.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1 +0,0 @@
1
- export{a as NativeProjectionBroker}from'./chunk-RT7YTAXU.js';import'./chunk-COXQYBTI.js';import'./chunk-WALOTASO.js';
@@ -1 +0,0 @@
1
- export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-PNPW22EQ.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-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';
@@ -1 +0,0 @@
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,2 +0,0 @@
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 +0,0 @@
1
- import {b as b$3}from'./chunk-FKAQDDUM.js';import {b as b$1,a as a$2}from'./chunk-ZA44REGI.js';import {a as a$1,b as b$4}from'./chunk-ONV44QWS.js';import {b as b$2,a as a$3}from'./chunk-CCCYE3XN.js';import {d,a}from'./chunk-3B4IDT2M.js';import {d as d$1,b as b$5}from'./chunk-2GX6GB6L.js';function R(s,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:s,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function x(s){let e;try{e=s instanceof Uint8Array?JSON.parse(new TextDecoder().decode(s)):s&&typeof s=="object"?s:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var P="openrtc-peer-stream/1",de=32,Q=16,L=4294967295,ue=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,he=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function S(s){let e=s?.trim()??"";if(!ue.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function B(s){let e=s?.trim()??"",t=he.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function Y(s){if(s===null||s===0)return null;if(!Number.isFinite(s)||s<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(L,Math.ceil(s))}function ee(s){if(!Number.isSafeInteger(s)||s<1||s>L)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${L}.`);return s}var _=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Q;this.outgoingLimit=Q;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=Y(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=Y(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=ee(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=ee(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},A=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:de});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},U=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new A;this.incomingUni=new A;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new _(i,this.peerId);}async createBidirectionalStream(e){let t=S(e.protocol),i=await this.client.channels.openBi(this.peerId,P,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=S(e.protocol);return (await this.client.channels.openUni(this.peerId,P,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},o=this.protocolHandlers.get(t);if(o){try{o(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=S(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},T=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:P,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(P,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new U(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=B(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(B(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(P);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$3]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=S(i);}catch{return this.declined+=1,false}let o=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return o?this.accepted+=1:this.declined+=1,o}resolveExistingPeer(e,t=""){let i=B(t);if(i){let o=this.peerIdsByConnection.get(i);if(!o)return this.lastResolution="unbound-connection",null;let a=this.peers.get(o);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(o=>[o.peerId,o.deviceId,o.deviceIdHint,o.connectionId,...o.connectionIds].some(a=>a===e));if(r){let o=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>o.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var F={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var w=new WeakMap;function pe(s){let e=w.get(s);if(!e||s.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function Fe(s,e){if(w.has(s))throw new Error("[OpenRTC] Capability runtime is already registered.");return w.set(s,pe(e)),()=>{w.delete(s);}}function me(s){let e=s?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function y(s){let e=s?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var W=/^[A-Za-z0-9_.:@-]{1,160}$/,ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,te=2,H=8,ge=H;function fe(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ve.test(t)?t:e}function ye(s){let e=`openrtc:v2:device-id:${s}`,t,i=(()=>{try{return t=globalThis.localStorage,fe(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(s){if(s===void 0)return [];if(!Array.isArray(s))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(s.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!W.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function N(s){let e=b$1(s.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var K=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},$=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(F[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw b(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=be(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),o=we(e.architecture),a=Ce(o,t,e.delivery),l=Ie(a,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),g=t*u,f=r*i,v=Math.max(0,Math.ceil(t/4)-1),ce=a==="managed"?f*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+v*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,le=l*h("broadcast.delivery");return {architecture:o,effectiveArchitecture:a,creditsUsd:Math.ceil((g+ce+le)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function we(s){return s??"auto"}function G(s,e,t,i){if(!Number.isSafeInteger(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return s}function be(s,e,t,i){if(!Number.isFinite(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return s}function h(s){let e=F[s];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${s} has no current customer-credit price.`);return e}function Ce(s,e,t){if(s==="mesh"){if(e>16)throw b("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return s}if(s==="sparse"){if(e>50)throw b("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw b("[OpenRTC] Sparse room quotes require latest-state delivery.");return s}if(s==="managed")throw b("[OpenRTC] Managed room architecture is unavailable in this release.");if(s==="authority")return s;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw b(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function b(s){return d(a.ROOM_ARCHITECTURE_UNAVAILABLE,s,{retryable:false,plane:"admission"})}function se(s){return d(a.TICKET_MESH_ALREADY_ACTIVE,`[OpenRTC] ticket:${s} is already active with different options.`,{retryable:false,plane:"admission"})}function ae(s){return s.mesh===true?s.maxPeers??ge:s.maxPeers}function Pe(s){return JSON.stringify({identity:s.identity??(s.mesh===true?"session":null),maxPeers:ae(s)??null,mesh:s.mesh===true,advancedFanout:s.advancedFanout===true})}function Ie(s,e){if(e<=1)return 0;if(s!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function oe(s){let e=s?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var q=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.cleanupComplete=false;this.closeAttempt=null;this.pendingStops=null;this.peerStreams=new T(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,o)=>{let a=x(r);!a||a.capability!==this.capabilityKey||o!==void 0&&a.name!==o||o===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.assertOpen(),this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=oe(e);return {set:i=>{this.assertOpen();let n=R("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{this.assertOpen();let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(o,a)=>i({peerId:o,value:a});n.add(r);for(let[o,a]of this.remoteState)a.has(t)&&i({peerId:o,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){this.assertOpen();let t=oe(e),i=n=>R("channel",t,n,this.capabilityKey);return {send:async n=>{this.assertOpen();let r=i(n);await this.roomFanout?.sendChannel(t,r)||(this.assertOpen(),await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:o})=>o?[o.send(r)]:[])));},sendTo:async(n,r)=>{this.assertOpen(),this.roomFanout?.assertTargetedSendAllowed();let o=this.logicalConnections.get(n)?.activeRaw;if(o){await o.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{this.assertOpen();let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let o=(a,c)=>n({peerId:a,message:c});return r.add(o),()=>r?.delete(o)}}}onConnection(e){this.assertOpen();let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Capability messages are closed.")}close(){if(this.cleanupComplete)return Promise.resolve();if(this.closeAttempt)return this.closeAttempt;this.closed=true;let e=this.releaseMessages();return this.closeAttempt=e,e.then(()=>{this.closeAttempt===e&&(this.closeAttempt=null);},()=>{this.closeAttempt===e&&(this.closeAttempt=null);}),e}async releaseMessages(){let e=[];this.pendingStops??(this.pendingStops=[()=>this.stopMessage(),()=>this.stopConnection(),()=>this.stopDisconnection(),()=>this.stopPeerLifecycle(),()=>this.roomFanout?.close()]),this.pendingStops=this.pendingStops.filter(i=>{try{return i(),!1}catch(n){return e.push(n),true}});let t=[];for(let i of this.logicalConnections.keys())try{t.push(this.retire(i));}catch(n){e.push(n);}this.pendingRawConnections.clear();try{this.peerStreams.close();}catch(i){e.push(i);}this.rawConnections.clear(),this.logicalConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),this.remoteState.clear(),this.rawListeners.clear(),this.closeListeners.clear();for(let i of await Promise.allSettled(t))i.status==="rejected"&&e.push(i.reason);if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability message cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.cleanupComplete=true;}add(e){if(this.closed)return;let t=this.rawConnections.get(e.id);if(t?.raw===e)return;t&&this.remove(t.raw);let i=e.remoteNodeId||e.id,n=this.mediaRetirements.get(i);if(n){let a={raw:e,peerId:i};this.pendingRawConnections.set(e.id,a),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==a||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let o=this.logicalConnections.get(i);if(!o){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),o={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(R("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let g=d;return u.add(g),()=>u?.delete(g)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,o);}o.rawIds.add(e.id),o.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(o.view));for(let[a,c]of this.localState)this.sendState(e,a,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let o=this.stateSenders.get(e);if(o){for(let a of o.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let o=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(o)&&Number(o)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(o),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let o of t.rawIds){let a=this.rawConnections.get(o)?.raw;if(this.rawConnections.delete(o),this.peerStreams.unbindConnection(o),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let o of i.keys())for(let a of this.stateListeners.get(o)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let o of this.closeListeners.get(e)??[])o();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let o of this.connectionListeners.values())o.delete(e);return r}receive(e,t){if(this.closed)return;this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=x(t);if(!n){for(let r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(this.closed)return;if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let r=n.get(t);r||(r=new a$1(o=>e.send(o)),n.set(t,r)),r.send(i).catch(()=>{});}},O=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;this.retired=false;this.shutdownAttempt=null;w.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}projectRuntime(e){w.set(this,e);}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}close(){if(this.retired)return Promise.resolve();if(this.shutdownAttempt)return this.shutdownAttempt;this.closed=true;let e=this.releaseCapability();return this.shutdownAttempt=e,e.then(()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);},()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);}),e}beforeRuntimeShutdown(){}async releaseCapability(){let e=[];try{this.beforeRuntimeShutdown();}catch(t){e.push(t);}try{await this.messages?.close();}catch(t){e.push(t);}try{await this.client.advanced.runtime.shutdown();}catch(t){e.push(t);}if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.onClosed(),w.delete(this),this.retired=true;}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new q(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},z=class extends O{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},E=class extends O{constructor(t,i,n,r,o,a){super("ticket",t,i,n);this.token=r;this.ownsMesh=a;this.kind="ticket";this.closing=null;this.inviteListeners=new Set;this.stopInviteWatch=()=>{};this.meshStopped=false;if(this.currentInvite=o,a){let c=i.advanced.runtime;this.stopInviteWatch=c.watchTicketMeshInvite?.(t,l=>{this.currentInvite=l,this.inviteListeners.forEach(d=>d(l));})??this.stopInviteWatch;}}get invite(){return this.currentInvite}watchInvite(t){return this.inviteListeners.add(t),t(this.currentInvite),()=>this.inviteListeners.delete(t)}async issuerNode(){if(!this.ownsMesh)throw new Error("[OpenRTC] This ticket is not a mesh.");return this.client.advanced.runtime.ticketMeshIssuerNode(this.id)}get peers(){if(this.scopedPeers)return this.scopedPeers;let t=this.client.peers,i=`ticket:${this.id}`,n=r=>r.scopes.includes(i)&&r.status==="connected"&&r.settledReady===true&&r.routable!==false&&r.logicalSessionTerminal!==true;return this.scopedPeers={...t,watch:r=>t.watch(o=>r(o.filter(n))),watchLifecycle:r=>t.watchLifecycle(o=>r(o.filter(n))),get:r=>{let o=t.get(r);return o&&n(o)?o:void 0},listConnected:()=>t.listConnected().filter(n)}}close(){if(this.retired)return Promise.resolve();if(this.closing)return this.closing;let t=this.closeOnce();return this.closing=t,t.catch(()=>{!this.retired&&this.closing===t&&(this.closing=null);}),t}async closeOnce(){this.ownsMesh&&!this.meshStopped&&(await this.client.advanced.runtime.closeTicketMesh(this.id),this.meshStopped=true),await super.close();}beforeRuntimeShutdown(){try{this.stopInviteWatch(),this.stopInviteWatch=()=>{};}finally{this.inviteListeners.clear();}}},M=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new K;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.pendingCapabilityShutdowns=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.closing=null;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:re(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId()),{DeviceHandle:n}=await import('./deviceHandle-OAF6XJPY.js');for(let r of this.handles)r instanceof n&&r.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);let{DeviceHandle:o}=await import('./deviceHandle-OAF6XJPY.js');for(let a of this.handles)a instanceof o&&a.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId(),{DeviceHandle:n}=await import('./deviceHandle-OAF6XJPY.js');for(let r of this.handles)r instanceof n&&r.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${y(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-52G6ONQZ.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${y(e)}`,Pe(t),void 0,()=>this.issueTicket(e,t),t.mesh===true?()=>se(y(e)):void 0),join:e=>{let t=b$4(e);return t.mesh?this.activateOnce(`ticket:${y(t.id)}`,`join:${e}`,void 0,()=>this.joinTicket(e),()=>se(y(t.id))):Promise.reject(d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"}))}};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async o=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(o),this.wrapBroadcastSession(await t.open(o))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=me(e.apiKey);let i=e.trust?.browserPersistence??"session";if(i!=="session"&&i!=="persistent")throw new Error("[OpenRTC] Invalid browser identity persistence policy.");this.browserPersistence=i,this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new $(e.usage);}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-HPGXZDDD.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$2,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-2NTRYCSR.js').then(({browserDeviceKeyProvider:e,createSessionDeviceKeyProvider:t})=>this.internals.platform!=="native"&&this.browserPersistence!=="persistent"?t():e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-2NTRYCSR.js').then(({createSessionDeviceKeyProvider:e})=>e())))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.");if(this.closing)throw new Error("[OpenRTC] Client is closing.")}activateOnce(e,t,i,n,r){this.assertOpen();let o=this.activations.get(e);if(o){if(o.handle?.closed)throw new Error(`[OpenRTC] ${e} is closing; retry close() to finish retirement.`);if(o.fingerprint!==t||o.auth!==i)throw r?r():new Error(`[OpenRTC] ${e} is already active with different options.`);return o.promise}let a={fingerprint:t,auth:i},l=(this.pendingCapabilityShutdowns.has(e)?this.settlePendingCapabilityShutdown(e).then(n):n()).then(d=>(a.handle=d,d)).catch(d=>{throw this.activations.get(e)===a&&this.activations.delete(e),d});return a.promise=l,this.activations.set(e,a),l}retainPendingCapabilityShutdown(e,t){this.pendingCapabilityShutdowns.has(e)||this.pendingCapabilityShutdowns.set(e,t);}async settlePendingCapabilityShutdown(e){let t=this.pendingCapabilityShutdowns.get(e);t&&(await t(),this.pendingCapabilityShutdowns.get(e)===t&&this.pendingCapabilityShutdowns.delete(e));}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):this.internals.platform!=="native"&&this.browserPersistence==="session"?this.sessionDeviceId??(this.sessionDeviceId=crypto.randomUUID()):ye(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let o=r?d$1(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$5)===true,l=!r||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeIdentityProvider:this.internals.platform==="native"&&e.nativeAuth?{providerId:e.nativeAuth.providerId,getSessionKey:async()=>e.nativeAuth.getSessionKey?.()??null,getAssertion:d=>e.nativeAuth.getAssertion(d)}:void 0,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$2).gateway,environment:"production",grantProvider:e.grantProvider,onServiceError:this.options.onServiceError,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:o},transportPriority:o}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,o={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:o,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async v=>{a={...a,...v},await c?.setAuth(l());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:d,deviceSign:e.authority?.deviceSign??(v=>t.signDeviceBytes(v)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeAuth:e.nativeAuth}),[g,{wrapAssembly:f}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=f(g,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({browserTrustPersistence:this.browserPersistence,sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(v){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),v}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),o=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,o),l=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:o.name,devicePlatform:o.platform,deviceMetadata:o.metadata,nativeAuth:i}),d=[];if(this.internals.platform!=="native")try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),{DeviceHandle:g}=await import('./deviceHandle-OAF6XJPY.js'),f;return f=new g(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(f);},new u(d)),this.handles.add(f),f}async joinSpace(e,t={}){this.assertOpen();let i=y(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),o=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new z(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-52G6ONQZ.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=y(e);if(t.mesh===true&&t.advancedFanout===true)throw d(a.TICKET_MESH_INVALID_OPTIONS,"[OpenRTC] Ticket mesh cannot use advancedFanout.",{retryable:false,plane:"admission"});let n=ae(t);if(t.mesh===true&&(!Number.isSafeInteger(n)||n<te||n>H))throw d(a.TICKET_MESH_INVALID_OPTIONS,`[OpenRTC] Ticket mesh maxPeers must be an integer between ${te} and ${H}.`,{retryable:false,plane:"admission"});let r=await(t.identity==="session"||t.mesh===true?this.sessionPlane():this.controlPlane()),o=await r.capability("ticket",i,n,t.advancedFanout),a$1=String(b$1(o.token).principalId),c=await this.activate({kind:"ticket",id:i,source:o,principalId:a$1,deviceId:N(o),maxPeers:n,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:r}),l=null;if(t.mesh===true)try{l=await c.advanced.runtime.issueTicketMesh(i,n);}catch(u){await this.shutdownFailedTicketActivation(i,c,u);}let d$1;return d$1=new E(i,c,()=>{this.channels.detach(c),this.onClosed(d$1);},o.token,l,t.mesh===true),this.handles.add(d$1),d$1}async joinTicket(e){this.assertOpen();let t=b$4(e);if(!t.mesh)throw d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"});let i=y(t.id),n=await this.sessionPlane(),r=await n.capability("ticket",i,t.maxPeers,false),o=String(b$1(r.token).principalId),a$1=await this.activate({kind:"ticket",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:false,controlPlane:n});try{await a$1.advanced.runtime.joinTicketMesh(e);}catch(l){await this.shutdownFailedTicketActivation(i,a$1,l);}let c;return c=new E(i,a$1,()=>{this.channels.detach(a$1),this.onClosed(c);},r.token,e,true),this.handles.add(c),c}async shutdownFailedTicketActivation(e,t,i){this.channels.detach(t);try{await t.advanced.runtime.shutdown();}catch(n){throw this.retainPendingCapabilityShutdown(`ticket:${e}`,()=>t.advanced.runtime.shutdown()),d(a.TICKET_MESH_UNAVAILABLE,"[OpenRTC] Ticket mesh startup failed and runtime teardown was not confirmed.",{retryable:true,plane:"coordination",cause:{startError:i,shutdownError:n}})}throw i}async close(){if(this.closed)return;if(this.closing)return this.closing;let e=this.closeOnce();this.closing=e;try{await e;}finally{this.closing===e&&(this.closing=null);}}async closeOnce(){await Promise.allSettled([...this.activations.values()].map(({promise:e})=>e)),await Promise.all([...this.handles].map(e=>e.close())),await Promise.all([...this.pendingCapabilityShutdowns.keys()].map(e=>this.settlePendingCapabilityShutdown(e))),await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.(),this.closed=true;}};function Ne(s,e){return new M(s,e)}function Ge(s,e){if(!(s instanceof M))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return s.openAuthorityRoom(e)}export{R as a,x as b,pe as c,Fe as d,y as e,ie as f,N as g,O as h,Ne as i,Ge as j};