openrtc 2.8.8 → 2.8.9

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.
@@ -4,9 +4,9 @@
4
4
  "platform": "darwin",
5
5
  "arch": "x64",
6
6
  "rustTarget": "x86_64-apple-darwin",
7
- "sourceCommit": "4787b5503309309ede62db6f6c3f42b183f7f4fa",
8
- "sourceDigest": "24dd8534300805268854e15d624c2d988650d0cfbdb24c89cc2dde19014b840d",
9
- "binarySha256": "406654a5bdb90468dfe0f9d7f44d9ec681fd3981f9b8979de542da2642d741ed",
7
+ "sourceCommit": "56bd11983572fa924e92796253625364185a550a",
8
+ "sourceDigest": "18f626c9d21dc2952bf9ff077089a6c1eb6f779135acc0c8778ae7693d6c958b",
9
+ "binarySha256": "b78e680a4ea0c639533c87d484a55412f636dd0531e866d47b5631874f35f513",
10
10
  "protocol": {
11
11
  "lifecycleOwner": "rust-peer-session",
12
12
  "maxApplicationPayloadBytes": 65536,
@@ -16,5 +16,5 @@
16
16
  },
17
17
  "signingKeySha256": "0391c617f3df12611b419e129cace36fa792e73da03271649cbed9e9f9f155ef",
18
18
  "signatureAlgorithm": "ed25519",
19
- "signature": "X5f2nMrW9onBUzNFQzUwiWBXvAxJoYb3u6hpEkIw4fO8xhQYpnPhOdaMv2U37xzYWZ2Iz/wCvkEBax22VacwBA=="
19
+ "signature": "xHIPV55+W5w4Vti7pwl4GbRqiHbwh0vMVmpQoE7YXkfQ1XSLFrOSwD+s8y0pC+9uKXtCUmu+kWvHz5VjfZ5PBA=="
20
20
  }
Binary file
@@ -4,9 +4,9 @@
4
4
  "platform": "linux",
5
5
  "arch": "x64",
6
6
  "rustTarget": "x86_64-unknown-linux-gnu",
7
- "sourceCommit": "70f39ead74ecc99cd407991d91d6b41e78d5ee8e",
8
- "sourceDigest": "24dd8534300805268854e15d624c2d988650d0cfbdb24c89cc2dde19014b840d",
9
- "binarySha256": "3f7bc8e6c78f1aeaf305dcae718148086e3c5010abc310c5667596c8f68e9d5b",
7
+ "sourceCommit": "b289f52657da53a436705b2cc449c3ef0d6b5672",
8
+ "sourceDigest": "18f626c9d21dc2952bf9ff077089a6c1eb6f779135acc0c8778ae7693d6c958b",
9
+ "binarySha256": "55a2cd4df6089ced7cc1fcaf22a571118fab001d6f2bcccb1a4b86792e532003",
10
10
  "protocol": {
11
11
  "lifecycleOwner": "rust-peer-session",
12
12
  "maxApplicationPayloadBytes": 65536,
@@ -16,5 +16,5 @@
16
16
  },
17
17
  "signingKeySha256": "0391c617f3df12611b419e129cace36fa792e73da03271649cbed9e9f9f155ef",
18
18
  "signatureAlgorithm": "ed25519",
19
- "signature": "1AZIAq3uZLUlldJ7FKoUrbE9S7FgSfR/8qgY7gkzyXjQx9M5U8elbthkaKLWZTp+jf6mqIXcrsAOFZIMfbQVAA=="
19
+ "signature": "GdxfroJYHDVvFVrbrUhCbsJyb6wK1KKFnmM1KreSpwHOEdkEPgOLgMtiLsGr6D5z8shoVgHyD8Erqof6sLeZCg=="
20
20
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openrtc",
3
- "version": "2.8.8",
3
+ "version": "2.8.9",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1 +0,0 @@
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,b as b$4}from'./chunk-OC4VXLX7.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {h as h$1,e}from'./chunk-577A77JB.js';import {d,b as b$5}from'./chunk-2GX6GB6L.js';function O(s,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:s,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function U(s){let e;try{e=s instanceof Uint8Array?JSON.parse(new TextDecoder().decode(s)):s&&typeof s=="object"?s:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var I="openrtc-peer-stream/1",he=32,ie=16,N=4294967295,pe=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,me=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function E(s){let e=s?.trim()??"";if(!pe.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function F(s){let e=s?.trim()??"",t=me.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function ne(s){if(s===null||s===0)return null;if(!Number.isFinite(s)||s<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(N,Math.ceil(s))}function re(s){if(!Number.isSafeInteger(s)||s<1||s>N)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${N}.`);return s}var G=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=ie;this.outgoingLimit=ie;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=ne(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=ne(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=re(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=re(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();}},D=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:he});}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);}},K=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new D;this.incomingUni=new D;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new G(i,this.peerId);}async createBidirectionalStream(e){let t=E(e.protocol),i=await this.client.channels.openBi(this.peerId,I,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=E(e.protocol);return (await this.client.channels.openUni(this.peerId,I,{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},o=this.protocolHandlers.get(t);if(o){try{o(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=E(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();}},M=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:I,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(I,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new K(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=F(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(F(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(I);}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=E(i);}catch{return this.declined+=1,false}let o=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return o?this.accepted+=1:this.declined+=1,o}resolveExistingPeer(e,t=""){let i=F(t);if(i){let o=this.peerIdsByConnection.get(i);if(!o)return this.lastResolution="unbound-connection",null;let a=this.peers.get(o);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(o=>[o.peerId,o.deviceId,o.deviceIdHint,o.connectionId,...o.connectionIds].some(a=>a===e));if(r){let o=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>o.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var H={"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 b=new WeakMap;function ve(s){let e=b.get(s);if(!e||s.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function Ge(s,e){if(b.has(s))throw new Error("[OpenRTC] Capability runtime is already registered.");return b.set(s,ve(e)),()=>{b.delete(s);}}function ge(s){let e=s?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function w(s){let e=s?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var Z=/^[A-Za-z0-9_.:@-]{1,160}$/,ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,se=2,q=8,fe=q;function we(s){let e=typeof s=="string"?s.trim():"";if(!Z.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ye.test(t)?t:e}function be(s){let e=`openrtc:v2:device-id:${s}`,t,i=(()=>{try{return t=globalThis.localStorage,we(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function oe(s){let e=typeof s=="string"?s.trim():"";if(!Z.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ae=250;function ce(s){if(s===void 0)return [];if(!Array.isArray(s))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(s.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!Z.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ae)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ae} devices.`);return e}function W(s){let e=b$1(s.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var z=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);}},j=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:(H[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=$(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw C(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=$(e.durationSeconds,"durationSeconds",1,744*60*60),n=$(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=Pe(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),o=Ce(e.architecture),a=Se(o,t,e.delivery),d=Re(a,t)*r*i*n/1e9,l=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")+l*h("coordination.lease.refresh"),p=t*u,v=r*i,m=Math.max(0,Math.ceil(t/4)-1),A=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")+m*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,g=d*h("broadcast.delivery");return {architecture:o,effectiveArchitecture:a,creditsUsd:Math.ceil((p+A+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 ${l} successful 55-minute lease renewal${l===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 Ce(s){return s??"auto"}function $(s,e,t,i){if(!Number.isSafeInteger(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return s}function Pe(s,e,t,i){if(!Number.isFinite(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return s}function h(s){let e=H[s];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${s} has no current customer-credit price.`);return e}function Se(s,e,t){if(s==="mesh"){if(e>16)throw C("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return s}if(s==="sparse"){if(e>50)throw C("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw C("[OpenRTC] Sparse room quotes require latest-state delivery.");return s}if(s==="managed")throw C("[OpenRTC] Managed room architecture is unavailable in this release.");if(s==="authority")return s;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw C(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function C(s){return h$1(e.ROOM_ARCHITECTURE_UNAVAILABLE,s,{retryable:false,plane:"admission"})}function le(s){return h$1(e.TICKET_MESH_ALREADY_ACTIVE,`[OpenRTC] ticket:${s} is already active with different options.`,{retryable:false,plane:"admission"})}function ue(s){return s.mesh===true?s.maxPeers??fe:s.maxPeers}function Ie(s){return JSON.stringify({identity:s.identity??(s.mesh===true?"session":null),maxPeers:ue(s)??null,mesh:s.mesh===true,advancedFanout:s.advancedFanout===true})}function Re(s,e){if(e<=1)return 0;if(s!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function de(s){let e=s?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var X=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 M(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,o)=>{let a=U(r);!a||a.capability!==this.capabilityKey||o!==void 0&&a.name!==o||o===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.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=de(e);return {set:i=>{let n=O("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=(o,a)=>i({peerId:o,value:a});n.add(r);for(let[o,a]of this.remoteState)a.has(t)&&i({peerId:o,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=de(e),i=n=>O("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:o})=>o?[o.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let o=this.logicalConnections.get(n)?.activeRaw;if(o){await o.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let o=(a,c)=>n({peerId:a,message:c});return r.add(o),()=>r?.delete(o)}}}onConnection(e){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 o=this.logicalConnections.get(i);if(!o){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(l,u)=>this.peerStreams.onProtocol(i,l,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),o={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async l=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(O("raw","message",l,this.capabilityKey));},onMessage:l=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let p=l;return u.add(p),()=>u?.delete(p)},onClose:l=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(l),()=>u?.delete(l)}}},this.logicalConnections.set(i,o);}o.rawIds.add(e.id),o.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(o.view));for(let[a,c]of this.localState)this.sendState(e,a,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let d of this.stateListeners.get(c)??[])d(i,null);this.remoteState.delete(i);}}let o=this.stateSenders.get(e);if(o){for(let a of o.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(d=>d.peerId===t||d.connectionId===t||d.connectionIds.some(l=>i.has(l)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let o=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(o)&&Number(o)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let d=this.mediaConnections.get(t);d&&d.observePhysicalGeneration({transportStableId:Number(o),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let o of t.rawIds){let a=this.rawConnections.get(o)?.raw;if(this.rawConnections.delete(o),this.peerStreams.unbindConnection(o),!a)continue;let c=this.stateSenders.get(a);if(c){for(let d of c.values())d.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let o of i.keys())for(let a of this.stateListeners.get(o)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let o of this.closeListeners.get(e)??[])o();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let o of this.connectionListeners.values())o.delete(e);return r}receive(e,t){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=U(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(o=>e.send(o)),n.set(t,r)),r.send(i).catch(()=>{});}},R=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;b.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}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{b.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new X(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},P=class extends R{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 o=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,d=i.devices.watchWithStatus,l=g=>(this.roster.reconcileLiveSnapshot(g),g),u=async()=>this.roster.mergeDevices(l(await o())),p=async()=>this.roster.mergeStatus(await a()),v=g=>c(B=>g(this.roster.mergeDevices(l(B)))),m=g=>d(B=>g(this.roster.mergeStatus(B))),A=Object.create(i);Object.defineProperties(A,{listDevices:{value:u,enumerable:false},listDeviceStatus:{value:p,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:m,enumerable:false},devices:{value:{...i.devices,list:u,listWithStatus:p,watch:v,watchWithStatus:m},enumerable:true}}),b.set(this,A),this.stopRosterSync=c(l);}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();}},V=class extends R{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},k=class extends R{constructor(t,i,n,r,o,a){super("ticket",t,i,n);this.token=r;this.ownsMesh=a;this.kind="ticket";this.closing=null;this.inviteListeners=new Set;this.stopInviteWatch=()=>{};if(this.currentInvite=o,a){let c=i.advanced.runtime;this.stopInviteWatch=c.watchTicketMeshInvite?.(t,d=>{this.currentInvite=d,this.inviteListeners.forEach(l=>l(d));})??this.stopInviteWatch;}}get invite(){return this.currentInvite}watchInvite(t){return this.inviteListeners.add(t),t(this.currentInvite),()=>this.inviteListeners.delete(t)}async issuerNode(){if(!this.ownsMesh)throw new Error("[OpenRTC] This ticket is not a mesh.");return this.client.advanced.runtime.ticketMeshIssuerNode(this.id)}get peers(){if(this.scopedPeers)return this.scopedPeers;let t=this.client.peers,i=`ticket:${this.id}`,n=r=>r.scopes.includes(i)&&r.status==="connected"&&r.settledReady===true&&r.routable!==false&&r.logicalSessionTerminal!==true;return this.scopedPeers={...t,watch:r=>t.watch(o=>r(o.filter(n))),watchLifecycle:r=>t.watchLifecycle(o=>r(o.filter(n))),get:r=>{let o=t.get(r);return o&&n(o)?o:void 0},listConnected:()=>t.listConnected().filter(n)}}close(){if(this.closed)return Promise.resolve();if(this.closing)return this.closing;let t=this.closeOnce();return this.closing=t,t.catch(()=>{!this.closed&&this.closing===t&&(this.closing=null);}),t}async closeOnce(){this.ownsMesh&&await this.client.advanced.runtime.closeTicketMesh(this.id),this.stopInviteWatch(),this.inviteListeners.clear(),await super.close();}},x=class{constructor(e$1,t){this.options=e$1;this.internals=t;this.channels=new z;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.pendingCapabilityShutdowns=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.closing=null;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:ce(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 P&&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=oe(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let o of this.handles)o instanceof P&&o.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 P&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${w(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-VVZXY3M2.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${w(e)}`,Ie(t),void 0,()=>this.issueTicket(e,t),t.mesh===true?()=>le(w(e)):void 0),join:e$1=>{let t=b$4(e$1);return t.mesh?this.activateOnce(`ticket:${w(t.id)}`,`join:${e$1}`,void 0,()=>this.joinTicket(e$1),()=>le(w(t.id))):Promise.reject(h$1(e.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"}))}};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async o=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(o),this.wrapBroadcastSession(await t.open(o))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=ge(e$1.apiKey);let i=e$1.trust?.browserPersistence??"session";if(i!=="session"&&i!=="persistent")throw new Error("[OpenRTC] Invalid browser identity persistence policy.");this.browserPersistence=i,this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new j(e$1.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-C5RUPLAM.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-XXY72BIM.js').then(({browserDeviceKeyProvider:e,createSessionDeviceKeyProvider:t})=>this.internals.platform!=="native"&&this.browserPersistence!=="persistent"?t():e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-XXY72BIM.js').then(({createSessionDeviceKeyProvider:e})=>e())))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.");if(this.closing)throw new Error("[OpenRTC] Client is closing.")}activateOnce(e,t,i,n,r){this.assertOpen();let o=this.activations.get(e);if(o){if(o.fingerprint!==t||o.auth!==i)throw r?r():new Error(`[OpenRTC] ${e} is already active with different options.`);return o.promise}let a={fingerprint:t,auth:i},d=(this.pendingCapabilityShutdowns.has(e)?this.settlePendingCapabilityShutdown(e).then(n):n()).then(l=>(a.handle=l,l)).catch(l=>{throw this.activations.get(e)===a&&this.activations.delete(e),l});return a.promise=d,this.activations.set(e,a),d}retainPendingCapabilityShutdown(e,t){this.pendingCapabilityShutdowns.has(e)||this.pendingCapabilityShutdowns.set(e,t);}async settlePendingCapabilityShutdown(e){let t=this.pendingCapabilityShutdowns.get(e);t&&(await t(),this.pendingCapabilityShutdowns.get(e)===t&&this.pendingCapabilityShutdowns.delete(e));}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):this.internals.platform!=="native"&&this.browserPersistence==="session"?this.sessionDeviceId??(this.sessionDeviceId=crypto.randomUUID()):be(this.appTag);return oe(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let o=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$5)===true,d$1=!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:l=>e.nativeAuth.getAssertion(l)}: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:d$1?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:o},transportPriority:o}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,o={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,d=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},l=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:o,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async m=>{a={...a,...m},await c?.setAuth(d());}}),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:l,deviceSign:e.authority?.deviceSign??(m=>t.signDeviceBytes(m)),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}),[p,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=v(p,this.internals.platform==="native"?"native":"web"),await c.setAuth(d()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({browserTrustPersistence:this.browserPersistence,sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(m){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),m}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=ce(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),o=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,o),d=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:o.name,devicePlatform:o.platform,deviceMetadata:o.metadata,nativeAuth:i}),l=[];if(this.internals.platform!=="native")try{l=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(d),await d.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),p;return p=new P(c.principalId,d,()=>{this.channels.detach(d),this.onClosed(p);},new u(l)),this.handles.add(p),p}async joinSpace(e,t={}){this.assertOpen();let i=w(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),o=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:o,deviceId:W(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new V(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-VVZXY3M2.js')).openAuthorityRoom(this,e)}async issueTicket(e$1,t={}){this.assertOpen();let i=w(e$1);if(t.mesh===true&&t.advancedFanout===true)throw h$1(e.TICKET_MESH_INVALID_OPTIONS,"[OpenRTC] Ticket mesh cannot use advancedFanout.",{retryable:false,plane:"admission"});let n=ue(t);if(t.mesh===true&&(!Number.isSafeInteger(n)||n<se||n>q))throw h$1(e.TICKET_MESH_INVALID_OPTIONS,`[OpenRTC] Ticket mesh maxPeers must be an integer between ${se} and ${q}.`,{retryable:false,plane:"admission"});let r=await(t.identity==="session"||t.mesh===true?this.sessionPlane():this.controlPlane()),o=await r.capability("ticket",i,n,t.advancedFanout),a=String(b$1(o.token).principalId),c=await this.activate({kind:"ticket",id:i,source:o,principalId:a,deviceId:W(o),maxPeers:n,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:r}),d=null;if(t.mesh===true)try{d=await c.advanced.runtime.issueTicketMesh(i,n);}catch(u){await this.shutdownFailedTicketActivation(i,c,u);}let l;return l=new k(i,c,()=>{this.channels.detach(c),this.onClosed(l);},o.token,d,t.mesh===true),this.handles.add(l),l}async joinTicket(e$1){this.assertOpen();let t=b$4(e$1);if(!t.mesh)throw h$1(e.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"});let i=w(t.id),n=await this.sessionPlane(),r=await n.capability("ticket",i,t.maxPeers,false),o=String(b$1(r.token).principalId),a=await this.activate({kind:"ticket",id:i,source:r,principalId:o,deviceId:W(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:false,controlPlane:n});try{await a.advanced.runtime.joinTicketMesh(e$1);}catch(d){await this.shutdownFailedTicketActivation(i,a,d);}let c;return c=new k(i,a,()=>{this.channels.detach(a),this.onClosed(c);},r.token,e$1,true),this.handles.add(c),c}async shutdownFailedTicketActivation(e$1,t,i){this.channels.detach(t);try{await t.advanced.runtime.shutdown();}catch(n){throw this.retainPendingCapabilityShutdown(`ticket:${e$1}`,()=>t.advanced.runtime.shutdown()),h$1(e.TICKET_MESH_UNAVAILABLE,"[OpenRTC] Ticket mesh startup failed and runtime teardown was not confirmed.",{retryable:true,plane:"coordination",cause:{startError:i,shutdownError:n}})}throw i}async close(){if(this.closed)return;if(this.closing)return this.closing;let e=this.closeOnce();this.closing=e;try{await e;}finally{this.closing===e&&(this.closing=null);}}async closeOnce(){await Promise.allSettled([...this.activations.values()].map(({promise:e})=>e)),await Promise.all([...this.handles].map(e=>e.close())),await Promise.all([...this.pendingCapabilityShutdowns.keys()].map(e=>this.settlePendingCapabilityShutdown(e))),await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.(),this.closed=true;}};function Ke(s,e){return new x(s,e)}function He(s,e){if(!(s instanceof x))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return s.openAuthorityRoom(e)}export{O as a,U as b,ve as c,Ge as d,w as e,oe as f,W as g,R as h,Ke as i,He as j};