openrtc 2.5.1 → 2.5.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/README.md +21 -1
- package/dist/NativeManagedBroadcastHost-WCQ6TPUU.js +1 -0
- package/dist/{WasmBridge-ZXBCXBBM.js → WasmBridge-LWMCETW4.js} +1 -1
- package/dist/{assembly-DvfsYFCL.d.ts → assembly-LOFcpH3S.d.ts} +2 -1
- package/dist/{chunk-FEF3DPPB.js → chunk-6Q2LAXM4.js} +1 -1
- package/dist/chunk-AAZPQQXX.js +2 -0
- package/dist/chunk-CNAW5BZ3.js +2 -0
- package/dist/{chunk-Z4KJHIV5.js → chunk-EFTDXE6M.js} +1 -1
- package/dist/chunk-FB5M6GIW.js +2 -0
- package/dist/chunk-J7NBMQQA.js +2 -0
- package/dist/{chunk-EIJNERKZ.js → chunk-PLIWPC45.js} +1 -1
- package/dist/chunk-TZLNKQNJ.js +1 -0
- package/dist/coreClient.d.ts +1 -1
- package/dist/{dist-XO466BRG.js → dist-FIVA6EPA.js} +0 -18
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/ipcFactory-PDVLUG2W.js +1 -0
- package/dist/native.d.ts +1 -1
- package/dist/native.js +1 -1
- package/dist/node.d.ts +5 -1
- package/dist/node.js +2 -2
- package/dist/openrtc-SQF7H4ZE.js +2 -0
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/room-A2FMQRNZ.js +1 -0
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/factories.d.ts +1 -1
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +2 -2
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/service-node.d.ts +2 -1
- package/dist/service-node.js +1 -1
- package/dist/testing/native.d.ts +1 -1
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +3 -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 +20 -0
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +20 -0
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +20 -0
- package/native/openrtc-node-host-signing-public.pem +3 -0
- package/package.json +3 -2
- package/dist/chunk-2K47N3QP.js +0 -2
- package/dist/chunk-GHAJW6SZ.js +0 -2
- package/dist/chunk-GTHSRQ7Y.js +0 -2
- package/dist/chunk-Z54XUIKZ.js +0 -1
- package/dist/ipcFactory-PRAJ7JP7.js +0 -1
- package/dist/openrtc-VCS6V3AN.js +0 -2
- package/dist/room-ULZ2FGWV.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {j,d as d$1,c}from'./chunk-TZLNKQNJ.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
|
+
export{p as a,S as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-GTHSRQ7Y.js';import {c,e,d,f,b as b$1}from'./chunk-XTYALGJN.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$3}from'./chunk-JPBW67B3.js';function A(l){if(!l)return null;let e=2166136261;for(let t=0;t<l.length;t+=1)e^=l.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var M=class M{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(r=>this.submitDesiredPeers(r),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let r=this.desiredPeersByDeviceId.get(i);if(r&&(!n||!r.nodeId||r.nodeId===n))return r}return n?Array.from(this.desiredPeersByDeviceId.values()).find(r=>r.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),n){if(typeof o.submit_browser_desired_peers_with_sparse_fanout!="function"){await o.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await o.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,r){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:r,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),a=await this.deps.withWebPresenceMetadata(r,s);o!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,M.PRESENCE_LEASE_MS,a,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};M.PRESENCE_LEASE_MS=15*6e4;var R=M;function ie(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function ne(){let l=await import('./openrtc-VCS6V3AN.js');return {initWasm:e=>l.default(e??ie()),WasmClient:l.WasmClient,start:l.start}}function re(l){try{let e=l.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function oe(l){let e=typeof l=="string"?l.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,r=n?re(n):null,o=r&&typeof r.t=="string"&&r.t.trim().length>0?r.t.trim():null,s=r&&typeof r.s=="string"&&r.s.trim().length>0?r.s.trim():null,a=r&&typeof r.m=="number"&&Number.isFinite(r.m)?r.m:null;return {present:true,irohFingerprint:A(i),tokenFingerprint:A(o),tokenSuffixFingerprint:A(n),scope:s,maxConnections:a}}function _(l,e,t={}){let i=typeof l.finishSend=="function"?l.finishSend.bind(l):typeof l.finish_send=="function"?l.finish_send.bind(l):null,n=typeof l.cancelSend=="function"?l.cancelSend.bind(l):typeof l.cancel_send=="function"?l.cancel_send.bind(l):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let r=e.getWriter(),o=new WritableStream({write:s=>r.write(s),async close(){await r.close(),await i();},async abort(s){await n?.(),await r.abort(s);}});return a$3(o,n)}var u=class u{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(o=false)=>this.currentUser?.getToken?.(o)??null,getAppCheckToken:async(o=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(o):a().getAppCheckToken(o)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(o,s)=>this.normalizeDevice(o,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(o,s)=>this.waitForWasmClient(o,s),warnMissingWasmOnce:o=>this.warnMissingWasmOnce(o),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(o,s)=>this.withWebPresenceMetadata(o,s),updatePresence:(o,s,a,c,d,p)=>this.updatePresence(o,s,a,c,d,p),updateExcludedPeers:(o,s)=>this.getCoordinationSignaling().updateDevice(o,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:o=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(o)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let r=a();this.app=r.getApp(),this.auth=r.getAuth(),r.onAuthStateChanged(o=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));return}let s=o?.uid??null,a=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,a&&a!==s&&this.stopAuthActivity({userId:a}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));});}async loadBrowserWasmRuntime(){return ne()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${u.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),r=null;try{let d=localStorage.getItem(i);r=d?JSON.parse(d):null;}catch{r=null;}let o=typeof r?.deviceId=="string"?r.deviceId.trim():"",s=typeof r?.expiresAt=="number"?r.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(o&&typeof s=="number"&&s>n){let d=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:o,expiresAt:d})),o}let a=this.createRandomDeviceId(),c=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:a,expiresAt:c})),a}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(r){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",r);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(r){console.warn("[WasmBridge] Failed to clear injected browser auth session:",r);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(r=>r(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let r=await i.prepareSparseFanoutMessage(e,t),o=new Uint8Array(r.signingInput??r.signing_input??[]),s=await n(o);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(r.requestId??r.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let r=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(r.payload??[]),authorDeviceId:String(r.authorDeviceId??r.author_device_id??""),authorPeerId:String(r.authorPeerId??r.author_peer_id??""),topologyRevision:Number(r.topologyRevision??r.topology_revision),hop:Number(r.hop),forwardPeerIds:Array.isArray(r.forwardPeerIds??r.forward_peer_ids)?(r.forwardPeerIds??r.forward_peer_ids).map(String):[],forwardPeerLimit:Number(r.forwardPeerLimit??r.forward_peer_limit),forwardQueueCapacity:Number(r.forwardQueueCapacity??r.forward_queue_capacity),...r.forward==null?{}:{forward:new Uint8Array(r.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let r=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(r.connectionId,r);let s=(n??this.lastDeliveredConnectionStates).get(r.connectionId);this.sameConnectionState(s,r)||(n&&n.set(r.connectionId,r),t(r));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let r=await t(i);if(r)return r}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,r,o){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),a=this.getDeviceIdPersistenceMode()==="ephemeral"?u.EPHEMERAL_DEVICE_ID_TTL_MS:n,c=await this.withWebPresenceMetadata(r,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:c,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,a,c,o);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let r=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(i,r);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,o,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let r=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),o=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!o||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return r;try{let[s,a]=await Promise.all([i.iroh_path_kind(o),i.iroh_transport_rtt_ms(o)]);if(typeof a!="number"||!Number.isFinite(a))return r;let c=Math.max(0,Math.round(a)),d={};if(s==="direct-lan")d.irohLan=c;else if(s==="direct-quic")d.iroh=c;else if(s==="ble")d.ble=c;else if(s==="relay")d.irohRelay=c;else if(s==="webrtc")d.webrtc=c;else if(s==="moq")d.moq=c;else return r;return {...r,latencyMs:c,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),r}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:_(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let r=await i.open_peer_bi_transport_only(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:r.recv,writable:_(r,r.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),r=n?.writable??n;if(!r)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:_(n,r)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),r=n?.sendPeerDatagram;if(typeof r!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await r.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let r=n;return {peerId:typeof r.peerId=="string"?r.peerId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,nodeId:typeof r.nodeId=="string"?r.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),r=i(n);if(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId)return r}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let r=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(r.connectionId,r),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:r.connectionId,deviceId:r.deviceId??r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null}),this.escalateManagedApplicationRoute(r);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let r=this.authScopedRuntimeGeneration,o=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let a=await o.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(r!==this.authScopedRuntimeGeneration)return;let c=a,d=c.id?.trim()||e.connectionId,p=c.remoteNodeId?.trim()||e.remoteNodeId?.trim()||c.deviceId?.trim()||n.deviceId;if(o.hasApplicationRouteForPeer?.(d,p)!==true&&o.hasApplicationRouteForPeer?.(d,p)!==true)throw new Error(`application crypto was not ready for ${p}`)})().catch(a=>{r===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:a?.message??String(a)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let a=this.lastDeliveredConnectionStates?.get(e.connectionId),c=a?[a.transportGeneration??0,a.routeGeneration??0].join(":"):null;a&&c!==t&&r===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(a));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:oe(e.endpointTicket),hasCoreClient:!!this.coreClient});let n=await t.connect_device(e.deviceId??null,e.endpointTicket);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});let r=e.endpointTicket;if(r&&this.coreClient){let o=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null});let s=await o.ensureManagedApplicationRoute({ticket:r,connectionId:n?.connectionId??null,remoteNodeId:n?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:n?.approvedScope??null,timeoutMs:2e4}),a=typeof s?.remoteNodeId=="string"?s.remoteNodeId.trim():"",c=typeof s?.deviceId=="string"?s.deviceId.trim():"",d=a||n?.remoteNodeId?.trim?.()||c||e.deviceId?.trim?.()||"",p=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&p?.(s?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!p||p(s?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});}catch(s){if(s?.applicationCryptoNotReady)throw s;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,error:s?.message??String(s)}),n}}return n}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,r){return this.presenceManager.startPresenceLoop(e,t,i,n,r)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),r=(Array.isArray(n)?n:[]).map(o=>this.normalizeStateSnapshot(o)).filter(o=>!!o);return r.length>0&&d$1("[WasmBridge] replaying current wasm connection states",r.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),r}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,r=false,o=c=>{let d=c.detail,p=this.normalizeStateSnapshot(d),h=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!h||r)return;if(p&&(p.state==="closed"||p.state==="failed"||p.state==="disconnected")){this.deliverConnectionState(p,e,"rust-event-detail",t);return}let g=(i.get(h)??0)+1;i.set(h,g);let f=this.authScopedRuntimeGeneration;(async()=>{let v=await this.waitForWasmClient(500);if(!(r||f!==this.authScopedRuntimeGeneration||i.get(h)!==g)){if(v&&typeof v.connection_state=="function"){let P=await v.connection_state(h),w=this.normalizeStateSnapshot(P);if(!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&p&&this.deliverConnectionState(p,e,"rust-event-detail",t);}})().catch(v=>{r||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:h,error:v});});},s=typeof window<"u"?window:null,a=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return a&&s.addEventListener("connection-state-changed",o),this.getConnectionStates().then(c=>{!r&&n===this.authScopedRuntimeGeneration&&c.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(c=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",c);}),()=>{r=true,i.clear(),a&&s.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return u.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let o of i){if([...n].length>=u.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||s<32||s===127?n+="_":n+=o;}let r=n.trim();return !r||r==="."||r===".."?u.FALLBACK_EXPLICIT_FILE_NAME:r}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return u.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=u.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let r=n.charCodeAt(0);r<33||r>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:u.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,r){let o=r?.headerFrame===true?4:0,s=new Uint8Array(25+o+n.byteLength);s[0]=u.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let a=new DataView(s.buffer);a.setUint32(17,t,false),a.setUint32(21,i,false);let c=r?.headerFrame===true?29:25;return r?.headerFrame===true&&a.setUint32(25,n.byteLength,false),s.set(n,c),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let a=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:a??null,fileName:i.name,fileSize:i.size,transferId:o}),!a)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let c=await this.waitForWasmClient();if(!c)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,p={transfer_id:o,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=d.encode(JSON.stringify(p));this.assertExplicitTransferHeaderSize(h);let g=new Uint8Array(4);new DataView(g.buffer).setUint32(0,h.byteLength,false);let f=new Uint8Array(g.byteLength+h.byteLength);f.set(g,0),f.set(h,g.byteLength);let v=async()=>{let P=c.open_peer_bi_explicit_file_sender;if(typeof P!="function")return false;let w=await P.call(c,a,5e3),E=w?.writable??w?.send;if(!E||typeof E.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:a,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=_(w,E,{requireFinish:true}).getWriter(),T=false;try{await C.write(f);let I=new Uint8Array(await i.arrayBuffer());for(let S=0;S<I.byteLength;S+=u.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let te=I.slice(S,Math.min(S+u.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await C.write(te);}}catch(I){throw T=true,I}finally{try{await C.close();}catch(I){if(!T)throw I}finally{C.releaseLock();}}return true};try{if(await v())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:a,transferId:o,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};u.EXPLICIT_FILE_PROTOCOL_TYPE=2,u.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,u.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",u.MAX_EXPLICIT_FILE_NAME_CHARS=180,u.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",u.MAX_EXPLICIT_MIME_TYPE_CHARS=255,u.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",u.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var ee=u;export{ne as a,ee as b};
|
|
1
|
+
import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-AAZPQQXX.js';import {c,e,d,f,b as b$1}from'./chunk-XTYALGJN.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$3}from'./chunk-JPBW67B3.js';function A(l){if(!l)return null;let e=2166136261;for(let t=0;t<l.length;t+=1)e^=l.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var M=class M{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(r=>this.submitDesiredPeers(r),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let r=this.desiredPeersByDeviceId.get(i);if(r&&(!n||!r.nodeId||r.nodeId===n))return r}return n?Array.from(this.desiredPeersByDeviceId.values()).find(r=>r.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),n){if(typeof o.submit_browser_desired_peers_with_sparse_fanout!="function"){await o.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await o.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,r){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:r,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),a=await this.deps.withWebPresenceMetadata(r,s);o!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,M.PRESENCE_LEASE_MS,a,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};M.PRESENCE_LEASE_MS=15*6e4;var R=M;function ie(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function ne(){let l=await import('./openrtc-SQF7H4ZE.js');return {initWasm:e=>l.default(e??ie()),WasmClient:l.WasmClient,start:l.start}}function re(l){try{let e=l.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function oe(l){let e=typeof l=="string"?l.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,r=n?re(n):null,o=r&&typeof r.t=="string"&&r.t.trim().length>0?r.t.trim():null,s=r&&typeof r.s=="string"&&r.s.trim().length>0?r.s.trim():null,a=r&&typeof r.m=="number"&&Number.isFinite(r.m)?r.m:null;return {present:true,irohFingerprint:A(i),tokenFingerprint:A(o),tokenSuffixFingerprint:A(n),scope:s,maxConnections:a}}function _(l,e,t={}){let i=typeof l.finishSend=="function"?l.finishSend.bind(l):typeof l.finish_send=="function"?l.finish_send.bind(l):null,n=typeof l.cancelSend=="function"?l.cancelSend.bind(l):typeof l.cancel_send=="function"?l.cancel_send.bind(l):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let r=e.getWriter(),o=new WritableStream({write:s=>r.write(s),async close(){await r.close(),await i();},async abort(s){await n?.(),await r.abort(s);}});return a$3(o,n)}var u=class u{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(o=false)=>this.currentUser?.getToken?.(o)??null,getAppCheckToken:async(o=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(o):a().getAppCheckToken(o)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(o,s)=>this.normalizeDevice(o,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(o,s)=>this.waitForWasmClient(o,s),warnMissingWasmOnce:o=>this.warnMissingWasmOnce(o),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(o,s)=>this.withWebPresenceMetadata(o,s),updatePresence:(o,s,a,c,d,p)=>this.updatePresence(o,s,a,c,d,p),updateExcludedPeers:(o,s)=>this.getCoordinationSignaling().updateDevice(o,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:o=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(o)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let r=a();this.app=r.getApp(),this.auth=r.getAuth(),r.onAuthStateChanged(o=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));return}let s=o?.uid??null,a=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,a&&a!==s&&this.stopAuthActivity({userId:a}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));});}async loadBrowserWasmRuntime(){return ne()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${u.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),r=null;try{let d=localStorage.getItem(i);r=d?JSON.parse(d):null;}catch{r=null;}let o=typeof r?.deviceId=="string"?r.deviceId.trim():"",s=typeof r?.expiresAt=="number"?r.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(o&&typeof s=="number"&&s>n){let d=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:o,expiresAt:d})),o}let a=this.createRandomDeviceId(),c=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:a,expiresAt:c})),a}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(r){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",r);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(r){console.warn("[WasmBridge] Failed to clear injected browser auth session:",r);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(r=>r(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let r=await i.prepareSparseFanoutMessage(e,t),o=new Uint8Array(r.signingInput??r.signing_input??[]),s=await n(o);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(r.requestId??r.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let r=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(r.payload??[]),authorDeviceId:String(r.authorDeviceId??r.author_device_id??""),authorPeerId:String(r.authorPeerId??r.author_peer_id??""),topologyRevision:Number(r.topologyRevision??r.topology_revision),hop:Number(r.hop),forwardPeerIds:Array.isArray(r.forwardPeerIds??r.forward_peer_ids)?(r.forwardPeerIds??r.forward_peer_ids).map(String):[],forwardPeerLimit:Number(r.forwardPeerLimit??r.forward_peer_limit),forwardQueueCapacity:Number(r.forwardQueueCapacity??r.forward_queue_capacity),...r.forward==null?{}:{forward:new Uint8Array(r.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let r=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(r.connectionId,r);let s=(n??this.lastDeliveredConnectionStates).get(r.connectionId);this.sameConnectionState(s,r)||(n&&n.set(r.connectionId,r),t(r));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let r=await t(i);if(r)return r}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,r,o){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),a=this.getDeviceIdPersistenceMode()==="ephemeral"?u.EPHEMERAL_DEVICE_ID_TTL_MS:n,c=await this.withWebPresenceMetadata(r,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:c,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,a,c,o);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let r=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(i,r);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,o,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let r=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),o=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!o||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return r;try{let[s,a]=await Promise.all([i.iroh_path_kind(o),i.iroh_transport_rtt_ms(o)]);if(typeof a!="number"||!Number.isFinite(a))return r;let c=Math.max(0,Math.round(a)),d={};if(s==="direct-lan")d.irohLan=c;else if(s==="direct-quic")d.iroh=c;else if(s==="ble")d.ble=c;else if(s==="relay")d.irohRelay=c;else if(s==="webrtc")d.webrtc=c;else if(s==="moq")d.moq=c;else return r;return {...r,latencyMs:c,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),r}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:_(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let r=await i.open_peer_bi_transport_only(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:r.recv,writable:_(r,r.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),r=n?.writable??n;if(!r)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:_(n,r)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),r=n?.sendPeerDatagram;if(typeof r!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await r.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let r=n;return {peerId:typeof r.peerId=="string"?r.peerId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,nodeId:typeof r.nodeId=="string"?r.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),r=i(n);if(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId)return r}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let r=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(r.connectionId,r),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:r.connectionId,deviceId:r.deviceId??r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null}),this.escalateManagedApplicationRoute(r);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let r=this.authScopedRuntimeGeneration,o=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let a=await o.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(r!==this.authScopedRuntimeGeneration)return;let c=a,d=c.id?.trim()||e.connectionId,p=c.remoteNodeId?.trim()||e.remoteNodeId?.trim()||c.deviceId?.trim()||n.deviceId;if(o.hasApplicationRouteForPeer?.(d,p)!==true&&o.hasApplicationRouteForPeer?.(d,p)!==true)throw new Error(`application crypto was not ready for ${p}`)})().catch(a=>{r===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:a?.message??String(a)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let a=this.lastDeliveredConnectionStates?.get(e.connectionId),c=a?[a.transportGeneration??0,a.routeGeneration??0].join(":"):null;a&&c!==t&&r===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(a));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:oe(e.endpointTicket),hasCoreClient:!!this.coreClient});let n=await t.connect_device(e.deviceId??null,e.endpointTicket);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});let r=e.endpointTicket;if(r&&this.coreClient){let o=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null});let s=await o.ensureManagedApplicationRoute({ticket:r,connectionId:n?.connectionId??null,remoteNodeId:n?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:n?.approvedScope??null,timeoutMs:2e4}),a=typeof s?.remoteNodeId=="string"?s.remoteNodeId.trim():"",c=typeof s?.deviceId=="string"?s.deviceId.trim():"",d=a||n?.remoteNodeId?.trim?.()||c||e.deviceId?.trim?.()||"",p=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&p?.(s?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!p||p(s?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});}catch(s){if(s?.applicationCryptoNotReady)throw s;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,error:s?.message??String(s)}),n}}return n}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,r){return this.presenceManager.startPresenceLoop(e,t,i,n,r)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),r=(Array.isArray(n)?n:[]).map(o=>this.normalizeStateSnapshot(o)).filter(o=>!!o);return r.length>0&&d$1("[WasmBridge] replaying current wasm connection states",r.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),r}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,r=false,o=c=>{let d=c.detail,p=this.normalizeStateSnapshot(d),h=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!h||r)return;if(p&&(p.state==="closed"||p.state==="failed"||p.state==="disconnected")){this.deliverConnectionState(p,e,"rust-event-detail",t);return}let g=(i.get(h)??0)+1;i.set(h,g);let f=this.authScopedRuntimeGeneration;(async()=>{let v=await this.waitForWasmClient(500);if(!(r||f!==this.authScopedRuntimeGeneration||i.get(h)!==g)){if(v&&typeof v.connection_state=="function"){let P=await v.connection_state(h),w=this.normalizeStateSnapshot(P);if(!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&p&&this.deliverConnectionState(p,e,"rust-event-detail",t);}})().catch(v=>{r||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:h,error:v});});},s=typeof window<"u"?window:null,a=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return a&&s.addEventListener("connection-state-changed",o),this.getConnectionStates().then(c=>{!r&&n===this.authScopedRuntimeGeneration&&c.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(c=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",c);}),()=>{r=true,i.clear(),a&&s.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return u.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let o of i){if([...n].length>=u.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||s<32||s===127?n+="_":n+=o;}let r=n.trim();return !r||r==="."||r===".."?u.FALLBACK_EXPLICIT_FILE_NAME:r}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return u.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=u.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let r=n.charCodeAt(0);r<33||r>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:u.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,r){let o=r?.headerFrame===true?4:0,s=new Uint8Array(25+o+n.byteLength);s[0]=u.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let a=new DataView(s.buffer);a.setUint32(17,t,false),a.setUint32(21,i,false);let c=r?.headerFrame===true?29:25;return r?.headerFrame===true&&a.setUint32(25,n.byteLength,false),s.set(n,c),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let a=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:a??null,fileName:i.name,fileSize:i.size,transferId:o}),!a)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let c=await this.waitForWasmClient();if(!c)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,p={transfer_id:o,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=d.encode(JSON.stringify(p));this.assertExplicitTransferHeaderSize(h);let g=new Uint8Array(4);new DataView(g.buffer).setUint32(0,h.byteLength,false);let f=new Uint8Array(g.byteLength+h.byteLength);f.set(g,0),f.set(h,g.byteLength);let v=async()=>{let P=c.open_peer_bi_explicit_file_sender;if(typeof P!="function")return false;let w=await P.call(c,a,5e3),E=w?.writable??w?.send;if(!E||typeof E.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:a,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=_(w,E,{requireFinish:true}).getWriter(),T=false;try{await C.write(f);let I=new Uint8Array(await i.arrayBuffer());for(let S=0;S<I.byteLength;S+=u.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let te=I.slice(S,Math.min(S+u.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await C.write(te);}}catch(I){throw T=true,I}finally{try{await C.close();}catch(I){if(!T)throw I}finally{C.releaseLock();}}return true};try{if(await v())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:a,transferId:o,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};u.EXPLICIT_FILE_PROTOCOL_TYPE=2,u.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,u.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",u.MAX_EXPLICIT_FILE_NAME_CHARS=180,u.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",u.MAX_EXPLICIT_MIME_TYPE_CHARS=255,u.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",u.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var ee=u;export{ne as a,ee as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$1,a as a$1}from'./chunk-ZA44REGI.js';import {b as b$3}from'./chunk-LLZT3MR6.js';import {a}from'./chunk-DUY34MGT.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {d as d$1,a as a$3}from'./chunk-N6LGTNUI.js';import {d,b as b$4}from'./chunk-2GX6GB6L.js';function I(o,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:o,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function B(o){let e;try{e=o instanceof Uint8Array?JSON.parse(new TextDecoder().decode(o)):o&&typeof o=="object"?o:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var b="openrtc-peer-stream/1",ae=32,Y=16,U=4294967295,ce=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,le=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function A(o){let e=o?.trim()??"";if(!ce.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function k(o){let e=o?.trim()??"",t=le.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function ee(o){if(o===null||o===0)return null;if(!Number.isFinite(o)||o<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(U,Math.ceil(o))}function te(o){if(!Number.isSafeInteger(o)||o<1||o>U)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${U}.`);return o}var L=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Y;this.outgoingLimit=Y;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=ee(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=ee(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=te(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=te(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},O=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:ae});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},F=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new O;this.incomingUni=new O;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new L(i,this.peerId);}async createBidirectionalStream(e){let t=A(e.protocol),i=await this.client.channels.openBi(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=A(e.protocol);return (await this.client.channels.openUni(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},s=this.protocolHandlers.get(t);if(s){try{s(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=A(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},D=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:b,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(b,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new F(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=k(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(k(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(b);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$2]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=A(i);}catch{return this.declined+=1,false}let s=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return s?this.accepted+=1:this.declined+=1,s}resolveExistingPeer(e,t=""){let i=k(t);if(i){let s=this.peerIdsByConnection.get(i);if(!s)return this.lastResolution="unbound-connection",null;let a=this.peers.get(s);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(s=>[s.peerId,s.deviceId,s.deviceIdHint,s.connectionId,...s.connectionIds].some(a=>a===e));if(r){let s=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>s.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var _={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var y=new WeakMap;function de(o){let e=y.get(o);if(!e||o.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function xe(o,e){if(y.has(o))throw new Error("[OpenRTC] Capability runtime is already registered.");return y.set(o,de(e)),()=>{y.delete(o);}}function ue(o){let e=o?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function T(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var z=/^[A-Za-z0-9_.:@-]{1,160}$/,he=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function me(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return he.test(t)?t:e}function pe(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,me(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(o){if(o===void 0)return [];if(!Array.isArray(o))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(o.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!z.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function oe(o){let e=b$1(o.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var N=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},K=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(_[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw f(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=ge(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),s=ve(e.architecture),a=ye(s,t,e.delivery),l=fe(a,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),m=t*u,v=r*i,p=Math.max(0,Math.ceil(t/4)-1),P=a==="managed"?v*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+p*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,g=l*h("broadcast.delivery");return {architecture:s,effectiveArchitecture:a,creditsUsd:Math.ceil((m+P+g)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function ve(o){return o??"auto"}function G(o,e,t,i){if(!Number.isSafeInteger(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return o}function ge(o,e,t,i){if(!Number.isFinite(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return o}function h(o){let e=_[o];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${o} has no current customer-credit price.`);return e}function ye(o,e,t){if(o==="mesh"){if(e>16)throw f("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return o}if(o==="sparse"){if(e>50)throw f("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw f("[OpenRTC] Sparse room quotes require latest-state delivery.");return o}if(o==="managed")throw f("[OpenRTC] Managed room architecture is unavailable in this release.");if(o==="authority")return o;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw f(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function f(o){return d$1(a$3.ROOM_ARCHITECTURE_UNAVAILABLE,o,{retryable:false,plane:"admission"})}function fe(o,e){if(e<=1)return 0;if(o!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function se(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var H=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.peerStreams=new D(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,s)=>{let a=B(r);!a||a.capability!==this.capabilityKey||s!==void 0&&a.name!==s||s===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=se(e);return {set:i=>{let n=I("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(s,a)=>i({peerId:s,value:a});n.add(r);for(let[s,a]of this.remoteState)a.has(t)&&i({peerId:s,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=se(e),i=n=>I("channel",t,n,this.capabilityKey);return {send:async n=>{let r=i(n);await this.roomFanout?.sendChannel(t,r)||await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:s})=>s?[s.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let s=this.logicalConnections.get(n)?.activeRaw;if(s){await s.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let s=(a,c)=>n({peerId:a,message:c});return r.add(s),()=>r?.delete(s)}}}onConnection(e){let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}async close(){if(this.closed)return;this.closed=true,this.stopMessage(),this.stopConnection(),this.stopDisconnection(),this.stopPeerLifecycle(),this.roomFanout?.close();let e=[...this.logicalConnections.keys()].map(t=>this.retire(t));this.pendingRawConnections.clear(),this.peerStreams.close(),this.rawConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),await Promise.allSettled(e);}add(e){if(this.closed)return;let t=this.rawConnections.get(e.id);if(t?.raw===e)return;t&&this.remove(t.raw);let i=e.remoteNodeId||e.id,n=this.mediaRetirements.get(i);if(n){let a={raw:e,peerId:i};this.pendingRawConnections.set(e.id,a),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==a||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let s=this.logicalConnections.get(i);if(!s){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),s={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(I("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let m=d;return u.add(m),()=>u?.delete(m)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,s);}s.rawIds.add(e.id),s.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(s.view));for(let[a,c]of this.localState)this.sendState(e,a,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let s=this.stateSenders.get(e);if(s){for(let a of s.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let s=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(s)&&Number(s)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(s),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let s of t.rawIds){let a=this.rawConnections.get(s)?.raw;if(this.rawConnections.delete(s),this.peerStreams.unbindConnection(s),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let s of i.keys())for(let a of this.stateListeners.get(s)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let s of this.closeListeners.get(e)??[])s();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let s of this.connectionListeners.values())s.delete(e);return r}receive(e,t){this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=B(t);if(!n){for(let r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let r=n.get(t);r||(r=new a(s=>e.send(s)),n.set(t,r)),r.send(i).catch(()=>{});}},C=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;y.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}async close(){if(!this.closed){this.closed=true,await this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{y.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new H(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},w=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let s=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=g=>(this.roster.reconcileLiveSnapshot(g),g),u=async()=>this.roster.mergeDevices(d(await s())),m=async()=>this.roster.mergeStatus(await a()),v=g=>c(M=>g(this.roster.mergeDevices(d(M)))),p=g=>l(M=>g(this.roster.mergeStatus(M))),P=Object.create(i);Object.defineProperties(P,{listDevices:{value:u,enumerable:false},listDeviceStatus:{value:m,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:p,enumerable:false},devices:{value:{...i.devices,list:u,listWithStatus:m,watch:v,watchWithStatus:p},enumerable:true}}),y.set(this,P),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},q=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},W=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},E=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new N;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:re(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof w&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let s of this.handles)s instanceof w&&s.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();for(let n of this.handles)n instanceof w&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${T(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-A2FMQRNZ.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${T(e)}`,JSON.stringify({identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async s=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(s),this.wrapBroadcastSession(await t.open(s))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=ue(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new K(e.usage);}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-IIPEJ77Q.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$1,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-EIMDBAQS.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-EIMDBAQS.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let s={fingerprint:t,auth:i},a=n().then(c=>(s.handle=c,c)).catch(c=>{throw this.activations.get(e)===s&&this.activations.delete(e),c});return s.promise=a,this.activations.set(e,s),a}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):pe(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let s=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$4)===true,l=!r||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$1).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:s},transportPriority:s}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,s={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:s,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async p=>{a={...a,...p},await c?.setAuth(l());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:d,deviceSign:e.authority?.deviceSign??(p=>t.signDeviceBytes(p)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds}),[m,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=v(m,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),s=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,s),l=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:s.name,devicePlatform:s.platform,deviceMetadata:s.metadata}),d;try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),m;return m=new w(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(m);},new u(d)),this.handles.add(m),m}async joinSpace(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new q(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-A2FMQRNZ.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("ticket",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"ticket",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new W(i,a,()=>{this.channels.detach(a),this.onClosed(c);},r.token),this.handles.add(c),c}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.();}}}};function Be(o,e){return new E(o,e)}function ke(o,e){if(!(o instanceof E))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return o.openAuthorityRoom(e)}export{I as a,B as b,de as c,xe as d,T as e,ie as f,oe as g,C as h,Be as i,ke as j};
|
package/dist/coreClient.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-
|
|
1
|
+
import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-LOFcpH3S.js';
|
|
2
2
|
import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, p as RuntimeDevice, q as ScopedLogicalChannel, r as ConnectionState, s as ReadinessOptions, t as ConnectionEvent, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, v as DeviceConnectOptions, w as ConnectDeviceResult, x as ConnectDeviceHooks, y as ConnectDeviceOptions, L as LocalDeviceInfo, z as DeviceProfile, A as RawConnection, J as JoinRoomOptions, B as RuntimeRoomMember, G as GrantScope, F as AuthContext, H as RuntimeClientOptions } from './Connection-CTpuImO-.js';
|
|
3
3
|
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CmzzxSvW.js';
|
|
4
4
|
|
|
@@ -1,24 +1,6 @@
|
|
|
1
1
|
var se=()=>{};var ae=function(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128);}return e},He=function(t){let e=[],n=0,r=0;for(;n<t.length;){let i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){let s=t[n++];e[r++]=String.fromCharCode((i&31)<<6|s&63);}else if(i>239&&i<365){let s=t[n++],o=t[n++],a=t[n++],c=((i&7)<<18|(s&63)<<12|(o&63)<<6|a&63)-65536;e[r++]=String.fromCharCode(55296+(c>>10)),e[r++]=String.fromCharCode(56320+(c&1023));}else {let s=t[n++],o=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(s&63)<<6|o&63);}}return e.join("")},ce={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();let n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i<t.length;i+=3){let s=t[i],o=i+1<t.length,a=o?t[i+1]:0,c=i+2<t.length,l=c?t[i+2]:0,u=s>>2,d=(s&3)<<4|a>>4,h=(a&15)<<2|l>>6,m=l&63;c||(m=64,o||(h=64)),r.push(n[u],n[d],n[h],n[m]);}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(ae(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):He(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<t.length;){let s=n[t.charAt(i++)],a=i<t.length?n[t.charAt(i)]:0;++i;let l=i<t.length?n[t.charAt(i)]:64;++i;let d=i<t.length?n[t.charAt(i)]:64;if(++i,s==null||a==null||l==null||d==null)throw new M;let h=s<<2|a>>4;if(r.push(h),l!==64){let m=a<<4&240|l>>2;if(r.push(m),d!==64){let A=l<<6&192|d;r.push(A);}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t);}}},M=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError";}},je=function(t){let e=ae(t);return ce.encodeByteArray(e,true)},$=function(t){return je(t).replace(/\./g,"")},le=function(t){try{return ce.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e);}return null};function ze(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}var Ve=()=>ze().__FIREBASE_DEFAULTS__,We=()=>{if(typeof process>"u"||typeof process.env>"u")return;let t=process.env.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},Ge=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);}catch{return}let e=t&&le(t[1]);return e&&JSON.parse(e)},ue=()=>{try{return se()||Ve()||We()||Ge()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},Je=t=>ue()?.emulatorHosts?.[t],fe=t=>{let e=Je(t);if(!e)return;let n=e.lastIndexOf(":");if(n<=0||n+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);let r=parseInt(e.substring(n+1),10);return e[0]==="["?[e.substring(1,n-1),r]:[e.substring(0,n),r]},F=()=>ue()?.config;var T=class{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,n)=>{this.resolve=e,this.reject=n;});}wrapCallback(e){return (n,r)=>{n?this.reject(n):this.resolve(r),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(n):e(n,r));}}};function he(){try{return typeof indexedDB=="object"}catch{return false}}function de(){return new Promise((t,e)=>{try{let n=!0,r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),t(!0);},i.onupgradeneeded=()=>{n=!1;},i.onerror=()=>{e(i.error?.message||"");};}catch(n){e(n);}})}var Ke="FirebaseError",b=class t extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=Ke,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,C.prototype.create);}},C=class{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r;}create(e,...n){let r=n[0]||{},i=`${this.service}/${e}`,s=this.errors[e],o=s?qe(s,r):"Error",a=`${this.serviceName}: ${o} (${i}).`;return new b(i,a,r)}};function qe(t,e){return t.replace(Ye,(n,r)=>{let i=e[r];return i!=null?String(i):`<${r}?>`})}var Ye=/\{\$([^}]+)}/g;function N(t,e){if(t===e)return true;let n=Object.keys(t),r=Object.keys(e);for(let i of n){if(!r.includes(i))return false;let s=t[i],o=e[i];if(oe(s)&&oe(o)){if(!N(s,o))return false}else if(s!==o)return false}for(let i of r)if(!n.includes(i))return false;return true}function oe(t){return t!==null&&typeof t=="object"}function S(t){return t&&t._delegate?t._delegate:t}function U(t){try{return (t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return false}}async function pe(t){return (await fetch(t,{credentials:"include"})).ok}var y=class{constructor(e,n,r){this.name=e,this.instanceFactory=n,this.type=r,this.multipleInstances=false,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null;}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var w="[DEFAULT]";var H=class{constructor(e,n){this.name=e,this.container=n,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map;}get(e){let n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){let r=new T;if(this.instancesDeferred.set(n,r),this.isInitialized(n)||this.shouldAutoInitialize())try{let i=this.getOrInitializeService({instanceIdentifier:n});i&&r.resolve(i);}catch{}}return this.instancesDeferred.get(n).promise}getImmediate(e){let n=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??false;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(r)return null;throw i}else {if(r)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(Qe(e))try{this.getOrInitializeService({instanceIdentifier:w});}catch{}for(let[n,r]of this.instancesDeferred.entries()){let i=this.normalizeInstanceIdentifier(n);try{let s=this.getOrInitializeService({instanceIdentifier:i});r.resolve(s);}catch{}}}}clearInstance(e=w){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e);}async delete(){let e=Array.from(this.instances.values());await Promise.all([...e.filter(n=>"INTERNAL"in n).map(n=>n.INTERNAL.delete()),...e.filter(n=>"_delete"in n).map(n=>n._delete())]);}isComponentSet(){return this.component!=null}isInitialized(e=w){return this.instances.has(e)}getOptions(e=w){return this.instancesOptions.get(e)||{}}initialize(e={}){let{options:n={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let i=this.getOrInitializeService({instanceIdentifier:r,options:n});for(let[s,o]of this.instancesDeferred.entries()){let a=this.normalizeInstanceIdentifier(s);r===a&&o.resolve(i);}return i}onInit(e,n){let r=this.normalizeInstanceIdentifier(n),i=this.onInitCallbacks.get(r)??new Set;i.add(e),this.onInitCallbacks.set(r,i);let s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e);}}invokeOnInitCallbacks(e,n){let r=this.onInitCallbacks.get(n);if(r)for(let i of r)try{i(e,n);}catch{}}getOrInitializeService({instanceIdentifier:e,options:n={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:Xe(e),options:n}),this.instances.set(e,r),this.instancesOptions.set(e,n),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r);}catch{}return r||null}normalizeInstanceIdentifier(e=w){return this.component?this.component.multipleInstances?e:w:e}shouldAutoInitialize(){return !!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function Xe(t){return t===w?void 0:t}function Qe(t){return t.instantiationMode==="EAGER"}var k=class{constructor(e){this.name=e,this.providers=new Map;}addComponent(e){let n=this.getProvider(e.name);if(n.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);n.setComponent(e);}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e);}getProvider(e){if(this.providers.has(e))return this.providers.get(e);let n=new H(e,this);return this.providers.set(e,n),n}getProviders(){return Array.from(this.providers.values())}};var f;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT";})(f||(f={}));var et={debug:f.DEBUG,verbose:f.VERBOSE,info:f.INFO,warn:f.WARN,error:f.ERROR,silent:f.SILENT},tt=f.INFO,nt={[f.DEBUG]:"log",[f.VERBOSE]:"log",[f.INFO]:"info",[f.WARN]:"warn",[f.ERROR]:"error"},rt=(t,e,...n)=>{if(e<t.logLevel)return;let r=new Date().toISOString(),i=nt[e];if(i)console[i](`[${r}] ${t.name}:`,...n);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},x=class{constructor(e){this.name=e,this._logLevel=tt,this._logHandler=rt,this._userLogHandler=null;}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in f))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e;}setLogLevel(e){this._logLevel=typeof e=="string"?et[e]:e;}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e;}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e;}debug(...e){this._userLogHandler&&this._userLogHandler(this,f.DEBUG,...e),this._logHandler(this,f.DEBUG,...e);}log(...e){this._userLogHandler&&this._userLogHandler(this,f.VERBOSE,...e),this._logHandler(this,f.VERBOSE,...e);}info(...e){this._userLogHandler&&this._userLogHandler(this,f.INFO,...e),this._logHandler(this,f.INFO,...e);}warn(...e){this._userLogHandler&&this._userLogHandler(this,f.WARN,...e),this._logHandler(this,f.WARN,...e);}error(...e){this._userLogHandler&&this._userLogHandler(this,f.ERROR,...e),this._logHandler(this,f.ERROR,...e);}};var it=(t,e)=>e.some(n=>t instanceof n),me,ge;function st(){return me||(me=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ot(){return ge||(ge=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var be=new WeakMap,z=new WeakMap,ye=new WeakMap,j=new WeakMap,W=new WeakMap;function at(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o);},s=()=>{n(g(t.result)),i();},o=()=>{r(t.error),i();};t.addEventListener("success",s),t.addEventListener("error",o);});return e.then(n=>{n instanceof IDBCursor&&be.set(n,t);}).catch(()=>{}),W.set(e,t),e}function ct(t){if(z.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o);},s=()=>{n(),i();},o=()=>{r(t.error||new DOMException("AbortError","AbortError")),i();};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o);});z.set(t,e);}var V={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return z.get(t);if(e==="objectStoreNames")return t.objectStoreNames||ye.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return g(t[e])},set(t,e,n){return t[e]=n,true},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?true:e in t}};function Ee(t){V=t(V);}function lt(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(R(this),e,...n);return ye.set(r,e.sort?e.sort():[e]),g(r)}:ot().includes(t)?function(...e){return t.apply(R(this),e),g(be.get(this))}:function(...e){return g(t.apply(R(this),e))}}function ut(t){return typeof t=="function"?lt(t):(t instanceof IDBTransaction&&ct(t),it(t,st())?new Proxy(t,V):t)}function g(t){if(t instanceof IDBRequest)return at(t);if(j.has(t))return j.get(t);let e=ut(t);return e!==t&&(j.set(t,e),W.set(e,t)),e}var R=t=>W.get(t);function we(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=g(o);return r&&o.addEventListener("upgradeneeded",c=>{r(g(o.result),c.oldVersion,c.newVersion,g(o.transaction),c);}),n&&o.addEventListener("blocked",c=>n(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l));}).catch(()=>{}),a}var ft=["get","getKey","getAll","getAllKeys","count"],ht=["put","add","delete","clear"],G=new Map;function _e(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(G.get(e))return G.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=ht.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||ft.includes(n)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),i&&c.done]))[0]};return G.set(e,s),s}Ee(t=>({...t,get:(e,n,r)=>_e(e,n)||t.get(e,n,r),has:(e,n)=>!!_e(e,n)||t.has(e,n)}));var K=class{constructor(e){this.container=e;}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(dt(n)){let r=n.getImmediate();return `${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}};function dt(t){return t.getComponent()?.type==="VERSION"}var q="@firebase/app",Ae="0.15.1";var E=new x("@firebase/app"),pt="@firebase/app-compat",mt="@firebase/analytics-compat",gt="@firebase/analytics",bt="@firebase/app-check-compat",yt="@firebase/app-check",Et="@firebase/auth",_t="@firebase/auth-compat",wt="@firebase/database",At="@firebase/data-connect",vt="@firebase/database-compat",Dt="@firebase/functions",Ct="@firebase/functions-compat",St="@firebase/installations",It="@firebase/installations-compat",Ot="@firebase/messaging",Tt="@firebase/messaging-compat",Nt="@firebase/performance",kt="@firebase/performance-compat",xt="@firebase/remote-config",Rt="@firebase/remote-config-compat",Bt="@firebase/storage",Lt="@firebase/storage-compat",Pt="@firebase/firestore",Mt="@firebase/ai",$t="@firebase/firestore-compat",Ft="firebase";var Y="[DEFAULT]",Ut={[q]:"fire-core",[pt]:"fire-core-compat",[gt]:"fire-analytics",[mt]:"fire-analytics-compat",[yt]:"fire-app-check",[bt]:"fire-app-check-compat",[Et]:"fire-auth",[_t]:"fire-auth-compat",[wt]:"fire-rtdb",[At]:"fire-data-connect",[vt]:"fire-rtdb-compat",[Dt]:"fire-fn",[Ct]:"fire-fn-compat",[St]:"fire-iid",[It]:"fire-iid-compat",[Ot]:"fire-fcm",[Tt]:"fire-fcm-compat",[Nt]:"fire-perf",[kt]:"fire-perf-compat",[xt]:"fire-rc",[Rt]:"fire-rc-compat",[Bt]:"fire-gcs",[Lt]:"fire-gcs-compat",[Pt]:"fire-fst",[$t]:"fire-fst-compat",[Mt]:"fire-vertex","fire-js":"fire-js",[Ft]:"fire-js-all"};var B=new Map,Ht=new Map,X=new Map;function ve(t,e){try{t.container.addComponent(e);}catch(n){E.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n);}}function I(t){let e=t.name;if(X.has(e))return E.debug(`There were multiple attempts to register component ${e}.`),false;X.set(e,t);for(let n of B.values())ve(n,t);for(let n of Ht.values())ve(n,t);return true}function Ie(t,e){let n=t.container.getProvider("heartbeat").getImmediate({optional:true});return n&&n.triggerHeartbeat(),t.container.getProvider(e)}function Oe(t){return t==null?false:t.settings!==void 0}var jt={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},_=new C("app","Firebase",jt);var Q=class{constructor(e,n,r){this._isDeleted=false,this._options={...e},this._config={...n},this._name=n.name,this._automaticDataCollectionEnabled=n.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new y("app",()=>this,"PUBLIC"));}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e;}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e;}checkDestroyed(){if(this.isDeleted)throw _.create("app-deleted",{appName:this._name})}};function zt(t,e={}){let n=t;typeof e!="object"&&(e={name:e});let r={name:Y,automaticDataCollectionEnabled:true,...e},i=r.name;if(typeof i!="string"||!i)throw _.create("bad-app-name",{appName:String(i)});if(n||(n=F()),!n)throw _.create("no-options");let s=B.get(i);if(s){if(N(n,s.options)&&N(r,s.config))return s;throw _.create("duplicate-app",{appName:i})}let o=new k(i);for(let c of X.values())o.addComponent(c);let a=new Q(n,r,o);return B.set(i,a),a}function Te(t=Y){let e=B.get(t);if(!e&&t===Y&&F())return zt();if(!e)throw _.create("no-app",{appName:t});return e}function v(t,e,n){let r=Ut[t]??t;n&&(r+=`-${n}`);let i=r.match(/\s|\//),s=e.match(/\s|\//);if(i||s){let o=[`Unable to register library "${r}" with version "${e}":`];i&&o.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&o.push("and"),s&&o.push(`version name "${e}" contains illegal characters (whitespace or "/")`),E.warn(o.join(" "));return}I(new y(`${r}-version`,()=>({library:r,version:e}),"VERSION"));}var Vt="firebase-heartbeat-database",Wt=1,O="firebase-heartbeat-store",J=null;function Ne(){return J||(J=we(Vt,Wt,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(O);}catch(n){console.warn(n);}}}}).catch(t=>{throw _.create("idb-open",{originalErrorMessage:t.message})})),J}async function Gt(t){try{let n=(await Ne()).transaction(O),r=await n.objectStore(O).get(ke(t));return await n.done,r}catch(e){if(e instanceof b)E.warn(e.message);else {let n=_.create("idb-get",{originalErrorMessage:e?.message});E.warn(n.message);}}}async function De(t,e){try{let r=(await Ne()).transaction(O,"readwrite");await r.objectStore(O).put(e,ke(t)),await r.done;}catch(n){if(n instanceof b)E.warn(n.message);else {let r=_.create("idb-set",{originalErrorMessage:n?.message});E.warn(r.message);}}}function ke(t){return `${t.name}!${t.options.appId}`}var Jt=1024,Kt=30,Z=class{constructor(e){this.container=e,this._heartbeatsCache=null;let n=this.container.getProvider("app").getImmediate();this._storage=new ee(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r));}async triggerHeartbeat(){try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=Ce();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(i=>i.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats.length>Kt){let i=Yt(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1);}return this._storage.overwrite(this._heartbeatsCache)}catch(e){E.warn(e);}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return "";let e=Ce(),{heartbeatsToSend:n,unsentEntries:r}=qt(this._heartbeatsCache.heartbeats),i=$(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return E.warn(e),""}}};function Ce(){return new Date().toISOString().substring(0,10)}function qt(t,e=Jt){let n=[],r=t.slice();for(let i of t){let s=n.find(o=>o.agent===i.agent);if(s){if(s.dates.push(i.date),Se(n)>e){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),Se(n)>e){n.pop();break}r=r.slice(1);}return {heartbeatsToSend:n,unsentEntries:r}}var ee=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck();}async runIndexedDBEnvironmentCheck(){return he()?de().then(()=>true).catch(()=>false):false}async read(){if(await this._canUseIndexedDBPromise){let n=await Gt(this.app);return n?.heartbeats?n:{heartbeats:[]}}else return {heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return De(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return De(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}};function Se(t){return $(JSON.stringify({version:2,heartbeats:t})).length}function Yt(t){if(t.length===0)return -1;let e=0,n=t[0].date;for(let r=1;r<t.length;r++)t[r].date<n&&(n=t[r].date,e=r);return e}function Xt(t){I(new y("platform-logger",e=>new K(e),"PRIVATE")),I(new y("heartbeat",e=>new Z(e),"PRIVATE")),v(q,Ae,t),v(q,Ae,"esm2020"),v("fire-js","");}Xt("");var Qt="type.googleapis.com/google.protobuf.Int64Value",Zt="type.googleapis.com/google.protobuf.UInt64Value";function Le(t,e){let n={};for(let r in t)t.hasOwnProperty(r)&&(n[r]=e(t[r]));return n}function L(t){if(t==null)return null;if(t instanceof Number&&(t=t.valueOf()),typeof t=="number"&&isFinite(t)||t===true||t===false||Object.prototype.toString.call(t)==="[object String]")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.map(e=>L(e));if(typeof t=="function"||typeof t=="object")return Le(t,e=>L(e));throw new Error("Data cannot be encoded in JSON: "+t)}function D(t){if(t==null)return t;if(t["@type"])switch(t["@type"]){case Qt:case Zt:{let e=Number(t.value);if(isNaN(e))throw new Error("Data cannot be decoded from JSON: "+t);return e}default:throw new Error("Data cannot be decoded from JSON: "+t)}return Array.isArray(t)?t.map(e=>D(e)):typeof t=="function"||typeof t=="object"?Le(t,e=>D(e)):t}var ie="functions";var xe={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},p=class t extends b{constructor(e,n,r){super(`${ie}/${e}`,n||""),this.details=r,Object.setPrototypeOf(this,t.prototype);}};function en(t){if(t>=200&&t<300)return "ok";switch(t){case 0:return "internal";case 400:return "invalid-argument";case 401:return "unauthenticated";case 403:return "permission-denied";case 404:return "not-found";case 409:return "aborted";case 429:return "resource-exhausted";case 499:return "cancelled";case 500:return "internal";case 501:return "unimplemented";case 503:return "unavailable";case 504:return "deadline-exceeded"}return "unknown"}function P(t,e){let n=en(t),r=n,i;try{let s=e&&e.error;if(s){let o=s.status;if(typeof o=="string"){if(!xe[o])return new p("internal","internal");n=xe[o],r=o;}let a=s.message;typeof a=="string"&&(r=a),i=s.details,i!==void 0&&(i=D(i));}}catch{}return n==="ok"?null:new p(n,r,i)}var te=class{constructor(e,n,r,i){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,Oe(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=n.getImmediate({optional:true}),this.messaging=r.getImmediate({optional:true}),this.auth||n.get().then(s=>this.auth=s,()=>{}),this.messaging||r.get().then(s=>this.messaging=s,()=>{}),this.appCheck||i?.get().then(s=>this.appCheck=s,()=>{});}async getAuthToken(){if(this.auth)try{return (await this.auth.getToken())?.accessToken}catch{return}}async getMessagingToken(){if(!(!this.messaging||!("Notification"in self)||Notification.permission!=="granted"))try{return await this.messaging.getToken()}catch{return}}async getAppCheckToken(e){if(this.serverAppAppCheckToken)return this.serverAppAppCheckToken;if(this.appCheck){let n=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return n.error?null:n.token}return null}async getContext(e){let n=await this.getAuthToken(),r=await this.getMessagingToken(),i=await this.getAppCheckToken(e);return {authToken:n,messagingToken:r,appCheckToken:i}}};var ne="us-central1",tn=/^data: (.*?)(?:\n|$)/;function nn(t){let e=null;return {promise:new Promise((n,r)=>{e=setTimeout(()=>{r(new p("deadline-exceeded","deadline-exceeded"));},t);}),cancel:()=>{e&&clearTimeout(e);}}}var re=class{constructor(e,n,r,i,s=ne,o=(...a)=>fetch(...a)){this.app=e,this.fetchImpl=o,this.emulatorOrigin=null,this.contextProvider=new te(e,n,r,i),this.cancelAllRequests=new Promise(a=>{this.deleteService=()=>Promise.resolve(a());});try{let a=new URL(s);this.customDomain=a.origin+(a.pathname==="/"?"":a.pathname),this.region=ne;}catch{this.customDomain=null,this.region=s;}}_delete(){return this.deleteService()}_url(e){let n=this.app.options.projectId;return this.emulatorOrigin!==null?`${this.emulatorOrigin}/${n}/${this.region}/${e}`:this.customDomain!==null?`${this.customDomain}/${e}`:`https://${this.region}-${n}.cloudfunctions.net/${e}`}};function rn(t,e,n){let r=U(e);t.emulatorOrigin=`http${r?"s":""}://${e}:${n}`,r&&pe(t.emulatorOrigin+"/backends");}function sn(t,e,n){let r=i=>cn(t,e,i,n||{});return r.stream=(i,s)=>ln(t,e,i,s),r}function on(t,e,n){let r=i=>$e(t,e,i,n||{});return r.stream=(i,s)=>Fe(t,e,i,s||{}),r}function Pe(t){return t.emulatorOrigin&&U(t.emulatorOrigin)?"include":void 0}async function an(t,e,n,r,i){n["Content-Type"]="application/json";let s;try{s=await r(t,{method:"POST",body:JSON.stringify(e),headers:n,credentials:Pe(i)});}catch{return {status:0,json:null}}let o=null;try{o=await s.json();}catch{}return {status:s.status,json:o}}async function Me(t,e){let n={},r=await t.contextProvider.getContext(e.limitedUseAppCheckTokens);return r.authToken&&(n.Authorization="Bearer "+r.authToken),r.messagingToken&&(n["Firebase-Instance-ID-Token"]=r.messagingToken),r.appCheckToken!==null&&(n["X-Firebase-AppCheck"]=r.appCheckToken),n}function cn(t,e,n,r){let i=t._url(e);return $e(t,i,n,r)}async function $e(t,e,n,r){n=L(n);let i={data:n},s=await Me(t,r),o=r.timeout||7e4,a=nn(o),c=await Promise.race([an(e,i,s,t.fetchImpl,t),a.promise,t.cancelAllRequests]);if(a.cancel(),!c)throw new p("cancelled","Firebase Functions instance was deleted.");let l=P(c.status,c.json);if(l)throw l;if(!c.json)throw new p("internal","Response is not valid JSON object.");let u=c.json.data;if(typeof u>"u"&&(u=c.json.result),typeof u>"u")throw new p("internal","Response is missing data field.");return {data:D(u)}}function ln(t,e,n,r){let i=t._url(e);return Fe(t,i,n,r||{})}async function Fe(t,e,n,r){n=L(n);let i={data:n},s=await Me(t,r);s["Content-Type"]="application/json",s.Accept="text/event-stream";let o;try{o=await t.fetchImpl(e,{method:"POST",body:JSON.stringify(i),headers:s,signal:r?.signal,credentials:Pe(t)});}catch(h){if(h instanceof Error&&h.name==="AbortError"){let A=new p("cancelled","Request was cancelled.");return {data:Promise.reject(A),stream:{[Symbol.asyncIterator](){return {next(){return Promise.reject(A)}}}}}}let m=P(0,null);return {data:Promise.reject(m),stream:{[Symbol.asyncIterator](){return {next(){return Promise.reject(m)}}}}}}let a,c,l=new Promise((h,m)=>{a=h,c=m;});r?.signal?.addEventListener("abort",()=>{let h=new p("cancelled","Request was cancelled.");c(h);});let u=o.body.getReader(),d=un(u,a,c,r?.signal);return {stream:{[Symbol.asyncIterator](){let h=d.getReader();return {async next(){let{value:m,done:A}=await h.read();return {value:m,done:A}},async return(){return await h.cancel(),{done:true,value:void 0}}}}},data:l}}function un(t,e,n,r){let i=(o,a)=>{let c=o.match(tn);if(!c)return;let l=c[1];try{let u=JSON.parse(l);if("result"in u){e(D(u.result));return}if("message"in u){a.enqueue(D(u.message));return}if("error"in u){let d=P(0,u);a.error(d),n(d);return}}catch(u){if(u instanceof p){a.error(u),n(u);return}}},s=new TextDecoder;return new ReadableStream({start(o){let a="";return c();async function c(){if(r?.aborted){let l=new p("cancelled","Request was cancelled");return o.error(l),n(l),Promise.resolve()}try{let{value:l,done:u}=await t.read();if(u){a.trim()&&i(a.trim(),o),o.close();return}if(r?.aborted){let h=new p("cancelled","Request was cancelled");o.error(h),n(h),await t.cancel();return}a+=s.decode(l,{stream:!0});let d=a.split(`
|
|
2
2
|
`);a=d.pop()||"";for(let h of d)h.trim()&&i(h.trim(),o);return c()}catch(l){let u=l instanceof p?l:P(0,null);o.error(u),n(u);}}},cancel(){return t.cancel()}})}var Re="@firebase/functions",Be="0.13.5";var fn="auth-internal",hn="app-check-internal",dn="messaging-internal";function pn(t){let e=(n,{instanceIdentifier:r})=>{let i=n.getProvider("app").getImmediate(),s=n.getProvider(fn),o=n.getProvider(dn),a=n.getProvider(hn);return new re(i,s,o,a,r)};I(new y(ie,e,"PUBLIC").setMultipleInstances(true)),v(Re,Be,t),v(Re,Be,"esm2020");}function Un(t=Te(),e=ne){let r=Ie(S(t),ie).getImmediate({identifier:e}),i=fe("functions");return i&&mn(r,...i),r}function mn(t,e,n){rn(S(t),e,n);}function Hn(t,e,n){return sn(S(t),e,n)}function jn(t,e,n){return on(S(t),e,n)}pn();/*! Bundled license information:
|
|
3
3
|
|
|
4
|
-
@firebase/util/dist/postinstall.mjs:
|
|
5
|
-
(**
|
|
6
|
-
* @license
|
|
7
|
-
* Copyright 2025 Google LLC
|
|
8
|
-
*
|
|
9
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
10
|
-
* you may not use this file except in compliance with the License.
|
|
11
|
-
* You may obtain a copy of the License at
|
|
12
|
-
*
|
|
13
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
14
|
-
*
|
|
15
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
16
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
17
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
18
|
-
* See the License for the specific language governing permissions and
|
|
19
|
-
* limitations under the License.
|
|
20
|
-
*)
|
|
21
|
-
|
|
22
4
|
@firebase/util/dist/node-esm/index.node.esm.js:
|
|
23
5
|
@firebase/util/dist/node-esm/index.node.esm.js:
|
|
24
6
|
@firebase/util/dist/node-esm/index.node.esm.js:
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
|
|
|
2
2
|
import { O as Options, C as Client } from './types-Cyc-mPjk.js';
|
|
3
3
|
export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a6 as UsageUpdate, a7 as UsageWarning } from './types-Cyc-mPjk.js';
|
|
4
4
|
import './coreClient.js';
|
|
5
|
-
import './assembly-
|
|
5
|
+
import './assembly-LOFcpH3S.js';
|
|
6
6
|
import './Connection-CTpuImO-.js';
|
|
7
7
|
import './capabilities-CmzzxSvW.js';
|
|
8
8
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-VTYVIKTM.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {
|
|
1
|
+
import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-VTYVIKTM.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-TZLNKQNJ.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function y(a){return i(a,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:t}]=await Promise.all([import('./BrowserManagedBroadcastHost-ARCP5MGJ.js'),import('./WasmBridge-LWMCETW4.js')]),r=t().then(async n=>(await n.initWasm(),n.start(),new n.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>r})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}y.native=function(a$2,e=d()){let o=new a;return i(a$2,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.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:()=>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:r}=await import('./ipcFactory-PDVLUG2W.js');return r(t,e,o)}})};export{y as OpenRTC};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-EFTDXE6M.js';import {s}from'./chunk-FB5M6GIW.js';import'./chunk-BGWJHPBC.js';import'./chunk-6Q2LAXM4.js';import'./chunk-AAZPQQXX.js';import {a as a$1}from'./chunk-XTYALGJN.js';import'./chunk-TYZS5LXQ.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-VTYVIKTM.js';import'./chunk-72NEEJQG.js';import'./chunk-CNAW5BZ3.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t=a$1(p);return a$2(t,new s({...t,bridge:n,projectionBroker:m}))}export{l as createIpcClient};
|
package/dist/native.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Aven
|
|
|
3
3
|
import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
|
|
4
4
|
export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CTpuImO-.js';
|
|
5
5
|
import './coreClient.js';
|
|
6
|
-
import './assembly-
|
|
6
|
+
import './assembly-LOFcpH3S.js';
|
|
7
7
|
import './capabilities-CmzzxSvW.js';
|
|
8
8
|
|
|
9
9
|
/**
|