openrtc 2.9.1 → 2.9.2
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.
- package/dist/{chunk-2W6QRVPG.js → chunk-5VCDW5BC.js} +1 -1
- package/dist/chunk-GMPEZXPD.js +2 -0
- package/dist/{chunk-PBAYXKEF.js → chunk-IAYQJZQQ.js} +1 -1
- package/dist/{chunk-7PJNNQGP.js → chunk-KXXQNKRK.js} +1 -1
- package/dist/{chunk-UBLYBL3O.js → chunk-NS32P65Z.js} +1 -1
- package/dist/{deviceHandle-WZYJYOLD.js → deviceHandle-OAF6XJPY.js} +1 -1
- package/dist/{deviceKey-XXY72BIM.js → deviceKey-2NTRYCSR.js} +1 -1
- package/dist/external-broadcast.js +1 -1
- package/dist/index.js +1 -1
- package/dist/native.js +1 -1
- package/dist/node.js +1 -1
- package/dist/{room-HNLTV274.js → room-52G6ONQZ.js} +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/service-node.js +1 -1
- package/dist/testing/native.js +1 -1
- package/dist/testing.js +1 -1
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
- package/package.json +1 -1
- package/dist/chunk-AUICRD2W.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {j,d as d$1,c}from'./chunk-
|
|
1
|
+
import {j,d as d$1,c}from'./chunk-KXXQNKRK.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
|
|
2
2
|
export{p as a,S as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import d from'tweetnacl';function c(t){let r=t instanceof Uint8Array?t:new Uint8Array(t),e="";for(let n of r)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function g(t){let r=JSON.stringify({crv:t.crv,kty:t.kty,x:t.x});return c(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function p(){return c(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function y(){return typeof indexedDB>"u"?null:new Promise((t,r)=>{let e=indexedDB.open("openrtc-v2-device-keys",1);e.onupgradeneeded=()=>{e.result.objectStoreNames.contains("keys")||e.result.createObjectStore("keys");},e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error);})}async function w(t){let r=await y().catch(()=>null);if(!r)throw new Error("[OpenRTC] Persistent browser identity storage is unavailable.");try{return await new Promise((e,n)=>{let s=r.transaction("keys","readonly").objectStore("keys").get(t);s.onsuccess=()=>e(s.result??null),s.onerror=()=>n(s.error);})}finally{r.close();}}async function K(t,r){let e=await y().catch(()=>null);if(!e)throw new Error("[OpenRTC] Persistent browser identity storage is unavailable.");try{return await new Promise((n,s)=>{let o=e.transaction("keys","readwrite"),i=r;o.oncomplete=()=>n(i),o.onabort=()=>s(o.error??new Error("[OpenRTC] Persistent browser identity storage transaction aborted."));let u=o.objectStore("keys"),a=u.get(t);a.onerror=()=>s(a.error),a.onsuccess=()=>{if(a.result!==void 0&&a.result!==null){i=a.result;return}let l=u.put(r,t);l.onerror=()=>s(l.error);};})}finally{e.close();}}async function P(t){let r=await y().catch(()=>null);if(r)try{await new Promise((e,n)=>{let s=r.transaction("keys","readwrite").objectStore("keys").delete(t);s.onsuccess=()=>e(),s.onerror=()=>n(s.error);});}finally{r.close();}}async function b(t){let r=await w(t);if(r)return r;let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return K(t,e)}async function f(t){let r=await crypto.subtle.exportKey("jwk",t.publicKey),e=await g(r);return {publicKeyJwk:r,thumbprint:e,async sign(n){return c(await crypto.subtle.sign({name:"Ed25519"},t.privateKey,n))},async proof(n){let s=p(),o=Math.floor(Date.now()/1e3),i=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,new TextEncoder().encode(n(s,o)));return {publicKeyJwk:r,signature:c(i),nonce:s,issuedAt:o}}}}async function m(){return f(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}async function v(){try{return await m()}catch(s){if(!(s instanceof Error)||s.name!=="NotSupportedError")throw s}let t=d.sign.keyPair(),r={kty:"OKP",crv:"Ed25519",x:c(t.publicKey)},e=await g(r),n=async s=>c(d.sign.detached(s,t.secretKey));return {publicKeyJwk:r,thumbprint:e,sign:n,async proof(s){let o=p(),i=Math.floor(Date.now()/1e3);return {publicKeyJwk:r,signature:await n(new TextEncoder().encode(s(o,i))),nonce:o,issuedAt:i}}}}var k={persistence:"persistent",async getOrCreate(t){return f(await b(t))},delete:P};function x(){let t=new Map,r=new Map;return {persistence:"session",getOrCreate(e){let n=t.get(e);return n||(n=v(),t.set(e,n)),n},async delete(e){t.delete(e),r.delete(e);},async readSecureRecord(e,n){return r.get(e)?.get(n)??null},async writeSecureRecord(e,n,s){let o=r.get(e);o||(o=new Map,r.set(e,o)),o.set(n,s);},async deleteSecureRecord(e,n){r.get(e)?.delete(n);}}}
|
|
2
|
+
export{g as a,m as b,k as c,x as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c}from'./chunk-
|
|
1
|
+
import {c}from'./chunk-GMPEZXPD.js';function s(t){let o=e=>`${e}:${t}`;return {getOrCreate:e=>c.getOrCreate(o(e)),delete:async e=>{await c.delete?.(o(e));},readSecureRecord:(e,c$1)=>c.readSecureRecord?.(o(e),c$1)??Promise.resolve(null),writeSecureRecord:(e,c$1,d)=>c.writeSecureRecord?.(o(e),c$1,d)??Promise.resolve(),deleteSecureRecord:(e,c$1)=>c.deleteSecureRecord?.(o(e),c$1)??Promise.resolve()}}export{s as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$3}from'./chunk-FKAQDDUM.js';import {b as b$1,a as a$2}from'./chunk-ZA44REGI.js';import {a as a$1,b as b$4}from'./chunk-ONV44QWS.js';import {b as b$2,a as a$3}from'./chunk-CCCYE3XN.js';import {d,a}from'./chunk-3B4IDT2M.js';import {d as d$1,b as b$5}from'./chunk-2GX6GB6L.js';function R(s,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:s,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function x(s){let e;try{e=s instanceof Uint8Array?JSON.parse(new TextDecoder().decode(s)):s&&typeof s=="object"?s:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var P="openrtc-peer-stream/1",de=32,Q=16,L=4294967295,ue=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,he=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function S(s){let e=s?.trim()??"";if(!ue.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function B(s){let e=s?.trim()??"",t=he.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function Y(s){if(s===null||s===0)return null;if(!Number.isFinite(s)||s<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(L,Math.ceil(s))}function ee(s){if(!Number.isSafeInteger(s)||s<1||s>L)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${L}.`);return s}var _=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Q;this.outgoingLimit=Q;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=Y(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=Y(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=ee(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=ee(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},A=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:de});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},U=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new A;this.incomingUni=new A;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new _(i,this.peerId);}async createBidirectionalStream(e){let t=S(e.protocol),i=await this.client.channels.openBi(this.peerId,P,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=S(e.protocol);return (await this.client.channels.openUni(this.peerId,P,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},o=this.protocolHandlers.get(t);if(o){try{o(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=S(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},T=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:P,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(P,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new U(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=B(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(B(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(P);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$3]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=S(i);}catch{return this.declined+=1,false}let o=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return o?this.accepted+=1:this.declined+=1,o}resolveExistingPeer(e,t=""){let i=B(t);if(i){let o=this.peerIdsByConnection.get(i);if(!o)return this.lastResolution="unbound-connection",null;let a=this.peers.get(o);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(o=>[o.peerId,o.deviceId,o.deviceIdHint,o.connectionId,...o.connectionIds].some(a=>a===e));if(r){let o=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>o.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var F={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var w=new WeakMap;function pe(s){let e=w.get(s);if(!e||s.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function Fe(s,e){if(w.has(s))throw new Error("[OpenRTC] Capability runtime is already registered.");return w.set(s,pe(e)),()=>{w.delete(s);}}function me(s){let e=s?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function y(s){let e=s?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var W=/^[A-Za-z0-9_.:@-]{1,160}$/,ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,te=2,H=8,ge=H;function fe(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ve.test(t)?t:e}function ye(s){let e=`openrtc:v2:device-id:${s}`,t,i=(()=>{try{return t=globalThis.localStorage,fe(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(s){if(s===void 0)return [];if(!Array.isArray(s))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(s.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!W.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function N(s){let e=b$1(s.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var K=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},$=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(F[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw b(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=be(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),o=we(e.architecture),a=Ce(o,t,e.delivery),l=Ie(a,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),g=t*u,f=r*i,v=Math.max(0,Math.ceil(t/4)-1),ce=a==="managed"?f*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+v*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,le=l*h("broadcast.delivery");return {architecture:o,effectiveArchitecture:a,creditsUsd:Math.ceil((g+ce+le)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function we(s){return s??"auto"}function G(s,e,t,i){if(!Number.isSafeInteger(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return s}function be(s,e,t,i){if(!Number.isFinite(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return s}function h(s){let e=F[s];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${s} has no current customer-credit price.`);return e}function Ce(s,e,t){if(s==="mesh"){if(e>16)throw b("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return s}if(s==="sparse"){if(e>50)throw b("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw b("[OpenRTC] Sparse room quotes require latest-state delivery.");return s}if(s==="managed")throw b("[OpenRTC] Managed room architecture is unavailable in this release.");if(s==="authority")return s;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw b(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function b(s){return d(a.ROOM_ARCHITECTURE_UNAVAILABLE,s,{retryable:false,plane:"admission"})}function se(s){return d(a.TICKET_MESH_ALREADY_ACTIVE,`[OpenRTC] ticket:${s} is already active with different options.`,{retryable:false,plane:"admission"})}function ae(s){return s.mesh===true?s.maxPeers??ge:s.maxPeers}function Pe(s){return JSON.stringify({identity:s.identity??(s.mesh===true?"session":null),maxPeers:ae(s)??null,mesh:s.mesh===true,advancedFanout:s.advancedFanout===true})}function Ie(s,e){if(e<=1)return 0;if(s!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function oe(s){let e=s?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var q=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.cleanupComplete=false;this.closeAttempt=null;this.pendingStops=null;this.peerStreams=new T(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,o)=>{let a=x(r);!a||a.capability!==this.capabilityKey||o!==void 0&&a.name!==o||o===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.assertOpen(),this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=oe(e);return {set:i=>{this.assertOpen();let n=R("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{this.assertOpen();let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(o,a)=>i({peerId:o,value:a});n.add(r);for(let[o,a]of this.remoteState)a.has(t)&&i({peerId:o,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){this.assertOpen();let t=oe(e),i=n=>R("channel",t,n,this.capabilityKey);return {send:async n=>{this.assertOpen();let r=i(n);await this.roomFanout?.sendChannel(t,r)||(this.assertOpen(),await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:o})=>o?[o.send(r)]:[])));},sendTo:async(n,r)=>{this.assertOpen(),this.roomFanout?.assertTargetedSendAllowed();let o=this.logicalConnections.get(n)?.activeRaw;if(o){await o.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{this.assertOpen();let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let o=(a,c)=>n({peerId:a,message:c});return r.add(o),()=>r?.delete(o)}}}onConnection(e){this.assertOpen();let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Capability messages are closed.")}close(){if(this.cleanupComplete)return Promise.resolve();if(this.closeAttempt)return this.closeAttempt;this.closed=true;let e=this.releaseMessages();return this.closeAttempt=e,e.then(()=>{this.closeAttempt===e&&(this.closeAttempt=null);},()=>{this.closeAttempt===e&&(this.closeAttempt=null);}),e}async releaseMessages(){let e=[];this.pendingStops??(this.pendingStops=[()=>this.stopMessage(),()=>this.stopConnection(),()=>this.stopDisconnection(),()=>this.stopPeerLifecycle(),()=>this.roomFanout?.close()]),this.pendingStops=this.pendingStops.filter(i=>{try{return i(),!1}catch(n){return e.push(n),true}});let t=[];for(let i of this.logicalConnections.keys())try{t.push(this.retire(i));}catch(n){e.push(n);}this.pendingRawConnections.clear();try{this.peerStreams.close();}catch(i){e.push(i);}this.rawConnections.clear(),this.logicalConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),this.remoteState.clear(),this.rawListeners.clear(),this.closeListeners.clear();for(let i of await Promise.allSettled(t))i.status==="rejected"&&e.push(i.reason);if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability message cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.cleanupComplete=true;}add(e){if(this.closed)return;let t=this.rawConnections.get(e.id);if(t?.raw===e)return;t&&this.remove(t.raw);let i=e.remoteNodeId||e.id,n=this.mediaRetirements.get(i);if(n){let a={raw:e,peerId:i};this.pendingRawConnections.set(e.id,a),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==a||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let o=this.logicalConnections.get(i);if(!o){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),o={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(R("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let g=d;return u.add(g),()=>u?.delete(g)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,o);}o.rawIds.add(e.id),o.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(o.view));for(let[a,c]of this.localState)this.sendState(e,a,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let o=this.stateSenders.get(e);if(o){for(let a of o.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let o=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(o)&&Number(o)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(o),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let o of t.rawIds){let a=this.rawConnections.get(o)?.raw;if(this.rawConnections.delete(o),this.peerStreams.unbindConnection(o),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let o of i.keys())for(let a of this.stateListeners.get(o)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let o of this.closeListeners.get(e)??[])o();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let o of this.connectionListeners.values())o.delete(e);return r}receive(e,t){if(this.closed)return;this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=x(t);if(!n){for(let r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(this.closed)return;if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let r=n.get(t);r||(r=new a$1(o=>e.send(o)),n.set(t,r)),r.send(i).catch(()=>{});}},O=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;this.retired=false;this.shutdownAttempt=null;w.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}projectRuntime(e){w.set(this,e);}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}close(){if(this.retired)return Promise.resolve();if(this.shutdownAttempt)return this.shutdownAttempt;this.closed=true;let e=this.releaseCapability();return this.shutdownAttempt=e,e.then(()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);},()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);}),e}beforeRuntimeShutdown(){}async releaseCapability(){let e=[];try{this.beforeRuntimeShutdown();}catch(t){e.push(t);}try{await this.messages?.close();}catch(t){e.push(t);}try{await this.client.advanced.runtime.shutdown();}catch(t){e.push(t);}if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.onClosed(),w.delete(this),this.retired=true;}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new q(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},z=class extends O{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},E=class extends O{constructor(t,i,n,r,o,a){super("ticket",t,i,n);this.token=r;this.ownsMesh=a;this.kind="ticket";this.closing=null;this.inviteListeners=new Set;this.stopInviteWatch=()=>{};this.meshStopped=false;if(this.currentInvite=o,a){let c=i.advanced.runtime;this.stopInviteWatch=c.watchTicketMeshInvite?.(t,l=>{this.currentInvite=l,this.inviteListeners.forEach(d=>d(l));})??this.stopInviteWatch;}}get invite(){return this.currentInvite}watchInvite(t){return this.inviteListeners.add(t),t(this.currentInvite),()=>this.inviteListeners.delete(t)}async issuerNode(){if(!this.ownsMesh)throw new Error("[OpenRTC] This ticket is not a mesh.");return this.client.advanced.runtime.ticketMeshIssuerNode(this.id)}get peers(){if(this.scopedPeers)return this.scopedPeers;let t=this.client.peers,i=`ticket:${this.id}`,n=r=>r.scopes.includes(i)&&r.status==="connected"&&r.settledReady===true&&r.routable!==false&&r.logicalSessionTerminal!==true;return this.scopedPeers={...t,watch:r=>t.watch(o=>r(o.filter(n))),watchLifecycle:r=>t.watchLifecycle(o=>r(o.filter(n))),get:r=>{let o=t.get(r);return o&&n(o)?o:void 0},listConnected:()=>t.listConnected().filter(n)}}close(){if(this.retired)return Promise.resolve();if(this.closing)return this.closing;let t=this.closeOnce();return this.closing=t,t.catch(()=>{!this.retired&&this.closing===t&&(this.closing=null);}),t}async closeOnce(){this.ownsMesh&&!this.meshStopped&&(await this.client.advanced.runtime.closeTicketMesh(this.id),this.meshStopped=true),await super.close();}beforeRuntimeShutdown(){try{this.stopInviteWatch(),this.stopInviteWatch=()=>{};}finally{this.inviteListeners.clear();}}},M=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new K;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.pendingCapabilityShutdowns=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.closing=null;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:re(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId()),{DeviceHandle:n}=await import('./deviceHandle-WZYJYOLD.js');for(let r of this.handles)r instanceof n&&r.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);let{DeviceHandle:o}=await import('./deviceHandle-WZYJYOLD.js');for(let a of this.handles)a instanceof o&&a.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId(),{DeviceHandle:n}=await import('./deviceHandle-WZYJYOLD.js');for(let r of this.handles)r instanceof n&&r.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${y(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-HNLTV274.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${y(e)}`,Pe(t),void 0,()=>this.issueTicket(e,t),t.mesh===true?()=>se(y(e)):void 0),join:e=>{let t=b$4(e);return t.mesh?this.activateOnce(`ticket:${y(t.id)}`,`join:${e}`,void 0,()=>this.joinTicket(e),()=>se(y(t.id))):Promise.reject(d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"}))}};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async o=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(o),this.wrapBroadcastSession(await t.open(o))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=me(e.apiKey);let i=e.trust?.browserPersistence??"session";if(i!=="session"&&i!=="persistent")throw new Error("[OpenRTC] Invalid browser identity persistence policy.");this.browserPersistence=i,this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new $(e.usage);}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-HPGXZDDD.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$2,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-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.handle?.closed)throw new Error(`[OpenRTC] ${e} is closing; retry close() to finish retirement.`);if(o.fingerprint!==t||o.auth!==i)throw r?r():new Error(`[OpenRTC] ${e} is already active with different options.`);return o.promise}let a={fingerprint:t,auth:i},l=(this.pendingCapabilityShutdowns.has(e)?this.settlePendingCapabilityShutdown(e).then(n):n()).then(d=>(a.handle=d,d)).catch(d=>{throw this.activations.get(e)===a&&this.activations.delete(e),d});return a.promise=l,this.activations.set(e,a),l}retainPendingCapabilityShutdown(e,t){this.pendingCapabilityShutdowns.has(e)||this.pendingCapabilityShutdowns.set(e,t);}async settlePendingCapabilityShutdown(e){let t=this.pendingCapabilityShutdowns.get(e);t&&(await t(),this.pendingCapabilityShutdowns.get(e)===t&&this.pendingCapabilityShutdowns.delete(e));}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):this.internals.platform!=="native"&&this.browserPersistence==="session"?this.sessionDeviceId??(this.sessionDeviceId=crypto.randomUUID()):ye(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let o=r?d$1(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$5)===true,l=!r||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeIdentityProvider:this.internals.platform==="native"&&e.nativeAuth?{providerId:e.nativeAuth.providerId,getSessionKey:async()=>e.nativeAuth.getSessionKey?.()??null,getAssertion:d=>e.nativeAuth.getAssertion(d)}:void 0,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$2).gateway,environment:"production",grantProvider:e.grantProvider,onServiceError:this.options.onServiceError,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:o},transportPriority:o}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,o={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:o,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async v=>{a={...a,...v},await c?.setAuth(l());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:d,deviceSign:e.authority?.deviceSign??(v=>t.signDeviceBytes(v)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeAuth:e.nativeAuth}),[g,{wrapAssembly:f}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=f(g,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({browserTrustPersistence:this.browserPersistence,sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(v){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),v}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),o=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,o),l=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:o.name,devicePlatform:o.platform,deviceMetadata:o.metadata,nativeAuth:i}),d=[];if(this.internals.platform!=="native")try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),{DeviceHandle:g}=await import('./deviceHandle-WZYJYOLD.js'),f;return f=new g(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(f);},new u(d)),this.handles.add(f),f}async joinSpace(e,t={}){this.assertOpen();let i=y(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),o=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new z(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-HNLTV274.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=y(e);if(t.mesh===true&&t.advancedFanout===true)throw d(a.TICKET_MESH_INVALID_OPTIONS,"[OpenRTC] Ticket mesh cannot use advancedFanout.",{retryable:false,plane:"admission"});let n=ae(t);if(t.mesh===true&&(!Number.isSafeInteger(n)||n<te||n>H))throw d(a.TICKET_MESH_INVALID_OPTIONS,`[OpenRTC] Ticket mesh maxPeers must be an integer between ${te} and ${H}.`,{retryable:false,plane:"admission"});let r=await(t.identity==="session"||t.mesh===true?this.sessionPlane():this.controlPlane()),o=await r.capability("ticket",i,n,t.advancedFanout),a$1=String(b$1(o.token).principalId),c=await this.activate({kind:"ticket",id:i,source:o,principalId:a$1,deviceId:N(o),maxPeers:n,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:r}),l=null;if(t.mesh===true)try{l=await c.advanced.runtime.issueTicketMesh(i,n);}catch(u){await this.shutdownFailedTicketActivation(i,c,u);}let d$1;return d$1=new E(i,c,()=>{this.channels.detach(c),this.onClosed(d$1);},o.token,l,t.mesh===true),this.handles.add(d$1),d$1}async joinTicket(e){this.assertOpen();let t=b$4(e);if(!t.mesh)throw d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"});let i=y(t.id),n=await this.sessionPlane(),r=await n.capability("ticket",i,t.maxPeers,false),o=String(b$1(r.token).principalId),a$1=await this.activate({kind:"ticket",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:false,controlPlane:n});try{await a$1.advanced.runtime.joinTicketMesh(e);}catch(l){await this.shutdownFailedTicketActivation(i,a$1,l);}let c;return c=new E(i,a$1,()=>{this.channels.detach(a$1),this.onClosed(c);},r.token,e,true),this.handles.add(c),c}async shutdownFailedTicketActivation(e,t,i){this.channels.detach(t);try{await t.advanced.runtime.shutdown();}catch(n){throw this.retainPendingCapabilityShutdown(`ticket:${e}`,()=>t.advanced.runtime.shutdown()),d(a.TICKET_MESH_UNAVAILABLE,"[OpenRTC] Ticket mesh startup failed and runtime teardown was not confirmed.",{retryable:true,plane:"coordination",cause:{startError:i,shutdownError:n}})}throw i}async close(){if(this.closed)return;if(this.closing)return this.closing;let e=this.closeOnce();this.closing=e;try{await e;}finally{this.closing===e&&(this.closing=null);}}async closeOnce(){await Promise.allSettled([...this.activations.values()].map(({promise:e})=>e)),await Promise.all([...this.handles].map(e=>e.close())),await Promise.all([...this.pendingCapabilityShutdowns.keys()].map(e=>this.settlePendingCapabilityShutdown(e))),await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.(),this.closed=true;}};function Ne(s,e){return new M(s,e)}function Ge(s,e){if(!(s instanceof M))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return s.openAuthorityRoom(e)}export{R as a,x as b,pe as c,Fe as d,y as e,ie as f,N as g,O as h,Ne as i,Ge as j};
|
|
1
|
+
import {b as b$3}from'./chunk-FKAQDDUM.js';import {b as b$1,a as a$2}from'./chunk-ZA44REGI.js';import {a as a$1,b as b$4}from'./chunk-ONV44QWS.js';import {b as b$2,a as a$3}from'./chunk-CCCYE3XN.js';import {d,a}from'./chunk-3B4IDT2M.js';import {d as d$1,b as b$5}from'./chunk-2GX6GB6L.js';function R(s,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:s,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function x(s){let e;try{e=s instanceof Uint8Array?JSON.parse(new TextDecoder().decode(s)):s&&typeof s=="object"?s:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var P="openrtc-peer-stream/1",de=32,Q=16,L=4294967295,ue=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,he=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function S(s){let e=s?.trim()??"";if(!ue.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function B(s){let e=s?.trim()??"",t=he.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function Y(s){if(s===null||s===0)return null;if(!Number.isFinite(s)||s<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(L,Math.ceil(s))}function ee(s){if(!Number.isSafeInteger(s)||s<1||s>L)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${L}.`);return s}var _=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Q;this.outgoingLimit=Q;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=Y(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=Y(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=ee(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=ee(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},A=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:de});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},U=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new A;this.incomingUni=new A;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new _(i,this.peerId);}async createBidirectionalStream(e){let t=S(e.protocol),i=await this.client.channels.openBi(this.peerId,P,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=S(e.protocol);return (await this.client.channels.openUni(this.peerId,P,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},o=this.protocolHandlers.get(t);if(o){try{o(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=S(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},T=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:P,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(P,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new U(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=B(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(B(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(P);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$3]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=S(i);}catch{return this.declined+=1,false}let o=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return o?this.accepted+=1:this.declined+=1,o}resolveExistingPeer(e,t=""){let i=B(t);if(i){let o=this.peerIdsByConnection.get(i);if(!o)return this.lastResolution="unbound-connection",null;let a=this.peers.get(o);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(o=>[o.peerId,o.deviceId,o.deviceIdHint,o.connectionId,...o.connectionIds].some(a=>a===e));if(r){let o=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>o.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var F={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var w=new WeakMap;function pe(s){let e=w.get(s);if(!e||s.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function Fe(s,e){if(w.has(s))throw new Error("[OpenRTC] Capability runtime is already registered.");return w.set(s,pe(e)),()=>{w.delete(s);}}function me(s){let e=s?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function y(s){let e=s?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var W=/^[A-Za-z0-9_.:@-]{1,160}$/,ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,te=2,H=8,ge=H;function fe(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ve.test(t)?t:e}function ye(s){let e=`openrtc:v2:device-id:${s}`,t,i=(()=>{try{return t=globalThis.localStorage,fe(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(s){if(s===void 0)return [];if(!Array.isArray(s))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(s.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!W.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function N(s){let e=b$1(s.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var K=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},$=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(F[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw b(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=be(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),o=we(e.architecture),a=Ce(o,t,e.delivery),l=Ie(a,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),g=t*u,f=r*i,v=Math.max(0,Math.ceil(t/4)-1),ce=a==="managed"?f*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+v*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,le=l*h("broadcast.delivery");return {architecture:o,effectiveArchitecture:a,creditsUsd:Math.ceil((g+ce+le)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function we(s){return s??"auto"}function G(s,e,t,i){if(!Number.isSafeInteger(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return s}function be(s,e,t,i){if(!Number.isFinite(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return s}function h(s){let e=F[s];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${s} has no current customer-credit price.`);return e}function Ce(s,e,t){if(s==="mesh"){if(e>16)throw b("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return s}if(s==="sparse"){if(e>50)throw b("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw b("[OpenRTC] Sparse room quotes require latest-state delivery.");return s}if(s==="managed")throw b("[OpenRTC] Managed room architecture is unavailable in this release.");if(s==="authority")return s;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw b(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function b(s){return d(a.ROOM_ARCHITECTURE_UNAVAILABLE,s,{retryable:false,plane:"admission"})}function se(s){return d(a.TICKET_MESH_ALREADY_ACTIVE,`[OpenRTC] ticket:${s} is already active with different options.`,{retryable:false,plane:"admission"})}function ae(s){return s.mesh===true?s.maxPeers??ge:s.maxPeers}function Pe(s){return JSON.stringify({identity:s.identity??(s.mesh===true?"session":null),maxPeers:ae(s)??null,mesh:s.mesh===true,advancedFanout:s.advancedFanout===true})}function Ie(s,e){if(e<=1)return 0;if(s!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function oe(s){let e=s?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var q=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.cleanupComplete=false;this.closeAttempt=null;this.pendingStops=null;this.peerStreams=new T(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,o)=>{let a=x(r);!a||a.capability!==this.capabilityKey||o!==void 0&&a.name!==o||o===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.assertOpen(),this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=oe(e);return {set:i=>{this.assertOpen();let n=R("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{this.assertOpen();let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(o,a)=>i({peerId:o,value:a});n.add(r);for(let[o,a]of this.remoteState)a.has(t)&&i({peerId:o,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){this.assertOpen();let t=oe(e),i=n=>R("channel",t,n,this.capabilityKey);return {send:async n=>{this.assertOpen();let r=i(n);await this.roomFanout?.sendChannel(t,r)||(this.assertOpen(),await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:o})=>o?[o.send(r)]:[])));},sendTo:async(n,r)=>{this.assertOpen(),this.roomFanout?.assertTargetedSendAllowed();let o=this.logicalConnections.get(n)?.activeRaw;if(o){await o.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{this.assertOpen();let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let o=(a,c)=>n({peerId:a,message:c});return r.add(o),()=>r?.delete(o)}}}onConnection(e){this.assertOpen();let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Capability messages are closed.")}close(){if(this.cleanupComplete)return Promise.resolve();if(this.closeAttempt)return this.closeAttempt;this.closed=true;let e=this.releaseMessages();return this.closeAttempt=e,e.then(()=>{this.closeAttempt===e&&(this.closeAttempt=null);},()=>{this.closeAttempt===e&&(this.closeAttempt=null);}),e}async releaseMessages(){let e=[];this.pendingStops??(this.pendingStops=[()=>this.stopMessage(),()=>this.stopConnection(),()=>this.stopDisconnection(),()=>this.stopPeerLifecycle(),()=>this.roomFanout?.close()]),this.pendingStops=this.pendingStops.filter(i=>{try{return i(),!1}catch(n){return e.push(n),true}});let t=[];for(let i of this.logicalConnections.keys())try{t.push(this.retire(i));}catch(n){e.push(n);}this.pendingRawConnections.clear();try{this.peerStreams.close();}catch(i){e.push(i);}this.rawConnections.clear(),this.logicalConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),this.remoteState.clear(),this.rawListeners.clear(),this.closeListeners.clear();for(let i of await Promise.allSettled(t))i.status==="rejected"&&e.push(i.reason);if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability message cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.cleanupComplete=true;}add(e){if(this.closed)return;let t=this.rawConnections.get(e.id);if(t?.raw===e)return;t&&this.remove(t.raw);let i=e.remoteNodeId||e.id,n=this.mediaRetirements.get(i);if(n){let a={raw:e,peerId:i};this.pendingRawConnections.set(e.id,a),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==a||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let o=this.logicalConnections.get(i);if(!o){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),o={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(R("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let g=d;return u.add(g),()=>u?.delete(g)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,o);}o.rawIds.add(e.id),o.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(o.view));for(let[a,c]of this.localState)this.sendState(e,a,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let o=this.stateSenders.get(e);if(o){for(let a of o.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let o=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(o)&&Number(o)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(o),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let o of t.rawIds){let a=this.rawConnections.get(o)?.raw;if(this.rawConnections.delete(o),this.peerStreams.unbindConnection(o),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let o of i.keys())for(let a of this.stateListeners.get(o)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let o of this.closeListeners.get(e)??[])o();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let o of this.connectionListeners.values())o.delete(e);return r}receive(e,t){if(this.closed)return;this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=x(t);if(!n){for(let r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(this.closed)return;if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let r=n.get(t);r||(r=new a$1(o=>e.send(o)),n.set(t,r)),r.send(i).catch(()=>{});}},O=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;this.retired=false;this.shutdownAttempt=null;w.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}projectRuntime(e){w.set(this,e);}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}close(){if(this.retired)return Promise.resolve();if(this.shutdownAttempt)return this.shutdownAttempt;this.closed=true;let e=this.releaseCapability();return this.shutdownAttempt=e,e.then(()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);},()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);}),e}beforeRuntimeShutdown(){}async releaseCapability(){let e=[];try{this.beforeRuntimeShutdown();}catch(t){e.push(t);}try{await this.messages?.close();}catch(t){e.push(t);}try{await this.client.advanced.runtime.shutdown();}catch(t){e.push(t);}if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.onClosed(),w.delete(this),this.retired=true;}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new q(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},z=class extends O{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},E=class extends O{constructor(t,i,n,r,o,a){super("ticket",t,i,n);this.token=r;this.ownsMesh=a;this.kind="ticket";this.closing=null;this.inviteListeners=new Set;this.stopInviteWatch=()=>{};this.meshStopped=false;if(this.currentInvite=o,a){let c=i.advanced.runtime;this.stopInviteWatch=c.watchTicketMeshInvite?.(t,l=>{this.currentInvite=l,this.inviteListeners.forEach(d=>d(l));})??this.stopInviteWatch;}}get invite(){return this.currentInvite}watchInvite(t){return this.inviteListeners.add(t),t(this.currentInvite),()=>this.inviteListeners.delete(t)}async issuerNode(){if(!this.ownsMesh)throw new Error("[OpenRTC] This ticket is not a mesh.");return this.client.advanced.runtime.ticketMeshIssuerNode(this.id)}get peers(){if(this.scopedPeers)return this.scopedPeers;let t=this.client.peers,i=`ticket:${this.id}`,n=r=>r.scopes.includes(i)&&r.status==="connected"&&r.settledReady===true&&r.routable!==false&&r.logicalSessionTerminal!==true;return this.scopedPeers={...t,watch:r=>t.watch(o=>r(o.filter(n))),watchLifecycle:r=>t.watchLifecycle(o=>r(o.filter(n))),get:r=>{let o=t.get(r);return o&&n(o)?o:void 0},listConnected:()=>t.listConnected().filter(n)}}close(){if(this.retired)return Promise.resolve();if(this.closing)return this.closing;let t=this.closeOnce();return this.closing=t,t.catch(()=>{!this.retired&&this.closing===t&&(this.closing=null);}),t}async closeOnce(){this.ownsMesh&&!this.meshStopped&&(await this.client.advanced.runtime.closeTicketMesh(this.id),this.meshStopped=true),await super.close();}beforeRuntimeShutdown(){try{this.stopInviteWatch(),this.stopInviteWatch=()=>{};}finally{this.inviteListeners.clear();}}},M=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new K;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.pendingCapabilityShutdowns=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.closing=null;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:re(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId()),{DeviceHandle:n}=await import('./deviceHandle-OAF6XJPY.js');for(let r of this.handles)r instanceof n&&r.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);let{DeviceHandle:o}=await import('./deviceHandle-OAF6XJPY.js');for(let a of this.handles)a instanceof o&&a.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId(),{DeviceHandle:n}=await import('./deviceHandle-OAF6XJPY.js');for(let r of this.handles)r instanceof n&&r.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${y(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-52G6ONQZ.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${y(e)}`,Pe(t),void 0,()=>this.issueTicket(e,t),t.mesh===true?()=>se(y(e)):void 0),join:e=>{let t=b$4(e);return t.mesh?this.activateOnce(`ticket:${y(t.id)}`,`join:${e}`,void 0,()=>this.joinTicket(e),()=>se(y(t.id))):Promise.reject(d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"}))}};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async o=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(o),this.wrapBroadcastSession(await t.open(o))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=me(e.apiKey);let i=e.trust?.browserPersistence??"session";if(i!=="session"&&i!=="persistent")throw new Error("[OpenRTC] Invalid browser identity persistence policy.");this.browserPersistence=i,this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new $(e.usage);}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-HPGXZDDD.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$2,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-2NTRYCSR.js').then(({browserDeviceKeyProvider:e,createSessionDeviceKeyProvider:t})=>this.internals.platform!=="native"&&this.browserPersistence!=="persistent"?t():e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-2NTRYCSR.js').then(({createSessionDeviceKeyProvider:e})=>e())))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.");if(this.closing)throw new Error("[OpenRTC] Client is closing.")}activateOnce(e,t,i,n,r){this.assertOpen();let o=this.activations.get(e);if(o){if(o.handle?.closed)throw new Error(`[OpenRTC] ${e} is closing; retry close() to finish retirement.`);if(o.fingerprint!==t||o.auth!==i)throw r?r():new Error(`[OpenRTC] ${e} is already active with different options.`);return o.promise}let a={fingerprint:t,auth:i},l=(this.pendingCapabilityShutdowns.has(e)?this.settlePendingCapabilityShutdown(e).then(n):n()).then(d=>(a.handle=d,d)).catch(d=>{throw this.activations.get(e)===a&&this.activations.delete(e),d});return a.promise=l,this.activations.set(e,a),l}retainPendingCapabilityShutdown(e,t){this.pendingCapabilityShutdowns.has(e)||this.pendingCapabilityShutdowns.set(e,t);}async settlePendingCapabilityShutdown(e){let t=this.pendingCapabilityShutdowns.get(e);t&&(await t(),this.pendingCapabilityShutdowns.get(e)===t&&this.pendingCapabilityShutdowns.delete(e));}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):this.internals.platform!=="native"&&this.browserPersistence==="session"?this.sessionDeviceId??(this.sessionDeviceId=crypto.randomUUID()):ye(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let o=r?d$1(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$5)===true,l=!r||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeIdentityProvider:this.internals.platform==="native"&&e.nativeAuth?{providerId:e.nativeAuth.providerId,getSessionKey:async()=>e.nativeAuth.getSessionKey?.()??null,getAssertion:d=>e.nativeAuth.getAssertion(d)}:void 0,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$2).gateway,environment:"production",grantProvider:e.grantProvider,onServiceError:this.options.onServiceError,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:o},transportPriority:o}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,o={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:o,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async v=>{a={...a,...v},await c?.setAuth(l());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:d,deviceSign:e.authority?.deviceSign??(v=>t.signDeviceBytes(v)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeAuth:e.nativeAuth}),[g,{wrapAssembly:f}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=f(g,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({browserTrustPersistence:this.browserPersistence,sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(v){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),v}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),o=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,o),l=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:o.name,devicePlatform:o.platform,deviceMetadata:o.metadata,nativeAuth:i}),d=[];if(this.internals.platform!=="native")try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),{DeviceHandle:g}=await import('./deviceHandle-OAF6XJPY.js'),f;return f=new g(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(f);},new u(d)),this.handles.add(f),f}async joinSpace(e,t={}){this.assertOpen();let i=y(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),o=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new z(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-52G6ONQZ.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=y(e);if(t.mesh===true&&t.advancedFanout===true)throw d(a.TICKET_MESH_INVALID_OPTIONS,"[OpenRTC] Ticket mesh cannot use advancedFanout.",{retryable:false,plane:"admission"});let n=ae(t);if(t.mesh===true&&(!Number.isSafeInteger(n)||n<te||n>H))throw d(a.TICKET_MESH_INVALID_OPTIONS,`[OpenRTC] Ticket mesh maxPeers must be an integer between ${te} and ${H}.`,{retryable:false,plane:"admission"});let r=await(t.identity==="session"||t.mesh===true?this.sessionPlane():this.controlPlane()),o=await r.capability("ticket",i,n,t.advancedFanout),a$1=String(b$1(o.token).principalId),c=await this.activate({kind:"ticket",id:i,source:o,principalId:a$1,deviceId:N(o),maxPeers:n,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:r}),l=null;if(t.mesh===true)try{l=await c.advanced.runtime.issueTicketMesh(i,n);}catch(u){await this.shutdownFailedTicketActivation(i,c,u);}let d$1;return d$1=new E(i,c,()=>{this.channels.detach(c),this.onClosed(d$1);},o.token,l,t.mesh===true),this.handles.add(d$1),d$1}async joinTicket(e){this.assertOpen();let t=b$4(e);if(!t.mesh)throw d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"});let i=y(t.id),n=await this.sessionPlane(),r=await n.capability("ticket",i,t.maxPeers,false),o=String(b$1(r.token).principalId),a$1=await this.activate({kind:"ticket",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:false,controlPlane:n});try{await a$1.advanced.runtime.joinTicketMesh(e);}catch(l){await this.shutdownFailedTicketActivation(i,a$1,l);}let c;return c=new E(i,a$1,()=>{this.channels.detach(a$1),this.onClosed(c);},r.token,e,true),this.handles.add(c),c}async shutdownFailedTicketActivation(e,t,i){this.channels.detach(t);try{await t.advanced.runtime.shutdown();}catch(n){throw this.retainPendingCapabilityShutdown(`ticket:${e}`,()=>t.advanced.runtime.shutdown()),d(a.TICKET_MESH_UNAVAILABLE,"[OpenRTC] Ticket mesh startup failed and runtime teardown was not confirmed.",{retryable:true,plane:"coordination",cause:{startError:i,shutdownError:n}})}throw i}async close(){if(this.closed)return;if(this.closing)return this.closing;let e=this.closeOnce();this.closing=e;try{await e;}finally{this.closing===e&&(this.closing=null);}}async closeOnce(){await Promise.allSettled([...this.activations.values()].map(({promise:e})=>e)),await Promise.all([...this.handles].map(e=>e.close())),await Promise.all([...this.pendingCapabilityShutdowns.keys()].map(e=>this.settlePendingCapabilityShutdown(e))),await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.(),this.closed=true;}};function Ne(s,e){return new M(s,e)}function Ge(s,e){if(!(s instanceof M))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return s.openAuthorityRoom(e)}export{R as a,x as b,pe as c,Fe as d,y as e,ie as f,N as g,O as h,Ne as i,Ge as j};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-GMPEZXPD.js';function u(){let r=crypto.getRandomValues(new Uint8Array(24)),e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(r){if(!r||typeof r!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=r;if(e.kty!=="OKP"||e.crv!=="Ed25519"||typeof e.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.x)||e.d!==void 0)throw new Error("[OpenRTC] Native host returned an invalid Ed25519 public key.");return {kty:"OKP",crv:"Ed25519",x:e.x}}function v(r){return {async readSecureRecord(e,t){return r.invoke("openrtc_read_secure_record",{appTag:e,key:t})},async writeSecureRecord(e,t,c){await r.invoke("openrtc_write_secure_record",{appTag:e,key:t,value:c});},async deleteSecureRecord(e,t){await r.invoke("openrtc_delete_secure_record",{appTag:e,key:t});},async delete(e){await r.invoke("openrtc_delete_device_key",{appTag:e});},async getOrCreate(e){let t=d(await r.invoke("openrtc_device_public_key",{appTag:e})),c=await a(t);return {publicKeyJwk:t,thumbprint:c,async sign(i){let o=new TextDecoder("utf-8",{fatal:true}).decode(i),n=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:o});if(!/^[A-Za-z0-9_-]{80,128}$/.test(n))throw new Error("[OpenRTC] Native host returned an invalid device signature.");return n},async proof(i){let o=u(),n=Math.floor(Date.now()/1e3),a=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:i(o,n)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(a))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:t,signature:a,nonce:o,issuedAt:n}}}}}}
|
|
2
2
|
export{v as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {h}from'./chunk-
|
|
1
|
+
import {h}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';var d=class extends h{constructor(e,t,u,w){super("devices",e,t,u);this.roster=w;this.kind="devices";this.rosterStopped=false;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=e=>this.client.devices.watch(t=>e(this.roster.mergeDevices(t)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let p=t.devices.list,m=t.devices.listWithStatus,c=t.devices.watch,S=t.devices.watchWithStatus,i=s=>(this.roster.reconcileLiveSnapshot(s),s),o=async()=>this.roster.mergeDevices(i(await p())),a=async()=>this.roster.mergeStatus(await m()),n=s=>c(r=>s(this.roster.mergeDevices(i(r)))),v=s=>S(r=>s(this.roster.mergeStatus(r))),l=Object.create(t);Object.defineProperties(l,{listDevices:{value:o,enumerable:false},listDeviceStatus:{value:a,enumerable:false},watchDevices:{value:n,enumerable:false},watchDeviceStatus:{value:v,enumerable:false},devices:{value:{...t.devices,list:o,listWithStatus:a,watch:n,watchWithStatus:v},enumerable:true}}),this.projectRuntime(l),this.stopRosterSync=c(i);}replaceEnrolledDevices(e){this.roster.replace(e);}removeEnrolledDevice(e){this.roster.remove(e);}retainCurrentEnrolledDevice(e){this.roster.retain(e);}beforeRuntimeShutdown(){this.rosterStopped||(this.stopRosterSync(),this.rosterStopped=true);}};export{d as DeviceHandle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as browserDeviceKeyProvider,b as createDeviceKey,d as createSessionDeviceKeyProvider,a as deviceKeyThumbprint}from'./chunk-
|
|
1
|
+
export{c as browserDeviceKeyProvider,b as createDeviceKey,d as createSessionDeviceKeyProvider,a as deviceKeyThumbprint}from'./chunk-GMPEZXPD.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-RB4UWXK6.js';import'./chunk-BGWJHPBC.js';import'./chunk-AYHD4X2R.js';import {a}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-RB4UWXK6.js';import'./chunk-BGWJHPBC.js';import'./chunk-AYHD4X2R.js';import {a}from'./chunk-IAYQJZQQ.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';async function K(r,e){if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r)||!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("[OpenRTC] External broadcast identity is invalid.");return (await a(e).getOrCreate(`app_${r.slice(-16)}`)).publicKeyJwk}function h(r){let e=new URL(r),t=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(t&&e.protocol==="http:")||e.pathname!=="/"||e.username||e.password||e.search||e.hash||r!==e.origin&&r!==`${e.origin}/`)throw new Error("[OpenRTC] External broadcast service must be an exact HTTPS origin.");return e.origin}function k(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function x(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(r,e){if(!(r.issuerPublicKey instanceof Uint8Array)||r.issuerPublicKey.length!==32)throw new Error("[OpenRTC] External broadcast issuer key must be 32 bytes.");let t=r.relay;if(t.kind==="sfu"){let a=new URL(t.controlUrl,e);if(a.origin!==e||a.protocol!==new URL(e).protocol||a.pathname==="/"||a.username||a.password||a.search||a.hash)throw new Error("[OpenRTC] External SFU control must stay on the trusted service origin.");return {issuerPublicKey:r.issuerPublicKey,relay:{kind:"sfu",controlUrl:a.href.replace(/\/$/,"")}}}else {let a=new URL(t.relayUrl);if(a.protocol!=="https:"||a.username||a.password||!t.token||!t.namespace)throw new Error("[OpenRTC] External MoQ relay access is invalid.");if(t.serverCertificateHash&&!["localhost","127.0.0.1","[::1]"].includes(a.hostname))throw new Error("[OpenRTC] Custom relay certificate hashes are limited to loopback.")}return r}function P(r,e){if(!r||typeof r.apiKey!="string"||!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r.apiKey))throw new Error("[OpenRTC] External broadcast identity is invalid.");let t=h(e.serviceOrigin);if(!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace)||typeof e.resolve!="function")throw new Error("[OpenRTC] External broadcast configuration is invalid.");let a$2=a(e.keyNamespace),d=`app_${r.apiKey.slice(-16)}`,l=()=>a$2.getOrCreate(d),u=async()=>{let{loadBrowserWasmRuntimeModule:i}=await import('./WasmBridge-EWVV4DFE.js'),n=await i();return await n.initWasm(),n.start(),new n.WasmClient(r.apiKey)},w,f=()=>w??(w=u()),m=new a$1({loadWasm:f,resolve:async(i,n)=>{let o=await l(),s=C(await e.resolve(i,o.publicKeyJwk,n),t),g=s.relay.kind==="sfu"?{kind:"sfu",controlUrl:s.relay.controlUrl,grant:i,bindingPublicJwk:o.publicKeyJwk,...n?{publicationVerifyingKey:x(n)}:{}}:s.relay;return {token:i,issuerPublicKey:s.issuerPublicKey,relay:g,signBindingChallenge:async b=>k(await o.sign(b))}}});return {client:i(r,{platform:"web",endpoints:{controlPlane:t,gateway:t},testingAllowInsecureLoopback:t.startsWith("http:"),deviceKeyProvider:a$2,broadcastHost:m,runtimeFactory:async i=>{let{createWasmClient:n}=await import('./runtime/factories.js');return n(i)}}),bindingPublicJwk:async()=>(await l()).publicKeyJwk}}
|
|
2
2
|
export{P as createExternalBroadcastClient,K as externalBroadcastBindingPublicJwk};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';export{b as parseTicketInvite}from'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function c(a){return i(a,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:n}]=await Promise.all([import('./BrowserManagedBroadcastHost-GLSYJIOR.js'),import('./WasmBridge-EWVV4DFE.js')]),t=n().then(async r=>(await r.initWasm(),r.start(),new r.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>t})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}c.native=function(a$1,e=d()){let o,n=()=>o??(o=import('./NativeProjectionBroker-2OH2SCPF.js').then(({NativeProjectionBroker:t})=>new t));return i(a$1,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new r(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let r=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:r,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:async()=>{o&&await(await o).close();},deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let[{createIpcClient:r},y]=await Promise.all([import('./ipcFactory-WNHLLXCB.js'),n()]);return r(t,e,y)}})};export{c as OpenRTC};
|
package/dist/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-RT7YTAXU.js';import'./chunk-COXQYBTI.js';import {a as a$1}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-RT7YTAXU.js';import'./chunk-COXQYBTI.js';import {a as a$1}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function u(p,t=d()){let r=new a;return i(p,{platform:"native",broadcastHostFactory:async e=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new o(t,e)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async e=>{let o=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:e.trustDomain,deviceId:e.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:e.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let e=await t.invoke("get_rtc_local_device_info");return String(e?.deviceId??"")},runtimeFactory:async e=>{let{createIpcClient:o}=await import('./ipcFactory-WNHLLXCB.js');return o(e,t,r)}})}export{u as OpenRTC};
|
package/dist/node.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-RT7YTAXU.js';import {a as a$2}from'./chunk-COXQYBTI.js';import {a as a$1}from'./chunk-UBLYBL3O.js';import {c}from'./chunk-72NEEJQG.js';import'./chunk-AUICRD2W.js';import {i,b as b$2,a as a$3}from'./chunk-7PJNNQGP.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import {e as e$1,b as b$3}from'./chunk-3B4IDT2M.js';import {b as b$1,d,e}from'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';import {spawn}from'child_process';import {constants}from'fs';import {access,readFile}from'fs/promises';import {isAbsolute,resolve,dirname}from'path';import {fileURLToPath}from'url';import {isDeepStrictEqual}from'util';import {randomUUID,verify,createHash}from'crypto';var N=1,F=24*1024,U=96*1024,E=128*1024,C=64*1024,ne=256,ie=256,L=3e4,se=/^[A-Za-z0-9_.:@-]+$/,ae=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,ce=1;function de(r){return Buffer.from(JSON.stringify({schema:r.schema,kind:r.kind,platform:r.platform,arch:r.arch,rustTarget:r.rustTarget,sourceCommit:r.sourceCommit,sourceDigest:r.sourceDigest,binarySha256:r.binarySha256,protocol:r.protocol,signingKeySha256:r.signingKeySha256,signatureAlgorithm:r.signatureAlgorithm}),"utf8")}async function le(r,e,t){let[o,n,a]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(r,"native","openrtc-node-host-signing-public.pem"))]).catch(()=>{throw new Error("[OpenRTC] Packaged Node host provenance is incomplete.")}),i;try{i=JSON.parse(n.toString("utf8"));}catch{throw new Error("[OpenRTC] Packaged Node host manifest is invalid.")}let c=s=>createHash("sha256").update(s).digest("hex"),l={"darwin-arm64":"aarch64-apple-darwin","darwin-x64":"x86_64-apple-darwin","linux-x64":"x86_64-unknown-linux-gnu"}[`${process.platform}-${process.arch}`];if(!(i!=null&&l!==void 0&&i.schema===ce&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===l&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===c(o)&&i.signingKeySha256===c(a)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,de(i),a,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function z(r){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!ae.test(e)&&(!r||!t?.includes(r))))}function f(r,e){queueMicrotask(()=>{try{let t=r(e);t&&typeof t.then=="function"&&t.catch(()=>{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}});}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function $(r){let e=/^\d{1,20}$/;return typeof r.transportStableId!="string"||!e.test(r.transportStableId)||!e.test(r.transportGeneration)||!e.test(r.routeGeneration)?null:{transportStableId:r.transportStableId,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration}}function ue(r,e){return r.transportStableId===e.transportStableId&&r.transportGeneration===e.transportGeneration&&r.routeGeneration===e.routeGeneration}function m(r,e,t=160){let o=r.trim();if(!o||o.length>t||!se.test(o))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return o}function v(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 pe(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(r.secretKey)||r.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...r.shardIds].map(t=>m(t,"shardId",80)).sort();if(e.length<1||e.length>64||new Set(e).size!==e.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");if(!isAbsolute(r.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return r.maxPeers!==void 0&&v(r.maxPeers,"maxPeers",50),r.startupTimeoutMs!==void 0&&v(r.startupTimeoutMs,"startupTimeoutMs",12e4),{...r,serviceId:m(r.serviceId,"serviceId",80),generation:v(r.generation,"generation"),shardIds:e,deviceId:m(r.deviceId,"deviceId"),deviceName:r.deviceName?.trim()||"OpenRTC Node service"}}async function y(r){try{return await access(r,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function V(r,e,t,o,n){return new Promise((a,i)=>{let c=spawn(r,e,{cwd:t,env:z(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),l=Buffer.alloc(0),u=(p,Y)=>Buffer.concat([p,Y]).subarray(-E);c.stdout.on("data",p=>{d=u(d,p);}),c.stderr.on("data",p=>{l=u(l,p);});let s=setTimeout(()=>{c.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${r}.`));},o);c.once("error",p=>{clearTimeout(s),i(p);}),c.once("exit",p=>{clearTimeout(s),p===0?a(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${l.toString("utf8").trim().slice(-4096)}`));});})}async function J(r){let e=r.binaryPath||process.env.OPENRTC_NODE_HOST_BINARY;if(e){if(!isAbsolute(e)||!await y(e))throw new Error("[OpenRTC] Node host binaryPath must name an executable absolute path.");return {command:e,args:[...r.binaryArgs??[]]}}if(r.buildFromSource){let a=r.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!a||!isAbsolute(a))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(a,"crates/openrtc/Cargo.toml"),c=resolve(a,"target");await V("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",c],a,12e4,r.secretKey);let d=resolve(c,"debug",`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(d))throw new Error("[OpenRTC] local Node host build did not produce an executable.");return {command:d,args:[]}}let t=resolve(dirname(fileURLToPath(import.meta.url)),".."),o=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(o,`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(n))throw new Error(`[OpenRTC] This package has no Node host for ${process.platform}-${process.arch}. Install a supported OpenRTC package, set OPENRTC_NODE_HOST_BINARY, or use buildFromSource with sourceRoot.`);return await le(t,o,n),{command:n,args:[]}}async function X(r,e){let t=await V(r.command,[...r.args,"--protocol-info"],process.cwd(),12e4,e),o=JSON.parse(t);if(o.protocolVersion!==N||o.lifecycleOwner!=="rust-peer-session"||o.maxConfigBytes!==F||o.maxCommandBytes!==U||o.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return o}var I=class{constructor(e,t,o){this.options=e;this.roomId=t;this.onEvent=o;this.child=null;this.childClosed=Promise.resolve();this.output=Buffer.alloc(0);this.stderr=Buffer.alloc(0);this.pending=new Map;this.writeQueue=Promise.resolve();this.stopped=false;this.closing=null;}async start(){let e=await J(this.options),t=await X(e,this.options.secretKey),o=new Promise((n,a)=>{let i=spawn(e.command,[...e.args],{env:z(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(u=>i.once("close",()=>u()));let c,d=setTimeout(()=>{a(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??L),l=u=>{clearTimeout(d);let s=b$3.is(u)?u:this.failure(u.message);a(s),this.failAll(s);};i.once("error",l),i.stderr.on("data",u=>{this.stderr=Buffer.concat([this.stderr,u]).subarray(-4096);}),i.stdout.on("data",u=>{try{for(let s of this.parse(u)){if(s.type==="failure"){c=this.failure(s.error,s.serviceError),l(c);continue}if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&s.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:s.snapshot.connectionId,deviceId:s.snapshot.deviceId,state:s.snapshot.state,routable:s.snapshot.routable,transportStableId:s.transportStableId,transportGeneration:s.transportGeneration,routeGeneration:s.routeGeneration}),s.type==="ready"){if(s.protocolVersion!==N||s.roomId!==this.roomId||s.deviceId!==this.options.deviceId||!isDeepStrictEqual(s.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(d),n();}this.dispatch(s);}}catch(s){l(s instanceof Error?s:new Error(String(s))),i.kill();}}),i.once("exit",(u,s)=>{clearTimeout(d),this.stopped=true;let p=c??this.failure(`Node host exited (${u??s??"unknown"})`);this.onEvent({type:"host-exit",error:p}),l(p);});});await this.writeLine({protocolVersion:N,apiKey:this.options.apiKey,secretKey:this.options.secretKey,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:this.options.deviceId,roomId:this.roomId,deviceName:this.options.deviceName,stateDirectory:this.options.stateDirectory,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false},F),await o;}async request(e,t){if(!this.child||this.stopped||!this.child.stdin.writable)throw new Error("[OpenRTC] Node host is closed.");if(this.pending.size>=ne)throw new Error("[OpenRTC] Node host has too many pending requests.");let o=randomUUID(),n=new Promise((a,i)=>{let c=setTimeout(()=>{this.pending.delete(o),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},L);this.pending.set(o,{resolve:a,reject:i,timer:c});});try{await this.writeLine({type:e,id:o,...t},U);}catch(a){let i=this.pending.get(o);throw i&&clearTimeout(i.timer),this.pending.delete(o),this.failure(a instanceof Error?a.message:String(a))}return n}close(){return this.closing??(this.closing=this.stop())}async stop(){if(!this.child)return;let e=this.child;try{this.stopped||await this.request("shutdown",{});}finally{e.stdin.end();let t=setTimeout(()=>e.kill("SIGTERM"),2e3),o=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(o);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>E&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let o=this.output.indexOf(10);if(o<0)break;if(o>E)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,o).toString("utf8").trim();this.output=this.output.subarray(o+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let o=`${JSON.stringify(e)}
|
|
1
|
+
import {a}from'./chunk-RT7YTAXU.js';import {a as a$2}from'./chunk-COXQYBTI.js';import {a as a$1}from'./chunk-NS32P65Z.js';import {c}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i,b as b$2,a as a$3}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import {e as e$1,b as b$3}from'./chunk-3B4IDT2M.js';import {b as b$1,d,e}from'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';import {spawn}from'child_process';import {constants}from'fs';import {access,readFile}from'fs/promises';import {isAbsolute,resolve,dirname}from'path';import {fileURLToPath}from'url';import {isDeepStrictEqual}from'util';import {randomUUID,verify,createHash}from'crypto';var N=1,F=24*1024,U=96*1024,E=128*1024,C=64*1024,ne=256,ie=256,L=3e4,se=/^[A-Za-z0-9_.:@-]+$/,ae=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,ce=1;function de(r){return Buffer.from(JSON.stringify({schema:r.schema,kind:r.kind,platform:r.platform,arch:r.arch,rustTarget:r.rustTarget,sourceCommit:r.sourceCommit,sourceDigest:r.sourceDigest,binarySha256:r.binarySha256,protocol:r.protocol,signingKeySha256:r.signingKeySha256,signatureAlgorithm:r.signatureAlgorithm}),"utf8")}async function le(r,e,t){let[o,n,a]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(r,"native","openrtc-node-host-signing-public.pem"))]).catch(()=>{throw new Error("[OpenRTC] Packaged Node host provenance is incomplete.")}),i;try{i=JSON.parse(n.toString("utf8"));}catch{throw new Error("[OpenRTC] Packaged Node host manifest is invalid.")}let c=s=>createHash("sha256").update(s).digest("hex"),l={"darwin-arm64":"aarch64-apple-darwin","darwin-x64":"x86_64-apple-darwin","linux-x64":"x86_64-unknown-linux-gnu"}[`${process.platform}-${process.arch}`];if(!(i!=null&&l!==void 0&&i.schema===ce&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===l&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===c(o)&&i.signingKeySha256===c(a)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,de(i),a,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function z(r){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!ae.test(e)&&(!r||!t?.includes(r))))}function f(r,e){queueMicrotask(()=>{try{let t=r(e);t&&typeof t.then=="function"&&t.catch(()=>{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}});}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function $(r){let e=/^\d{1,20}$/;return typeof r.transportStableId!="string"||!e.test(r.transportStableId)||!e.test(r.transportGeneration)||!e.test(r.routeGeneration)?null:{transportStableId:r.transportStableId,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration}}function ue(r,e){return r.transportStableId===e.transportStableId&&r.transportGeneration===e.transportGeneration&&r.routeGeneration===e.routeGeneration}function m(r,e,t=160){let o=r.trim();if(!o||o.length>t||!se.test(o))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return o}function v(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 pe(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(r.secretKey)||r.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...r.shardIds].map(t=>m(t,"shardId",80)).sort();if(e.length<1||e.length>64||new Set(e).size!==e.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");if(!isAbsolute(r.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return r.maxPeers!==void 0&&v(r.maxPeers,"maxPeers",50),r.startupTimeoutMs!==void 0&&v(r.startupTimeoutMs,"startupTimeoutMs",12e4),{...r,serviceId:m(r.serviceId,"serviceId",80),generation:v(r.generation,"generation"),shardIds:e,deviceId:m(r.deviceId,"deviceId"),deviceName:r.deviceName?.trim()||"OpenRTC Node service"}}async function y(r){try{return await access(r,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function V(r,e,t,o,n){return new Promise((a,i)=>{let c=spawn(r,e,{cwd:t,env:z(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),l=Buffer.alloc(0),u=(p,Y)=>Buffer.concat([p,Y]).subarray(-E);c.stdout.on("data",p=>{d=u(d,p);}),c.stderr.on("data",p=>{l=u(l,p);});let s=setTimeout(()=>{c.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${r}.`));},o);c.once("error",p=>{clearTimeout(s),i(p);}),c.once("exit",p=>{clearTimeout(s),p===0?a(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${l.toString("utf8").trim().slice(-4096)}`));});})}async function J(r){let e=r.binaryPath||process.env.OPENRTC_NODE_HOST_BINARY;if(e){if(!isAbsolute(e)||!await y(e))throw new Error("[OpenRTC] Node host binaryPath must name an executable absolute path.");return {command:e,args:[...r.binaryArgs??[]]}}if(r.buildFromSource){let a=r.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!a||!isAbsolute(a))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(a,"crates/openrtc/Cargo.toml"),c=resolve(a,"target");await V("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",c],a,12e4,r.secretKey);let d=resolve(c,"debug",`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(d))throw new Error("[OpenRTC] local Node host build did not produce an executable.");return {command:d,args:[]}}let t=resolve(dirname(fileURLToPath(import.meta.url)),".."),o=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(o,`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(n))throw new Error(`[OpenRTC] This package has no Node host for ${process.platform}-${process.arch}. Install a supported OpenRTC package, set OPENRTC_NODE_HOST_BINARY, or use buildFromSource with sourceRoot.`);return await le(t,o,n),{command:n,args:[]}}async function X(r,e){let t=await V(r.command,[...r.args,"--protocol-info"],process.cwd(),12e4,e),o=JSON.parse(t);if(o.protocolVersion!==N||o.lifecycleOwner!=="rust-peer-session"||o.maxConfigBytes!==F||o.maxCommandBytes!==U||o.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return o}var I=class{constructor(e,t,o){this.options=e;this.roomId=t;this.onEvent=o;this.child=null;this.childClosed=Promise.resolve();this.output=Buffer.alloc(0);this.stderr=Buffer.alloc(0);this.pending=new Map;this.writeQueue=Promise.resolve();this.stopped=false;this.closing=null;}async start(){let e=await J(this.options),t=await X(e,this.options.secretKey),o=new Promise((n,a)=>{let i=spawn(e.command,[...e.args],{env:z(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(u=>i.once("close",()=>u()));let c,d=setTimeout(()=>{a(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??L),l=u=>{clearTimeout(d);let s=b$3.is(u)?u:this.failure(u.message);a(s),this.failAll(s);};i.once("error",l),i.stderr.on("data",u=>{this.stderr=Buffer.concat([this.stderr,u]).subarray(-4096);}),i.stdout.on("data",u=>{try{for(let s of this.parse(u)){if(s.type==="failure"){c=this.failure(s.error,s.serviceError),l(c);continue}if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&s.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:s.snapshot.connectionId,deviceId:s.snapshot.deviceId,state:s.snapshot.state,routable:s.snapshot.routable,transportStableId:s.transportStableId,transportGeneration:s.transportGeneration,routeGeneration:s.routeGeneration}),s.type==="ready"){if(s.protocolVersion!==N||s.roomId!==this.roomId||s.deviceId!==this.options.deviceId||!isDeepStrictEqual(s.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(d),n();}this.dispatch(s);}}catch(s){l(s instanceof Error?s:new Error(String(s))),i.kill();}}),i.once("exit",(u,s)=>{clearTimeout(d),this.stopped=true;let p=c??this.failure(`Node host exited (${u??s??"unknown"})`);this.onEvent({type:"host-exit",error:p}),l(p);});});await this.writeLine({protocolVersion:N,apiKey:this.options.apiKey,secretKey:this.options.secretKey,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:this.options.deviceId,roomId:this.roomId,deviceName:this.options.deviceName,stateDirectory:this.options.stateDirectory,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false},F),await o;}async request(e,t){if(!this.child||this.stopped||!this.child.stdin.writable)throw new Error("[OpenRTC] Node host is closed.");if(this.pending.size>=ne)throw new Error("[OpenRTC] Node host has too many pending requests.");let o=randomUUID(),n=new Promise((a,i)=>{let c=setTimeout(()=>{this.pending.delete(o),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},L);this.pending.set(o,{resolve:a,reject:i,timer:c});});try{await this.writeLine({type:e,id:o,...t},U);}catch(a){let i=this.pending.get(o);throw i&&clearTimeout(i.timer),this.pending.delete(o),this.failure(a instanceof Error?a.message:String(a))}return n}close(){return this.closing??(this.closing=this.stop())}async stop(){if(!this.child)return;let e=this.child;try{this.stopped||await this.request("shutdown",{});}finally{e.stdin.end();let t=setTimeout(()=>e.kill("SIGTERM"),2e3),o=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(o);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>E&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let o=this.output.indexOf(10);if(o<0)break;if(o>E)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,o).toString("utf8").trim();this.output=this.output.subarray(o+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let o=`${JSON.stringify(e)}
|
|
2
2
|
`;if(Buffer.byteLength(o,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((a,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(o,c=>{c?i(c):a();});}));return this.writeQueue=n.catch(()=>{}),n}dispatch(e){if(e.type!=="response"){this.onEvent(e);return}let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(this.failure(e.error||"Node host request failed",e.serviceError)));}failure(e$2,t){let o=c=>c.split(this.options.secretKey).join("[REDACTED]"),n=o(e$2),a=o(this.stderr.toString("utf8")).trim(),i=`[OpenRTC] ${n}.${a?` Host stderr: ${a}`:""}`;if(t&&typeof t=="object"&&!Array.isArray(t)){let c=t,d$1=b$1(c.code);if(d(c.code)||d$1){let l=e(c);return e$1({...l,requestId:l.requestId?o(l.requestId):void 0,code:c.code,retryable:typeof c.retryable=="boolean"?c.retryable:!!d$1,message:i})}}return new Error(i)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},S=class{constructor(e,t,o,n,a){this.id=e;this.peerId=t;this.host=o;this.nativeGeneration=n;this.capabilityKey=a;this.messages=new Set;this.closeListeners=new Set;this.queued=[];this.isClosed=false;}async send(e){if(this.isClosed)throw new Error("[OpenRTC] Connection is closed.");let t=he(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$3("raw","message",e,this.capabilityKey));await this.host.request("send",{connectionId:this.id,payloadBase64:t.toString("base64")});}onMessage(e){let t=e;this.messages.add(t);for(let o of this.queued.splice(0))f(t,o);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?f(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===ie&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)f(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)f(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ue(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t,o){this.id=e;this.host=t;this.onServiceError=o;this.kind="room";this.listeners=new Set;this.connections=new Map;this.closed=false;}publishAssignment(e){if(this.closed)return Promise.reject(new Error("[OpenRTC] Service room is closed."));let t=(e.priorityDeviceIds??[]).map(n=>m(n,"priorityDeviceId")),o=(e.relevantEntityIds??[]).map(n=>m(n,"relevantEntityId"));return t.length>8||o.length>32||new Set(t).size!==t.length||new Set(o).size!==o.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:m(e.subjectDeviceId,"subjectDeviceId"),shardId:m(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:o,ttlMs:e.ttlMs===void 0?void 0:v(e.ttlMs,"ttlMs",12e4)})}onConnection(e){this.listeners.add(e);for(let t of this.connections.values())f(e,t);return ()=>this.listeners.delete(e)}project(e){if(this.closed)return;if(e.type==="host-exit"){this.closed=true;for(let d of this.connections.values())d.close();this.connections.clear(),this.listeners.clear();return}if(e.type==="service-error"){let d=e.avenue;if(!d||typeof d!="object"||Array.isArray(d))return;let l=d;if(l.kind!=="room"||l.id!==this.id||typeof e.runtimeInstanceId!="string"||e.runtimeInstanceId.trim().length===0)return;let u=a$2(e.serviceError,{kind:"room",id:this.id});u&&this.onServiceError&&f(()=>{if(!this.closed)return this.onServiceError?.(u)},void 0);return}if(e.type==="peer-message"){let d=this.connections.get(e.connectionId),l=$(e);if(d&&l&&d.accepts(l)){let u=fe(e.payloadBase64),s=b$2(u);s?s.capability===`room:${this.id}`&&s.kind==="raw"&&d.receive(s.value):d.receive(u);}return}if(e.type!=="connection-state")return;let t=e.snapshot,o=$(e);if(typeof t.connectionId!="string"||!o)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(o)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(o);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let c=new S(t.connectionId,i,this.host,o,`room:${this.id}`);this.connections.set(c.id,c);for(let d of this.listeners)f(d,c);}async close(){if(this.closed)return this.host.close();this.closed=true;for(let e of this.connections.values())e.close();this.connections.clear(),this.listeners.clear(),await this.host.close();}};function he(r){let e;if(r instanceof Uint8Array)e=Buffer.from(r);else if(r instanceof ArrayBuffer)e=Buffer.from(r);else if(typeof r=="string")e=Buffer.from(r,"utf8");else {let t=JSON.stringify(r);if(t===void 0)throw new TypeError("[OpenRTC] Message must be a string, bytes, or JSON value.");e=Buffer.from(t,"utf8");}if(e.length>C)throw new RangeError("[OpenRTC] Message exceeds the Node host payload limit.");return e}function fe(r){let e=Buffer.from(r,"base64");if(e.length>C)throw new Error("[OpenRTC] Node host returned an oversized application payload.");try{let t=new TextDecoder("utf-8",{fatal:!0}).decode(e);try{return JSON.parse(t)}catch{return t}}catch{return new Uint8Array(e)}}var b=class{constructor(e){this.listeners=new Set;this.roomPromise=null;this.roomId=null;this.closed=false;this.closing=null;this.options=pe(e);}onConnection(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");return this.listeners.add(e),()=>this.listeners.delete(e)}listen(e){return this.closed?Promise.reject(new Error("[OpenRTC] ServiceNode is closed.")):(e=m(e,"roomId"),this.roomId&&this.roomId!==e?Promise.reject(new Error("[OpenRTC] A Node ServiceNode owns exactly one room.")):this.roomPromise?this.roomPromise:(this.roomId=e,this.roomPromise=this.open(e),this.roomPromise))}close(){return this.closing??(this.closing=this.stop())}async stop(){this.closed=true,await(await this.roomPromise?.catch(()=>null))?.close(),this.listeners.clear();}async open(e){let t,o=new I(this.options,e,n=>t?.project(n));t=new T(e,o,this.options.onServiceError);try{return await o.start(),t.onConnection(n=>{for(let a of this.listeners)f(a,{room:t,connection:n});}),t}catch(n){throw await o.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function me(r){let e=await J(r);return X(e)}function ke(r,e){let t=c(e,"openrtc/node"),o=new a;return i(r,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:a}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new a(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let a=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:a,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>o.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let n=await t.invoke("get_rtc_local_device_info");return String(n?.deviceId??"")},runtimeFactory:async n=>{let{createIpcClient:a}=await import('./ipcFactory-WNHLLXCB.js');return a(n,t,o)}})}export{ke as OpenRTC,b as ServiceNode,me as inspectNodeHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {h,e,g,f}from'./chunk-7PJNNQGP.js';import'./chunk-FKAQDDUM.js';import {b}from'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function M(t){let e=t.architecture??(t.advancedFanout===true?"sparse":"auto");if(t.advancedFanout===true&&e!=="sparse")throw new Error("[OpenRTC] advancedFanout conflicts with architecture; use architecture: sparse only.");return {architecture:e,delivery:t.payload??(t.advancedFanout===true?"latest-state":"reliable")}}var R=class{constructor(e){this.mode=e==="sparse"?"sparse":"direct";}create(e){return new w(e,()=>this.mode)}setArchitecture(e){e.phase==="settled"&&(this.mode=e.effective==="sparse"?"sparse":e.effective==="managed"?"managed":"direct");}},w=class{constructor(e,r){this.host=e;this.mode=r;this.sparseForwardQueue=[];this.sparseForwardRunning=false;this.sparseForwardQueueDropsPending=0;this.sparseForwardDropReport=null;this.closed=false;let i=e.client.advanced.runtime.onManagedRoomMessage;this.stopManagedMessage=typeof i=="function"?i.call(e.client.advanced.runtime,a=>{e.deliver(a.senderId,a.payload,a.channel);}):()=>{};}isSparse(){return this.mode()==="sparse"}publishState(e,r){return this.mode()!=="managed"?false:(this.publishManaged(e,r).catch(()=>{}),true)}async sendChannel(e,r){let i=this.mode();if(i==="managed")return await this.publishManaged(e,r),true;if(i!=="sparse")return false;let a=this.host.connections();if(a.length===0)return true;let o=await this.host.client.advanced.runtime.encodeSparseFanoutMessage(this.host.capabilityKey,r);return await Promise.all(a.map(n=>n.send(o))),true}assertTargetedSendAllowed(){if(this.mode()==="managed")throw new Error("[OpenRTC] Targeted messages are not available in managed fanout rooms; use authority mode for targeted request semantics.")}receive(e,r,i){return this.mode()!=="sparse"?false:(i instanceof Uint8Array&&this.receiveSparseBroadcast(e,r,i),true)}close(){this.closed||(this.closed=true,this.stopManagedMessage(),this.sparseForwardQueue.length=0);}publishManaged(e,r){return this.host.client.advanced.runtime.publishManagedRoomMessage({messageId:crypto.randomUUID(),channel:e,priority:1,payload:r})}async receiveSparseBroadcast(e,r,i){let a;try{a=await this.host.client.advanced.runtime.acceptSparseFanoutMessage(this.host.capabilityKey,r,i);}catch{return}if(a.forward){let o=Number.isSafeInteger(a.forwardPeerLimit)&&a.forwardPeerLimit>0?a.forwardPeerLimit:0,n=Number.isSafeInteger(a.forwardQueueCapacity)&&a.forwardQueueCapacity>0?Math.min(a.forwardQueueCapacity,64):0,c=new Set(Array.isArray(a.forwardPeerIds)?a.forwardPeerIds.slice(0,o):[]),s=this.host.connections().filter(u=>u.id!==e.id).filter(u=>c.has(u.remoteNodeId)).slice(0,o);this.enqueueSparseForward(a.forward,s,n);}this.host.deliver(a.authorDeviceId,a.payload);}enqueueSparseForward(e,r,i){if(i===0||r.length===0||this.closed)return;if(this.sparseForwardQueue.length+(this.sparseForwardRunning?1:0)>=i){this.sparseForwardQueueDropsPending+=1,this.flushSparseForwardDropReport();return}this.sparseForwardQueue.push({payload:e,targets:r}),this.sparseForwardRunning||this.drainSparseForwardQueue();}async drainSparseForwardQueue(){if(!this.sparseForwardRunning){this.sparseForwardRunning=true;try{for(;!this.closed;){let e=this.sparseForwardQueue.shift();if(!e)break;await Promise.allSettled(e.targets.map(r=>r.send(e.payload)));}}finally{this.sparseForwardRunning=false,!this.closed&&this.sparseForwardQueue.length>0&&this.drainSparseForwardQueue();}}}flushSparseForwardDropReport(){if(this.sparseForwardDropReport||this.sparseForwardQueueDropsPending===0)return;let e=this.sparseForwardQueueDropsPending;this.sparseForwardQueueDropsPending=0,this.sparseForwardDropReport=this.host.client.advanced.runtime.recordSparseFanoutForwardQueueDrop(this.host.capabilityKey,e).catch(()=>{}).finally(()=>{this.sparseForwardDropReport=null,this.flushSparseForwardDropReport();});}},y=class extends h{constructor(r,i,a,o,n,c="auto"){let s=new R(c);super("room",r,i,a,s);this.membership=o;this.onLeave=n;this.kind="room";this.left=false;this.architectureListeners=new Set;this.authorityAssignmentSnapshot=null;this.authorityAssignmentListeners=new Set;this.architectureSnapshot=x(c);let u=i.advanced.runtime.onRoomArchitectureChange;this.stopArchitecture=typeof u=="function"?u.call(i.advanced.runtime,d=>{if(!(d.epoch<this.architectureSnapshot.epoch)){this.architectureSnapshot=Object.freeze({...d}),this.setArchitecture(d);for(let l of this.architectureListeners)l(this.architectureSnapshot);}}):()=>{};let h=i.advanced.runtime.onRoomAuthorityAssignmentChange;this.stopAuthorityAssignment=typeof h=="function"?h.call(i.advanced.runtime,d=>{this.authorityAssignmentSnapshot=d?O(d):null;for(let l of this.authorityAssignmentListeners)l(S(this.authorityAssignmentSnapshot));}):()=>{};}architecture(){return {...this.architectureSnapshot}}onArchitectureChanged(r){return this.architectureListeners.add(r),r(this.architecture()),()=>this.architectureListeners.delete(r)}authorityAssignment(){return S(this.authorityAssignmentSnapshot)}onAuthorityAssignmentChanged(r){return this.authorityAssignmentListeners.add(r),r(this.authorityAssignment()),()=>this.authorityAssignmentListeners.delete(r)}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}async close(){this.stopArchitecture(),this.stopAuthorityAssignment(),this.architectureListeners.clear(),this.authorityAssignmentListeners.clear(),await super.close();}};async function L(t,e$1,r){t.assertOpen();let i=e(e$1),a=r.access??"capability",{architecture:o,delivery:n}=M(r);return t.activateOnce(`room:${i}`,JSON.stringify({access:a,membership:r.membership??"ephemeral",identity:r.identity??null,maxPeers:r.maxPeers??null,payload:n,architecture:o,advancedFanout:r.advancedFanout===true}),a==="authenticated"?r.auth??t.options.auth:void 0,()=>D(t,i,r,o,n))}async function D(t,e,r,i,a){let o=r.membership??"ephemeral",n=r.access??"capability";if(i==="sparse"&&a!=="latest-state")throw new Error("[OpenRTC] Sparse rooms require payload: latest-state.");if(o==="durable"&&n!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r.identity==="session"&&n!=="capability")throw new Error("[OpenRTC] Session room identity requires access: capability.");if(n==="authenticated"){let l=r.auth??t.options.auth;if(!l)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let A=await t.deviceId(),v=await t.controlPlane(),m=await v.deviceCertificate(l,A,{kind:"room",id:e});o==="durable"&&await v.durableRoomMembership(m.source,e,"join");let f;try{f=await t.activate({kind:"room",id:e,source:m.source,principalId:m.principalId,deviceId:A,maxPeers:r.maxPeers,autoConnect:!0,durableMembership:o==="durable",advancedFanout:r.advancedFanout,architecture:i,defaultDelivery:a});}catch(I){throw o==="durable"&&await v.durableRoomMembership(m.source,e,"leave").catch(()=>{}),I}let g;return g=new y(e,f,()=>{t.channels.detach(f),t.onClosed(g);},o,o==="durable"?async()=>{await v.durableRoomMembership(m.source,e,"leave");}:void 0,i),t.trackHandle(g)}let c=await(r.identity==="session"?t.sessionPlane():t.controlPlane()),s=await c.capability("room",e,r.maxPeers,r.advancedFanout,i,a),u=String(b(s.token).principalId),h=await t.activate({kind:"room",id:e,source:s,principalId:u,deviceId:g(s),maxPeers:r.maxPeers,autoConnect:true,advancedFanout:r.advancedFanout,architecture:i,defaultDelivery:a,controlPlane:c}),d;return d=new y(e,h,()=>{t.channels.detach(h),t.onClosed(d);},"ephemeral",void 0,i),t.trackHandle(d)}function T(t,e$1){t.assertOpen();let r=e(e$1.roomId),i=e(e$1.serviceId),a=f(e$1.deviceId);if(!Number.isSafeInteger(e$1.generation)||e$1.generation<1)throw new Error("[OpenRTC] Authority service generation is invalid.");let o=[...e$1.shardIds].map(e).sort();if(o.length<1||o.length>64||new Set(o).size!==o.length)throw new Error("[OpenRTC] Authority service shards are invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.devicePublicKeyX))throw new Error("[OpenRTC] Authority service device public key is invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.assignmentPublicKeyX))throw new Error("[OpenRTC] Authority assignment public key is invalid.");if(e$1.maxPeers!==void 0&&(!Number.isSafeInteger(e$1.maxPeers)||e$1.maxPeers<1||e$1.maxPeers>50))throw new Error("[OpenRTC] Authority service maxPeers must be within 1..50.");return t.activateOnce(`room:${r}`,JSON.stringify({architecture:"authority",serviceId:i,generation:e$1.generation,shardIds:o,deviceId:a,maxPeers:e$1.maxPeers??null,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSignerId:t.authorityCallableId(e$1.deviceSign),grantProviderId:t.authorityCallableId(e$1.grantProvider)}),void 0,async()=>{let n={type:"capability",token:"",avenue:{kind:"room",id:r},expiresAtMs:Number.MAX_SAFE_INTEGER,irohRelay:e$1.irohRelay,managedTurn:false},c=await t.activate({kind:"room",id:r,source:n,principalId:i,deviceId:a,maxPeers:e$1.maxPeers,autoConnect:true,architecture:"authority",defaultDelivery:"reliable",authority:{serviceId:i,generation:e$1.generation,shardIds:o,deviceId:a,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSign:e$1.deviceSign,grantProvider:e$1.grantProvider}}),s;return s=new y(r,c,()=>{t.channels.detach(c),t.onClosed(s);},"ephemeral",void 0,"authority"),t.trackHandle(s)})}function O(t){return Object.freeze({...t,priorityDeviceIds:Object.freeze([...t.priorityDeviceIds]),relevantEntityIds:Object.freeze([...t.relevantEntityIds])})}function S(t){return t?{...t,priorityDeviceIds:[...t.priorityDeviceIds],relevantEntityIds:[...t.relevantEntityIds]}:null}function x(t){return {requested:t,effective:t==="sparse"?"sparse":"mesh",epoch:0,phase:t==="mesh"||t==="sparse"?"settled":"preparing",reason:t==="auto"?"size":"manual",heldCreditsUsd:0,quoteExpiresAtMs:Date.now()+5*6e4}}export{y as RoomHandle,L as joinRoom,T as openAuthorityRoom,M as resolveRoomJoinOptions};
|
|
1
|
+
import {h,e,g,f}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import {b}from'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function M(t){let e=t.architecture??(t.advancedFanout===true?"sparse":"auto");if(t.advancedFanout===true&&e!=="sparse")throw new Error("[OpenRTC] advancedFanout conflicts with architecture; use architecture: sparse only.");return {architecture:e,delivery:t.payload??(t.advancedFanout===true?"latest-state":"reliable")}}var R=class{constructor(e){this.mode=e==="sparse"?"sparse":"direct";}create(e){return new w(e,()=>this.mode)}setArchitecture(e){e.phase==="settled"&&(this.mode=e.effective==="sparse"?"sparse":e.effective==="managed"?"managed":"direct");}},w=class{constructor(e,r){this.host=e;this.mode=r;this.sparseForwardQueue=[];this.sparseForwardRunning=false;this.sparseForwardQueueDropsPending=0;this.sparseForwardDropReport=null;this.closed=false;let i=e.client.advanced.runtime.onManagedRoomMessage;this.stopManagedMessage=typeof i=="function"?i.call(e.client.advanced.runtime,a=>{e.deliver(a.senderId,a.payload,a.channel);}):()=>{};}isSparse(){return this.mode()==="sparse"}publishState(e,r){return this.mode()!=="managed"?false:(this.publishManaged(e,r).catch(()=>{}),true)}async sendChannel(e,r){let i=this.mode();if(i==="managed")return await this.publishManaged(e,r),true;if(i!=="sparse")return false;let a=this.host.connections();if(a.length===0)return true;let o=await this.host.client.advanced.runtime.encodeSparseFanoutMessage(this.host.capabilityKey,r);return await Promise.all(a.map(n=>n.send(o))),true}assertTargetedSendAllowed(){if(this.mode()==="managed")throw new Error("[OpenRTC] Targeted messages are not available in managed fanout rooms; use authority mode for targeted request semantics.")}receive(e,r,i){return this.mode()!=="sparse"?false:(i instanceof Uint8Array&&this.receiveSparseBroadcast(e,r,i),true)}close(){this.closed||(this.closed=true,this.stopManagedMessage(),this.sparseForwardQueue.length=0);}publishManaged(e,r){return this.host.client.advanced.runtime.publishManagedRoomMessage({messageId:crypto.randomUUID(),channel:e,priority:1,payload:r})}async receiveSparseBroadcast(e,r,i){let a;try{a=await this.host.client.advanced.runtime.acceptSparseFanoutMessage(this.host.capabilityKey,r,i);}catch{return}if(a.forward){let o=Number.isSafeInteger(a.forwardPeerLimit)&&a.forwardPeerLimit>0?a.forwardPeerLimit:0,n=Number.isSafeInteger(a.forwardQueueCapacity)&&a.forwardQueueCapacity>0?Math.min(a.forwardQueueCapacity,64):0,c=new Set(Array.isArray(a.forwardPeerIds)?a.forwardPeerIds.slice(0,o):[]),s=this.host.connections().filter(u=>u.id!==e.id).filter(u=>c.has(u.remoteNodeId)).slice(0,o);this.enqueueSparseForward(a.forward,s,n);}this.host.deliver(a.authorDeviceId,a.payload);}enqueueSparseForward(e,r,i){if(i===0||r.length===0||this.closed)return;if(this.sparseForwardQueue.length+(this.sparseForwardRunning?1:0)>=i){this.sparseForwardQueueDropsPending+=1,this.flushSparseForwardDropReport();return}this.sparseForwardQueue.push({payload:e,targets:r}),this.sparseForwardRunning||this.drainSparseForwardQueue();}async drainSparseForwardQueue(){if(!this.sparseForwardRunning){this.sparseForwardRunning=true;try{for(;!this.closed;){let e=this.sparseForwardQueue.shift();if(!e)break;await Promise.allSettled(e.targets.map(r=>r.send(e.payload)));}}finally{this.sparseForwardRunning=false,!this.closed&&this.sparseForwardQueue.length>0&&this.drainSparseForwardQueue();}}}flushSparseForwardDropReport(){if(this.sparseForwardDropReport||this.sparseForwardQueueDropsPending===0)return;let e=this.sparseForwardQueueDropsPending;this.sparseForwardQueueDropsPending=0,this.sparseForwardDropReport=this.host.client.advanced.runtime.recordSparseFanoutForwardQueueDrop(this.host.capabilityKey,e).catch(()=>{}).finally(()=>{this.sparseForwardDropReport=null,this.flushSparseForwardDropReport();});}},y=class extends h{constructor(r,i,a,o,n,c="auto"){let s=new R(c);super("room",r,i,a,s);this.membership=o;this.onLeave=n;this.kind="room";this.left=false;this.architectureListeners=new Set;this.authorityAssignmentSnapshot=null;this.authorityAssignmentListeners=new Set;this.architectureSnapshot=x(c);let u=i.advanced.runtime.onRoomArchitectureChange;this.stopArchitecture=typeof u=="function"?u.call(i.advanced.runtime,d=>{if(!(d.epoch<this.architectureSnapshot.epoch)){this.architectureSnapshot=Object.freeze({...d}),this.setArchitecture(d);for(let l of this.architectureListeners)l(this.architectureSnapshot);}}):()=>{};let h=i.advanced.runtime.onRoomAuthorityAssignmentChange;this.stopAuthorityAssignment=typeof h=="function"?h.call(i.advanced.runtime,d=>{this.authorityAssignmentSnapshot=d?O(d):null;for(let l of this.authorityAssignmentListeners)l(S(this.authorityAssignmentSnapshot));}):()=>{};}architecture(){return {...this.architectureSnapshot}}onArchitectureChanged(r){return this.architectureListeners.add(r),r(this.architecture()),()=>this.architectureListeners.delete(r)}authorityAssignment(){return S(this.authorityAssignmentSnapshot)}onAuthorityAssignmentChanged(r){return this.authorityAssignmentListeners.add(r),r(this.authorityAssignment()),()=>this.authorityAssignmentListeners.delete(r)}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}async close(){this.stopArchitecture(),this.stopAuthorityAssignment(),this.architectureListeners.clear(),this.authorityAssignmentListeners.clear(),await super.close();}};async function L(t,e$1,r){t.assertOpen();let i=e(e$1),a=r.access??"capability",{architecture:o,delivery:n}=M(r);return t.activateOnce(`room:${i}`,JSON.stringify({access:a,membership:r.membership??"ephemeral",identity:r.identity??null,maxPeers:r.maxPeers??null,payload:n,architecture:o,advancedFanout:r.advancedFanout===true}),a==="authenticated"?r.auth??t.options.auth:void 0,()=>D(t,i,r,o,n))}async function D(t,e,r,i,a){let o=r.membership??"ephemeral",n=r.access??"capability";if(i==="sparse"&&a!=="latest-state")throw new Error("[OpenRTC] Sparse rooms require payload: latest-state.");if(o==="durable"&&n!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r.identity==="session"&&n!=="capability")throw new Error("[OpenRTC] Session room identity requires access: capability.");if(n==="authenticated"){let l=r.auth??t.options.auth;if(!l)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let A=await t.deviceId(),v=await t.controlPlane(),m=await v.deviceCertificate(l,A,{kind:"room",id:e});o==="durable"&&await v.durableRoomMembership(m.source,e,"join");let f;try{f=await t.activate({kind:"room",id:e,source:m.source,principalId:m.principalId,deviceId:A,maxPeers:r.maxPeers,autoConnect:!0,durableMembership:o==="durable",advancedFanout:r.advancedFanout,architecture:i,defaultDelivery:a});}catch(I){throw o==="durable"&&await v.durableRoomMembership(m.source,e,"leave").catch(()=>{}),I}let g;return g=new y(e,f,()=>{t.channels.detach(f),t.onClosed(g);},o,o==="durable"?async()=>{await v.durableRoomMembership(m.source,e,"leave");}:void 0,i),t.trackHandle(g)}let c=await(r.identity==="session"?t.sessionPlane():t.controlPlane()),s=await c.capability("room",e,r.maxPeers,r.advancedFanout,i,a),u=String(b(s.token).principalId),h=await t.activate({kind:"room",id:e,source:s,principalId:u,deviceId:g(s),maxPeers:r.maxPeers,autoConnect:true,advancedFanout:r.advancedFanout,architecture:i,defaultDelivery:a,controlPlane:c}),d;return d=new y(e,h,()=>{t.channels.detach(h),t.onClosed(d);},"ephemeral",void 0,i),t.trackHandle(d)}function T(t,e$1){t.assertOpen();let r=e(e$1.roomId),i=e(e$1.serviceId),a=f(e$1.deviceId);if(!Number.isSafeInteger(e$1.generation)||e$1.generation<1)throw new Error("[OpenRTC] Authority service generation is invalid.");let o=[...e$1.shardIds].map(e).sort();if(o.length<1||o.length>64||new Set(o).size!==o.length)throw new Error("[OpenRTC] Authority service shards are invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.devicePublicKeyX))throw new Error("[OpenRTC] Authority service device public key is invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.assignmentPublicKeyX))throw new Error("[OpenRTC] Authority assignment public key is invalid.");if(e$1.maxPeers!==void 0&&(!Number.isSafeInteger(e$1.maxPeers)||e$1.maxPeers<1||e$1.maxPeers>50))throw new Error("[OpenRTC] Authority service maxPeers must be within 1..50.");return t.activateOnce(`room:${r}`,JSON.stringify({architecture:"authority",serviceId:i,generation:e$1.generation,shardIds:o,deviceId:a,maxPeers:e$1.maxPeers??null,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSignerId:t.authorityCallableId(e$1.deviceSign),grantProviderId:t.authorityCallableId(e$1.grantProvider)}),void 0,async()=>{let n={type:"capability",token:"",avenue:{kind:"room",id:r},expiresAtMs:Number.MAX_SAFE_INTEGER,irohRelay:e$1.irohRelay,managedTurn:false},c=await t.activate({kind:"room",id:r,source:n,principalId:i,deviceId:a,maxPeers:e$1.maxPeers,autoConnect:true,architecture:"authority",defaultDelivery:"reliable",authority:{serviceId:i,generation:e$1.generation,shardIds:o,deviceId:a,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSign:e$1.deviceSign,grantProvider:e$1.grantProvider}}),s;return s=new y(r,c,()=>{t.channels.detach(c),t.onClosed(s);},"ephemeral",void 0,"authority"),t.trackHandle(s)})}function O(t){return Object.freeze({...t,priorityDeviceIds:Object.freeze([...t.priorityDeviceIds]),relevantEntityIds:Object.freeze([...t.relevantEntityIds])})}function S(t){return t?{...t,priorityDeviceIds:[...t.priorityDeviceIds],relevantEntityIds:[...t.relevantEntityIds]}:null}function x(t){return {requested:t,effective:t==="sparse"?"sparse":"mesh",epoch:0,phase:t==="mesh"||t==="sparse"?"settled":"preparing",reason:t==="auto"?"size":"manual",heldCreditsUsd:0,quoteExpiresAtMs:Date.now()+5*6e4}}export{y as RoomHandle,L as joinRoom,T as openAuthorityRoom,M as resolveRoomJoinOptions};
|
package/dist/runtime/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as isDeviceActive,c as isDeviceConnectable,b as isDeviceRoutable}from'../chunk-CK6WQV7J.js';export{h as ConnectionActor,e as ConnectionActorError,i as ConnectionActors,a as ConnectionController,s as IpcRuntimeAdapter,r as RuntimeClient,d as clog,p as concatRuntimeBytes,f as connectionActorKey,g as connectionActorKeyString,o as createJsonDecoder,k as createU32Decoder,m as decodeJsonPayload,n as encodeJsonFrame,l as encodeJsonPayload,j as encodeU32Frame,c as grantCorrelation,q as readRuntimeU32BE,b as renderCorrelation}from'../chunk-PEDATFS2.js';import'../chunk-BGWJHPBC.js';import'../chunk-3PDMPSVP.js';export{q as BROWSER_CAPABILITIES,r as NATIVE_CAPABILITIES,o as RUNTIME_POLICY,t as browserCapabilities,v as capabilityProfile,s as cloneCapabilities,p as getRuntimePolicy,h as logTeardownTrace,d as openRtcDebug,c as openRtcDebugEnabled,e as openRtcDebugInfo,f as openRtcDebugLog,u as statusCapabilities}from'../chunk-XK2JESZY.js';import'../chunk-XMYBBLYK.js';import'../chunk-TYZS5LXQ.js';import'../chunk-OT7IPLZE.js';import'../chunk-OWKAJPOI.js';import'../chunk-COXQYBTI.js';export{a as classifyIpcFailure,b as isIpcUnavailable}from'../chunk-72NEEJQG.js';import'../chunk-CNAW5BZ3.js';export{c as runtimeFromCapability}from'../chunk-
|
|
1
|
+
export{a as isDeviceActive,c as isDeviceConnectable,b as isDeviceRoutable}from'../chunk-CK6WQV7J.js';export{h as ConnectionActor,e as ConnectionActorError,i as ConnectionActors,a as ConnectionController,s as IpcRuntimeAdapter,r as RuntimeClient,d as clog,p as concatRuntimeBytes,f as connectionActorKey,g as connectionActorKeyString,o as createJsonDecoder,k as createU32Decoder,m as decodeJsonPayload,n as encodeJsonFrame,l as encodeJsonPayload,j as encodeU32Frame,c as grantCorrelation,q as readRuntimeU32BE,b as renderCorrelation}from'../chunk-PEDATFS2.js';import'../chunk-BGWJHPBC.js';import'../chunk-3PDMPSVP.js';export{q as BROWSER_CAPABILITIES,r as NATIVE_CAPABILITIES,o as RUNTIME_POLICY,t as browserCapabilities,v as capabilityProfile,s as cloneCapabilities,p as getRuntimePolicy,h as logTeardownTrace,d as openRtcDebug,c as openRtcDebugEnabled,e as openRtcDebugInfo,f as openRtcDebugLog,u as statusCapabilities}from'../chunk-XK2JESZY.js';import'../chunk-XMYBBLYK.js';import'../chunk-TYZS5LXQ.js';import'../chunk-OT7IPLZE.js';import'../chunk-OWKAJPOI.js';import'../chunk-COXQYBTI.js';export{a as classifyIpcFailure,b as isIpcUnavailable}from'../chunk-72NEEJQG.js';import'../chunk-CNAW5BZ3.js';export{c as runtimeFromCapability}from'../chunk-KXXQNKRK.js';import'../chunk-FKAQDDUM.js';import'../chunk-ZA44REGI.js';import'../chunk-ONV44QWS.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-3B4IDT2M.js';import'../chunk-WALOTASO.js';import'../chunk-2GX6GB6L.js';
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-5VCDW5BC.js';import'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function y(n){let e=new URL(n??"https://api.openrtc.app"),t=e.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(e.hostname.toLowerCase());if(e.protocol!=="https:"&&!t||e.username||e.password||e.search||e.hash)throw new TypeError("[OpenRTC] authority control-plane endpoint is invalid.");return e.toString().replace(/\/$/,"")}function h(){if(typeof document<"u"||typeof window<"u")throw new Error("[OpenRTC] openrtc/server is unavailable in browsers; use openrtc/service-node with a delegated grant.")}var c=class{constructor(e){h();let t=e.secretKey?.trim()??"";if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(t))throw new TypeError("[OpenRTC] secretKey is invalid.");let i=e.fetch??globalThis.fetch;if(typeof i!="function")throw new TypeError("[OpenRTC] a Fetch-compatible implementation is required.");let u=y(e.endpoint);this.authority=new a({apiKey:e.apiKey,serviceId:e.serviceId,generation:e.generation,shardIds:e.shardIds,deviceId:e.deviceId,deviceSigner:e.deviceSigner,assignmentSigner:e.assignmentSigner,grantIssuer:async s=>{let r=await i(`${u}/v2/developer/authority/grants`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json","x-openrtc-idempotency-key":s.idempotencyKey},body:JSON.stringify(s.body)});if(!r.ok){let o=await r.json().catch(()=>null),d=typeof o?.error=="string"?o.error.slice(0,256):`HTTP ${r.status}`;throw new Error(`[OpenRTC] authority service grant failed: ${d}`)}return r.json()}});}requestGrant(e){return this.authority.requestGrant(e)}signAssignment(e){return this.authority.signAssignment(e)}devicePublicKey(){return this.authority.devicePublicKey()}signDeviceBytes(e){return this.authority.signDeviceBytes(e)}grantIssuer(){return async e=>{let t=e.body;return this.requestGrant({roomId:String(t.avenue?.id??""),runtimeInstanceId:String(t.runtimeInstanceId??""),ticketFingerprint:String(t.ticketFingerprint??""),maxPeers:typeof t.maxPeers=="number"?t.maxPeers:void 0,refreshGrant:typeof t.refreshGrant=="string"?t.refreshGrant:void 0,features:typeof t.features=="object"&&t.features?t.features:void 0})}}};
|
|
2
2
|
export{c as AuthorityServiceControlPlane};
|
package/dist/service-node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as DelegatedAuthorityService,b as ServiceNode}from'./chunk-
|
|
1
|
+
export{a as DelegatedAuthorityService,b as ServiceNode}from'./chunk-5VCDW5BC.js';import'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';
|
package/dist/testing/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'../chunk-RT7YTAXU.js';import'../chunk-COXQYBTI.js';import {a as a$1}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-RT7YTAXU.js';import'../chunk-COXQYBTI.js';import {a as a$1}from'../chunk-NS32P65Z.js';import'../chunk-GMPEZXPD.js';import {i}from'../chunk-KXXQNKRK.js';import'../chunk-FKAQDDUM.js';import'../chunk-ZA44REGI.js';import'../chunk-ONV44QWS.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-3B4IDT2M.js';import'../chunk-WALOTASO.js';import'../chunk-2GX6GB6L.js';function v(c,p,e){let o=new a;return i(c,{endpoints:p,testingAllowInsecureLoopback:true,platform:"native",close:()=>o.close(),deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:a}=await import('../ipcFactory-WNHLLXCB.js');return a(t,e,o)}})}export{v as OpenRTC};
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-7KWWA3M6.js';import {a as a$1}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-7KWWA3M6.js';import {a as a$1}from'./chunk-IAYQJZQQ.js';import {a as a$2,d,c}from'./chunk-CNAW5BZ3.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-KXXQNKRK.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-ONV44QWS.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-3B4IDT2M.js';import'./chunk-WALOTASO.js';import'./chunk-2GX6GB6L.js';function v(i,o,e){let n=s=>{let t=new URL(s);return t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)&&Number(t.port)>0&&t.pathname==="/"&&!t.username&&!t.password&&!t.search&&!t.hash};if(i.apiKey!=="pk_test_0000000000000000000000000000000000000000"||!n(o.controlPlane)||!n(o.gateway)||!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace))throw new Error("Local broadcast testing requires the disposable loopback service lane")}function b(i){let o=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=");return Uint8Array.from(atob(o),e=>e.charCodeAt(0))}function A(i,o,e){return new a(i,o,a$1(e))}function R(i$1,o,e={}){if(e.localBroadcast&&v(i$1,o,e.localBroadcast),e.initialTicketLifetimeMs!==void 0){let t=(p,c)=>{let a=new URL(p);return a.protocol===c&&["127.0.0.1","[::1]"].includes(a.hostname)&&Number(a.port)>0&&a.pathname==="/"&&!a.username&&!a.password&&!a.search&&!a.hash};if(e.initialTicketLifetimeMs!==9e4||i$1.apiKey!=="pk_test_0000000000000000000000000000000000000000"||!t(o.controlPlane,"http:")||!t(o.gateway,"http:")||!e.irohTestRelayUrl||!t(e.irohTestRelayUrl,"https:"))throw new Error("Short initial tickets require the disposable local service lane")}let n=e.localBroadcast,s=n?a$1(n.keyNamespace):void 0;return i(i$1,{endpoints:o,testingAllowInsecureLoopback:true,platform:"web",...s?{deviceKeyProvider:s}:{},...n&&s?{broadcastHostFactory:async t=>{let[{BrowserManagedBroadcastHost:p},{loadBrowserWasmRuntimeModule:c}]=await Promise.all([import('./BrowserManagedBroadcastHost-GLSYJIOR.js'),import('./WasmBridge-EWVV4DFE.js')]),a=c().then(async r=>(await r.initWasm(),r.start(),new r.WasmClient(t.apiKey))),y=await s.getOrCreate(`app_${t.apiKey.slice(-16)}`);return new p({resolve:async(r,l)=>({token:r,...await n.resolve(r,l),signBindingChallenge:async m=>b(await y.sign(m))}),loadWasm:()=>a})}}:{},...e.deviceId?{deviceIdProvider:async()=>e.deviceId}:{},...e.irohTestRelayUrl?{irohTestRelayUrl:e.irohTestRelayUrl}:{},runtimeFactory:async t=>{let{createWasmClient:p}=await import('./runtime/factories.js'),c$1=await p(t);if(e.initialTicketLifetimeMs!==void 0){let a=c$1.runtime,y=a.getTicketWithToken.bind(a);a.getTicketWithToken=async(r,l=0)=>{if(a.getTicketWithToken=y,!r.startsWith("v2:room:"))throw new Error("Short initial ticket requires room scope");let{irohTicket:m,tokenSuffix:u}=a$2(await y(r,l)),d$1=u&&d(m,u);if(!d$1||!d$1.t||d$1.s!==r||d$1.m!==l)throw new Error("Invalid initial service ticket");let f=Date.now()+9e4;return await a.registerToken({token:d$1.t,scope:r,maxConnections:l,expiresAtMs:f}),c(m,d$1.t,r,l,f)};}return c$1}})}export{R as OpenRTC,A as controlPlane};
|
|
Binary file
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"platform": "darwin",
|
|
5
5
|
"arch": "arm64",
|
|
6
6
|
"rustTarget": "aarch64-apple-darwin",
|
|
7
|
-
"sourceCommit": "
|
|
8
|
-
"sourceDigest": "
|
|
9
|
-
"binarySha256": "
|
|
7
|
+
"sourceCommit": "133da570608c080c8ccfed64d96aeb31c275599a",
|
|
8
|
+
"sourceDigest": "e4f5cca4c25f0a666c1255189d815783a00ae2cc45d353693eb90137137bcb8b",
|
|
9
|
+
"binarySha256": "6d1dd0f3a12050a8823c1200e0f949d046e0a545644f0fb166010a54eb8ca499",
|
|
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": "
|
|
19
|
+
"signature": "5HOPRWoAmnhMUCt+ZoQ6xnHl/ZCI8VdTilRaOnJuo7GQcLL+QGWO0Dnhy3GOW4jz/58rCEp740sr1MbRC/iqBw=="
|
|
20
20
|
}
|
|
Binary file
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"platform": "darwin",
|
|
5
5
|
"arch": "x64",
|
|
6
6
|
"rustTarget": "x86_64-apple-darwin",
|
|
7
|
-
"sourceCommit": "
|
|
8
|
-
"sourceDigest": "
|
|
9
|
-
"binarySha256": "
|
|
7
|
+
"sourceCommit": "133da570608c080c8ccfed64d96aeb31c275599a",
|
|
8
|
+
"sourceDigest": "e4f5cca4c25f0a666c1255189d815783a00ae2cc45d353693eb90137137bcb8b",
|
|
9
|
+
"binarySha256": "a9ec91615c1ab571bd295a655f5fb8b84a2e6c19871294cd3074693e1e48a5db",
|
|
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": "
|
|
19
|
+
"signature": "ReckMpRf+THfQd+6WqrDoA1B4rcLnjPGhzLMewR5t+GGaER/WNVyI1FMK0lNEmFPrr71r7Ihr0f9zhufSRKjCg=="
|
|
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": "
|
|
8
|
-
"sourceDigest": "
|
|
9
|
-
"binarySha256": "
|
|
7
|
+
"sourceCommit": "3d60241256f179e12f1c7aec9d064ca75af202bf",
|
|
8
|
+
"sourceDigest": "e4f5cca4c25f0a666c1255189d815783a00ae2cc45d353693eb90137137bcb8b",
|
|
9
|
+
"binarySha256": "0914866c9bf0ee73971858bf7757eddc4b879ef96dd6cd68fdf53324a64022d1",
|
|
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": "
|
|
19
|
+
"signature": "bSJk9MSDagG4ddsCCf9PHkxlny4sC6TEwA5gaMiMFs1q2UDd9EV/gZAbV7msbqiRsvvgKwsBvlu521xHb0JlCw=="
|
|
20
20
|
}
|
package/package.json
CHANGED
package/dist/chunk-AUICRD2W.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function c(t){let r=new Uint8Array(t),e="";for(let n of r)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function g(t){let r=JSON.stringify({crv:t.crv,kty:t.kty,x:t.x});return c(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function p(){return c(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function y(){return typeof indexedDB>"u"?null:new Promise((t,r)=>{let e=indexedDB.open("openrtc-v2-device-keys",1);e.onupgradeneeded=()=>{e.result.objectStoreNames.contains("keys")||e.result.createObjectStore("keys");},e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error);})}async function f(t){let r=await y().catch(()=>null);if(!r)throw new Error("[OpenRTC] Persistent browser identity storage is unavailable.");try{return await new Promise((e,n)=>{let s=r.transaction("keys","readonly").objectStore("keys").get(t);s.onsuccess=()=>e(s.result??null),s.onerror=()=>n(s.error);})}finally{r.close();}}async function w(t,r){let e=await y().catch(()=>null);if(!e)throw new Error("[OpenRTC] Persistent browser identity storage is unavailable.");try{return await new Promise((n,s)=>{let o=e.transaction("keys","readwrite"),a=r;o.oncomplete=()=>n(a),o.onabort=()=>s(o.error??new Error("[OpenRTC] Persistent browser identity storage transaction aborted."));let u=o.objectStore("keys"),i=u.get(t);i.onerror=()=>s(i.error),i.onsuccess=()=>{if(i.result!==void 0&&i.result!==null){a=i.result;return}let l=u.put(r,t);l.onerror=()=>s(l.error);};})}finally{e.close();}}async function b(t){let r=await y().catch(()=>null);if(r)try{await new Promise((e,n)=>{let s=r.transaction("keys","readwrite").objectStore("keys").delete(t);s.onsuccess=()=>e(),s.onerror=()=>n(s.error);});}finally{r.close();}}async function v(t){let r=await f(t);if(r)return r;let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return w(t,e)}async function d(t){let r=await crypto.subtle.exportKey("jwk",t.publicKey),e=await g(r);return {publicKeyJwk:r,thumbprint:e,async sign(n){return c(await crypto.subtle.sign({name:"Ed25519"},t.privateKey,n))},async proof(n){let s=p(),o=Math.floor(Date.now()/1e3),a=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,new TextEncoder().encode(n(s,o)));return {publicKeyJwk:r,signature:c(a),nonce:s,issuedAt:o}}}}async function P(){return d(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}var K={persistence:"persistent",async getOrCreate(t){return d(await v(t))},delete:b};function m(){let t=new Map,r=new Map;return {persistence:"session",getOrCreate(e){let n=t.get(e);return n||(n=P(),t.set(e,n)),n},async delete(e){t.delete(e),r.delete(e);},async readSecureRecord(e,n){return r.get(e)?.get(n)??null},async writeSecureRecord(e,n,s){let o=r.get(e);o||(o=new Map,r.set(e,o)),o.set(n,s);},async deleteSecureRecord(e,n){r.get(e)?.delete(n);}}}
|
|
2
|
-
export{g as a,P as b,K as c,m as d};
|