openrtc 2.5.3 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/{Connection-CovQdc8E.d.ts → Connection-CQdRHqjO.d.ts} +36 -1
  2. package/dist/{DelegatingRuntimeAdapter-3ykiNvyh.d.ts → DelegatingRuntimeAdapter-B8ubDv86.d.ts} +2 -2
  3. package/dist/{IpcRuntimeAdapter-BkM_1HyL.d.ts → IpcRuntimeAdapter-D4vIpOre.d.ts} +16 -6
  4. package/dist/WasmBridge-W3GRBTTZ.js +1 -0
  5. package/dist/{assembly-C235UKSS.d.ts → assembly-D9vP5Q6M.d.ts} +2 -2
  6. package/dist/{capabilities-CdZpAKvE.d.ts → capabilities-BgxJVk9q.d.ts} +1 -1
  7. package/dist/chunk-4R5BLX2U.js +2 -0
  8. package/dist/{chunk-WMA4OMJL.js → chunk-5KN6YOM6.js} +1 -1
  9. package/dist/chunk-BEYBIRAN.js +2 -0
  10. package/dist/chunk-C7UBBRYW.js +2 -0
  11. package/dist/{chunk-CHT46RA7.js → chunk-DOI7F3VQ.js} +1 -1
  12. package/dist/{chunk-4CC6YIGG.js → chunk-FQB3VTOC.js} +1 -1
  13. package/dist/chunk-GQWHEDGU.js +2 -0
  14. package/dist/chunk-HQ6ANBIU.js +1 -0
  15. package/dist/chunk-ISTROQQJ.js +1 -0
  16. package/dist/chunk-NHIANLEM.js +1 -0
  17. package/dist/{chunk-P5GCLQHS.js → chunk-V7E4OUN5.js} +1 -1
  18. package/dist/controlPlane-T3TOHY3D.js +1 -0
  19. package/dist/coreClient.d.ts +3 -3
  20. package/dist/deviceEnrollment-2UW67OPP.js +2 -0
  21. package/dist/index.d.ts +24 -7
  22. package/dist/index.js +1 -1
  23. package/dist/ipcFactory-ZEHQMCEM.js +1 -0
  24. package/dist/native.d.ts +5 -5
  25. package/dist/native.js +1 -1
  26. package/dist/node.d.ts +8 -5
  27. package/dist/node.js +2 -2
  28. package/dist/{openrtc-KERRTMSG.js → openrtc-R6EPOY3N.js} +1 -1
  29. package/dist/openrtc_bg.wasm +0 -0
  30. package/dist/{room-2MUFAJ4M.js → room-Z6F46KMH.js} +1 -1
  31. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  32. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  33. package/dist/runtime/device-status.d.ts +1 -1
  34. package/dist/runtime/factories.d.ts +5 -5
  35. package/dist/runtime/factories.js +1 -1
  36. package/dist/runtime/index.d.ts +9 -9
  37. package/dist/runtime/index.js +1 -1
  38. package/dist/server-browser.d.ts +4 -4
  39. package/dist/server.d.ts +4 -4
  40. package/dist/server.js +1 -1
  41. package/dist/service-node.d.ts +4 -4
  42. package/dist/service-node.js +1 -1
  43. package/dist/testing/native.d.ts +4 -4
  44. package/dist/testing/native.js +1 -1
  45. package/dist/testing.d.ts +4 -4
  46. package/dist/testing.js +1 -1
  47. package/dist/transport/index.d.ts +2 -2
  48. package/dist/{types-C6SMXBzJ.d.ts → types-jxyrOzCw.d.ts} +7 -1
  49. package/native/darwin-arm64/openrtc-node-host +0 -0
  50. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  51. package/native/darwin-x64/openrtc-node-host +0 -0
  52. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  53. package/native/linux-x64/openrtc-node-host +0 -0
  54. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  55. package/package.json +1 -1
  56. package/dist/WasmBridge-LP7FHTHZ.js +0 -1
  57. package/dist/chunk-25CN4MLA.js +0 -2
  58. package/dist/chunk-42TNJH5S.js +0 -1
  59. package/dist/chunk-4J4F32QT.js +0 -1
  60. package/dist/chunk-BFN3AVHA.js +0 -2
  61. package/dist/chunk-N6LGTNUI.js +0 -1
  62. package/dist/chunk-VC7TGJFS.js +0 -2
  63. package/dist/controlPlane-IIPEJ77Q.js +0 -1
  64. package/dist/deviceEnrollment-ZQZ2WP5H.js +0 -2
  65. package/dist/ipcFactory-2WMR4PH6.js +0 -1
@@ -1,2 +1,2 @@
1
- import {j,d as d$1,c}from'./chunk-42TNJH5S.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
1
+ import {j,d as d$1,c}from'./chunk-HQ6ANBIU.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
2
2
  export{p as a,S as b};
@@ -1 +1 @@
1
- import {t}from'./chunk-25CN4MLA.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
1
+ import {t}from'./chunk-GQWHEDGU.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
@@ -0,0 +1,2 @@
1
+ import {b,d,l}from'./chunk-OT7IPLZE.js';import {a}from'./chunk-ISTROQQJ.js';import {e,g as g$1,f,c,i}from'./chunk-4R5BLX2U.js';import*as G from'tweetnacl';function Nt(){throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an AuthProvider; legacy runtimes must import openrtc/auth explicitly.");}var xe="openrtc-trust";var ce="identity",I="managed-room-keys",A="managed-room-state";function Ge(){if(typeof globalThis.indexedDB>"u")throw new Error("[OpenRTC] Managed rooms require durable IndexedDB storage.");return globalThis.indexedDB}function Ne(){return new Promise((t,e)=>{let n=Ge().open(xe,2);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(ce)||i.createObjectStore(ce),i.objectStoreNames.contains(I)||i.createObjectStore(I),i.objectStoreNames.contains(A)||i.createObjectStore(A);},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("managed room database failed")),n.onblocked=()=>e(new Error("managed room database upgrade is blocked"));})}function V(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>n(t.error??new Error("managed room storage failed"));})}function P(t){return new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error??new Error("managed room storage failed")),t.onabort=()=>n(t.error??new Error("managed room storage aborted"));})}function Oe(t,e,n){return `${t}:${e}:${n}`}function Ke(t,e){return `${t}:${e}`}function de(t){return new TextEncoder().encode(`openrtc-managed-room-state-v1:${t}`)}async function Le(t,e){let n=t.transaction(I,"readonly"),i=P(n),r=await V(n.objectStore(I).get(e));if(await i,r)return r;let o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},false,["encrypt","decrypt"]),s=t.transaction(I,"readwrite"),c=P(s);s.objectStore(I).add(o,e);try{return await c,o}catch{let a=t.transaction(I,"readonly"),l=P(a),u=await V(a.objectStore(I).get(e));if(await l,!u)throw new Error("[OpenRTC] Managed room wrapping key could not be persisted.");return u}}function He(t){let e=t;return e?.schemaVersion===1&&e.wrappedKey instanceof Uint8Array&&e.wrappingNonce instanceof Uint8Array&&e.wrappingNonce.byteLength===12&&(e.sealedState===void 0||e.sealedState instanceof Uint8Array)?e:null}async function $(t,e,n){let i=await Ne(),r=Oe(t,e,n);try{let o=await Le(i,Ke(t,e)),s=i.transaction(A,"readonly"),c=P(s),a=He(await V(s.objectStore(A).get(r)));await c;let l,u;if(a){let d=await crypto.subtle.decrypt({name:"AES-GCM",iv:a.wrappingNonce,additionalData:de(r)},o,a.wrappedKey).catch(()=>{throw new Error("[OpenRTC] Managed room state key authentication failed.")});if(l=new Uint8Array(d),l.byteLength!==32)throw new Error("[OpenRTC] Managed room state key is invalid.");u=a;}else {l=crypto.getRandomValues(new Uint8Array(32));let d=crypto.getRandomValues(new Uint8Array(12)),b=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:de(r)},o,l));u={schemaVersion:1,wrappingNonce:d,wrappedKey:b};let y=i.transaction(A,"readwrite"),f=P(y);y.objectStore(A).add(u,r),await f;}return {wrappingKey:l,sealedState:u.sealedState,async persist(d){if(!(d instanceof Uint8Array)||d.byteLength===0)throw new Error("[OpenRTC] Managed room sealed state is invalid.");let b=i.transaction(A,"readwrite"),y=P(b);b.objectStore(A).put({...u,sealedState:d},r),await y,u={...u,sealedState:d};},close(){l.fill(0),i.close();}}}catch(o){throw i.close(),o}}var Be=3e4,Fe=5*6e4,ze=3e4,je=100,We=48*1024,le=12,qe=10*6e4,Ve=5*6e4,k=15e3,$e=15e3,Je=1e3,ue=250;function pe(t){let e=[...new Set(t.map(n=>String(n??"").trim().toLowerCase()).filter(Boolean))].sort();if(e.length>ue)throw new Error(`Coordination excluded-peer set exceeds ${ue} devices.`);return e}var Ye="openrtc.v2",Qe="openrtc.auth.";function fe(t){try{let e=t.split(".")[1];if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),i=JSON.parse(globalThis.atob(n));return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}catch{return null}}function he(t){let e=fe(t)?.jti;return typeof e=="string"&&e.length>0?e:null}var h=class extends f{constructor(n,i$1,r,o={}){super({code:e.COORDINATION_DISCONNECTED,plane:"coordination",...c(r)?i({...o,code:r,message:n,retryable:i$1}):{},message:n,retryable:i$1});this.gatewayCode=r;this.name="CoordinationConnectError";}},H=class extends f{constructor(n,i$1,r,o={}){let s=i({...o,code:n,message:i$1,retryable:r});super({...s,retryable:r,message:`Coordination gateway ${n}: ${i$1}`});this.name="CoordinationGatewayProtocolError";}};function ge(t){return t instanceof h&&/\bstale-budget\b/i.test(t.message)}function D(t){if(!t||typeof t!="object")return false;let e=t;return e.gatewayCode==="credential-revoked"||e.code==="credential-revoked"||e.reason==="device-certificate-revoked"}function me(t){if(D(t))return true;if(typeof t!="object"||t===null)return false;let e=t;if(e.retryable===false)return true;let n=e.status??e.statusCode,i=typeof n=="number"?n:Number.NaN;if(Number.isInteger(i)&&i>=400&&i<500&&![408,425,429].includes(i))return true;let r=String(e.code??"");return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(r)}function Xe(t){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(t*(.75+e[0]/4294967295*.5)))}function v(t){if(typeof crypto.randomUUID=="function")return `${t}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${t}:${n}`}async function Ze(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),n="";for(let i of new Uint8Array(e))n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function _(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error("[OpenRTC] Managed room payload encoding is invalid.");let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e.padEnd(Math.ceil(e.length/4)*4,"="));return Uint8Array.from(n,i=>i.charCodeAt(0))}function et(t,e,n){let i=new URL(t);if(i.search||i.hash||i.username||i.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(i.protocol==="https:")i.protocol="wss:";else if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol!=="wss:"&&i.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return i.pathname=`${i.pathname.replace(/\/+$/,"")}/v${n}/connect/${e}`,i.toString()}function ye(t){let e=new URL(t);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var U=class t{constructor(e){this.options=e;this.runtimeInstanceId=v("runtime");this.socket=null;this.serviceObservationGeneration=0;this.socketReady=false;this.activeGrantToken=null;this.refillCredential=null;this.activeGrantJti=null;this.activeAvenue=null;this.activeGrantExpiresAtMs=0;this.activeGrantProtocolVersion=1;this.leaseRefreshMode="off";this.pendingLeaseRefreshKey=null;this.authenticationRefreshTail=Promise.resolve();this.authenticationRefreshes=new Map;this.connectPromise=null;this.desiredPresence=null;this.friendObservationPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.sparseMembers=new Map;this.sparseRoutes=new Map;this.pendingMembershipPageSnapshot=null;this.sparseTopologyRevision=0;this.roomArchitectureSnapshot=null;this.roomAuthorityAssignment=null;this.roomAuthorityAssignmentExpiry=null;this.roomEncryptionEpoch=0;this.managedWasmClient=null;this.peerAdmissionRuntime=null;this.peerAdmissionScope=null;this.peerAdmissionRevision=0;this.managedStateProvider=$;this.managedState=null;this.managedInitialization=null;this.managedActions=Promise.resolve();this.managedPublishQueue=[];this.managedPublishScheduled=false;this.managedMessageListeners=new Set;this.deviceListeners=new Set;this.architectureListeners=new Set;this.authorityAssignmentListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.keepaliveTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectOutageStartedAtMs=null;this.reconnectCircuitOpen=false;this.hostAvailable=true;this.connectionReadyWaiters=new Set;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;this.credentialRevoked=false;if(this.initialExcludedPeers=pe(e.initialExcludedPeers??[]),this.desiredExcludedPeers=[...this.initialExcludedPeers],e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let n=new URL(e.gateway.endpoint),i=n.hostname==="127.0.0.1"||n.hostname==="localhost"||n.hostname==="[::1]",r=n.protocol==="https:"||n.protocol==="wss:",o=e.gateway.testingAllowInsecureLoopback===true&&i&&(n.protocol==="http:"||n.protocol==="ws:");if(!r&&!o)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(n.username||n.password||n.search||n.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,n,i,r,o,s){let c=this.desiredPresence;if(i&&this.options.roomArchitecture==="authority"){let u=this.options.avenueOverride;if(u?.kind!=="room"||!this.peerAdmissionRuntime)throw new Error("[OpenRTC] Authority rooms require Rust peer admission support.");let d=`v2:room:${u.id}`;this.peerAdmissionRuntime.__requireScopePeerAdmission(d),this.peerAdmissionScope=d;}this.desiredPresence={localNodeId:e,ticket:n,online:i,ttlMs:r,metadata:o,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!c||c.localNodeId!==e||c.ticket!==n||c.online!==i||c.ttlMs!==r||c.metadata!==o||c.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);for(let u of this.friendConnections.values())u.updatePresence(e,n,i,r,o,this.desiredPresence.deviceName).catch(()=>{});let l=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(u){if(!(u instanceof h)||!u.retryable)throw u;await this.waitForConnectionReady();}this.appliedPresenceRevision>=l||(c&&c.ticket!==n&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:v("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,l));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:v("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<$e)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}setHostAvailability(e){let n=e.available&&!this.hostAvailable;this.hostAvailable=e.available;for(let i of this.roomConnections.values())i.setHostAvailability(e);for(let i of this.friendConnections.values())i.setHostAvailability(e);if(!e.available){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}n&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(i=>this.scheduleReconnect(i));}async updateDevice(e,n){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=n;if(n.excludedPeers!==void 0){let r=pe(n.excludedPeers);this.desiredExcludedPeers=r,i={...n,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:v("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let n=new t({...this.options,credentialPurpose:"device-control"});try{await n.deleteDevice(e);}finally{n.stopAuthActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:v("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,n){let i=r=>e(n?r.filter(o=>o.nodeId!==n):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected().catch(()=>{}),()=>this.deviceListeners.delete(i)}onRoomArchitectureChange(e){return this.architectureListeners.add(e),this.roomArchitectureSnapshot&&e({...this.roomArchitectureSnapshot}),()=>this.architectureListeners.delete(e)}onRoomAuthorityAssignmentChange(e){return this.authorityAssignmentListeners.add(e),e(this.roomAuthorityAssignmentSnapshot()),()=>this.authorityAssignmentListeners.delete(e)}async publishAuthorityAssignment(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"authority.assignment.publish",idempotencyKey:v("authority-assignment"),assignment:e.assignment,signature:e.signature});}setWasmClient(e){this.setManagedRoomRuntime(e,$);}setManagedRoomRuntime(e,n){let i=e;this.peerAdmissionRuntime=i&&typeof i.__requireScopePeerAdmission=="function"&&typeof i.__updateScopePeerAdmission=="function"?i:null;let r=e;this.managedWasmClient=r&&typeof r.__initManagedRoomGroup=="function"&&typeof r.__handleManagedRoomPreparePage=="function"&&typeof r.__handleManagedRoomArtifactChunk=="function"&&typeof r.__sealManagedRoomPayload=="function"&&typeof r.__openManagedRoomPayload=="function"&&typeof r.__forgetManagedRoomGroup=="function"?r:null,this.managedStateProvider=n,this.roomArchitectureSnapshot?.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}onManagedRoomMessage(e){return this.managedMessageListeners.add(e),()=>this.managedMessageListeners.delete(e)}async publishManagedRoomMessage(e){return new Promise((n,i)=>{this.managedPublishQueue.push({input:e,resolve:n,reject:i}),!this.managedPublishScheduled&&(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));})}async subscribeDevices(){let e=null;return new ReadableStream({start:n=>{e=n,this.deviceStreams.add(n);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&n.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:v("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,n){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:v("session-update"),sessionId:this.unscopedId(e),session:n,expiresAtMs:typeof n.expiresAt=="number"?n.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let n=null;return new ReadableStream({start:i=>{n=i,this.sessionStreams.add(i);},cancel:()=>{n&&this.sessionStreams.delete(n),n=null;}})}async sendMessage(e,n,i,r){await this.ensureConnected();let o=v("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:n,state:i,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,n){let i=[...new Set(e.map(c=>c.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let c of i)if(c.length>128||c.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,s=[];n(new Map);for(let c of i){if(!c||c===this.options.getCurrentUserId())continue;let a=this.friendConnection(c);s.push(a.onDevicesChange(l=>{if(r.value)return;let u=l.filter(d=>d.online);o.set(c,u),n(new Map(o));}));}return ()=>{r.value=true;for(let c of s)c();for(let c of i)this.friendConnections.get(c)?.stopAuthActivity(),this.friendConnections.delete(c);}}waitForFriendDevice(e,n,i=1e4){let r=e.trim(),o=n.trim();return !r||!o?Promise.reject(new Error("Capability-authorized device observation requires user and device ids.")):new Promise((s,c)=>{let a=()=>{},l=false,u=y=>{l||(l=true,clearTimeout(d),a(),y.error?c(y.error):s(y.device));},d=setTimeout(()=>u({error:new Error(`Timed out waiting for capability-authorized device ${o}`)}),Math.max(1,i));a=this.watchFriendDevices([r],y=>{let f=(y.get(r)??[]).find(m=>m.deviceId===o&&m.online&&typeof m.ticket=="string"&&m.ticket.trim().startsWith("endpoint"));f&&u({device:f});}),l&&a();})}setFriendObservationIdentity(e){this.friendObservationPresence={localNodeId:e.localNodeId,ticket:e.ticket,online:true,ttlMs:e.ttlMs,metadata:e.metadata,deviceName:e.deviceName?.trim()||this.options.getDefaultDeviceName()};for(let n of this.friendConnections.values())this.activateFriendConnection(n,this.friendObservationPresence);}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:v("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.credentialRevoked=false,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthActivity(){this.stopped=true,this.friendObservationPresence=null,this.reconnectOutageStartedAtMs=null,this.stopSocket(),this.rejectConnectionReadyWaiters(new h("Coordination activity stopped before capability admission completed.",false)),this.desiredExcludedPeers=[...this.initialExcludedPeers];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();this.pendingAcks.clear();for(let e of this.managedPublishQueue.splice(0))e.reject(new Error("[OpenRTC] Managed room activity stopped."));if(this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.managedState){try{this.managedWasmClient?.__forgetManagedRoomGroup(this.managedAvenueKey());}catch{}this.managedState.close(),this.managedState=null;}this.managedInitialization=null,this.managedMessageListeners.clear(),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment=null,this.authorityAssignmentListeners.clear(),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,n,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new t({...this.options,avenueOverride:{kind:"room",id:r}}),o.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(r,o));try{await o.updatePresence(n,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(s){if(!(s instanceof h)||!s.retryable)throw s;await o.waitForConnectionReady();}}async leaveCoordinationRoom(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthActivity(),this.roomConnections.delete(n));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,n){return this.requireRoomConnection(e).onDevicesChange(r=>n(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.credentialRevoked)throw new h("Coordination credential revoked.",false,"credential-revoked");if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new h("Coordination reconnect is parked until the host is foregrounded and online.",true);if(this.reconnectCircuitOpen)throw new h("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new h("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.serviceObservationGeneration,n=this.desiredPresence??this.controlPresence(),i=this.desiredPresenceRevision,r=async()=>{let o=await this.mintGatewayCredential(n,false);await new Promise((s,c)=>{let a=new WebSocket(et(o.gatewayUrl,o.routeKey,o.protocolVersion),[Ye,`${Qe}${o.token}`]);this.socket=a;let l=false,u=false,d=null,b=()=>{u||a.readyState!==WebSocket.OPEN||(u=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?i:0),clearTimeout(y),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(o.expiresAtMs,o.protocolVersion),this.resolveConnectionReadyWaiters(),s());},y=setTimeout(()=>{a.close(4408,"authentication timeout"),d=new h("Coordination gateway authentication timed out.",true),c(d);},k);a.onopen=()=>{a.send(JSON.stringify({v:1,type:"auth",token:o.token,socketLiveness:"ping-v1",device:this.gatewayDevice(n)}));},a.onmessage=f=>{if(this.stopped||this.socket!==a||f.data==="pong")return;let m;try{m=JSON.parse(String(f.data));}catch{a.close(4400,"invalid gateway frame"),u||(clearTimeout(y),c(new Error("Coordination gateway returned an invalid frame.")));return}if(m.type==="error"&&e===this.serviceObservationGeneration&&this.observeServiceError(m,o.avenue),this.stopped||this.socket!==a)return;if(m.type==="ready"&&!l&&this.socket===a&&(this.activeGrantToken=o.token,this.refillCredential={grant:o,ticket:n.ticket},this.activeGrantJti=he(o.token),this.activeAvenue=o.avenue,this.activeGrantExpiresAtMs=o.expiresAtMs,this.activeGrantProtocolVersion=o.protocolVersion,this.leaseRefreshMode=m.leaseRefreshMode??"off",l=true,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{if(this.socket===a&&a.readyState===WebSocket.OPEN)try{a.send("ping");}catch{a.close(4408,"gateway keepalive failed");}},3e4)),m.type==="error"&&!u){d=new h(`Coordination gateway ${m.code}: ${m.message}`,m.retryable,m.code,m),clearTimeout(y),c(d),a.close(4403,m.code);return}this.handleFrame(m,a);let De=m.type==="roster.snapshot"||m.type==="membership.snapshot"||m.type==="membership.page"&&this.pendingMembershipPageSnapshot===null;l&&(this.options.credentialPurpose==="device-control"||De)&&b();},a.onerror=()=>{u||(clearTimeout(y),d??(d=new h("Coordination gateway connection failed.",true)),c(d));},a.onclose=f=>{clearTimeout(y);let m=this.socket===a;m&&this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),m&&f.code===4403&&(!d||D(d))&&this.stopForCredentialRevocation(new h("Coordination credential revoked.",false,"credential-revoked")),u||(d??(d=new h(`Coordination gateway closed (${f.code}) before its initial projection.`,f.code!==4401&&f.code!==4403)),c(d)),this.socket===a&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed.",a),this.rejectPendingAuthRefresh(new h("Coordination gateway closed during credential refresh.",f.code!==4401&&f.code!==4403),a),m&&!this.stopped&&this.desiredPresence&&f.code!==1e3&&!ge(d)&&this.scheduleReconnect(d??new h(`Coordination gateway closed (${f.code}).`,f.code!==4401));};});};try{await r();}catch(o){if(!ge(o))throw o;await r();}}async mintGatewayCredential(e,n){let i=this.serviceObservationGeneration,r=await this.resolveAvenue(),o={avenue:r,deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await Ze(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:v("credential")},s;try{if(!this.options.gateway.grantProvider)throw new h("OpenRTC 2.0 coordination requires a v2 gateway grant provider.",!1);s=await this.options.gateway.grantProvider({...o,...n&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(a){throw i===this.serviceObservationGeneration&&this.observeServiceError(a,r),a instanceof h?a:new h(a instanceof Error?a.message:"Coordination credential mint failed.",!me(a),D(a)?"credential-revoked":void 0)}if(s.protocolVersion!==2)throw new h("Unsupported coordination gateway protocol.",false);let c=ye(this.options.gateway.endpoint);if(ye(s.gatewayUrl)!==c)throw new h("Coordination credential returned an unexpected gateway origin.",false);return s}observeServiceError(e,n){if(this.stopped||!this.options.gateway.onServiceError)return;let i=a(e,n);if(i)try{Promise.resolve(this.options.gateway.onServiceError(i)).catch(()=>{});}catch{}}handleFrame(e,n=this.socket){if(!(n&&n!==this.socket)){if(e.type==="error"&&e.code==="credential-revoked"){let i=new h(`Coordination gateway ${e.code}: ${e.message}`,false,e.code);this.rejectPendingAcks(i.message,n??void 0),this.rejectPendingAuthRefresh(i,n??void 0),this.stopForCredentialRevocation(i);return}if(e.type==="auth.refreshed"){let i=this.pendingAuthRefresh;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve());}else if(e.type==="lease.refreshed"){let i=this.pendingAuthRefresh;if(i&&i.socket===n&&e.idempotencyKey===this.pendingLeaseRefreshKey){if(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=Date.now()){this.rejectPendingAuthRefresh(new h("Coordination lease refresh is already expired or invalid.",false),n);return}clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.activeGrantExpiresAtMs=e.expiresAtMs,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve();}}else if(e.type==="roster.snapshot"){this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.devices.clear();for(let i of e.devices)this.devices.set(i.deviceId,this.toDevice(i));this.emitDevices();}else if(e.type==="membership.snapshot"){this.pendingMembershipPageSnapshot=null,this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let i of e.members)this.sparseMembers.set(i.deviceId,i);this.rebuildSparseDevices();}else if(e.type==="membership.page"){let i=/^[A-Za-z0-9:_-]{1,160}$/.test(e.snapshotId)&&Number.isSafeInteger(e.pageIndex)&&Number.isSafeInteger(e.pageCount)&&Number.isSafeInteger(e.memberCount)&&e.pageIndex>=0&&e.pageCount>=2&&e.pageCount<=50&&e.pageIndex<e.pageCount&&e.memberCount>100&&e.memberCount<=5e3&&e.members.length>0&&e.members.length<=100;e.pageIndex===0&&i&&(this.pendingMembershipPageSnapshot={snapshotId:e.snapshotId,nextPageIndex:0,pageCount:e.pageCount,memberCount:e.memberCount,members:new Map});let r=this.pendingMembershipPageSnapshot;if(!(i&&r!==null&&r.snapshotId===e.snapshotId&&r.nextPageIndex===e.pageIndex&&r.pageCount===e.pageCount&&r.memberCount===e.memberCount&&e.members.every(s=>s.deviceId.length>0&&!r.members.has(s.deviceId)))||!r){n?.close(4400,"invalid membership page");return}for(let s of e.members)r.members.set(s.deviceId,s);if(r.nextPageIndex+=1,r.nextPageIndex===r.pageCount){if(r.members.size!==r.memberCount){n?.close(4400,"incomplete membership pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let s of r.members.values())this.sparseMembers.set(s.deviceId,s);this.pendingMembershipPageSnapshot=null,this.rebuildSparseDevices();}}else if(e.type==="membership.changed")e.operation==="delete"?this.sparseMembers.delete(e.member.deviceId):this.sparseMembers.set(e.member.deviceId,e.member),this.rebuildSparseDevices();else if(e.type==="topology.lease")this.acceptTopologyLease(e.lease);else if(e.type==="authority.assignment")this.acceptAuthorityAssignment(e.assignment,e.signature);else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let i=this.devices.has(e.device.deviceId),r=this.toDevice(e.device);this.devices.set(r.deviceId,r),this.emitDeviceEvents([{type:i?"modified":"added",device:r}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=Je&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="managed.prepare.page"||e.type==="managed.commit.chunk.received"||e.type==="managed.received")this.enqueueManagedWork(()=>this.handleManagedFrame(e));else if(e.type==="session.changed"){let i=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let r of this.sessionStreams)r.enqueue(i);}else if(e.type==="ack"){let i=this.pendingAcks.get(e.idempotencyKey);i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh?.socket===n&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let r=this.pendingAuthRefresh;clearTimeout(r.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,r.reject(new h(`Coordination gateway ${e.code}: ${e.message}`,e.retryable,e.code,e));return}let i=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.reject(new H(e.code,e.message,e.retryable,e)));}}}enqueueManagedWork(e){let n=this.managedActions.then(e);this.managedActions=n.catch(i=>{console.error("[OpenRTC] Managed room owner rejected a gateway frame:",i),this.socket?.close(4400,"managed room state invalid");});}async flushManagedPublishBatch(){let e=this.managedPublishQueue.splice(0,je);if(e.length!==0)try{await this.ensureConnected(),await this.ensureManagedGroupInitialized();let n=this.roomArchitectureSnapshot,i=this.managedWasmClient,r=this.managedState;if(!n||n.effective!=="managed"||n.phase!=="settled"||this.roomEncryptionEpoch<1||!i||!r)throw new Error("[OpenRTC] Managed room encryption is not settled.");let o=[];for(let l of e){let u=await i.__sealManagedRoomPayload(this.managedAvenueKey(),BigInt(n.epoch),BigInt(this.roomEncryptionEpoch),l.input.messageId,l.input.channel,l.input.priority,l.input.zoneId,l.input.payload);o.push({item:l,sealedState:u.sealedState,envelope:{messageId:l.input.messageId,channel:l.input.channel,priority:l.input.priority,scope:l.input.zoneId?{kind:"zone",zoneId:l.input.zoneId}:{kind:"global"},ciphertext:u.payload}});}await r.persist(_(o[o.length-1].sealedState));let s=[],c=0,a=async()=>{if(s.length===0)return;let l=s;s=[],c=0,await this.sendOperation({v:1,type:"managed.publish",idempotencyKey:v("managed-publish"),architectureEpoch:n.epoch,encryptionEpoch:this.roomEncryptionEpoch,batch:l.map(({envelope:u})=>u)});for(let{item:u}of l)u.resolve();};for(let l of o){let u=l.envelope.ciphertext.length;s.length>0&&c+u>We&&await a(),s.push(l),c+=u;}await a();}catch(n){for(let i of e)i.reject(n);throw n}finally{this.managedPublishQueue.length>0&&!this.managedPublishScheduled&&(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));}}managedAvenueKey(){let e=this.activeAvenue??this.options.avenueOverride;if(!e||e.kind!=="room"&&e.kind!=="space")throw new Error("[OpenRTC] Managed groups require an active room or space.");return `${e.kind}:${e.id}`}async ensureManagedGroupInitialized(){if(this.managedState)return;if(this.managedInitialization)return this.managedInitialization;let e=this.managedWasmClient;if(!e)throw new Error("[OpenRTC] This browser runtime has no managed-room Rust/WASM owner.");let n=this.managedAvenueKey(),i=(async()=>{let r=await this.managedStateProvider(this.options.appTag,this.options.getLocalDeviceId(),n),o=await e.__initManagedRoomGroup(n,this.options.getLocalDeviceId(),r.wrappingKey,r.sealedState);this.managedState=r,await this.executeManagedGroupActions([o]);})();this.managedInitialization=i;try{await i;}finally{this.managedInitialization===i&&(this.managedInitialization=null);}}async executeManagedGroupActions(e){for(let n of e)if(n.type==="persist-state"){let i=this.managedState;if(!i)throw new Error("[OpenRTC] Managed room state store is unavailable.");await i.persist(_(n.sealedState));}else n.type==="publish-key-package"?await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:v("managed-key-package"),keyPackageHash:n.keyPackageHash,keyPackage:n.keyPackage}):n.type==="request-prepare-page"?await this.sendOperation({v:1,type:"managed.prepare.page.request",idempotencyKey:v("managed-prepare-page"),preparationId:n.preparationId,pageIndex:n.pageIndex}):n.type==="send-artifact-chunk"?await this.sendOperation({v:1,type:"managed.commit.chunk",idempotencyKey:v("managed-artifact"),...n.chunk}):n.type==="acknowledge-commit"&&await this.sendOperation({v:1,type:"managed.commit.ack",idempotencyKey:v("managed-commit-ack"),preparationId:n.preparationId,encryptionEpoch:n.encryptionEpoch,groupIdHash:n.groupIdHash});}async handleManagedFrame(e){await this.ensureManagedGroupInitialized();let n=this.managedWasmClient;if(!n)throw new Error("[OpenRTC] Managed room Rust/WASM owner is unavailable.");let i=this.managedAvenueKey();if(e.type==="managed.prepare.page"){await this.executeManagedGroupActions(await n.__handleManagedRoomPreparePage(i,e));return}if(e.type==="managed.commit.chunk.received"){await this.executeManagedGroupActions(await n.__handleManagedRoomArtifactChunk(i,e));return}let r=this.roomArchitectureSnapshot;if(!r||r.effective!=="managed"||r.phase!=="settled"||e.architectureEpoch!==r.epoch||e.encryptionEpoch!==this.roomEncryptionEpoch)throw new Error("[OpenRTC] Managed room delivery uses a stale room lease.");let o=[],s=null;for(let c of e.batch){let a=c.scope.kind==="zone"?c.scope.zoneId:void 0,l=await n.__openManagedRoomPayload(i,BigInt(e.architectureEpoch),BigInt(e.encryptionEpoch),c.messageId,c.channel,c.priority,a,_(c.ciphertext));s=l.sealedState,o.push({senderId:e.senderDeviceId,messageId:c.messageId,channel:c.channel,priority:c.priority,...a?{zoneId:a}:{},payload:_(l.payload)});}if(s){let c=this.managedState;if(!c)throw new Error("[OpenRTC] Managed room state store is unavailable.");await c.persist(_(s));}for(let c of o)for(let a of this.managedMessageListeners)a(c);}async sendOperation(e$1){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let n=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e$1);}catch(i){if(!(i instanceof H)||i.code!=="budget-renewal-required"&&i.code!==e.BUDGET_RENEWAL_REQUIRED||!i.retryable)throw i;this.budgetRenewalEpoch===n&&await this.renewBudget(),await this.sendOperationOnce(e$1);}}async sendOperationOnce(e){let n=this.socket;if(!n||n.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.get(e.idempotencyKey)?.timer===o&&this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},k);this.pendingAcks.set(e.idempotencyKey,{socket:n,resolve:i,reject:r,timer:o});try{n.send(JSON.stringify(e));}catch(s){clearTimeout(o),this.pendingAcks.delete(e.idempotencyKey),r(s instanceof Error?s:new Error(String(s)));}});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication(true,true).then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let n=await this.options.resolveSpaceNamespaceId();if(!n)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:n}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}rebuildSparseDevices(){this.devices.clear();for(let e of this.sparseMembers.values()){let n=this.sparseRoutes.get(e.deviceId),i=n?{...e,...n}:{...e,runtimeInstanceId:"",nodeId:"",ticket:""};this.devices.set(e.deviceId,this.toDevice(i));}this.emitDevices();}acceptTopologyLease(e){if(e.topologyRevision<=this.sparseTopologyRevision)return;let n=this.activeAvenue,i=[...e.active,...e.backups],r=i.map(d=>d.deviceId),o=e.schemaVersion===1||this.validArchitectureLease(e.architecture),s=e.schemaVersion===1||this.validGroupEncryptionLease(e.groupEncryption,e.architecture),c=e.schemaVersion===2&&e.architecture.effectiveMode==="authority",a=e.schemaVersion===2?e.admissionPeers:void 0,l=!c||this.peerAdmissionScope!==null&&this.peerAdmissionRuntime!==null&&Array.isArray(a)&&a.length<=50&&new Set(a.map(d=>d.deviceId)).size===a.length&&a.every(d=>this.sparseMembers.get(d.deviceId)?.online&&d.deviceId!==this.options.getLocalDeviceId()&&/^[0-9a-f]{64}$/.test(d.nodeId));if(!((e.schemaVersion===1||e.schemaVersion===2)&&o&&s&&l&&Number.isSafeInteger(e.topologyRevision)&&e.topologyRevision>0&&(this.sparseTopologyRevision===0?e.previousTopologyRevision===void 0:e.previousTopologyRevision===this.sparseTopologyRevision)&&e.grantJti===this.activeGrantJti&&n!==null&&e.avenue.kind===n.kind&&e.avenue.id===n.id&&Number.isSafeInteger(e.expiresAtMs)&&e.expiresAtMs>Date.now()&&e.expiresAtMs<=this.activeGrantExpiresAtMs&&e.active.length<=16&&e.backups.length<=4&&i.length<=20&&new Set(r).size===r.length&&i.every(d=>d.online&&this.sparseMembers.has(d.deviceId)&&d.deviceId!==this.options.getLocalDeviceId()&&d.nodeId.trim().length>0&&d.ticket.trim().length>0))){this.socket?.close(4400,"invalid topology lease");return}if(c)try{this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,e.expiresAtMs,JSON.stringify(a.map(d=>d.nodeId)));}catch{this.socket?.close(4400,"invalid peer admission lease");return}if(e.schemaVersion===2){e.groupEncryption&&(this.roomEncryptionEpoch=e.groupEncryption.epoch);let d={requested:e.architecture.requestedMode,effective:e.architecture.effectiveMode,epoch:e.architecture.epoch,phase:e.architecture.phase,reason:e.architecture.reason,heldCreditsUsd:e.architecture.heldCreditsMicrousd/1e6,quoteExpiresAtMs:e.architecture.quoteExpiresAtMs},b=JSON.stringify(d)!==JSON.stringify(this.roomArchitectureSnapshot);if(this.roomArchitectureSnapshot=d,b)for(let y of this.architectureListeners)y({...d});if(d.effective!=="authority"&&this.roomAuthorityAssignment){this.roomAuthorityAssignmentExpiry&&(clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null),this.roomAuthorityAssignment=null;for(let y of this.authorityAssignmentListeners)y(null);}d.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}this.sparseTopologyRevision=e.topologyRevision,this.sparseRoutes.clear();for(let d of e.active)this.sparseRoutes.set(d.deviceId,{...d,topologyRole:"active",topologyRevision:e.topologyRevision});for(let d of e.backups)this.sparseRoutes.set(d.deviceId,{...d,topologyRole:"backup",topologyRevision:e.topologyRevision});this.rebuildSparseDevices();}acceptAuthorityAssignment(e,n){let i=this.roomAuthorityAssignment,r=this.options.getLocalDeviceId(),o=[e.serviceId,e.subjectDeviceId,e.shardId,...e.priorityDeviceIds,...e.relevantEntityIds];if(i&&e.generation===i.generation&&e.revision===i.revision){if(JSON.stringify({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:e.priorityDeviceIds,relevantEntityIds:e.relevantEntityIds,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs})===JSON.stringify(i))return;this.socket?.close(4400,"invalid authority assignment");return}if(!(e.policyVersion==="room-authority-assignment-v1"&&this.roomArchitectureSnapshot?.effective==="authority"&&e.subjectDeviceId===r&&Number.isSafeInteger(e.generation)&&e.generation>0&&Number.isSafeInteger(e.revision)&&e.revision>0&&Number.isSafeInteger(e.issuedAtMs)&&Number.isSafeInteger(e.expiresAtMs)&&e.issuedAtMs<=Date.now()+3e4&&e.expiresAtMs>Date.now()&&e.expiresAtMs-e.issuedAtMs<=12e4&&e.priorityDeviceIds.length<=8&&e.relevantEntityIds.length<=32&&new Set(e.priorityDeviceIds).size===e.priorityDeviceIds.length&&new Set(e.relevantEntityIds).size===e.relevantEntityIds.length&&o.every(a=>/^[A-Za-z0-9_.:@-]{1,160}$/.test(a))&&/^[A-Za-z0-9_-]{86}$/.test(n)&&(!i||e.generation>i.generation||e.generation===i.generation&&e.revision>i.revision))){this.socket?.close(4400,"invalid authority assignment");return}this.roomAuthorityAssignment=Object.freeze({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:Object.freeze([...e.priorityDeviceIds]),relevantEntityIds:Object.freeze([...e.relevantEntityIds]),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs}),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=setTimeout(()=>{if(this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment?.expiresAtMs===e.expiresAtMs){this.roomAuthorityAssignment=null;for(let a of this.authorityAssignmentListeners)a(null);}},Math.max(0,e.expiresAtMs-Date.now()));for(let a of this.authorityAssignmentListeners)a(this.roomAuthorityAssignmentSnapshot());}roomAuthorityAssignmentSnapshot(){let e=this.roomAuthorityAssignment;return !e||e.expiresAtMs<=Date.now()?null:{...e,priorityDeviceIds:[...e.priorityDeviceIds],relevantEntityIds:[...e.relevantEntityIds]}}validArchitectureLease(e){let n=this.roomArchitectureSnapshot?.epoch??0,i=new Set(["auto","mesh","sparse","managed","authority"]),r=new Set(["mesh","sparse","managed","authority"]),o=new Set(["size","traffic","latency","cost","capacity","manual","recovery"]);return e.policyVersion==="room-architecture-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=n&&(e.epoch===n||n===0||e.previousArchitectureEpoch===n)&&i.has(e.requestedMode)&&r.has(e.effectiveMode)&&(e.phase==="settled"||e.phase==="preparing")&&o.has(e.reason)&&Number.isSafeInteger(e.heldCreditsMicrousd)&&e.heldCreditsMicrousd>=0&&Number.isSafeInteger(e.quoteExpiresAtMs)&&e.quoteExpiresAtMs>0&&(e.reservationId===void 0||/^[A-Za-z0-9:_-]{1,160}$/.test(e.reservationId))}validGroupEncryptionLease(e,n){if(!e)return n.effectiveMode!=="managed"||n.phase==="preparing";let i=this.roomEncryptionEpoch;return e.policyVersion==="room-mls-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=i&&(e.epoch===i||i===0||e.previousEncryptionEpoch===i)&&(e.phase==="preparing"||e.phase==="settled")&&(n.effectiveMode!=="managed"||n.phase!=="settled"||e.phase==="settled")&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(e.committerDeviceId)&&/^[A-Za-z0-9_-]{43}$/.test(e.groupIdHash)}snapshot(e){return [...this.devices.values()].filter(n=>!e||n.nodeId!==e).sort((n,i)=>n.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let n of this.deviceListeners)n(e);}emitDeviceEvents(e){for(let n of this.deviceStreams)n.enqueue(e);}updateLocalDeviceExpiry(e){let n=this.options.getLocalDeviceId(),i=this.devices.get(n);if(!i||i.expiresAt===e)return;let r={...i,expiresAt:e};this.devices.set(n,r),this.emitDeviceEvents([{type:"modified",device:r}]),this.emitDevices();}scheduleAuthRefresh(e,n){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),r=n===2?Fe:Be,o=i>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!o){this.stopSocket(false),this.scheduleReconnect(new h("Coordination credential crossed a billing boundary.",true));return}(n===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(c=>{this.stopSocket(false),this.scheduleReconnect(c);});},o?i-r:Math.max(1e3,i+1e3));}refreshAuthentication(e=false,n=false){let i=`${n?"refill":e?"issue":"refresh"}\0${this.desiredPresence?.ticket??""}`,r=this.authenticationRefreshes.get(i);if(r)return r;let o=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performAuthenticationRefresh(e,n));this.authenticationRefreshTail=o,this.authenticationRefreshes.set(i,o);let s=()=>{this.authenticationRefreshes.get(i)===o&&this.authenticationRefreshes.delete(i);};return o.then(s,s),o}currentRefillCredential(e){let n=this.refillCredential;if(!n||n.ticket!==e||n.grant.token!==this.activeGrantToken||n.grant.protocolVersion!==2||n.grant.expiresAtMs<this.activeGrantExpiresAtMs)return null;let i=fe(n.grant.token);return i?.budget?.controlFunding?.recipeVersion!=="coordination-provider-control-v3"||!Number.isSafeInteger(i?.exp)||!Number.isSafeInteger(n.grant.expiresAtMs)||Math.min(n.grant.expiresAtMs,Number(i?.exp)*1e3)<=Date.now()+k?null:n.grant}async performAuthenticationRefresh(e,n=false){let i=this.socket,r=this.desiredPresence;if(!i||i.readyState!==WebSocket.OPEN||!this.socketReady||!r)throw new h("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let o=(n?this.currentRefillCredential(r.ticket):null)??await this.mintGatewayCredential(r,!e);if(this.socket!==i||i.readyState!==WebSocket.OPEN||!this.socketReady)throw new h("Coordination socket changed while minting a credential refresh.",true);let s,c,a=new Promise((u,d)=>{s=u,c=d;}),l=setTimeout(()=>{this.pendingAuthRefresh?.timer===l&&(this.pendingAuthRefresh=null),c(new h("Coordination credential refresh timed out.",true));},k);this.pendingAuthRefresh={socket:i,promise:a,resolve:s,reject:c,timer:l};try{i.send(JSON.stringify({v:1,type:"auth.refresh",token:o.token}));}catch(u){this.rejectPendingAuthRefresh(new h(u instanceof Error?u.message:"Coordination credential refresh send failed.",true),i);}await a,this.activeGrantToken=o.token,this.refillCredential={grant:o,ticket:r.ticket},this.activeGrantJti=he(o.token),this.activeAvenue=o.avenue,this.activeGrantExpiresAtMs=o.expiresAtMs,this.activeGrantProtocolVersion=o.protocolVersion;}refreshLease(){let e=`lease\0${this.desiredPresence?.ticket??""}`,n=this.authenticationRefreshes.get(e);if(n)return n;let i=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performLeaseRefresh());this.authenticationRefreshTail=i,this.authenticationRefreshes.set(e,i);let r=()=>{this.authenticationRefreshes.get(e)===i&&this.authenticationRefreshes.delete(e);};return i.then(r,r),i}async performLeaseRefresh(){let e=this.socket;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady)throw new h("Coordination socket is unavailable for lease refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let n=v("lease"),i,r,o=new Promise((c,a)=>{i=c,r=a;}),s=setTimeout(()=>{this.pendingAuthRefresh?.timer===s&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),r(new h("Coordination lease refresh timed out.",true));},k);this.pendingLeaseRefreshKey=n,this.pendingAuthRefresh={socket:e,promise:o,resolve:i,reject:r,timer:s};try{e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:n}));}catch(c){this.rejectPendingAuthRefresh(new h(c instanceof Error?c.message:"Coordination lease refresh send failed.",true),e);}try{await o;}catch(c){if(this.stopped||D(c))throw c;await this.performAuthenticationRefresh(true);}}stopForCredentialRevocation(e){return D(e)?(this.credentialRevoked=true,this.reconnectCircuitOpen=true,this.stopAuthActivity(),true):false}scheduleReconnect(e){if(this.stopForCredentialRevocation(e)||this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof h?e.retryable:!me(e))){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new h("Coordination reconnect circuit is open.",false));return}if(this.reconnectOutageStartedAtMs??(this.reconnectOutageStartedAtMs=Date.now()),!this.hostAvailable)return;let i=Math.min(this.reconnectAttempt,le),r=Date.now()-this.reconnectOutageStartedAtMs>=qe,o=Xe(r?Ve:d(i,250,ze));this.reconnectAttempt=Math.min(i+1,le),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(s=>this.scheduleReconnect(s));},o);}stopSocket(e=true){this.serviceObservationGeneration+=1,this.peerAdmissionScope&&this.peerAdmissionRuntime&&this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,0,"[]"),e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null,this.authRefreshTimer=null,this.leaseRefreshMode="off",this.pendingLeaseRefreshKey=null,this.rejectPendingAuthRefresh(new h("Coordination credential refresh was canceled.",true));let n=this.socket;this.socket=null,this.socketReady=false,this.activeGrantJti=null,this.refillCredential=null,this.activeAvenue=null,this.activeGrantExpiresAtMs=0,this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.pendingMembershipPageSnapshot=null,this.sparseMembers.size>0&&this.rebuildSparseDevices(),n?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new h("Coordination reconnect circuit is unavailable.",false)):new Promise((e,n)=>{this.connectionReadyWaiters.add({resolve:e,reject:n});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let n of this.connectionReadyWaiters)n.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e,n){let i=this.pendingAuthRefresh;!i||n&&i.socket!==n||(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,i.reject(e));}rejectPendingAcks(e,n){for(let[i,r]of this.pendingAcks)n&&r.socket!==n||(clearTimeout(r.timer),r.reject(new Error(e)),this.pendingAcks.delete(i));}unscopedId(e){let n=e.split("::");return n.length===2?n[1]:e}requireRoomConnection(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);if(!i)throw new Error(`Room ${n} is not joined through the coordination gateway.`);return i}friendConnection(e){let n=this.friendConnections.get(e);n||(n=new t({...this.options,avenueOverride:{kind:"user",id:e}}),n.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,n));let i=this.desiredPresence??this.friendObservationPresence;return !n.desiredPresence&&i&&this.activateFriendConnection(n,i),n}activateFriendConnection(e,n){e.updatePresence(n.localNodeId,n.ticket,n.online,n.ttlMs,n.metadata,n.deviceName).catch(()=>{});}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var B=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let n=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>n+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",s=Number(r?.expiresAtMs),c=Date.now();if(!o||!Number.isFinite(s)||s<=c+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let a={token:o,expiresAtMs:s};return this.cached=a,this.refreshRetryUsed=false,this.notify(a),this.scheduleRefresh(a),a})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,n){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(n?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let n of this.listeners)n(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let n=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},n);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};var ve=class{constructor(e){this.options=e;this.signaling=null;this.wasmClient=null;this.managedStateProvider=null;this.hostAvailability={available:true,reason:"initial"};this.nativeTrustTokens=e.gateway?new B(e.gateway.nativeTrustTokenProvider):null;}usesGateway(){return !!this.options.gateway}getSignaling(){if(this.options.signalingMode==="ticket-only")throw new Error('[openrtc] Managed signaling is disabled when signalingMode="ticket-only".');if(!this.options.gateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");if(!this.signaling){this.signaling=new U({projectId:this.options.projectId,gateway:this.options.gateway,appTag:this.options.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:this.options.resolveSpaceNamespaceId,getCurrentUserId:this.options.getCurrentUserId,getAuthToken:this.options.getAuthToken,getAppCheckToken:this.options.getAppCheckToken,getLocalDeviceId:this.options.getLocalDeviceId,getDefaultDeviceName:this.options.getDefaultDeviceName,getPlatformType:this.options.getPlatformType,normalizeDevice:this.options.normalizeDevice,avenueOverride:this.options.avenueOverride,roomArchitecture:this.options.roomArchitecture,initialExcludedPeers:this.options.initialExcludedPeers,nativeTrustTokens:this.nativeTrustTokens});let e=this.signaling;this.managedStateProvider?e.setManagedRoomRuntime(this.wasmClient,this.managedStateProvider):e.setWasmClient(this.wasmClient),this.signaling.setHostAvailability?.(this.hostAvailability);}return this.signaling}setWasmClient(e){this.wasmClient=e,this.managedStateProvider=null,this.signaling?.setWasmClient(e);}setManagedRoomRuntime(e,n){this.wasmClient=e,this.managedStateProvider=n,this.signaling?.setManagedRoomRuntime(e,n);}setHostAvailability(e){this.hostAvailability=e,this.signaling?.setHostAvailability?.(e);}async reconnectAfterHostResume(){await this.signaling?.reconnectAfterHostResume?.();}async handleScopeChange(){await this.signaling?.handleScopeChange();}stopAuthActivity(){this.signaling?.stopAuthActivity();}async getNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeNativeTrustToken(e,n){return this.nativeTrustTokens?.subscribe(e,n)??(()=>{})}};function tt(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function J(t,e,n){if(tt()){if(typeof n>"u"){console[t](e);return}console[t](e,n);}}function $t(t,e){J("debug",t,e);}function Jt(t,e){J("info",t,e);}function Yt(t,e){J("log",t,e);}function be(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var nt="[OpenRTC][teardown-trace]";function it(){try{let t=globalThis;if(t.OPENRTC_TEARDOWN_TRACE===!0||t.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function Zt(t,e={}){console.info(nt,{kind:t,ts:new Date().toISOString(),...e}),it()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:t,stack:new Error(`teardown: ${t}`).stack});}var z="trustedDevice",rt="plutonium:e2ee:identity:v1",ot="plutonium:e2ee:identity:session:v1",st="openrtc-trust",C="identity",Re="transport-trust:v1",at=2,we="managed-room-keys",Se="managed-room-state",ct=1,w=null,x=null;function R(t){let e=atob(t),n=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return n}function N(t){let e="";for(let n=0;n<t.length;n+=1)e+=String.fromCharCode(t[n]);return btoa(e)}async function Y(t){let e=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join("")}function dt(){return typeof sessionStorage>"u"?null:sessionStorage}function lt(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(rt);}catch{}}var F=null;async function Ie(){return F||(F=(async()=>{let t=globalThis.crypto?.subtle;if(!t||typeof t.generateKey!="function")return false;try{let e=await t.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),F)}async function ut(t){let e=await crypto.subtle.exportKey("raw",t);return new Uint8Array(e)}function pt(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Ae(){let t=pt();return t?new Promise(e=>{let n;try{n=t.open(st,at);}catch{e(null);return}n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(C)||i.createObjectStore(C),i.objectStoreNames.contains(we)||i.createObjectStore(we),i.objectStoreNames.contains(Se)||i.createObjectStore(Se);},n.onsuccess=()=>e(n.result),n.onerror=()=>e(null),n.onblocked=()=>e(null);}):Promise.resolve(null)}async function ht(){let t=await Ae();if(!t)return null;try{return await new Promise(e=>{let r=t.transaction(C,"readonly").objectStore(C).get(Re);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{t.close();}}async function gt(t){let e=await Ae();if(!e)return false;try{return await new Promise(n=>{let i=e.transaction(C,"readwrite");i.objectStore(C).put(t,Re),i.oncomplete=()=>n(!0),i.onerror=()=>n(!1),i.onabort=()=>n(!1);})}catch{return false}finally{e.close();}}async function Te(t,e){let n=await ut(t.publicKey),i=await Y(n),r=t.privateKey;return {publicKey:n,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let s=await crypto.subtle.sign({name:"Ed25519"},r,R(o));return N(new Uint8Array(s))}}}function mt(t,e,n){let i=t.secretKey;return {publicKey:t.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:n,async signChallenge(r){return yt(r,i)}}}function rn(t=32){let e=crypto.getRandomValues(new Uint8Array(t));return N(e)}function yt(t,e){let n=G.sign.detached(R(t),e);return N(n)}function ft(t,e,n){try{return G.sign.detached.verify(R(t),R(e),R(n))}catch{return false}}async function on(t,e,n){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",R(n),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,R(e),R(t))}catch{}return ft(t,e,n)}function sn(t){return N(t)}function an(t){if(!t||!t.trim())return null;try{let e=JSON.parse(t),n=e&&typeof e=="object"&&!Array.isArray(e)?e[z]:null;if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,s=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!s?null:{version:r,identityPublicKey:o,identityFingerprint:s}}catch{return null}}async function vt(){let t=await It().catch(()=>null);return t?{version:ct,identityPublicKey:N(t.publicKey),identityFingerprint:t.fingerprint}:null}async function cn(t){let e=await vt();if(!e)return t??void 0;let n=typeof t=="string"?t.trim():"";if(!n)return JSON.stringify({[z]:e});try{let i=JSON.parse(n);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[z]:e})}catch{}return JSON.stringify({metadata:t,[z]:e})}function bt(){if(typeof window>"u")return null;let t=window.__TAURI_INTERNALS__;return !t||typeof t.invoke!="function"?null:t.invoke.bind(t)}async function wt(){if(typeof window>"u")return null;let t=bt();if(!be()&&!t)return null;if(!t)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await t("openrtc_get_transport_trust_identity"),n=R(e.publicKeyBase64);if(n.byteLength!==G.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await Y(n);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:n,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return t("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let n=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw n.cause=e,n}}function St(){let t=dt();t&&t.removeItem(ot);}async function Rt(){if(lt(),St(),w)return w;let t=await wt();if(t)return w=t,w;if(await Ie()){let e=await ht();if(e)return w=await Te(e,true),w}return null}async function It(t={}){let e=await Rt();if(e)return e;if(x)return x;let n=At(t);x=n;try{return await n}finally{x===n&&(x=null);}}async function At(t){if(w)return w;let e=t.ephemeral===true;if(await Ie())try{let n=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await gt(n)),w=await Te(n,i),w}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let n=G.sign.keyPair(),i=await Y(b(n.publicKey));return w=mt(n,i,!1),w}catch{return null}}var Tt={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function ln(){return Tt}var Pt={adapter:"browser-wasm",productMaturity:{boundedRooms:"stable",serviceNodes:"preview",offlineEdge:"support-only",broadcast:"preview"},signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:false,irohLan:false,webRtc:true,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},Ct={adapter:"native-ipc",productMaturity:{boundedRooms:"stable",serviceNodes:"unavailable",offlineEdge:"unavailable",broadcast:"unavailable"},signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function Pe(t){return {adapter:t.adapter,productMaturity:t.productMaturity?{...t.productMaturity}:void 0,signaling:{...t.signaling},transport:{...t.transport},nativeProtocols:{...t.nativeProtocols},lifecycle:{...t.lifecycle},transfers:{...t.transfers},fallback:{...t.fallback}}}function pn(t=globalThis){let e=Pe(Pt),n=typeof t?.RTCPeerConnection=="function";return e.transport.webRtc=n,e}function O(t){return t?.compiled===true&&t.enabled===true}function hn(t,e=false){let n=Pe(Ct),i=t?.transport;return n.productMaturity={...n.productMaturity,...t?.productMaturity},i&&(n.transport.irohQuic=O(i.irohQuic),n.transport.irohLan=O(i.irohLan),n.transport.webRtc=O(i.webRtc),n.transport.moq=O(i.moq),n.transport.ble=O(i.ble)),n.transport.wasm=false,n.fallback.wasm=e,n}function gn(t){return {environment:t.adapter==="native-ipc"||t.adapter==="tauri-ipc"?"native":t.adapter==="browser-wasm"?"web":"unknown",productMaturity:t.productMaturity?{...t.productMaturity}:void 0,transports:{quic:t.transport.irohQuic,irohRelay:t.transport.irohQuic||t.adapter==="browser-wasm",irohLan:t.transport.irohLan,webRtc:t.transport.webRtc,moq:t.transport.moq,ble:t.transport.ble},lifecycle:{...t.lifecycle},storage:{localFileSystem:t.transfers.explicitFilePath,transferHistory:t.transfers.history},nativeProtocols:{...t.nativeProtocols}}}function Ce(t){if(t.errorCode)return t;let e=t.error||t.readinessReason;if(!e)return t;let n=g$1(e);return {...t,errorCode:n.errorCode,retryable:n.retryable,errorPlane:n.errorPlane}}function M(t){return !t||typeof t!="object"?{}:t instanceof Map?Object.fromEntries(t):t}function Q(t){let e=M(t),n=M(e.device);if(!Object.keys(n).length)return e;let i={...n,...e};return delete i.device,i}function p(t,...e){for(let n of e){let i=t[n];if(typeof i=="string"&&i.trim().length>0)return i}}function S(t,...e){for(let n of e){let i=t[n];if(typeof i=="boolean")return i}}function g(t,...e){for(let n of e){let i=t[n];if(typeof i=="number"&&Number.isFinite(i))return i}}function T(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date){let e=t.getTime();return Number.isFinite(e)?e:void 0}if(typeof t=="string"){let e=Date.parse(t);return Number.isFinite(e)?e:void 0}if(t&&typeof t=="object"){let e=t;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let n=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(n!==void 0&&Number.isFinite(n)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function X(...t){let e=t.map(T).filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length?Math.max(...e):void 0}function Z(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Me(t){let e=Z("presenceStatus"in t?t.presenceStatus:void 0),n="presenceUpdatedAt"in t?T(t.presenceUpdatedAt):void 0,i="presenceExpiresAt"in t?T(t.presenceExpiresAt):void 0,r=n??X(t.lastSeenAt,t.updatedAt,t.createdAt),o=i??T(t.expiresAt),s=e;s||(t.online?r!==void 0&&r+3e5<=Date.now()?s="idle":s="online":s="offline");let c=typeof t.ticket=="string"?t.ticket.trim():"",a="connectable"in t&&typeof t.connectable=="boolean"?t.connectable:s==="online"&&c.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:a}}function Ee(t){return l(t)}function E(t,...e){return Ee(p(t,...e))}function L(t){if(!Array.isArray(t))return;let e=Array.from(new Set(t.map(Ee).filter(n=>!!n)));return e.length?e:void 0}function ke(t){let e=M(t),n={webrtc:g(e,"webrtc"),iroh:g(e,"iroh"),irohLan:g(e,"irohLan","iroh_lan"),irohRelay:g(e,"irohRelay","iroh_relay"),ble:g(e,"ble"),moq:g(e,"moq")};return Object.values(n).some(i=>i!==void 0)?n:void 0}function bn(t){return (t.discoveryMode??"space")==="space"&&typeof t.apiKey=="string"&&t.apiKey.trim().length>0&&typeof t.spaceKey=="string"&&t.spaceKey.trim().length>0}function wn(t,e,n){return n?true:(typeof t.appTag=="string"?t.appTag:typeof t.tag=="string"?t.tag:void 0)===e}function Mt(t,e){let n=Q(t),i=p(n,"deviceId","device_id")||e||"",r=p(n,"nodeId","node_id")||"",o=p(n,"ticket")||"";return {deviceId:i,deviceName:p(n,"deviceName","device_name")||"Unknown Device",online:!!n.online,ticket:o,friendTicket:p(n,"friendTicket","friend_ticket"),presenceStatus:Z(p(n,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:g(n,"presenceUpdatedAt","presence_updated_at")??X(n.presenceUpdatedAt,n.presence_updated_at,n.lastSeenAt,n.last_seen_at,n.updatedAt,n.updated_at,n.createdAt,n.created_at),presenceExpiresAt:g(n,"presenceExpiresAt","presence_expires_at")??T(n.presenceExpiresAt??n.presence_expires_at)??T(n.expiresAt??n.expires_at),connectable:S(n,"connectable"),kind:p(n,"kind"),nodeId:r||void 0,devicePublicKeyJwk:n.devicePublicKeyJwk??n.device_public_key_jwk,platformType:p(n,"platformType","platform_type"),capabilities:n.capabilities||void 0,sessionId:p(n,"sessionId","session_id"),userId:p(n,"userId","user_id"),lastSeenAt:n.lastSeenAt??n.last_seen_at,expiresAt:n.expiresAt??n.expires_at,createdAt:n.createdAt??n.created_at,updatedAt:n.updatedAt??n.updated_at,metadata:p(n,"metadata"),excludedPeers:ee(n.excludedPeers??n.excluded_peers),availableTransports:L(n.availableTransports??n.available_transports),transports:L(n.transports),topologyRole:n.topologyRole==="active"||n.topologyRole==="backup"?n.topologyRole:void 0,topologyRevision:Number.isSafeInteger(n.topologyRevision)&&Number(n.topologyRevision)>0?Number(n.topologyRevision):void 0}}function ee(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Et(t){let e=Me(t);return {...t,...e,connectionStatus:"connectionStatus"in t&&typeof t.connectionStatus=="string"?t.connectionStatus:t.online?"online":"disconnected",settledReady:"settledReady"in t&&typeof t.settledReady=="boolean"?t.settledReady:false,readinessState:"readinessState"in t&&typeof t.readinessState=="string"?t.readinessState:void 0,readinessReason:"readinessReason"in t&&typeof t.readinessReason=="string"?t.readinessReason:void 0,peerHealth:"peerHealth"in t&&typeof t.peerHealth=="string"?t.peerHealth:"unknown",peerId:"peerId"in t&&typeof t.peerId=="string"?t.peerId:void 0,promotionEligible:"promotionEligible"in t&&typeof t.promotionEligible=="boolean"?t.promotionEligible:true,scopes:"scopes"in t?ee(t.scopes):[],connectionId:"connectionId"in t&&typeof t.connectionId=="string"?t.connectionId:void 0,deviceIdHint:"deviceIdHint"in t&&typeof t.deviceIdHint=="string"?t.deviceIdHint:void 0,transportStableId:"transportStableId"in t&&typeof t.transportStableId=="number"?t.transportStableId:"transportStableId"in t?t.transportStableId??null:void 0,transportGeneration:"transportGeneration"in t&&typeof t.transportGeneration=="number"?t.transportGeneration:void 0,routeGeneration:"routeGeneration"in t&&typeof t.routeGeneration=="number"?t.routeGeneration:void 0,activeTransport:"activeTransport"in t?t.activeTransport:void 0,parallelTransport:"parallelTransport"in t?t.parallelTransport:void 0,availableTransports:"availableTransports"in t?L(t.availableTransports):"transports"in t?L(t.transports):void 0,latencyMs:"latencyMs"in t&&typeof t.latencyMs=="number"?t.latencyMs:void 0,latencyByTransport:"latencyByTransport"in t?ke(t.latencyByTransport):void 0}}function K(t,e){return e===void 0?true:e===null?t==null:t==null||t===e}function _e(t,e){let n=K(t.connectionId,e.connectionId)&&K(t.nodeId,e.nodeId)&&K(t.transportStableId,e.transportStableId)&&K(t.transportGeneration,e.transportGeneration)&&K(t.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:n?o:void 0;return {inheritsSnapshot:n,fields:{connectionId:i(e.connectionId??void 0,t.connectionId),transportStableId:i(e.transportStableId,t.transportStableId),transportGeneration:i(e.transportGeneration,t.transportGeneration),routeGeneration:i(e.routeGeneration,t.routeGeneration),activeTransport:i(e.activeTransport,t.activeTransport),parallelTransport:i(e.parallelTransport,t.parallelTransport),latencyMs:n?t.latencyMs:void 0,latencyByTransport:n?t.latencyByTransport:void 0}}}var kt={connectionId:void 0,transportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function _t(t,e,n){let i=_e(t,{connectionId:e.activeConnectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=n?n({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):t.promotionEligible??true;if(!r)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let o=e.status??t.connectionStatus,s=typeof o=="string"?o.trim().toLowerCase():"",c=s==="failed"||s==="closed"||s==="disconnected",l=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,u=t.settledReady===true||t.readinessState==="routable";if(i.inheritsSnapshot&&u&&!c&&!l)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let d=c?false:l,b=l&&!c&&(s==="connecting"||s==="connected")?"connected":o,y=l?"routable":e.readinessState??(i.inheritsSnapshot?t.readinessState:void 0),f=d?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?t.readinessReason:void 0);return {...t,connectionStatus:b,settledReady:d,readinessState:y,readinessReason:f,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields}}function Dt(t,e){let n=_e(t,{connectionId:e.connectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:false,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let i=e.status??t.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",s=t.settledReady===true||t.readinessState==="routable",c=e.routable===false;if(n.inheritsSnapshot&&s&&o&&!c)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};if(s&&o)return {...t,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??t.readinessReason,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...kt,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let a=e.routable===true||e.protocolState==="routable";if(n.inheritsSnapshot&&s&&!o&&!a)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,transportStableId:t.transportStableId??e.transportStableId,transportGeneration:t.transportGeneration??e.transportGeneration,routeGeneration:t.routeGeneration??e.routeGeneration,activeTransport:t.activeTransport??e.activeTransport,parallelTransport:t.parallelTransport===void 0?e.parallelTransport:t.parallelTransport,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};let l=e.transportState==="connected"&&e.health==="healthy",u=o?false:a,d=!o&&(a||l)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,b=u?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(n.inheritsSnapshot?t.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=u?(n.inheritsSnapshot?t.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(n.inheritsSnapshot?t.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...t,connectionStatus:d,settledReady:u,readinessState:b,readinessReason:y,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes}}function xt(t){let{device:e,session:n=null,peer:i=null,isPromotionEligible:r}=t,o=Et(e);return n&&(o=_t(o,n,r)),i&&(o=Dt(o,i)),Ce(o)}function Sn(t){let e=Q(t),n=Mt(e),i=Z(p(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Me({...n,...i?{presenceStatus:i}:{},presenceUpdatedAt:g(e,"presenceUpdatedAt","presence_updated_at")??X(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:g(e,"presenceExpiresAt","presence_expires_at")??T(e.presenceExpiresAt??e.presence_expires_at)??T(e.expiresAt??e.expires_at),connectable:S(e,"connectable")}),o={...n,...r,connectionStatus:p(e,"connectionStatus","connection_status")||"disconnected",settledReady:S(e,"settledReady","settled_ready")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,peerHealth:p(e,"peerHealth","peer_health")||"unknown",peerId:p(e,"peerId","peer_id"),scopes:ee(e.scopes),connectionId:p(e,"connectionId","connection_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,activeTransport:E(e,"activeTransport","active_transport"),parallelTransport:E(e,"parallelTransport","parallel_transport")??null,availableTransports:L(e.availableTransports??e.available_transports),latencyMs:g(e,"latencyMs","latency_ms"),latencyByTransport:ke(e.latencyByTransport??e.latency_by_transport)};return xt({device:o})}function Rn(t){let e=Q(t);return Ce({peerId:p(e,"peerId","peer_id")||"",deviceId:p(e,"deviceId","device_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),nodeId:p(e,"nodeId","node_id"),activeConnectionId:p(e,"activeConnectionId","active_connection_id"),candidates:Array.isArray(e.candidates)?e.candidates.filter(n=>typeof n=="string"):Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(n=>typeof n=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(n=>typeof n=="string"):[],status:p(e,"status")||"disconnected",health:p(e,"health")||"unknown",settledReady:S(e,"settledReady","settled_ready")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,activeTransport:E(e,"activeTransport","active_transport"),parallelTransport:E(e,"parallelTransport","parallel_transport")??null,replacementPending:S(e,"replacementPending","replacement_pending")??void 0,logicalSessionTerminal:S(e,"logicalSessionTerminal","logical_session_terminal")??false,lastTransitionAtMs:g(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,transitionCount:g(e,"transitionCount","transition_count")??void 0,connectTransitions:g(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:g(e,"replacementCount","replacement_count")??void 0,retireCount:g(e,"retireCount","retire_count")??void 0,lastDisconnectReason:p(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:p(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:p(e,"error"),errorCode:p(e,"errorCode","error_code")??void 0,retryable:S(e,"retryable")??void 0,errorPlane:p(e,"errorPlane","error_plane")??void 0})}function In(t){let e=M(t);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectTransitions:typeof e.connectTransitions=="number"?e.connectTransitions:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function An(t){let e=M(t);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function Gt(t){switch(t){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Tn(t){let e=t.activeConnectionId||t.candidates[0]||null;if(!e)return null;let n=Gt(t.status),i=n==="connected"?"connected":n==="connecting"?"connecting":"closed",r=n==="connected"?t.settledReady?"routable":"transport-only":n==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:t.deviceId??null,deviceIdHint:t.deviceIdHint??null,remoteNodeId:t.nodeId??null,state:n,transportState:i,protocolState:r,routable:!!t.settledReady,readinessState:t.readinessState,readinessReason:t.readinessReason,transportGeneration:t.transportGeneration,routeGeneration:t.routeGeneration,transportStableId:t.transportStableId,activeTransport:t.activeTransport,parallelTransport:t.parallelTransport??null,replacementInProgress:t.replacementPending,logicalSessionTerminal:t.logicalSessionTerminal===true,lastTransitionAtMs:t.lastTransitionAtMs,transitionCount:t.transitionCount,connectTransitions:t.connectTransitions,replacementCount:t.replacementCount,retireCount:t.retireCount,lastDisconnectReason:t.lastDisconnectReason??void 0,lastReconnectReason:t.lastReconnectReason??void 0,updatedAt:t.lastSeenAtMs,error:t.error??void 0}}function Pn(t){let e=M(t),n=p(e,"connectionId","connection_id");if(!n)return null;let i=p(e,"state")||"connecting",r=g(e,"createdAt","created_at")??g(e,"updatedAt","updated_at")??Date.now(),o=g(e,"updatedAt","updated_at")??r;return {connectionId:n,deviceId:p(e,"deviceId","device_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),remoteNodeId:p(e,"remoteNodeId","remote_node_id"),state:i,transportState:p(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:p(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:S(e,"routable")??false,logicalSessionTerminal:S(e,"logicalSessionTerminal","logical_session_terminal")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:E(e,"activeTransport","active_transport"),parallelTransport:E(e,"parallelTransport","parallel_transport")??null,replacementInProgress:S(e,"replacementInProgress","replacement_in_progress")??void 0,lastTransitionAtMs:g(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:g(e,"transitionCount","transition_count")??void 0,connectTransitions:g(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:g(e,"replacementCount","replacement_count")??void 0,retireCount:g(e,"retireCount","retire_count")??void 0,lastDisconnectReason:p(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:p(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:p(e,"error")??void 0,createdAt:r,updatedAt:o}}function Cn(t,e){return t?t.connectionId===e.connectionId&&(t.deviceId??null)===(e.deviceId??null)&&(t.deviceIdHint??null)===(e.deviceIdHint??null)&&(t.remoteNodeId??null)===(e.remoteNodeId??null)&&t.state===e.state&&(t.transportState??null)===(e.transportState??null)&&(t.protocolState??null)===(e.protocolState??null)&&!!t.routable==!!e.routable&&(t.activeTransport??null)===(e.activeTransport??null)&&(t.parallelTransport??null)===(e.parallelTransport??null)&&(t.transportStableId??null)===(e.transportStableId??null)&&(t.transportGeneration??null)===(e.transportGeneration??null)&&(t.routeGeneration??null)===(e.routeGeneration??null)&&!!t.replacementInProgress==!!e.replacementInProgress&&!!t.logicalSessionTerminal==!!e.logicalSessionTerminal&&(t.transitionCount??null)===(e.transitionCount??null)&&(t.connectTransitions??null)===(e.connectTransitions??null)&&(t.replacementCount??null)===(e.replacementCount??null)&&(t.retireCount??null)===(e.retireCount??null)&&(t.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(t.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(t.error??null)===(e.error??null):false}
2
+ export{xt as A,Sn as B,Rn as C,In as D,An as E,Tn as F,Pn as G,Cn as H,Nt as a,ve as b,tt as c,$t as d,Jt as e,Yt as f,be as g,Zt as h,rn as i,on as j,sn as k,an as l,cn as m,It as n,Tt as o,ln as p,Pt as q,Ct as r,Pe as s,pn as t,hn as u,gn as v,Q as w,bn as x,wn as y,Mt as z};
@@ -0,0 +1 @@
1
+ import {b as b$1,a as a$1}from'./chunk-ZA44REGI.js';import {b as b$3}from'./chunk-LLZT3MR6.js';import {a}from'./chunk-DUY34MGT.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {h as h$1,e}from'./chunk-4R5BLX2U.js';import {d,b as b$4}from'./chunk-2GX6GB6L.js';function I(o,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:o,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 B(o){let e;try{e=o instanceof Uint8Array?JSON.parse(new TextDecoder().decode(o)):o&&typeof o=="object"?o:{};}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 b="openrtc-peer-stream/1",ae=32,Y=16,U=4294967295,ce=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,le=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function A(o){let e=o?.trim()??"";if(!ce.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function k(o){let e=o?.trim()??"",t=le.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function ee(o){if(o===null||o===0)return null;if(!Number.isFinite(o)||o<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(U,Math.ceil(o))}function te(o){if(!Number.isSafeInteger(o)||o<1||o>U)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${U}.`);return o}var L=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Y;this.outgoingLimit=Y;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=ee(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=ee(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=te(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=te(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();}},O=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:ae});}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);}},F=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new O;this.incomingUni=new O;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new L(i,this.peerId);}async createBidirectionalStream(e){let t=A(e.protocol),i=await this.client.channels.openBi(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=A(e.protocol);return (await this.client.channels.openUni(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]: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},s=this.protocolHandlers.get(t);if(s){try{s(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=A(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();}},D=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:b,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(b,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new F(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=k(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(k(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(b);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$2]!==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=A(i);}catch{return this.declined+=1,false}let s=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return s?this.accepted+=1:this.declined+=1,s}resolveExistingPeer(e,t=""){let i=k(t);if(i){let s=this.peerIdsByConnection.get(i);if(!s)return this.lastResolution="unbound-connection",null;let a=this.peers.get(s);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(s=>[s.peerId,s.deviceId,s.deviceIdHint,s.connectionId,...s.connectionIds].some(a=>a===e));if(r){let s=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])=>s.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var _={"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 y=new WeakMap;function de(o){let e=y.get(o);if(!e||o.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function xe(o,e){if(y.has(o))throw new Error("[OpenRTC] Capability runtime is already registered.");return y.set(o,de(e)),()=>{y.delete(o);}}function ue(o){let e=o?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function T(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var z=/^[A-Za-z0-9_.:@-]{1,160}$/,he=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function me(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return he.test(t)?t:e}function pe(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,me(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(o){if(o===void 0)return [];if(!Array.isArray(o))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(o.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!z.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 oe(o){let e=b$1(o.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var N=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);}},K=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:(_[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw f(`[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=ge(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),s=ve(e.architecture),a=ye(s,t,e.delivery),l=fe(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"),m=t*u,v=r*i,p=Math.max(0,Math.ceil(t/4)-1),P=a==="managed"?v*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")+p*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,g=l*h("broadcast.delivery");return {architecture:s,effectiveArchitecture:a,creditsUsd:Math.ceil((m+P+g)*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 ve(o){return o??"auto"}function G(o,e,t,i){if(!Number.isSafeInteger(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return o}function ge(o,e,t,i){if(!Number.isFinite(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return o}function h(o){let e=_[o];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${o} has no current customer-credit price.`);return e}function ye(o,e,t){if(o==="mesh"){if(e>16)throw f("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return o}if(o==="sparse"){if(e>50)throw f("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw f("[OpenRTC] Sparse room quotes require latest-state delivery.");return o}if(o==="managed")throw f("[OpenRTC] Managed room architecture is unavailable in this release.");if(o==="authority")return o;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw f(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function f(o){return h$1(e.ROOM_ARCHITECTURE_UNAVAILABLE,o,{retryable:false,plane:"admission"})}function fe(o,e){if(e<=1)return 0;if(o!=="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 se(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var H=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.peerStreams=new D(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,s)=>{let a=B(r);!a||a.capability!==this.capabilityKey||s!==void 0&&a.name!==s||s===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(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=se(e);return {set:i=>{let n=I("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=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(s,a)=>i({peerId:s,value:a});n.add(r);for(let[s,a]of this.remoteState)a.has(t)&&i({peerId:s,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=se(e),i=n=>I("channel",t,n,this.capabilityKey);return {send:async n=>{let r=i(n);await this.roomFanout?.sendChannel(t,r)||await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:s})=>s?[s.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let s=this.logicalConnections.get(n)?.activeRaw;if(s){await s.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let s=(a,c)=>n({peerId:a,message:c});return r.add(s),()=>r?.delete(s)}}}onConnection(e){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)}async close(){if(this.closed)return;this.closed=true,this.stopMessage(),this.stopConnection(),this.stopDisconnection(),this.stopPeerLifecycle(),this.roomFanout?.close();let e=[...this.logicalConnections.keys()].map(t=>this.retire(t));this.pendingRawConnections.clear(),this.peerStreams.close(),this.rawConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),await Promise.allSettled(e);}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 s=this.logicalConnections.get(i);if(!s){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),s={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(I("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let m=d;return u.add(m),()=>u?.delete(m)},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,s);}s.rawIds.add(e.id),s.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(s.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 s=this.stateSenders.get(e);if(s){for(let a of s.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 s=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(s)&&Number(s)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(s),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 s of t.rawIds){let a=this.rawConnections.get(s)?.raw;if(this.rawConnections.delete(s),this.peerStreams.unbindConnection(s),!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 s of i.keys())for(let a of this.stateListeners.get(s)??[])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 s of this.closeListeners.get(e)??[])s();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let s of this.connectionListeners.values())s.delete(e);return r}receive(e,t){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=B(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(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(s=>e.send(s)),n.set(t,r)),r.send(i).catch(()=>{});}},C=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;y.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)}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}async close(){if(!this.closed){this.closed=true,await this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{y.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new H(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},w=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let s=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=g=>(this.roster.reconcileLiveSnapshot(g),g),u=async()=>this.roster.mergeDevices(d(await s())),m=async()=>this.roster.mergeStatus(await a()),v=g=>c(M=>g(this.roster.mergeDevices(d(M)))),p=g=>l(M=>g(this.roster.mergeStatus(M))),P=Object.create(i);Object.defineProperties(P,{listDevices:{value:u,enumerable:false},listDeviceStatus:{value:m,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:p,enumerable:false},devices:{value:{...i.devices,list:u,listWithStatus:m,watch:v,watchWithStatus:p},enumerable:true}}),y.set(this,P),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},q=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},W=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},E=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new N;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;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());for(let n of this.handles)n instanceof w&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let s of this.handles)s instanceof w&&s.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();for(let n of this.handles)n instanceof w&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${T(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-Z6F46KMH.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${T(e)}`,JSON.stringify({identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};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 s=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(s),this.wrapBroadcastSession(await t.open(s))},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=ue(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new K(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-T3TOHY3D.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$1,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-EIMDBAQS.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-EIMDBAQS.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let s={fingerprint:t,auth:i},a=n().then(c=>(s.handle=c,c)).catch(c=>{throw this.activations.get(e)===s&&this.activations.delete(e),c});return s.promise=a,this.activations.set(e,s),a}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):pe(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 s=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$4)===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$1).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:s},transportPriority:s}}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,s={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:s,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 p=>{a={...a,...p},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??(p=>t.signDeviceBytes(p)),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}),[m,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=v(m,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({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(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}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'),s=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,s),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:s.name,devicePlatform:s.platform,deviceMetadata:s.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'),m;return m=new w(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(m);},new u(d)),this.handles.add(m),m}async joinSpace(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new q(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-Z6F46KMH.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("ticket",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"ticket",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new W(i,a,()=>{this.channels.detach(a),this.onClosed(c);},r.token),this.handles.add(c),c}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{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?.();}}}};function Be(o,e){return new E(o,e)}function ke(o,e){if(!(o instanceof E))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return o.openAuthorityRoom(e)}export{I as a,B as b,de as c,xe as d,T as e,ie as f,oe as g,C as h,Be as i,ke as j};
@@ -0,0 +1 @@
1
+ import {b,d}from'./chunk-4R5BLX2U.js';function l(n,c){if(!n||typeof n!="object")return null;let r=n,t=r.details&&typeof r.details=="object"?r.details:null,i=t&&b(t.code),o=i?t:r,e=i||b(o.code);return e?Object.freeze({...d(o),...e.scope?{scope:e.scope}:{},code:e.code,retryable:typeof o.retryable=="boolean"?o.retryable:!!e.scope,avenue:Object.freeze({kind:c.kind,id:c.id})}):null}export{l as a};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-ISTROQQJ.js';function m(l){return [...new Set(l.capabilityKeys.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))]}async function p(l,r){if(!l||typeof l!="object")return;let t=l.stream,e=[];t?.recv&&e.push(t.recv.cancel(r)),t?.send&&e.push(t.send.abort(r)),await Promise.allSettled(e);}var v=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.consecutiveEstablishedFaults=0;this.closed=false;}register(r,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=r.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set,deviceListeners:new Set,serviceErrorListeners:new Set,latestDevices:null}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:s=>this.subscribeState(e,s),onPeerMessage:s=>this.subscribePeerData(e,s),onDevices:s=>this.subscribeDevices(e,s),onServiceError:s=>this.subscribeServiceError(e,s),isCurrentTransport:(s,o)=>this.currentHost().isCurrentTransport(s,o)}}unregister(r){let t=r.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),e.deviceListeners.clear(),e.serviceErrorListeners.clear(),e.latestDevices=null,this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(r,t){let e=this.requireConsumer(r);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(r,t){let e=this.requireConsumer(r);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribeDevices(r,t){let e=this.requireConsumer(r);return e.deviceListeners.add(t),this.ensureHostPump(),e.latestDevices&&t(e.latestDevices),()=>{e.deviceListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribeServiceError(r,t){let e=this.requireConsumer(r);return e.serviceErrorListeners.add(t),this.ensureHostPump(),()=>{e.serviceErrorListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(r);if(!t)throw new Error(`[OpenRTC] Native capability '${r}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(r);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:s=>{t.controller=s,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){if(this.hostPump||this.closed)return;let r=false;this.hostPump=this.pumpHost().then(t=>{r=t;}).finally(()=>{this.hostPump=null,this.hostReader=null,r&&!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();});}async pumpHost(){let r=this.currentHost(),t=null,e=false;try{let s=await r.incoming_projected_streams();if(this.closed)return await s.cancel("OpenRTC native root client closed").catch(()=>{}),!1;for(t=s.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:o,value:n}=await t.read();if(o){if(!this.closed&&this.host!==r&&this.hasActiveConsumers())return !0;for(let i of this.consumers.values()){try{i.controller?.close();}catch{}i.controller=null,i.stream=null,i.stateListeners.clear(),i.messageListeners.clear(),i.deviceListeners.clear(),i.serviceErrorListeners.clear(),i.latestDevices=null;}return this.consecutiveEstablishedFaults=0,!1}this.consecutiveEstablishedFaults=0;let u=m(n);if(n.kind==="stream"){let i=u.length===1?u[0]:null,a=i?this.consumers.get(i):void 0;if(!a?.controller||(a.controller.desiredSize??0)<=0){await p(n.payload,i?`inactive native capability ${i}`:"ambiguous unscoped native projection");continue}a.controller.enqueue(n.payload);continue}for(let i of u){let a$1=this.consumers.get(i);if(a$1)if(n.kind==="connection-state")for(let c of a$1.stateListeners)c(n.payload);else if(n.kind==="devices"){a$1.latestDevices=n.payload.devices;for(let c of a$1.deviceListeners)c(n.payload.devices);}else if(n.kind==="service-error"){let c=a(n.payload.serviceError,n.payload.avenue);if(c)for(let h of a$1.serviceErrorListeners)try{Promise.resolve(h(c)).catch(()=>{});}catch{}}else for(let c of a$1.messageListeners)c(n.payload);}}return !this.closed&&this.host!==r&&this.hasActiveConsumers()}catch(s){if(!this.closed){e=t!==null&&this.consecutiveEstablishedFaults===0,e?this.consecutiveEstablishedFaults=1:this.consecutiveEstablishedFaults=0;for(let o of this.consumers.values()){try{o.controller?.error(s);}catch{}o.controller=null,o.stream=null,e||(o.stateListeners.clear(),o.messageListeners.clear(),o.deviceListeners.clear(),o.serviceErrorListeners.clear(),o.latestDevices=null);}}return e}finally{let s=t;if(this.hostReader===s&&(this.hostReader=null),s)try{s.releaseLock();}catch{}typeof r.releaseNativeProjectionSubscription=="function"&&await r.releaseNativeProjectionSubscription().catch(()=>{});}}hasActiveConsumers(){return [...this.consumers.values()].some(r=>r.controller!==null||r.stateListeners.size>0||r.messageListeners.size>0||r.deviceListeners.size>0||r.serviceErrorListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(r){let t=this.hostReader;this.hostReader=null,await t?.cancel(r).catch(()=>{});}async close(){if(this.closed){await this.hostPump;return}this.closed=true;for(let r of this.consumers.values())try{r.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump;}};export{v as a};