openrtc 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ITransport-CjxCQ6q7.d.ts → Connection-DZ5eP5hL.d.ts} +445 -94
- package/dist/DelegatingRuntimeAdapter-4cgiIWMN.d.ts +150 -0
- package/dist/IpcRuntimeAdapter-Dduaxscj.d.ts +80 -0
- package/dist/WasmBridge-3W2HHADU.js +1 -0
- package/dist/{assembly-Bmi65-tK.d.ts → assembly-By3UBQsE.d.ts} +36 -19
- package/dist/{capabilities-BPuynml5.d.ts → capabilities-B2mHv_H7.d.ts} +2 -6
- package/dist/chunk-2GX6GB6L.js +1 -0
- package/dist/chunk-2LATKLCC.js +118 -0
- package/dist/{chunk-KRJECX7X.js → chunk-5XOLKH66.js} +1 -1
- package/dist/chunk-6OFAKLDB.js +2 -0
- package/dist/chunk-72NEEJQG.js +1 -0
- package/dist/chunk-BCGCJGIV.js +2 -0
- package/dist/chunk-GNW63SM6.js +2 -0
- package/dist/chunk-JPBW67B3.js +1 -0
- package/dist/chunk-MI3ZMVPK.js +2 -0
- package/dist/chunk-OT7IPLZE.js +1 -0
- package/dist/chunk-OWKAJPOI.js +1 -0
- package/dist/chunk-P2SHJMS3.js +1 -0
- package/dist/chunk-TYZS5LXQ.js +2 -0
- package/dist/chunk-WB66633N.js +1 -0
- package/dist/chunk-XEHBTMJQ.js +1 -0
- package/dist/chunk-YYI6AY6W.js +2 -0
- package/dist/{controlPlane-KVFZ7BR5.js → controlPlane-7E6KGQPP.js} +1 -1
- package/dist/coreClient.d.ts +3 -4
- package/dist/coreClient.js +1 -1
- package/dist/{deviceEnrollment-VACC64CQ.js → deviceEnrollment-CBJYXZ43.js} +2 -2
- package/dist/index.d.ts +6 -7
- package/dist/index.js +1 -1
- package/dist/{ipc-CPnNwv6f.d.ts → ipc-DgzKqHH3.d.ts} +3 -0
- package/dist/ipcFactory-4PCGKZIN.js +1 -0
- package/dist/native.d.ts +21 -0
- package/dist/native.js +1 -0
- package/dist/openrtc-5HAYVDHT.js +2 -0
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/protocol-BSBjMb7p.d.ts +6 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +4 -5
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +1 -2
- package/dist/runtime/factories.d.ts +283 -8
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +13 -160
- package/dist/runtime/index.js +1 -1
- package/dist/testing/native.d.ts +11 -0
- package/dist/testing/native.js +1 -0
- package/dist/testing.d.ts +13 -19
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +7 -18
- package/dist/transport/index.js +1 -1
- package/dist/{types--jQzenZR.d.ts → types-BArEthJr.d.ts} +178 -10
- package/package.json +11 -2
- package/dist/DelegatingRuntimeAdapter-DE4LTGAJ.d.ts +0 -399
- package/dist/IpcRuntimeAdapter-CE0va9Tr.d.ts +0 -19
- package/dist/WasmBridge-75F6GKHG.js +0 -1
- package/dist/chunk-2L6ULC32.js +0 -1
- package/dist/chunk-2SUSPEC4.js +0 -1
- package/dist/chunk-7BJKDBLP.js +0 -2
- package/dist/chunk-DUY34MGT.js +0 -1
- package/dist/chunk-HEAJ7ZUR.js +0 -1
- package/dist/chunk-HUG5AX7R.js +0 -1
- package/dist/chunk-Q6KXVTSH.js +0 -2
- package/dist/chunk-R35AWMNY.js +0 -1
- package/dist/chunk-UILOGUOU.js +0 -1
- package/dist/chunk-WA434EWD.js +0 -2
- package/dist/chunk-XAL4T6TB.js +0 -3
- package/dist/chunk-Z2IS6NH2.js +0 -2
- package/dist/ipcFactory-32R47AVK.js +0 -1
- package/dist/openrtc-4EZPCHWM.js +0 -2
- package/dist/types-DDhMQkK8.d.ts +0 -621
package/dist/chunk-Z2IS6NH2.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {c as c$2,a,e as e$2}from'./chunk-AJQVMVYW.js';import {c,e,d,f as f$1,b as b$1}from'./chunk-WA434EWD.js';import {f,e as e$1,b,c as c$1,w,z as z$1,h as h$1,p}from'./chunk-2L6ULC32.js';import*as U from'tweetnacl';function M(){throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an AuthProvider; legacy runtimes must import openrtc/auth explicitly.");}var nt=3e4,it=5*6e4,rt=3e4,_e=12,ot=10*6e4,st=5*6e4,X=15e3,at=15e3,ct=1e3,Ee=250,dt="openrtc.v2",lt="openrtc.auth.",g=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="CoordinationConnectError";this.code=a.COORDINATION_DISCONNECTED;this.plane="coordination";}},V=class extends Error{constructor(t,n,r){let o=e$2({code:t,message:n,retryable:r});super(`Coordination gateway ${t}: ${n}`);this.name="CoordinationGatewayProtocolError";this.code=o.code||t||a.COORDINATION_PROTOCOL,this.retryable=r,this.plane=o.plane;}};function Me(i){return i instanceof g&&/\bstale-budget\b/i.test(i.message)}function De(i){if(typeof i!="object"||i===null)return false;let e=i;if(e.retryable===false)return true;let t=e.status??e.statusCode,n=typeof t=="number"?t:Number.NaN;if(Number.isInteger(n)&&n>=400&&n<500&&![408,425,429].includes(n))return true;let r=String(e.code??"");return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(r)}function ut(i){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(i*(.75+e[0]/4294967295*.5)))}function R(i){if(typeof crypto.randomUUID=="function")return `${i}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return `${i}:${t}`}async function pt(i){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(i)),t="";for(let n of new Uint8Array(e))t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function ht(i,e,t){let n=new URL(i);if(n.search||n.hash||n.username||n.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(n.protocol==="https:")n.protocol="wss:";else if(n.protocol==="http:")n.protocol="ws:";else if(n.protocol!=="wss:"&&n.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return n.pathname=`${n.pathname.replace(/\/+$/,"")}/v${t}/connect/${e}`,n.toString()}function ke(i){let e=new URL(i);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var J=class i{constructor(e){this.options=e;this.runtimeInstanceId=R("runtime");this.socket=null;this.socketReady=false;this.activeGrantToken=null;this.activeGrantProtocolVersion=1;this.leaseRefreshMode="off";this.pendingLeaseRefreshKey=null;this.connectPromise=null;this.desiredPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.deviceListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectOutageStartedAtMs=null;this.reconnectCircuitOpen=false;this.hostAvailable=true;this.connectionReadyWaiters=new Set;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;if(e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),n=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",r=t.protocol==="https:"||t.protocol==="wss:",o=e.gateway.testingAllowInsecureLoopback===true&&n&&(t.protocol==="http:"||t.protocol==="ws:");if(!r&&!o)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,t,n,r,o,s){let a=this.desiredPresence;this.desiredPresence={localNodeId:e,ticket:t,online:n,ttlMs:r,metadata:o,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!a||a.localNodeId!==e||a.ticket!==t||a.online!==n||a.ttlMs!==r||a.metadata!==o||a.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);let d=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(l){if(!(l instanceof g)||!l.retryable)throw l;await this.waitForConnectionReady();}this.appliedPresenceRevision>=d||(a&&a.ticket!==t&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:R("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,d));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:R("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<at)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}setHostAvailability(e){let t=e.available&&!this.hostAvailable;this.hostAvailable=e.available;for(let n of this.roomConnections.values())n.setHostAvailability(e);for(let n of this.friendConnections.values())n.setHostAvailability(e);if(!e.available){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}t&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(n=>this.scheduleReconnect(n));}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let n=t;if(t.excludedPeers!==void 0){let r=[...new Set(t.excludedPeers.map(o=>String(o??"").trim().toLowerCase()).filter(Boolean))].sort();if(r.length>Ee)throw new Error(`Coordination excluded-peer set exceeds ${Ee} devices.`);this.desiredExcludedPeers=r,n={...t,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:R("device-patch"),patch:n});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let t=new i({...this.options,credentialPurpose:"device-control"});try{await t.deleteDevice(e);}finally{t.stopAuthActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:R("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,t){let n=r=>e(t?r.filter(o=>o.nodeId!==t):r);return this.deviceListeners.add(n),n(this.snapshot()),this.desiredPresence&&this.ensureConnected(),()=>this.deviceListeners.delete(n)}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let n=this.snapshot().map(r=>({type:"added",device:r}));n.length>0&&t.enqueue(n);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:R("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:R("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:n=>{t=n,this.sessionStreams.add(n);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,n,r){await this.ensureConnected();let o=R("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:t,state:n,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];if(n.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let a of n)if(a.length>128||a.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,s=[];t(new Map);for(let a of n)!a||a===this.options.getCurrentUserId()||this.openFriendConnection(a).then(c=>{if(r.value){c.stopAuthActivity();return}s.push(c.onDevicesChange(d=>{o.set(a,d.filter(l=>l.online)),t(new Map(o));}));}).catch(()=>{r.value||(o.set(a,[]),t(new Map(o)));});return ()=>{r.value=true;for(let a of s)a();for(let a of n)this.friendConnections.get(a)?.stopAuthActivity(),this.friendConnections.delete(a);}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:R("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthActivity(){this.stopped=true,this.reconnectOutageStartedAtMs=null,this.stopSocket(),this.rejectConnectionReadyWaiters(new g("Coordination activity stopped before capability admission completed.",false)),this.desiredExcludedPeers=[];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();this.pendingAcks.clear(),this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,t,n){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new i({...this.options,avenueOverride:{kind:"room",id:r}}),o.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(r,o));try{await o.updatePresence(t,n,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(s){if(!(s instanceof g)||!s.retryable)throw s;await o.waitForConnectionReady();}}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),n=this.roomConnections.get(t);n&&(await n.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),n.stopAuthActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(n=>this.roomMember(n))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(r=>t(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new g("Coordination reconnect is parked until the host is foregrounded and online.",true);if(this.reconnectCircuitOpen)throw new g("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new g("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence??this.controlPresence(),t=this.desiredPresenceRevision,n=async()=>{let r=await this.mintGatewayCredential(e,false);await new Promise((o,s)=>{let a=new WebSocket(ht(r.gatewayUrl,r.routeKey,r.protocolVersion),[dt,`${lt}${r.token}`]);this.socket=a;let c=false,d=null,l=setTimeout(()=>{a.close(4408,"authentication timeout"),d=new g("Coordination gateway authentication timed out.",true),s(d);},X);a.onopen=()=>{a.send(JSON.stringify({v:1,type:"auth",token:r.token,device:this.gatewayDevice(e)}));},a.onmessage=f=>{let p;try{p=JSON.parse(String(f.data));}catch{a.close(4400,"invalid gateway frame"),c||(clearTimeout(l),s(new Error("Coordination gateway returned an invalid frame.")));return}if(p.type==="ready"&&!c&&(this.activeGrantToken=r.token,this.activeGrantProtocolVersion=r.protocolVersion,this.leaseRefreshMode=p.leaseRefreshMode??"off",c=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?t:0),clearTimeout(l),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(r.expiresAtMs,r.protocolVersion),this.resolveConnectionReadyWaiters(),o()),p.type==="error"&&!c){d=new g(`Coordination gateway ${p.code}: ${p.message}`,p.retryable),clearTimeout(l),s(d),a.close(4403,p.code);return}this.handleFrame(p);},a.onerror=()=>{c||(clearTimeout(l),d??(d=new g("Coordination gateway connection failed.",true)),s(d));},a.onclose=f=>{clearTimeout(l),this.socket===a&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),this.rejectPendingAuthRefresh(new g("Coordination gateway closed during credential refresh.",f.code!==4401&&f.code!==4403)),!this.stopped&&this.desiredPresence&&f.code!==1e3&&!Me(d)&&this.scheduleReconnect(d??new g(`Coordination gateway closed (${f.code}).`,f.code!==4401));};});};try{await n();}catch(r){if(!Me(r))throw r;await n();}}async mintGatewayCredential(e,t){let r={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await pt(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:R("credential")},o;try{if(!this.options.gateway.grantProvider)throw new g("OpenRTC 2.0 coordination requires a v2 gateway grant provider.",!1);o=await this.options.gateway.grantProvider({...r,...t&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(a){throw a instanceof g?a:new g(a instanceof Error?a.message:"Coordination credential mint failed.",!De(a))}if(o.protocolVersion!==2)throw new g("Unsupported coordination gateway protocol.",false);let s=ke(this.options.gateway.endpoint);if(ke(o.gatewayUrl)!==s)throw new g("Coordination credential returned an unexpected gateway origin.",false);return o}handleFrame(e){if(e.type==="auth.refreshed"){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),t.resolve());}else if(e.type==="lease.refreshed"){let t=this.pendingAuthRefresh;t&&e.idempotencyKey===this.pendingLeaseRefreshKey&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),t.resolve());}else if(e.type==="roster.snapshot"){this.devices.clear();for(let t of e.devices)this.devices.set(t.deviceId,this.toDevice(t));this.emitDevices();}else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let t=this.devices.has(e.device.deviceId),n=this.toDevice(e.device);this.devices.set(n.deviceId,n),this.emitDeviceEvents([{type:t?"modified":"added",device:n}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=ct&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="session.changed"){let t=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let n of this.sessionStreams)n.enqueue(t);}else if(e.type==="ack"){let t=this.pendingAcks.get(e.idempotencyKey);t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let n=this.pendingAuthRefresh;clearTimeout(n.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,n.reject(new g(`Coordination gateway ${e.code}: ${e.message}`,e.retryable));return}let t=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.reject(new V(e.code,e.message,e.retryable)));}}async sendOperation(e){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let t=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(n){if(!(n instanceof V)||n.code!=="budget-renewal-required"&&n.code!==a.BUDGET_RENEWAL_REQUIRED||!n.retryable)throw n;this.budgetRenewalEpoch===t&&await this.renewBudget(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((n,r)=>{let o=setTimeout(()=>{this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},X);this.pendingAcks.set(e.idempotencyKey,{resolve:n,reject:r,timer:o}),t.send(JSON.stringify(e));});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication().then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}snapshot(e){return [...this.devices.values()].filter(t=>!e||t.nodeId!==e).sort((t,n)=>t.deviceId.localeCompare(n.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}updateLocalDeviceExpiry(e){let t=this.options.getLocalDeviceId(),n=this.devices.get(t);if(!n||n.expiresAt===e)return;let r={...n,expiresAt:e};this.devices.set(t,r),this.emitDeviceEvents([{type:"modified",device:r}]),this.emitDevices();}scheduleAuthRefresh(e,t){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let n=e-Date.now(),r=t===2?it:nt,o=n>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!o){this.stopSocket(false),this.scheduleReconnect(new g("Coordination credential crossed a billing boundary.",true));return}(t===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(a=>{this.stopSocket(false),this.scheduleReconnect(a);});},o?n-r:Math.max(1e3,n+1e3));}async refreshAuthentication(e=false){let t=this.socket,n=this.desiredPresence;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady||!n)throw new g("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let r=await this.mintGatewayCredential(n,!e),o,s,a=new Promise((d,l)=>{o=d,s=l;}),c=setTimeout(()=>{this.pendingAuthRefresh?.timer===c&&(this.pendingAuthRefresh=null),s(new g("Coordination credential refresh timed out.",true));},X);this.pendingAuthRefresh={promise:a,resolve:o,reject:s,timer:c},t.send(JSON.stringify({v:1,type:"auth.refresh",token:r.token})),await a,this.activeGrantToken=r.token,this.activeGrantProtocolVersion=r.protocolVersion;}async refreshLease(){let e=this.socket;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady)throw new g("Coordination socket is unavailable for lease refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let t=R("lease"),n,r,o=new Promise((a,c)=>{n=a,r=c;}),s=setTimeout(()=>{this.pendingAuthRefresh?.timer===s&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),r(new g("Coordination lease refresh timed out.",true));},X);this.pendingLeaseRefreshKey=t,this.pendingAuthRefresh={promise:o,resolve:n,reject:r,timer:s},e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:t}));try{await o;}catch{await this.refreshAuthentication(true);}}scheduleReconnect(e){if(this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof g?e.retryable:!De(e))){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new g("Coordination reconnect circuit is open.",false));return}if(this.reconnectOutageStartedAtMs??(this.reconnectOutageStartedAtMs=Date.now()),!this.hostAvailable)return;let n=Math.min(this.reconnectAttempt,_e),r=Date.now()-this.reconnectOutageStartedAtMs>=ot,o=ut(r?st:h$1(n,250,rt));this.reconnectAttempt=Math.min(n+1,_e),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(s=>this.scheduleReconnect(s));},o);}stopSocket(e=true){e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null,this.leaseRefreshMode="off",this.pendingLeaseRefreshKey=null,this.rejectPendingAuthRefresh(new g("Coordination credential refresh was canceled.",true));let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new g("Coordination reconnect circuit is unavailable.",false)):new Promise((e,t)=>{this.connectionReadyWaiters.add({resolve:e,reject:t});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let t of this.connectionReadyWaiters)t.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,t.reject(e));}rejectPendingAcks(e){for(let t of this.pendingAcks.values())clearTimeout(t.timer),t.reject(new Error(e));this.pendingAcks.clear();}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),n=this.roomConnections.get(t);if(!n)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return n}async openFriendConnection(e){let t=this.friendConnections.get(e);if(t||(t=new i({...this.options,avenueOverride:{kind:"user",id:e}}),t.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,t)),!t.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");t.desiredPresence={...this.desiredPresence};}return await t.ensureConnected(),t}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var Q=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let t=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>t+3e4)return this.cached;if(this.inFlight)return this.inFlight;let n=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",s=Number(r?.expiresAtMs),a=Date.now();if(!o||!Number.isFinite(s)||s<=a+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let c={token:o,expiresAtMs:s};return this.cached=c,this.refreshRetryUsed=false,this.notify(c),this.scheduleRefresh(c),c})();this.inFlight=n;try{return await n}finally{this.inFlight===n&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,t){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(t?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let t of this.listeners)t(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let t=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},t);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};function Z(i){if(!i)return null;let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}function oe(i,e){return i<e?-1:i>e?1:0}function Ne(i,e){let t=e.trim();if(!t)return [];let n=new Map;for(let a of i){let c=String(a?.deviceId??"").trim();c&&c!==t&&n.set(c,a);}if(n.size<=4)return [...n.values()].sort((a,c)=>oe(a.deviceId,c.deviceId));let r=[...n.keys(),t].sort(oe),o=r.indexOf(t),s=new Set;for(let a=1;s.size<4;a+=1)s.add(r[(o+a)%r.length]),s.add(r[(o-a+r.length)%r.length]);return s.delete(t),[...s].map(a=>n.get(a)).filter(a=>a!==void 0).sort((a,c)=>oe(a.deviceId,c.deviceId))}var v=class v{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.durablePresenceRetryTimer=null;this.durablePresenceRetryAttempt=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;}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 n=t.trim()||this.deps.resolveWebLogicalDeviceId(),r=`${e}::${n}`;this.startedAutoConnectKey===r&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=n,this.startedAutoConnectKey=r,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),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 t=this.normalizeDesiredPeers(e),n=this.deps.roomGossipFanout&&this.localDesiredPeerDeviceId?Ne(t,this.localDesiredPeerDeviceId):t;this.desiredPeersByDeviceId=new Map(n.map(o=>[o.deviceId,o]));let r=JSON.stringify(n);r!==this.desiredPeerSignature&&(this.desiredPeerSignature=r,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=n,this.flushDesiredPeerSubmission());}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let n=this.startedAutoConnectKey;if(!n)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let r=this.normalizeDesiredPeers(t),o=JSON.stringify(r),s=o!==this.desiredPeerSignature;this.desiredPeerSignature=o,this.desiredPeersByDeviceId=new Map(r.map(a=>[a.deviceId,a])),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),s&&this.deps.onDesiredPeersChanged?.(),await this.enqueueDesiredPeerSubmission(n,e,r);}resolveDesiredPeer(e,t){let n=typeof e=="string"?e.trim():"",r=typeof t=="string"?t.trim():"";if(n){let o=this.desiredPeersByDeviceId.get(n);if(o&&(!r||!o.nodeId||o.nodeId===r))return o}return r?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===r)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,n=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,n,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(n=>String(n??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(t=>t.deviceId.length>0).sort((t,n)=>t.deviceId.localeCompare(n.deviceId))}enqueueDesiredPeerSubmission(e,t,n){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}await Promise.all(n.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});}})),await o.submit_browser_desired_peers(t,JSON.stringify(n));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}async excludeAutoConnect(e,t){let n=await this.deps.waitForWasmClient();n&&typeof n.set_auto_connect_excluded=="function"&&await n.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async recordAutoConnectExcludedForPresence(e,t){let n=e.trim().toLowerCase();if(!n)return;t?this.localExcludedPeers.add(n):this.localExcludedPeers.delete(n);let r=this.deps.resolveWebLogicalDeviceId();r&&await this.deps.updateExcludedPeers(r,this.currentExcludedPeersSnapshot());}startPresenceLoop(e,t,n,r,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let s=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:r,metadata:o,deviceName:n};let a=this.deps.resolveWebLogicalDeviceId();(async()=>{let d=await this.deps.withWebPresenceMetadata(o,a);if(!(s===this.presenceStartGeneration&&this.presenceState!==null))return;let f=false,p=null,y=(w,C)=>{this.scheduleDurableRosterRetry(a,s,v.PRESENCE_LEASE_MS,w,C);};p=setTimeout(()=>{f||y("initial coordination presence write timed out");},v.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),this.deps.updatePresence(t,r,true,v.PRESENCE_LEASE_MS,d,n).then(()=>{f=true,p&&(clearTimeout(p),p=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(w=>{p&&(clearTimeout(p),p=null),y("initial coordination presence write failed",w);});})();}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,n,r,o){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer||this.isPermanentProviderError(o))return;let s=this.durablePresenceRetryAttempt+1;if(s>v.PRESENCE_RETRY_LIMIT){console.warn(`[WasmBridge] ${r}; durable roster retry circuit opened after ${v.PRESENCE_RETRY_LIMIT} attempts`,o);return}this.durablePresenceRetryAttempt=s;let a=Math.min(v.PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,s-1),v.PRESENCE_RETRY_MAX_DELAY_MS),c=(s*17%21-10)/100,d=Math.max(v.PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying coordination presence in ${d}ms`,o),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let l=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,true,n,l,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(l=>{this.scheduleDurableRosterRetry(e,t,n,"durable roster registration retry failed",l);});},d);}isPermanentProviderError(e){let t=e&&typeof e=="object"?e:null;if(t?.retryable===false)return true;let r=(t?String(t.code??""):"").toLowerCase().replace(/^functions\//,"");return ["auth/invalid-user-token","auth/user-token-expired","auth/user-disabled","permission-denied","unauthenticated","invalid-argument","failed-precondition"].some(o=>r===o||r.endsWith(`/${o}`))}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.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};v.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,v.PRESENCE_RETRY_MIN_DELAY_MS=2e3,v.PRESENCE_RETRY_MAX_DELAY_MS=6e4,v.PRESENCE_RETRY_LIMIT=8,v.PRESENCE_LEASE_MS=15*6e4;var ee=v;function te(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var ft="[OpenRTC][teardown-trace]";function mt(){try{let i=globalThis;if(i.OPENRTC_TEARDOWN_TRACE===!0||i.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function xe(i,e={}){console.info(ft,{kind:i,ts:new Date().toISOString(),...e}),mt()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:i,stack:new Error(`teardown: ${i}`).stack});}var ie="trustedDevice",gt="plutonium:e2ee:identity:v1",yt="plutonium:e2ee:identity:session:v1",vt="openrtc-trust",W="identity",Oe="transport-trust:v1",wt=1,S=null,B=null;function A(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function H(i){let e="";for(let t=0;t<i.length;t+=1)e+=String.fromCharCode(i[t]);return btoa(e)}async function se(i){let e=await crypto.subtle.digest("SHA-256",i),t=new Uint8Array(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function bt(){return typeof sessionStorage>"u"?null:sessionStorage}function It(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(gt);}catch{}}var ne=null;async function Le(){return ne||(ne=(async()=>{let i=globalThis.crypto?.subtle;if(!i||typeof i.generateKey!="function")return false;try{let e=await i.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),ne)}async function St(i){let e=await crypto.subtle.exportKey("raw",i);return new Uint8Array(e)}function Pt(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function We(){let i=Pt();return i?new Promise(e=>{let t;try{t=i.open(vt,1);}catch{e(null);return}t.onupgradeneeded=()=>{let n=t.result;n.objectStoreNames.contains(W)||n.createObjectStore(W);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function Rt(){let i=await We();if(!i)return null;try{return await new Promise(e=>{let r=i.transaction(W,"readonly").objectStore(W).get(Oe);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{i.close();}}async function Ct(i){let e=await We();if(!e)return false;try{return await new Promise(t=>{let n=e.transaction(W,"readwrite");n.objectStore(W).put(i,Oe),n.oncomplete=()=>t(!0),n.onerror=()=>t(!1),n.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Fe(i,e){let t=await St(i.publicKey),n=await se(t),r=i.privateKey;return {publicKey:t,fingerprint:n,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let s=await crypto.subtle.sign({name:"Ed25519"},r,A(o));return H(new Uint8Array(s))}}}function Tt(i,e,t){let n=i.secretKey;return {publicKey:i.publicKey,secretKey:n,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return At(r,n)}}}function sn(i=32){let e=crypto.getRandomValues(new Uint8Array(i));return H(e)}function At(i,e){let t=U.sign.detached(A(i),e);return H(t)}function _t(i,e,t){try{return U.sign.detached.verify(A(i),A(e),A(t))}catch{return false}}async function an(i,e,t){let n=globalThis.crypto?.subtle;if(n&&typeof n.importKey=="function"&&typeof n.verify=="function")try{let r=await n.importKey("raw",A(t),{name:"Ed25519"},!1,["verify"]);return await n.verify({name:"Ed25519"},r,A(e),A(i))}catch{}return _t(i,e,t)}function cn(i){return H(i)}function dn(i){if(!i||!i.trim())return null;try{let e=JSON.parse(i),t=e&&typeof e=="object"&&!Array.isArray(e)?e[ie]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,r=typeof n.version=="number"?n.version:null,o=typeof n.identityPublicKey=="string"?n.identityPublicKey:null,s=typeof n.identityFingerprint=="string"?n.identityFingerprint:null;return !r||!o||!s?null:{version:r,identityPublicKey:o,identityFingerprint:s}}catch{return null}}async function Et(){let i=await xt().catch(()=>null);return i?{version:wt,identityPublicKey:H(i.publicKey),identityFingerprint:i.fingerprint}:null}async function ae(i){let e=await Et();if(!e)return i??void 0;let t=typeof i=="string"?i.trim():"";if(!t)return JSON.stringify({[ie]:e});try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return JSON.stringify({...n,[ie]:e})}catch{}return JSON.stringify({metadata:i,[ie]:e})}function Mt(){if(typeof window>"u")return null;let i=window.__TAURI_INTERNALS__;return !i||typeof i.invoke!="function"?null:i.invoke.bind(i)}async function Dt(){if(typeof window>"u")return null;let i=Mt();if(!te()&&!i)return null;if(!i)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await i("openrtc_get_transport_trust_identity"),t=A(e.publicKeyBase64);if(t.byteLength!==U.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let n=await se(t);if(e.fingerprint!==n)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:t,fingerprint:n,backend:"native-provider",durable:!0,async signChallenge(r){return i("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let t=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw t.cause=e,t}}function kt(){let i=bt();i&&i.removeItem(yt);}async function Nt(){if(It(),kt(),S)return S;let i=await Dt();if(i)return S=i,S;if(await Le()){let e=await Rt();if(e)return S=await Fe(e,true),S}return null}async function xt(i={}){let e=await Nt();if(e)return e;if(B)return B;let t=Ot(i);B=t;try{return await t}finally{B===t&&(B=null);}}async function Ot(i){if(S)return S;let e=i.ephemeral===true;if(await Le())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),n=!1;return e||(n=await Ct(t)),S=await Fe(t,n),S}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let t=U.sign.keyPair(),n=await se(f(t.publicKey));return S=Tt(t,n,!1),S}catch{return null}}var ce={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function un(){return ce}var Lt={adapter:"browser-wasm",signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:false,irohLan:false,webRtcUpgrade:true,webRtcLan:true,nativeWebRtc:false,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},Wt={adapter:"native-ipc",signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:false,webRtcLan:false,nativeWebRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function Ge(i){return {adapter:i.adapter,signaling:{...i.signaling},transport:{...i.transport},nativeProtocols:{...i.nativeProtocols},lifecycle:{...i.lifecycle},transfers:{...i.transfers},fallback:{...i.fallback}}}function Be(i=globalThis){let e=Ge(Lt),t=typeof i?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function L(i){return i?.compiled===true&&i.enabled===true}function hn(i,e=false){let t=Ge(Wt),n=i?.transport;return n&&(t.transport.irohQuic=L(n.irohQuic),t.transport.irohLan=L(n.irohLan),t.transport.webRtcUpgrade=L(n.webRtc),t.transport.nativeWebRtc=L(n.webRtc),t.transport.webRtcLan=L(n.webRtcLan),t.transport.moq=L(n.moq),t.transport.ble=L(n.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function fn(i){return {environment:i.adapter==="native-ipc"||i.adapter==="tauri-ipc"?"native":i.adapter==="browser-wasm"?"web":"unknown",transports:{quic:i.transport.irohQuic,irohRelay:i.transport.irohQuic||i.adapter==="browser-wasm",irohLan:i.transport.irohLan,webRtc:i.transport.webRtcUpgrade||i.transport.nativeWebRtc,webRtcLan:i.transport.webRtcLan,moq:i.transport.moq,ble:i.transport.ble},lifecycle:{...i.lifecycle},storage:{localFileSystem:i.transfers.explicitFilePath,transferHistory:i.transfers.history},nativeProtocols:{...i.nativeProtocols}}}function Ue(i){if(i.errorCode)return i;let e=i.error||i.readinessReason;if(!e)return i;let t=c$2(e);return {...i,errorCode:t.errorCode,retryable:t.retryable,errorPlane:t.errorPlane}}function F(i){return !i||typeof i!="object"?{}:i instanceof Map?Object.fromEntries(i):i}function de(i){let e=F(i),t=F(e.device);if(!Object.keys(t).length)return e;let n={...t,...e};return delete n.device,n}function u(i,...e){for(let t of e){let n=i[t];if(typeof n=="string"&&n.trim().length>0)return n}}function D(i,...e){for(let t of e){let n=i[t];if(typeof n=="boolean")return n}}function h(i,...e){for(let t of e){let n=i[t];if(typeof n=="number"&&Number.isFinite(n))return n}}function k(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(i instanceof Date){let e=i.getTime();return Number.isFinite(e)?e:void 0}if(typeof i=="string"){let e=Date.parse(i);return Number.isFinite(e)?e:void 0}if(i&&typeof i=="object"){let e=i;if(typeof e.toMillis=="function"){let n=e.toMillis();return Number.isFinite(n)?n:void 0}let t=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(t!==void 0&&Number.isFinite(t)){let n=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(n)?n:0)/1e6)}}}function le(...i){let e=i.map(k).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function ue(i){if(typeof i!="string")return;let e=i.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function He(i){let e=ue("presenceStatus"in i?i.presenceStatus:void 0),t="presenceUpdatedAt"in i?k(i.presenceUpdatedAt):void 0,n="presenceExpiresAt"in i?k(i.presenceExpiresAt):void 0,r=t??le(i.lastSeenAt,i.updatedAt,i.createdAt),o=n??k(i.expiresAt),s=e;s||(i.online?r!==void 0&&r+3e5<=Date.now()?s="idle":s="online":s="offline");let a=typeof i.ticket=="string"?i.ticket.trim():"",c="connectable"in i&&typeof i.connectable=="boolean"?i.connectable:s==="online"&&a.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:c}}function Ke(i){return p(i)}function G(i,...e){return Ke(u(i,...e))}function z(i){if(!Array.isArray(i))return;let e=Array.from(new Set(i.map(Ke).filter(t=>!!t)));return e.length?e:void 0}function ze(i){let e=F(i),t={webrtc:h(e,"webrtc"),webrtcLan:h(e,"webrtcLan","webrtc_lan"),webrtcTurn:h(e,"webrtcTurn","webrtc_turn"),iroh:h(e,"iroh"),irohLan:h(e,"irohLan","iroh_lan"),irohRelay:h(e,"irohRelay","iroh_relay"),irohWebrtc:h(e,"irohWebrtc","iroh_webrtc"),irohMoq:h(e,"irohMoq","iroh_moq"),ble:h(e,"ble"),moq:h(e,"moq")};return Object.values(t).some(n=>n!==void 0)?t:void 0}function qe(i){return (i.discoveryMode??"space")==="space"&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof i.spaceKey=="string"&&i.spaceKey.trim().length>0}function je(i,e,t){return t?true:(typeof i.appTag=="string"?i.appTag:typeof i.tag=="string"?i.tag:void 0)===e}function pe(i,e){let t=de(i),n=u(t,"deviceId","device_id")||e||"",r=u(t,"nodeId","node_id")||"",o=u(t,"ticket")||"";return {deviceId:n,deviceName:u(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:o,friendTicket:u(t,"friendTicket","friend_ticket"),presenceStatus:ue(u(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:h(t,"presenceUpdatedAt","presence_updated_at")??le(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:h(t,"presenceExpiresAt","presence_expires_at")??k(t.presenceExpiresAt??t.presence_expires_at)??k(t.expiresAt??t.expires_at),connectable:D(t,"connectable"),kind:u(t,"kind"),nodeId:r||void 0,platformType:u(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:u(t,"sessionId","session_id"),userId:u(t,"userId","user_id"),lastSeenAt:t.lastSeenAt??t.last_seen_at,expiresAt:t.expiresAt??t.expires_at,createdAt:t.createdAt??t.created_at,updatedAt:t.updatedAt??t.updated_at,metadata:u(t,"metadata"),excludedPeers:he(t.excludedPeers??t.excluded_peers),availableTransports:z(t.availableTransports??t.available_transports),transports:z(t.transports)}}function he(i){return Array.isArray(i)?i.filter(e=>typeof e=="string"):[]}function Ft(i){let e=He(i);return {...i,...e,connectionStatus:"connectionStatus"in i&&typeof i.connectionStatus=="string"?i.connectionStatus:i.online?"online":"disconnected",settledReady:"settledReady"in i&&typeof i.settledReady=="boolean"?i.settledReady:false,readinessState:"readinessState"in i&&typeof i.readinessState=="string"?i.readinessState:void 0,readinessReason:"readinessReason"in i&&typeof i.readinessReason=="string"?i.readinessReason:void 0,peerHealth:"peerHealth"in i&&typeof i.peerHealth=="string"?i.peerHealth:"unknown",peerId:"peerId"in i&&typeof i.peerId=="string"?i.peerId:void 0,promotionEligible:"promotionEligible"in i&&typeof i.promotionEligible=="boolean"?i.promotionEligible:true,scopes:"scopes"in i?he(i.scopes):[],connectionId:"connectionId"in i&&typeof i.connectionId=="string"?i.connectionId:void 0,deviceIdHint:"deviceIdHint"in i&&typeof i.deviceIdHint=="string"?i.deviceIdHint:void 0,transportStableId:"transportStableId"in i&&typeof i.transportStableId=="number"?i.transportStableId:"transportStableId"in i?i.transportStableId??null:void 0,transportGeneration:"transportGeneration"in i&&typeof i.transportGeneration=="number"?i.transportGeneration:void 0,routeGeneration:"routeGeneration"in i&&typeof i.routeGeneration=="number"?i.routeGeneration:void 0,activeTransport:"activeTransport"in i?i.activeTransport:void 0,parallelTransport:"parallelTransport"in i?i.parallelTransport:void 0,availableTransports:"availableTransports"in i?z(i.availableTransports):"transports"in i?z(i.transports):void 0,latencyMs:"latencyMs"in i&&typeof i.latencyMs=="number"?i.latencyMs:void 0,latencyByTransport:"latencyByTransport"in i?ze(i.latencyByTransport):void 0}}function K(i,e){return e===void 0?true:e===null?i==null:i==null||i===e}function $e(i,e){let t=K(i.connectionId,e.connectionId)&&K(i.nodeId,e.nodeId)&&K(i.transportStableId,e.transportStableId)&&K(i.transportGeneration,e.transportGeneration)&&K(i.routeGeneration,e.routeGeneration),n=(r,o)=>r!==void 0?r:t?o:void 0;return {inheritsSnapshot:t,fields:{connectionId:n(e.connectionId??void 0,i.connectionId),transportStableId:n(e.transportStableId,i.transportStableId),transportGeneration:n(e.transportGeneration,i.transportGeneration),routeGeneration:n(e.routeGeneration,i.routeGeneration),activeTransport:n(e.activeTransport,i.activeTransport),parallelTransport:n(e.parallelTransport,i.parallelTransport),latencyMs:t?i.latencyMs:void 0,latencyByTransport:t?i.latencyByTransport:void 0}}}var Gt={connectionId:void 0,transportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Bt(i,e,t){let n=$e(i,{connectionId:e.activeConnectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):i.promotionEligible??true;if(!r)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:i.scopes,nodeId:e.nodeId===void 0?i.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...n.fields,readinessReason:e.readinessReason??i.readinessReason};let o=e.status??i.connectionStatus,s=typeof o=="string"?o.trim().toLowerCase():"",a=s==="failed"||s==="closed"||s==="disconnected",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,l=i.settledReady===true||i.readinessState==="routable";if(n.inheritsSnapshot&&l&&!a&&!d)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:i.scopes,nodeId:e.nodeId===void 0?i.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...n.fields,readinessReason:e.readinessReason??i.readinessReason};let f=a?false:d,p=d&&!a&&(s==="connecting"||s==="connected")?"connected":o,y=d?"routable":e.readinessState??(n.inheritsSnapshot?i.readinessState:void 0),w=f?e.readinessReason??"peer-session-settled":e.readinessReason??(n.inheritsSnapshot?i.readinessReason:void 0);return {...i,connectionStatus:p,settledReady:f,readinessState:y,readinessReason:w,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:i.scopes,nodeId:e.nodeId===void 0?i.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...n.fields}}function Ut(i,e){let t=$e(i,{connectionId:e.connectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:false,nodeId:e.nodeId??i.nodeId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:i.scopes};let n=e.status??i.connectionStatus,r=typeof n=="string"?n.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",s=i.settledReady===true||i.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&s&&o&&!a)return {...i,peerHealth:i.peerHealth??e.health,peerId:i.peerId??e.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:i.connectionId??e.connectionId,deviceIdHint:i.deviceIdHint??e.deviceIdHint,scopes:i.scopes?.length?i.scopes:e.scopes??i.scopes};if(s&&o)return {...i,connectionStatus:n,settledReady:false,readinessState:void 0,readinessReason:e.error??i.readinessReason,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...Gt,scopes:e.scopes?.length?[...e.scopes]:i.scopes};let c=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&s&&!o&&!c)return {...i,peerHealth:i.peerHealth??e.health,peerId:i.peerId??e.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:i.connectionId??e.connectionId,deviceIdHint:i.deviceIdHint??e.deviceIdHint,transportStableId:i.transportStableId??e.transportStableId,transportGeneration:i.transportGeneration??e.transportGeneration,routeGeneration:i.routeGeneration??e.routeGeneration,activeTransport:i.activeTransport??e.activeTransport,parallelTransport:i.parallelTransport===void 0?e.parallelTransport:i.parallelTransport,scopes:i.scopes?.length?i.scopes:e.scopes??i.scopes};let d=e.transportState==="connected"&&e.health==="healthy",l=o?false:c,f=!o&&(c||d)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":n,p=l?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?i.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=l?(t.inheritsSnapshot?i.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?i.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...i,connectionStatus:f,settledReady:l,readinessState:p,readinessReason:y,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,nodeId:e.nodeId??i.nodeId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:i.scopes}}function Ht(i){let{device:e,session:t=null,peer:n=null,isPromotionEligible:r}=i,o=Ft(e);return t&&(o=Bt(o,t,r)),n&&(o=Ut(o,n)),Ue(o)}function Ye(i){let e=de(i),t=pe(e),n=ue(u(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=He({...t,...n?{presenceStatus:n}:{},presenceUpdatedAt:h(e,"presenceUpdatedAt","presence_updated_at")??le(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:h(e,"presenceExpiresAt","presence_expires_at")??k(e.presenceExpiresAt??e.presence_expires_at)??k(e.expiresAt??e.expires_at),connectable:D(e,"connectable")}),o={...t,...r,connectionStatus:u(e,"connectionStatus","connection_status")||"disconnected",settledReady:D(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,peerHealth:u(e,"peerHealth","peer_health")||"unknown",peerId:u(e,"peerId","peer_id"),scopes:he(e.scopes),connectionId:u(e,"connectionId","connection_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),transportStableId:h(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:h(e,"transportGeneration","transport_generation")??void 0,routeGeneration:h(e,"routeGeneration","route_generation")??void 0,activeTransport:G(e,"activeTransport","active_transport"),parallelTransport:G(e,"parallelTransport","parallel_transport")??null,availableTransports:z(e.availableTransports??e.available_transports),latencyMs:h(e,"latencyMs","latency_ms"),latencyByTransport:ze(e.latencyByTransport??e.latency_by_transport)};return Ht({device:o})}function Xe(i){let e=de(i);return Ue({peerId:u(e,"peerId","peer_id")||"",deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),nodeId:u(e,"nodeId","node_id"),activeConnectionId:u(e,"activeConnectionId","active_connection_id"),candidates:Array.isArray(e.candidates)?e.candidates.filter(t=>typeof t=="string"):Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(t=>typeof t=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(t=>typeof t=="string"):[],status:u(e,"status")||"disconnected",health:u(e,"health")||"unknown",settledReady:D(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,transportStableId:h(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:h(e,"transportGeneration","transport_generation")??void 0,routeGeneration:h(e,"routeGeneration","route_generation")??void 0,activeTransport:G(e,"activeTransport","active_transport"),parallelTransport:G(e,"parallelTransport","parallel_transport")??null,replacementPending:D(e,"replacementPending","replacement_pending")??void 0,lastTransitionAtMs:h(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transitionCount:h(e,"transitionCount","transition_count")??void 0,connectTransitions:h(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:h(e,"replacementCount","replacement_count")??void 0,retireCount:h(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(t=>typeof t=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:u(e,"error"),errorCode:u(e,"errorCode","error_code")??void 0,retryable:D(e,"retryable")??void 0,errorPlane:u(e,"errorPlane","error_plane")??void 0})}function wn(i){let e=F(i);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectTransitions:typeof e.connectTransitions=="number"?e.connectTransitions:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function bn(i){let e=F(i);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function Kt(i){switch(i){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Ve(i){let e=i.activeConnectionId||i.candidates[0]||null;if(!e)return null;let t=Kt(i.status),n=t==="connected"?"connected":t==="connecting"?"connecting":"closed",r=t==="connected"?i.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:i.deviceId??null,deviceIdHint:i.deviceIdHint??null,remoteNodeId:i.nodeId??null,state:t,transportState:n,protocolState:r,routable:!!i.settledReady,readinessState:i.readinessState,readinessReason:i.readinessReason,transportGeneration:i.transportGeneration,routeGeneration:i.routeGeneration,transportStableId:i.transportStableId,activeTransport:i.activeTransport,parallelTransport:i.parallelTransport??null,replacementInProgress:i.replacementPending,lastTransitionAtMs:i.lastTransitionAtMs,transitionCount:i.transitionCount,connectTransitions:i.connectTransitions,replacementCount:i.replacementCount,retireCount:i.retireCount,lastDisconnectReason:i.lastDisconnectReason??void 0,lastReconnectReason:i.lastReconnectReason??void 0,updatedAt:i.lastSeenAtMs,error:i.error??void 0}}function Je(i){let e=F(i),t=u(e,"connectionId","connection_id");if(!t)return null;let n=u(e,"state")||"connecting",r=h(e,"createdAt","created_at")??h(e,"updatedAt","updated_at")??Date.now(),o=h(e,"updatedAt","updated_at")??r;return {connectionId:t,deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),remoteNodeId:u(e,"remoteNodeId","remote_node_id"),state:n,transportState:u(e,"transportState","transport_state")??(n==="connected"?"connected":n==="connecting"?"connecting":"closed"),protocolState:u(e,"protocolState","protocol_state")??(n==="connected"?"routable":n==="connecting"?"connecting":"closed"),routable:D(e,"routable")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transportGeneration:h(e,"transportGeneration","transport_generation")??void 0,routeGeneration:h(e,"routeGeneration","route_generation")??void 0,transportStableId:h(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:G(e,"activeTransport","active_transport"),parallelTransport:G(e,"parallelTransport","parallel_transport")??null,replacementInProgress:D(e,"replacementInProgress","replacement_in_progress")??void 0,lastTransitionAtMs:h(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:h(e,"transitionCount","transition_count")??void 0,connectTransitions:h(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:h(e,"replacementCount","replacement_count")??void 0,retireCount:h(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:u(e,"error")??void 0,createdAt:r,updatedAt:o}}function Qe(i,e){return i?i.connectionId===e.connectionId&&(i.deviceId??null)===(e.deviceId??null)&&(i.deviceIdHint??null)===(e.deviceIdHint??null)&&(i.remoteNodeId??null)===(e.remoteNodeId??null)&&i.state===e.state&&(i.transportState??null)===(e.transportState??null)&&(i.protocolState??null)===(e.protocolState??null)&&!!i.routable==!!e.routable&&(i.activeTransport??null)===(e.activeTransport??null)&&(i.parallelTransport??null)===(e.parallelTransport??null)&&(i.transportStableId??null)===(e.transportStableId??null)&&(i.transportGeneration??null)===(e.transportGeneration??null)&&(i.routeGeneration??null)===(e.routeGeneration??null)&&!!i.replacementInProgress==!!e.replacementInProgress&&(i.transitionCount??null)===(e.transitionCount??null)&&(i.connectTransitions??null)===(e.connectTransitions??null)&&(i.replacementCount??null)===(e.replacementCount??null)&&(i.retireCount??null)===(e.retireCount??null)&&(i.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(i.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(i.error??null)===(e.error??null):false}function zt(i){try{let e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(n,"base64").toString("utf8"))}catch{return null}return null}function qt(i){let e=typeof i=="string"?i.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,o=r?zt(r):null,s=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,a=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:Z(n),tokenFingerprint:Z(s),tokenSuffixFingerprint:Z(r),scope:a,maxConnections:c}}function q(i,e,t={}){let n=typeof i.finishSend=="function"?i.finishSend.bind(i):typeof i.finish_send=="function"?i.finish_send.bind(i):null;if(!n){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();return new WritableStream({write:o=>r.write(o),async close(){await r.close(),await n();},abort:o=>r.abort(o)})}var m=class m{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.coordinationHostAvailability={available:true,reason:"initial"};this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;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;if(this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.nativeTrustTokens=this.options.coordinationGateway?new Q(this.options.coordinationGateway.nativeTrustTokenProvider):null,this.presenceManager=new ee({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(n,r)=>this.waitForWasmClient(n,r),warnMissingWasmOnce:n=>this.warnMissingWasmOnce(n),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(n,r)=>this.withWebPresenceMetadata(n,r),updatePresence:(n,r,o,s,a,c)=>this.updatePresence(n,r,o,s,a,c),updateExcludedPeers:(n,r)=>this.getCoordinationSignaling().updateDevice(n,{excludedPeers:r}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:n=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(n)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:this.options.coordinationRoomGossipFanout===true}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let t=M();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(n=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(s=>s(this.toRuntimeIdentity(n)));return}let r=n?.uid??null,o=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=r,o&&o!==r&&this.stopAuthActivity({userId:o}),this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(s=>s(this.toRuntimeIdentity(n)));});}get tag(){return this.appTag}capabilities(){return Be()}getDeviceIdentityStorageKey(){let e=f$1(this.options);return `${m.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 n=this.getDeviceIdentityStorageKey(),r=Date.now(),o=null;try{let l=localStorage.getItem(n);o=l?JSON.parse(l):null;}catch{o=null;}let s=typeof o?.deviceId=="string"?o.deviceId.trim():"",a=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let l=s||this.createRandomDeviceId();return localStorage.setItem(n,JSON.stringify({deviceId:l})),l}if(s&&typeof a=="number"&&a>r){let l=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:s,expiresAt:l})),s}let c=this.createRandomDeviceId(),d=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:c,expiresAt:d})),c}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(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');if(!this.options.coordinationGateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");return this.browserCoordinationSignaling||(this.browserCoordinationSignaling=new J({projectId:this.options.projectId,gateway:this.options.coordinationGateway,appTag:this.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(e=false)=>{let t=this.currentUser;return t?.getToken?t.getToken(e):null},getAppCheckToken:async(e=false)=>{let t=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return t?t(e):M().getAppCheckToken(e)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t),avenueOverride:this.options.coordinationAvenueOverride,nativeTrustTokens:this.nativeTrustTokens}),this.browserCoordinationSignaling.setHostAvailability?.(this.coordinationHostAvailability)),this.browserCoordinationSignaling}usesCoordinationGateway(){return !!this.options.coordinationGateway}setCoordinationHostAvailability(e){this.coordinationHostAvailability=e,this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){await this.browserCoordinationSignaling?.reconnectAfterHostResume?.();}async getCoordinationNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateCoordinationNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeCoordinationNativeTrustToken(e,t){return this.nativeTrustTokens?this.nativeTrustTokens.subscribe(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,n){let r=this.getCoordinationSignaling();if(!r.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await r.joinCoordinationRoom(e,t,n);}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 n=this.getCoordinationSignaling();if(!n.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return n.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let n;if(!e||!e.trim())n=JSON.stringify({deviceId:t});else {try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return n=JSON.stringify({...r,deviceId:t}),await ae(n)??n}catch{}n=JSON.stringify({deviceId:t,metadata:e});}return await ae(n)??n}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,n=this.authContext?.userId??null,r=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(te()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&n!==r&&await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await M().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,n=this.authContext?.token,r=typeof n=="string"&&n.trim().length>0?n:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===r)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=r,this.hasSyncedAuthToWasmClient=true,r===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,r);}}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 qe(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 je(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){xe("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(n){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",n);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),n=t?.__initPersistentIrohProtocols;if(typeof n!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await n.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,n){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(n))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,n){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(n));}async putPersistentIrohBytes(e,t,n){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,n)}async setPersistentIrohHash(e,t,n,r){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,n,BigInt(r))}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 n=Date.now();for(;!this.wasmClient&&Date.now()-n<e;)await e$1(t);return this.wasmClient??null}normalizeDevice(e,t){return pe(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return Ye(e)}normalizePeerSessionSnapshot(e){return Xe(e)}toBackendConnectionStateFromPeerSession(e){return Ve(e)}normalizeStateSnapshot(e){return Je(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 Qe(e,t)}deliverConnectionState(e,t,n,r){let o=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(o),this.lastDeliveredConnectionStates.set(o.connectionId,o);let a=(r??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(a,o)||(r&&r.set(o.connectionId,o),t(o));}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(n=false)=>{if(e&&(!n||!t))return e;if(t)try{let o=await t(n);if(o)return o}catch{}let r=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(r&&r.uid===this.authContext?.userId)try{return await r.getIdToken(n)}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 M().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await M().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 M().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await M().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,n=true,r=3e5,o,s){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?m.EPHEMERAL_DEVICE_ID_TTL_MS:r,d=await this.withWebPresenceMetadata(o,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:d,deviceName:s?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,n,c,d,s);}async refreshLivePresence(e,t,n,r){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),s=await this.withWebPresenceMetadata(n,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:s,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,s,r);}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,n,r){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,n,r)}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(),n=this.wasmClient;return Promise.all(t.map(async r=>{let o=this.normalizeDeviceStatusSnapshot({...r,connectionStatus:r.online?"online":"disconnected"}),s=typeof r.nodeId=="string"?r.nodeId.trim():"";if(!s||typeof n?.iroh_path_kind!="function"||typeof n?.iroh_transport_rtt_ms!="function")return o;try{let[a,c]=await Promise.all([n.iroh_path_kind(s),n.iroh_transport_rtt_ms(s)]);if(typeof c!="number"||!Number.isFinite(c))return o;let d=Math.max(0,Math.round(c)),l={};if(a==="direct-lan")l.irohLan=d;else if(a==="direct-quic")l.iroh=d;else if(a==="ble")l.ble=d;else if(a==="relay")l.irohRelay=d;else if(a==="iroh-webrtc")l.irohWebrtc=d;else if(a==="iroh-moq")l.irohMoq=d;else return o;return {...o,latencyMs:d,latencyByTransport:l}}catch(a){return b("[WasmBridge] iroh transport latency unavailable",{deviceId:r.deviceId,error:a instanceof Error?a.message:String(a)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let n=await t.peer_session(e);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}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(r=>this.normalizePeerSessionSnapshot(r)).filter(r=>!!(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId||r.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.wait_for_peer=="function"){let r=await n.wait_for_peer(e,t);return !r||typeof r!="object"?null:this.normalizePeerSessionSnapshot(r)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_bi=="function"){let r=await n.open_peer_bi(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:r.recv,writable:q(r,r.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,n){let r=await this.waitForWasmClient(500),o=r&&r.open_peer_native_bi;if(typeof o=="function"){let s=await o.call(r,e,t,n);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:s.recv,writable:q(s,s.send)}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_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 n=await this.waitForWasmClient(500),r=n&&typeof n.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!n,hasTransportOnly:r,timeoutMs:t}),r){let o=await n.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:q(o,o.send)}}return console.debug("[WasmBridge] openPeerBiRaw falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_uni=="function"){let r=await n.open_peer_uni(e,t),o=r?.writable??r;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:q(r,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let n=await t.resolve_peer_connection_records(e);return (Array.isArray(n)?n:[]).map(r=>({connectionId:typeof r.connectionId=="string"?r.connectionId:"",nodeId:typeof r.nodeId=="string"?r.nodeId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,endpointId:typeof r.endpointId=="string"?r.endpointId:null,transportGeneration:typeof r.transportGeneration=="number"?r.transportGeneration:0,routeGeneration:typeof r.routeGeneration=="number"?r.routeGeneration:void 0,transportStableId:typeof r.transportStableId=="number"?r.transportStableId:null,transportSource:typeof r.transportSource=="string"?r.transportSource:null,lastTransportChangeAtMs:typeof r.lastTransportChangeAtMs=="number"?r.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof r.lastRouteChangeAtMs=="number"?r.lastRouteChangeAtMs:void 0,state:typeof r.state=="string"?r.state:"pending",statusReason:typeof r.statusReason=="string"?r.statusReason:null,createdAtMs:typeof r.createdAtMs=="number"?r.createdAtMs:0,updatedAtMs:typeof r.updatedAtMs=="number"?r.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let n=r=>{if(!r||typeof r!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=r;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let r=await t.peer_session(e),o=n(r);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return n(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)}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 n=this.authScopedRuntimeGeneration;try{let r=await this.waitForWasmClient();if(n!==this.authScopedRuntimeGeneration||!r||typeof r.start_auto_connect!="function")return;await r.start_auto_connect(e,t),n===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(r){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:r});}}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(n){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:n?.message??String(n)}),n}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}setCoreClient(e){e&&typeof e.connect=="function"?(this.coreClient=e,this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,n=this.onStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(n).then(r=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){r();return}this.applicationRouteEscalationUnsubscribe=r,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.readinessReason==="application-crypto-key-pending"||e.readinessReason==="application-crypto-confirmation-pending",n=t?[e.transportGeneration??0,e.routeGeneration??0,e.readinessReason].join(":"):null,r=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(n&&r.get(e.connectionId)===n||this.applicationRouteEscalations.has(e.connectionId)||!t&&e.remoteNodeId&&this.coreClient.hasApplicationRouteForPeer?.(e.connectionId,e.remoteNodeId)===true)return;let o=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!o?.ticket)return;let s=this.authScopedRuntimeGeneration,a=this.coreClient;n&&r.set(e.connectionId,n);let c;c=(async()=>{let d=typeof a.ensureManagedApplicationRoute=="function"?await a.ensureManagedApplicationRoute({ticket:o.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??o.nodeId,expectedDeviceId:o.deviceId,timeoutMs:2e4}):await a.connect(o.ticket,2e4,o.deviceId,void 0,{admissionAlreadyPresented:true});if(s!==this.authScopedRuntimeGeneration)return;let l=d,f=l.id?.trim()||e.connectionId,p=l.remoteNodeId?.trim()||e.remoteNodeId?.trim()||l.deviceId?.trim()||o.deviceId;if(a.hasApplicationRouteForPeer?.(f,p)!==true&&a.hasApplicationRouteForPeer?.(f,p)!==true)throw new Error(`application crypto was not ready for ${p}`)})().catch(d=>{s===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:o.deviceId,remoteNodeId:e.remoteNodeId??o.nodeId,error:d?.message??String(d)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===c){this.applicationRouteEscalations.delete(e.connectionId);let d=this.lastDeliveredConnectionStates?.get(e.connectionId);d&&s===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(d));}}),this.applicationRouteEscalations.set(e.connectionId,c);}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 n=Date.now();c$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:qt(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);c$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,elapsedMs:Date.now()-n});let o=e.endpointTicket;if(o&&this.coreClient){let s=this.coreClient;try{c$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null});let a=typeof s.ensureManagedApplicationRoute=="function"?await s.ensureManagedApplicationRoute({ticket:o,connectionId:r?.connectionId??null,remoteNodeId:r?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:r?.approvedScope??null,timeoutMs:2e4}):await s.connect(o,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0,approvedScope:r?.approvedScope??null}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",d=typeof a?.deviceId=="string"?a.deviceId.trim():"",l=c||r?.remoteNodeId?.trim?.()||d||e.deviceId?.trim?.()||"",f=typeof s.hasApplicationRouteForPeer=="function"?s.hasApplicationRouteForPeer.bind(s):null;if(!(!!l&&f?.(a?.id??void 0,l)===!0)&&l&&typeof s.waitForApplicationCryptoForPeer=="function"&&!(!!await s.waitForApplicationCryptoForPeer(l,2e4)&&(!f||f(a?.id??void 0,l)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:l,elapsedMs:Date.now()-n}),Object.assign(new Error(`application crypto was not ready for ${l}`),{applicationCryptoNotReady:!0});c$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,elapsedMs:Date.now()-n});}catch(a){if(a?.applicationCryptoNotReady)throw a;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,error:a?.message??String(a)}),r}}return r}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,n,r,o){this.presenceManager.startPresenceLoop(e,t,n,r,o);}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(n=>(this.cachedSpaceNamespaceId=n,n)).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 n={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(n);}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"&&await t.is_connected(e)?true:this.hasConnectedIndependentPeerRoute(t,e)}async hasConnectedIndependentPeerRoute(e,t){if(!e||typeof t!="string"||t.trim().length===0)return false;let n=t.trim(),r=[];if(typeof e.peer_session=="function")try{let o=await e.peer_session(n);o&&typeof o=="object"&&r.push(this.normalizePeerSessionSnapshot(o));}catch{}if(typeof e.peer_sessions=="function")try{let o=await e.peer_sessions();Array.isArray(o)&&r.push(...o.filter(s=>!!s&&typeof s=="object").map(s=>this.normalizePeerSessionSnapshot(s)));}catch{}return r.some(o=>{let s=typeof o.peerId=="string"?o.peerId.trim():"",a=typeof o.deviceId=="string"?o.deviceId.trim():"",c=typeof o.deviceIdHint=="string"?o.deviceIdHint.trim():"",d=typeof o.nodeId=="string"?o.nodeId.trim():"";return (n===s||n===a||n===c||n===d)&&o.status==="connected"&&o.settledReady===true&&o.replacementPending!==true&&w(o.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let r=await e.connection_states(),o=(Array.isArray(r)?r:[]).map(s=>this.normalizeStateSnapshot(s)).filter(s=>!!s);return o.length>0&&b("[WasmBridge] replaying current wasm connection states",o.map(s=>({connectionId:s.connectionId,deviceId:s.deviceId??null,deviceIdHint:s.deviceIdHint??null,remoteNodeId:s.remoteNodeId??null,state:s.state,transportState:s.transportState??null,protocolState:s.protocolState??null,routable:s.routable??null}))),o}let n=(await this.listPeerSessions().catch(()=>[])).map(r=>this.toBackendConnectionStateFromPeerSession(r)).filter(r=>!!r);return n.length>0&&b("[WasmBridge] replaying current wasm connection states",n.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),n}onStateChange(e){let t=new Map,n=new Map,r=this.authScopedRuntimeGeneration,o=false,s=d=>{let l=d.detail,f=this.normalizeStateSnapshot(l),p=typeof l?.connectionId=="string"?l.connectionId.trim():"";if(!p||o)return;if(f&&(f.state==="closed"||f.state==="failed"||f.state==="disconnected")){this.deliverConnectionState(f,e,"rust-event-detail",t);return}let y=(n.get(p)??0)+1;n.set(p,y);let w=this.authScopedRuntimeGeneration;(async()=>{let C=await this.waitForWasmClient(500);if(!(o||w!==this.authScopedRuntimeGeneration||n.get(p)!==y)){if(C&&typeof C.connection_state=="function"){let re=await C.connection_state(p),b=this.normalizeStateSnapshot(re);if(!o&&w===this.authScopedRuntimeGeneration&&n.get(p)===y&&b){this.deliverConnectionState(b,e,"rust-event",t);return}}!o&&w===this.authScopedRuntimeGeneration&&n.get(p)===y&&f&&this.deliverConnectionState(f,e,"rust-event-detail",t);}})().catch(C=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:p,error:C});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",s),this.getConnectionStates().then(d=>{!o&&r===this.authScopedRuntimeGeneration&&d.forEach(l=>{n.has(l.connectionId)||this.deliverConnectionState(l,e,"replay",t);});}).catch(d=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",d);}),()=>{o=true,n.clear(),c&&a.removeEventListener("connection-state-changed",s);}}async sendExplicitFilePath(e,t,n=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let n=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(s=>s.trim().length>0)?.trim()??"";if(!n||n==="."||n==="..")return m.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let s of n){if([...r].length>=m.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=s.charCodeAt(0);s==="/"||s==="\\"||s==="\0"||a<32||a===127?r+="_":r+=s;}let o=r.trim();return !o||o==="."||o===".."?m.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return m.FALLBACK_EXPLICIT_MIME_TYPE;let n="";for(let r of t){if(n.length>=m.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=r.charCodeAt(0);o<33||o>126||r==='"'||r==="\\"?n+="_":n+=r;}return n.length>0?n:m.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>m.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 n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,n,r,o){let s=o?.headerFrame===true?4:0,a=new Uint8Array(25+s+r.byteLength);a[0]=m.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,n,false);let d=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,r.byteLength,false),a.set(r,d),a}async sendExplicitFileData(e){let t=e.connection,n=e.file,r=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!r)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let s=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(c$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:n.name,fileSize:n.size,transferId:s}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let d=await this.waitForWasmClient();if(!d)throw new Error("WASM explicit transfer requires an initialized WASM client");let l=new TextEncoder,f={transfer_id:s,filename:this.sanitizeExplicitFileName(n.name),size:n.size,mime_type:this.sanitizeExplicitMimeType(n.type)},p=l.encode(JSON.stringify(f));this.assertExplicitTransferHeaderSize(p);let y=new Uint8Array(4);new DataView(y.buffer).setUint32(0,p.byteLength,false);let w=new Uint8Array(y.byteLength+p.byteLength);w.set(y,0),w.set(p,y.byteLength);let C=async()=>{if(a!=="web"||!t||typeof t.sendOnWebRTC!="function"||typeof t.isWebRtcApplicationRouteReady!="function"||t.isWebRtcApplicationRouteReady()!==true)return a&&a!=="web"&&typeof t?.isWebRtcApplicationRouteReady=="function"&&t.isWebRtcApplicationRouteReady()===true&&c$1("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:c,transferId:s,receiverPlatformType:a}),false;let b=r?z$1(r):null,_=O=>b?b.protectFrame(O):O,T=new Uint8Array(await n.arrayBuffer()),E=this.createWebRTCExplicitTransferId(),N=Math.max(1,Math.ceil(T.byteLength/m.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),I=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,x=async()=>{I&&typeof I.getBufferedAmount=="function"&&typeof I.waitForDrain=="function"&&I.getBufferedAmount()>m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await I.waitForDrain(m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,4294967295,N,_(p),{headerFrame:true})),await x(),T.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,0,N,_(new Uint8Array(0)))),true;let j=0;for(let O=0;O<T.byteLength;O+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let et=T.slice(O,Math.min(O+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,T.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,j,N,_(et))),j+=1,await x();}return c$1("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:s,chunks:N,encrypted:!!b}),true},re=async()=>{let b=d.open_peer_bi_explicit_file_sender;if(typeof b!="function")return false;let _=await b.call(d,c,5e3),T=_?.writable??_?.send;if(!T||typeof T.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");c$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:_.applicationCryptoWrapped===true});let E=q(_,T,{requireFinish:true}).getWriter(),N=false;try{await E.write(w);let I=new Uint8Array(await n.arrayBuffer());for(let x=0;x<I.byteLength;x+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let j=I.slice(x,Math.min(x+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await E.write(j);}}catch(I){throw N=true,I}finally{try{await E.close();}catch(I){if(!N)throw I}finally{E.releaseLock();}}return true};try{try{if(await C())return}catch(b){c$1("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:s,error:b instanceof Error?b.message:String(b)});}if(await re())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{c$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:s,fileName:n.name,fileSize:n.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);}};m.EXPLICIT_FILE_PROTOCOL_TYPE=2,m.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,m.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,m.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",m.MAX_EXPLICIT_FILE_NAME_CHARS=180,m.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",m.MAX_EXPLICIT_MIME_TYPE_CHARS=255,m.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",m.EPHEMERAL_DEVICE_ID_TTL_MS=ce.browserIdentity.ephemeralDeviceIdTtlMs;var Ze=m;
|
|
2
|
-
export{M as a,te as b,sn as c,an as d,cn as e,dn as f,ae as g,xt as h,xe as i,de as j,Ht as k,Ye as l,Xe as m,wn as n,bn as o,Je as p,ce as q,un as r,Lt as s,Wt as t,Ge as u,Be as v,hn as w,fn as x,Ne as y,Ze as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-KRJECX7X.js';import {t}from'./chunk-XAL4T6TB.js';import'./chunk-HUG5AX7R.js';import'./chunk-DUY34MGT.js';import'./chunk-R35AWMNY.js';import'./chunk-Z2IS6NH2.js';import'./chunk-AJQVMVYW.js';import {a}from'./chunk-WA434EWD.js';import'./chunk-HEAJ7ZUR.js';import'./chunk-7BJKDBLP.js';import'./chunk-2L6ULC32.js';import'./chunk-2SUSPEC4.js';function c(i,r){let t$1=a(i);return a$1(t$1,new t({...t$1,bridge:r}))}export{c as createIpcClient};
|
package/dist/openrtc-4EZPCHWM.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var q=class b{static __wrap(t){let e=Object.create(b.prototype);return e.__wbg_ptr=t,$.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,$.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_bistream_free(t,0);}get applicationCryptoWrapped(){return n.bistream_applicationCryptoWrapped(this.__wbg_ptr)!==0}get endpoint_id(){let t,e;try{let o=n.__wbindgen_add_to_stack_pointer(-16);n.bistream_endpoint_id(o,this.__wbg_ptr);var _=x().getInt32(o+0,!0),r=x().getInt32(o+4,!0);return t=_,e=r,I(_,r)}finally{n.__wbindgen_add_to_stack_pointer(16),n.__wbindgen_export4(t,e,1);}}finishSend(){let t=n.bistream_finishSend(this.__wbg_ptr);return p(t)}get recv(){let t=n.bistream_recv(this.__wbg_ptr);return p(t)}get send(){let t=n.bistream_send(this.__wbg_ptr);return p(t)}};Symbol.dispose&&(q.prototype[Symbol.dispose]=q.prototype.free);var L=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Rt.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_intounderlyingbytesource_free(t,0);}get autoAllocateChunkSize(){return n.intounderlyingbytesource_autoAllocateChunkSize(this.__wbg_ptr)>>>0}cancel(){let t=this.__destroy_into_raw();n.intounderlyingbytesource_cancel(t);}pull(t){let e=n.intounderlyingbytesource_pull(this.__wbg_ptr,g(t));return p(e)}start(t){n.intounderlyingbytesource_start(this.__wbg_ptr,g(t));}get type(){let t=n.intounderlyingbytesource_type(this.__wbg_ptr);return mt[t]}};Symbol.dispose&&(L.prototype[Symbol.dispose]=L.prototype.free);var N=class b{static __wrap(t){let e=Object.create(b.prototype);return e.__wbg_ptr=t,K.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,K.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_intounderlyingsink_free(t,0);}abort(t){let e=this.__destroy_into_raw(),_=n.intounderlyingsink_abort(e,g(t));return p(_)}close(){let t=this.__destroy_into_raw(),e=n.intounderlyingsink_close(t);return p(e)}write(t){let e=n.intounderlyingsink_write(this.__wbg_ptr,g(t));return p(e)}};Symbol.dispose&&(N.prototype[Symbol.dispose]=N.prototype.free);var O=class b{static __wrap(t){let e=Object.create(b.prototype);return e.__wbg_ptr=t,J.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,J.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_intounderlyingsource_free(t,0);}cancel(){let t=this.__destroy_into_raw();n.intounderlyingsource_cancel(t);}pull(t){let e=n.intounderlyingsource_pull(this.__wbg_ptr,g(t));return p(e)}};Symbol.dispose&&(O.prototype[Symbol.dispose]=O.prototype.free);var B=class b{static __wrap(t){let e=Object.create(b.prototype);return e.__wbg_ptr=t,Y.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Y.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_peerunistream_free(t,0);}get applicationCryptoWrapped(){return n.peerunistream_applicationCryptoWrapped(this.__wbg_ptr)!==0}finishSend(){let t=n.peerunistream_finishSend(this.__wbg_ptr);return p(t)}get writable(){let t=n.peerunistream_writable(this.__wbg_ptr);return p(t)}};Symbol.dispose&&(B.prototype[Symbol.dispose]=B.prototype.free);var U=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Q.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_wasmclient_free(t,0);}__acknowledgePersistentIrohOutbox(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient___acknowledgePersistentIrohOutbox(this.__wbg_ptr,e,_);return p(r)}__advancePreferredIrohCarrier(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(_,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=n.wasmclient___advancePreferredIrohCarrier(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}__attachIrohMoqCarrier(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(r,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=n.wasmclient___attachIrohMoqCarrier(this.__wbg_ptr,o,a,w,d,g(_),l,f);return p(m)}__attachIrohWebRtcCarrier(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(r,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=n.wasmclient___attachIrohWebRtcCarrier(this.__wbg_ptr,o,a,w,d,g(_),l,f);return p(m)}__beginIrohMoqCarrier(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=n.wasmclient___beginIrohMoqCarrier(this.__wbg_ptr,r,o,a,w,_);return p(d)}__beginIrohWebRtcCarrier(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=n.wasmclient___beginIrohWebRtcCarrier(this.__wbg_ptr,r,o,a,w,_);return p(d)}__beginPreferredIrohCarrier(t,e,_,r,o,a){let w=c(t,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(e,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=n.wasmclient___beginPreferredIrohCarrier(this.__wbg_ptr,w,d,l,f,_,r,o,a);return p(m)}__configureIrohMoqCarrier(t,e){var _=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),r=i;let o=n.wasmclient___configureIrohMoqCarrier(this.__wbg_ptr,t,_,r);return p(o)}__configureIrohRoutePolicy(t,e,_){var r=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),o=i;let a=n.wasmclient___configureIrohRoutePolicy(this.__wbg_ptr,t,r,o,g(_));return p(a)}__configureIrohWebRtcCarrier(t,e){let _=n.wasmclient___configureIrohWebRtcCarrier(this.__wbg_ptr,t,e);return p(_)}__createPersistentIrohNamespace(t,e){let _=n.wasmclient___createPersistentIrohNamespace(this.__wbg_ptr,t,e);return p(_)}__deletePersistentIrohPrefix(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=k(e,n.__wbindgen_export),a=i,w=n.wasmclient___deletePersistentIrohPrefix(this.__wbg_ptr,_,r,o,a);return p(w)}__flushPersistentIrohProtocols(){let t=n.wasmclient___flushPersistentIrohProtocols(this.__wbg_ptr);return p(t)}__handleIrohCarrierControl(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=n.wasmclient___handleIrohCarrierControl(this.__wbg_ptr,r,o,a,w,g(_));return p(d)}__hydratePersistentIrohBlob(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient___hydratePersistentIrohBlob(this.__wbg_ptr,e,_);return p(r)}__importPersistentIrohAuthor(t){let e=k(t,n.__wbindgen_export),_=i,r=n.wasmclient___importPersistentIrohAuthor(this.__wbg_ptr,e,_);return p(r)}__importPersistentIrohNamespace(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=k(e,n.__wbindgen_export),d=i,l=n.wasmclient___importPersistentIrohNamespace(this.__wbg_ptr,o,a,w,d,_,r);return p(l)}__importPersistentIrohTicket(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=n.wasmclient___importPersistentIrohTicket(this.__wbg_ptr,r,o,e,_);return p(a)}__initPersistentIrohProtocols(t){let e=n.wasmclient___initPersistentIrohProtocols(this.__wbg_ptr,g(t));return p(e)}__irohMoqCarrierFailed(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(_,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=n.wasmclient___irohMoqCarrierFailed(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}__irohMoqCarrierPrepared(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient___irohMoqCarrierPrepared(this.__wbg_ptr,_,r,o,a);return p(w)}__irohWebRtcCarrierFailed(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(_,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=n.wasmclient___irohWebRtcCarrierFailed(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}__irohWebRtcCarrierPrepared(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient___irohWebRtcCarrierPrepared(this.__wbg_ptr,_,r,o,a);return p(w)}__putPersistentIrohBytes(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=k(e,n.__wbindgen_export),w=i,d=k(_,n.__wbindgen_export),l=i,f=n.wasmclient___putPersistentIrohBytes(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}__queryPersistentIrohNamespace(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=k(e,n.__wbindgen_export),a=i,w=n.wasmclient___queryPersistentIrohNamespace(this.__wbg_ptr,_,r,o,a);return p(w)}__removePersistentIrohNamespace(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=n.wasmclient___removePersistentIrohNamespace(this.__wbg_ptr,r,o,e,_);return p(a)}__retireIrohMoqCarrier(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i;var o=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i;let w=n.wasmclient___retireIrohMoqCarrier(this.__wbg_ptr,_,r,o,a);return p(w)}__retireIrohWebRtcCarrier(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i;var o=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i;let w=n.wasmclient___retireIrohWebRtcCarrier(this.__wbg_ptr,_,r,o,a);return p(w)}__setIrohCarrierActionHandler(t){n.wasmclient___setIrohCarrierActionHandler(this.__wbg_ptr,u(t)?0:g(t));}__setPersistentIrohHash(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=k(e,n.__wbindgen_export),d=i,l=c(_,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=n.wasmclient___setPersistentIrohHash(this.__wbg_ptr,o,a,w,d,l,f,r);return p(m)}__sharePersistentIrohNamespace(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient___sharePersistentIrohNamespace(this.__wbg_ptr,_,r,e);return p(o)}__shutdownPersistentIrohProtocols(){let t=n.wasmclient___shutdownPersistentIrohProtocols(this.__wbg_ptr);return p(t)}add_peer_scope(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_add_peer_scope(this.__wbg_ptr,_,r,o,a);return p(w)}bind_connection_device_id(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_bind_connection_device_id(this.__wbg_ptr,_,r,o,a);return p(w)}bind_node_device_id(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_bind_node_device_id(this.__wbg_ptr,_,r,o,a);return p(w)}clearConnectionApplicationCryptoKey(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i;n.wasmclient_clearConnectionApplicationCryptoKey(this.__wbg_ptr,e,_);}clearIdentityCredential(){n.wasmclient_clearIdentityCredential(this.__wbg_ptr);}clear_session_tokens(){n.wasmclient_clear_session_tokens(this.__wbg_ptr);}confirm_reciprocal_admission(t,e,_,r,o,a){let w=c(t,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(_,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=c(r,n.__wbindgen_export,n.__wbindgen_export2),y=i;var v=u(a)?0:c(a,n.__wbindgen_export,n.__wbindgen_export2),R=i;let S=n.wasmclient_confirm_reciprocal_admission(this.__wbg_ptr,w,d,e,l,f,m,y,o,v,R);return p(S)}connect(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_connect(this.__wbg_ptr,e,_);return p(r)}connect_device(t,e){var _=u(t)?0:c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i;let o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_connect_device(this.__wbg_ptr,_,r,o,a);return p(w)}connection_state(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_connection_state(this.__wbg_ptr,e,_);return p(r)}connection_states(){let t=n.wasmclient_connection_states(this.__wbg_ptr);return p(t)}create_room(t,e,_,r,o,a){let w=c(t,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(e,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=c(_,n.__wbindgen_export,n.__wbindgen_export2),y=i,v=c(r,n.__wbindgen_export,n.__wbindgen_export2),R=i,S=c(o,n.__wbindgen_export,n.__wbindgen_export2),E=i,V=n.wasmclient_create_room(this.__wbg_ptr,w,d,l,f,m,y,v,R,S,E,u(a)?Number.MAX_SAFE_INTEGER:a>>>0);return p(V)}create_session(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_create_session(this.__wbg_ptr,e,_);return p(r)}delete_device(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_delete_device(this.__wbg_ptr,_,r,o,a);return p(w)}devices_with_status(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_devices_with_status(this.__wbg_ptr,e,_);return p(r)}disconnect(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_disconnect(this.__wbg_ptr,e,_);return p(r)}disconnect_device(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i;var o=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i;let w=n.wasmclient_disconnect_device(this.__wbg_ptr,_,r,o,a);return p(w)}disconnect_transient(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_disconnect_transient(this.__wbg_ptr,e,_);return p(r)}endpoint_id_from_ticket(t){let e,_;try{let f=n.__wbindgen_add_to_stack_pointer(-16),m=c(t,n.__wbindgen_export,n.__wbindgen_export2),y=i;n.wasmclient_endpoint_id_from_ticket(f,this.__wbg_ptr,m,y);var r=x().getInt32(f+0,!0),o=x().getInt32(f+4,!0),a=x().getInt32(f+8,!0),w=x().getInt32(f+12,!0),d=r,l=o;if(w)throw d=0,l=0,p(a);return e=d,_=l,I(d,l)}finally{n.__wbindgen_add_to_stack_pointer(16),n.__wbindgen_export4(e,_,1);}}endpoint_ticket(){let t=n.wasmclient_endpoint_ticket(this.__wbg_ptr);return p(t)}endpoint_ticket_with_token(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_endpoint_ticket_with_token(this.__wbg_ptr,_,r,e);return p(o)}force_reconnect_snapshot(){n.wasmclient_force_reconnect_snapshot(this.__wbg_ptr);}get_members(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(_,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=n.wasmclient_get_members(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}incoming_streams(){let t=n.wasmclient_incoming_streams(this.__wbg_ptr);return p(t)}initIrohWithTestRelay(t,e){var _=u(t)?0:k(t,n.__wbindgen_export),r=i,o=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i;let w=n.wasmclient_initIrohWithTestRelay(this.__wbg_ptr,_,r,o,a);return p(w)}init_iroh(t){var e=u(t)?0:k(t,n.__wbindgen_export),_=i;let r=n.wasmclient_init_iroh(this.__wbg_ptr,e,_);return p(r)}iroh_path_kind(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_iroh_path_kind(this.__wbg_ptr,e,_);return p(r)}iroh_secret_key(){let t=n.wasmclient_iroh_secret_key(this.__wbg_ptr);return p(t)}iroh_transport_rtt_ms(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_iroh_transport_rtt_ms(this.__wbg_ptr,e,_);return p(r)}is_auto_connect_excluded(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i;return n.wasmclient_is_auto_connect_excluded(this.__wbg_ptr,e,_)!==0}is_connected(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_is_connected(this.__wbg_ptr,e,_);return p(r)}is_current_transport_stable_id(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_is_current_transport_stable_id(this.__wbg_ptr,_,r,e);return p(o)}is_remote_admitted(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_is_remote_admitted(this.__wbg_ptr,e,_);return p(r)}join_room(t,e,_,r,o){let a=c(t,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(e,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=c(_,n.__wbindgen_export,n.__wbindgen_export2),m=i,y=c(r,n.__wbindgen_export,n.__wbindgen_export2),v=i,R=c(o,n.__wbindgen_export,n.__wbindgen_export2),S=i,E=n.wasmclient_join_room(this.__wbg_ptr,a,w,d,l,f,m,y,v,R,S);return p(E)}leave_room(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(_,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=n.wasmclient_leave_room(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}list_managed_connections(){let t=n.wasmclient_list_managed_connections(this.__wbg_ptr);return p(t)}constructor(t){try{let o=n.__wbindgen_add_to_stack_pointer(-16),a=c(t,n.__wbindgen_export,n.__wbindgen_export2),w=i;n.wasmclient_new(o,a,w);var e=x().getInt32(o+0,!0),_=x().getInt32(o+4,!0),r=x().getInt32(o+8,!0);if(r)throw p(_);return this.__wbg_ptr=e,Q.register(this,this.__wbg_ptr,this),this}finally{n.__wbindgen_add_to_stack_pointer(16);}}node_addr(){let t=n.wasmclient_node_addr(this.__wbg_ptr);return p(t)}open_bi(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_open_bi(this.__wbg_ptr,e,_);return p(r)}open_native_main_control_bi(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_open_native_main_control_bi(this.__wbg_ptr,e,_);return p(r)}open_peer_bi(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_open_peer_bi(this.__wbg_ptr,_,r,u(e)?Number.MAX_SAFE_INTEGER:e>>>0);return p(o)}open_peer_bi_explicit_file_sender(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_open_peer_bi_explicit_file_sender(this.__wbg_ptr,_,r,u(e)?Number.MAX_SAFE_INTEGER:e>>>0);return p(o)}open_peer_bi_transport_only(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_open_peer_bi_transport_only(this.__wbg_ptr,_,r,u(e)?Number.MAX_SAFE_INTEGER:e>>>0);return p(o)}open_peer_native_bi(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=n.wasmclient_open_peer_native_bi(this.__wbg_ptr,r,o,a,w,u(_)?Number.MAX_SAFE_INTEGER:_>>>0);return p(d)}open_peer_uni(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_open_peer_uni(this.__wbg_ptr,_,r,u(e)?Number.MAX_SAFE_INTEGER:e>>>0);return p(o)}open_uni(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_open_uni(this.__wbg_ptr,e,_);return p(r)}peer_scopes(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_peer_scopes(this.__wbg_ptr,e,_);return p(r)}peer_session(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_peer_session(this.__wbg_ptr,e,_);return p(r)}peer_sessions(){let t=n.wasmclient_peer_sessions(this.__wbg_ptr);return p(t)}peer_snapshot(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_peer_snapshot(this.__wbg_ptr,e,_);return p(r)}prepare_reciprocal_admission(t,e,_,r,o,a,w,d){let l=c(t,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=c(_,n.__wbindgen_export,n.__wbindgen_export2),y=i,v=c(r,n.__wbindgen_export,n.__wbindgen_export2),R=i,S=c(o,n.__wbindgen_export,n.__wbindgen_export2),E=i,V=c(a,n.__wbindgen_export,n.__wbindgen_export2),_t=i,rt=c(w,n.__wbindgen_export,n.__wbindgen_export2),ot=i,it=c(d,n.__wbindgen_export,n.__wbindgen_export2),st=i,ct=n.wasmclient_prepare_reciprocal_admission(this.__wbg_ptr,l,f,e,m,y,v,R,S,E,V,_t,rt,ot,it,st);return p(ct)}present_session_token(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i;var l=u(_)?0:c(_,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=u(r)?0:c(r,n.__wbindgen_export,n.__wbindgen_export2),y=i;let v=n.wasmclient_present_session_token(this.__wbg_ptr,o,a,w,d,l,f,m,y);return p(v)}rankRoutes(t,e){try{let a=n.__wbindgen_add_to_stack_pointer(-16),w=tt(t,n.__wbindgen_export),d=i,l=tt(e,n.__wbindgen_export),f=i;n.wasmclient_rankRoutes(a,this.__wbg_ptr,w,d,l,f);var _=x().getInt32(a+0,!0),r=x().getInt32(a+4,!0),o=At(_,r).slice();return n.__wbindgen_export4(_,r*4,4),o}finally{n.__wbindgen_add_to_stack_pointer(16);}}register_session_token(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i;n.wasmclient_register_session_token(this.__wbg_ptr,r,o,a,w,_);}register_token_until(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i;n.wasmclient_register_token_until(this.__wbg_ptr,o,a,w,d,_,r);}reject_connection_admission(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_reject_connection_admission(this.__wbg_ptr,_,r,o,a);return p(w)}release_peer_scope(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i;var o=u(e)?0:c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i;let w=n.wasmclient_release_peer_scope(this.__wbg_ptr,_,r,o,a);return p(w)}report_managed_connection_settled(t,e,_,r,o,a){let w=c(t,n.__wbindgen_export,n.__wbindgen_export2),d=i;var l=u(_)?0:c(_,n.__wbindgen_export,n.__wbindgen_export2),f=i;let m=n.wasmclient_report_managed_connection_settled(this.__wbg_ptr,w,d,e,l,f,!u(r),u(r)?BigInt(0):r,!u(o),u(o)?BigInt(0):o,!u(a),u(a)?BigInt(0):a);return p(m)}report_transport_status(t,e,_,r,o,a){let w=c(t,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(e,n.__wbindgen_export,n.__wbindgen_export2),f=i;var m=u(_)?0:c(_,n.__wbindgen_export,n.__wbindgen_export2),y=i;let v=n.wasmclient_report_transport_status(this.__wbg_ptr,w,d,l,f,m,y,!u(r),u(r)?BigInt(0):r,!u(o),u(o)?BigInt(0):o,!u(a),u(a)?BigInt(0):a);return p(v)}resolve_peer_connection_records(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_resolve_peer_connection_records(this.__wbg_ptr,e,_);return p(r)}revoke_session_token(t){try{let o=n.__wbindgen_add_to_stack_pointer(-16),a=c(t,n.__wbindgen_export,n.__wbindgen_export2),w=i;n.wasmclient_revoke_session_token(o,this.__wbg_ptr,a,w);var e=x().getInt32(o+0,!0),_=x().getInt32(o+4,!0),r=x().getInt32(o+8,!0);if(r)throw p(_);return p(e)}finally{n.__wbindgen_add_to_stack_pointer(16);}}revoke_tokens_by_scope(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_revoke_tokens_by_scope(this.__wbg_ptr,e,_);return p(r)}runtime_policy(){try{let r=n.__wbindgen_add_to_stack_pointer(-16);n.wasmclient_runtime_policy(r,this.__wbg_ptr);var t=x().getInt32(r+0,!0),e=x().getInt32(r+4,!0),_=x().getInt32(r+8,!0);if(_)throw p(e);return p(t)}finally{n.__wbindgen_add_to_stack_pointer(16);}}same_peer(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_same_peer(this.__wbg_ptr,_,r,o,a);return p(w)}search_devices(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_search_devices(this.__wbg_ptr,e,_);return p(r)}send_message(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i;var l=u(_)?0:c(_,n.__wbindgen_export,n.__wbindgen_export2),f=i,m=u(r)?0:c(r,n.__wbindgen_export,n.__wbindgen_export2),y=i;let v=n.wasmclient_send_message(this.__wbg_ptr,o,a,w,d,l,f,m,y);return p(v)}send_native_main_control_frame(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=k(e,n.__wbindgen_export),a=i,w=n.wasmclient_send_native_main_control_frame(this.__wbg_ptr,_,r,o,a);return p(w)}send_peer(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=k(e,n.__wbindgen_export),a=i,w=n.wasmclient_send_peer(this.__wbg_ptr,_,r,o,a);return p(w)}send_peer_application_frame(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=k(e,n.__wbindgen_export),w=i,d=n.wasmclient_send_peer_application_frame(this.__wbg_ptr,r,o,a,w,u(_)?Number.MAX_SAFE_INTEGER:_>>>0);return p(d)}setConnectionApplicationCryptoKey(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=k(e,n.__wbindgen_export),a=i,w=n.wasmclient_setConnectionApplicationCryptoKey(this.__wbg_ptr,_,r,o,a);return p(w)}setConnectionApplicationCryptoRequired(t){try{let r=n.__wbindgen_add_to_stack_pointer(-16),o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i;n.wasmclient_setConnectionApplicationCryptoRequired(r,this.__wbg_ptr,o,a);var e=x().getInt32(r+0,!0),_=x().getInt32(r+4,!0);if(_)throw p(e)}finally{n.__wbindgen_add_to_stack_pointer(16);}}setIdentityCredential(t){var e=u(t)?0:c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i;n.wasmclient_setIdentityCredential(this.__wbg_ptr,e,_);}setRelay(t){let e=n.wasmclient_setRelay(this.__wbg_ptr,t);return p(e)}set_auto_connect_excluded(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_set_auto_connect_excluded(this.__wbg_ptr,_,r,e);return p(o)}set_offline(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmclient_set_offline(this.__wbg_ptr,e,_);return p(r)}start_auto_connect(t,e){try{let o=n.__wbindgen_add_to_stack_pointer(-16),a=c(t,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(e,n.__wbindgen_export,n.__wbindgen_export2),l=i;n.wasmclient_start_auto_connect(o,this.__wbg_ptr,a,w,d,l);var _=x().getInt32(o+0,!0),r=x().getInt32(o+4,!0);if(r)throw p(_)}finally{n.__wbindgen_add_to_stack_pointer(16);}}start_presence_loop(t,e,_,r){let o=c(t,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i,l=c(_,n.__wbindgen_export,n.__wbindgen_export2),f=i;var m=u(r)?0:c(r,n.__wbindgen_export,n.__wbindgen_export2),y=i;n.wasmclient_start_presence_loop(this.__wbg_ptr,o,a,w,d,l,f,m,y);}stop_auth_scoped_activity(){n.wasmclient_stop_auth_scoped_activity(this.__wbg_ptr);}stop_auto_connect(){n.wasmclient_stop_auto_connect(this.__wbg_ptr);}stop_presence_loop(){n.wasmclient_stop_presence_loop(this.__wbg_ptr);}submit_browser_desired_peers(t,e){try{let a=n.__wbindgen_add_to_stack_pointer(-16),w=c(e,n.__wbindgen_export,n.__wbindgen_export2),d=i;n.wasmclient_submit_browser_desired_peers(a,this.__wbg_ptr,t,w,d);var _=x().getInt32(a+0,!0),r=x().getInt32(a+4,!0),o=x().getInt32(a+8,!0);if(o)throw p(r);return _!==0}finally{n.__wbindgen_add_to_stack_pointer(16);}}update_device(t,e,_,r,o){let a=c(t,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(e,n.__wbindgen_export,n.__wbindgen_export2),l=i;var f=u(_)?0:c(_,n.__wbindgen_export,n.__wbindgen_export2),m=i,y=u(o)?0:c(o,n.__wbindgen_export,n.__wbindgen_export2),v=i;let R=n.wasmclient_update_device(this.__wbg_ptr,a,w,d,l,f,m,u(r)?0:g(r),y,v);return p(R)}update_presence(t,e,_,r,o){let a=c(t,n.__wbindgen_export,n.__wbindgen_export2),w=i,d=c(e,n.__wbindgen_export,n.__wbindgen_export2),l=i,f=c(_,n.__wbindgen_export,n.__wbindgen_export2),m=i;var y=u(r)?0:c(r,n.__wbindgen_export,n.__wbindgen_export2),v=i;let R=n.wasmclient_update_presence(this.__wbg_ptr,a,w,d,l,f,m,y,v,!u(o),u(o)?BigInt(0):o);return p(R)}update_session(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=c(e,n.__wbindgen_export,n.__wbindgen_export2),a=i,w=n.wasmclient_update_session(this.__wbg_ptr,_,r,o,a);return p(w)}validate_connection_token(t,e,_){let r=c(t,n.__wbindgen_export,n.__wbindgen_export2),o=i,a=c(e,n.__wbindgen_export,n.__wbindgen_export2),w=i;var d=u(_)?0:c(_,n.__wbindgen_export,n.__wbindgen_export2),l=i;let f=n.wasmclient_validate_connection_token(this.__wbg_ptr,r,o,a,w,d,l);return p(f)}validate_session_token(t){let e,_;try{let f=n.__wbindgen_add_to_stack_pointer(-16),m=c(t,n.__wbindgen_export,n.__wbindgen_export2),y=i;n.wasmclient_validate_session_token(f,this.__wbg_ptr,m,y);var r=x().getInt32(f+0,!0),o=x().getInt32(f+4,!0),a=x().getInt32(f+8,!0),w=x().getInt32(f+12,!0),d=r,l=o;if(w)throw d=0,l=0,p(a);return e=d,_=l,I(d,l)}finally{n.__wbindgen_add_to_stack_pointer(16),n.__wbindgen_export4(e,_,1);}}wait_for_peer(t,e){let _=c(t,n.__wbindgen_export,n.__wbindgen_export2),r=i,o=n.wasmclient_wait_for_peer(this.__wbg_ptr,_,r,u(e)?Number.MAX_SAFE_INTEGER:e>>>0);return p(o)}wake_browser_auto_connect(){return n.wasmclient_wake_browser_auto_connect(this.__wbg_ptr)!==0}};Symbol.dispose&&(U.prototype[Symbol.dispose]=U.prototype.free);var D=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Z.unregister(this),t}free(){let t=this.__destroy_into_raw();n.__wbg_wasmconnection_free(t,0);}create_data_channel(t){let e=c(t,n.__wbindgen_export,n.__wbindgen_export2),_=i,r=n.wasmconnection_create_data_channel(this.__wbg_ptr,e,_);return p(r)}constructor(){try{let r=n.__wbindgen_add_to_stack_pointer(-16);n.wasmconnection_new(r);var t=x().getInt32(r+0,!0),e=x().getInt32(r+4,!0),_=x().getInt32(r+8,!0);if(_)throw p(e);return this.__wbg_ptr=t,Z.register(this,this.__wbg_ptr,this),this}finally{n.__wbindgen_add_to_stack_pointer(16);}}};Symbol.dispose&&(D.prototype[Symbol.dispose]=D.prototype.free);function Wt(){n.start();}function et(){return {__proto__:null,"./openrtc_bg.js":{__proto__:null,__wbg_Error_9dc85fe1bc224456:function(t,e){let _=Error(I(t,e));return g(_)},__wbg_Number_4779d427bae39753:function(t){return Number(s(t))},__wbg_String_8564e559799eccda:function(t,e){let _=String(s(e)),r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg___wbindgen_bigint_get_as_i64_8ea6736501f396b6:function(t,e){let _=s(e),r=typeof _=="bigint"?_:void 0;x().setBigInt64(t+8,u(r)?BigInt(0):r,true),x().setInt32(t+0,!u(r),true);},__wbg___wbindgen_boolean_get_b131b2f36d6b2f55:function(t){let e=s(t),_=typeof e=="boolean"?e:void 0;return u(_)?16777215:_?1:0},__wbg___wbindgen_debug_string_56c147eb1a51f0c4:function(t,e){let _=H(s(e)),r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg___wbindgen_in_ce8569b2fc6f5088:function(t,e){return s(t)in s(e)},__wbg___wbindgen_is_bigint_df272c65456269c2:function(t){return typeof s(t)=="bigint"},__wbg___wbindgen_is_function_147961669f068cd4:function(t){return typeof s(t)=="function"},__wbg___wbindgen_is_null_ced4761460071341:function(t){return s(t)===null},__wbg___wbindgen_is_object_3a2c414391dbf751:function(t){let e=s(t);return typeof e=="object"&&e!==null},__wbg___wbindgen_is_string_6541b0f6ecd4e8e5:function(t){return typeof s(t)=="string"},__wbg___wbindgen_is_undefined_4410e3c20a99fa97:function(t){return s(t)===void 0},__wbg___wbindgen_jsval_eq_174c93ec61bab0c5:function(t,e){return s(t)===s(e)},__wbg___wbindgen_jsval_loose_eq_e07e3b1f5db6da6c:function(t,e){return s(t)==s(e)},__wbg___wbindgen_number_get_588ed6b97f0d7e14:function(t,e){let _=s(e),r=typeof _=="number"?_:void 0;x().setFloat64(t+8,u(r)?0:r,true),x().setInt32(t+0,!u(r),true);},__wbg___wbindgen_string_get_fa2687d531ed17a5:function(t,e){let _=s(e),r=typeof _=="string"?_:void 0;var o=u(r)?0:c(r,n.__wbindgen_export,n.__wbindgen_export2),a=i;x().setInt32(t+4,a,true),x().setInt32(t+0,o,true);},__wbg___wbindgen_throw_bbadd78c1bac3a77:function(t,e){throw new Error(I(t,e))},__wbg__wbg_cb_unref_c2301a3c9b78104b:function(t){s(t)._wbg_cb_unref();},__wbg_abort_56c00f462c9261d9:function(t,e){s(t).abort(s(e));},__wbg_abort_f2416f4a9852003e:function(t){s(t).abort();},__wbg_addEventListener_b635263c509aa7de:function(){return h(function(t,e,_,r){s(t).addEventListener(I(e,_),s(r));},arguments)},__wbg_append_c5a0c94a6a73b22e:function(){return h(function(t,e,_,r,o){s(t).append(I(e,_),I(r,o));},arguments)},__wbg_apply_5d99f956e2dda74d:function(){return h(function(t,e,_){let r=s(t).apply(s(e),s(_));return g(r)},arguments)},__wbg_arrayBuffer_cc7704fa158b907a:function(){return h(function(t){let e=s(t).arrayBuffer();return g(e)},arguments)},__wbg_bistream_new:function(t){let e=q.__wrap(t);return g(e)},__wbg_body_442a47f02322d7b0:function(t){let e=s(t).body;return u(e)?0:g(e)},__wbg_buffer_8524b3453cde4918:function(t){let e=s(t).buffer;return g(e)},__wbg_bufferedAmount_c1581bbb06f4f36c:function(t){return s(t).bufferedAmount},__wbg_byobRequest_cc72d210de793e64:function(t){let e=s(t).byobRequest;return u(e)?0:g(e)},__wbg_byteLength_96807b1d9ab24a4c:function(t){return s(t).byteLength},__wbg_byteOffset_a9c7002428843c41:function(t){return s(t).byteOffset},__wbg_call_91f00ddc43e01490:function(){return h(function(t,e){let _=s(t).call(s(e));return g(_)},arguments)},__wbg_call_ec09a4cf93377d3a:function(){return h(function(t,e,_){let r=s(t).call(s(e),s(_));return g(r)},arguments)},__wbg_cancel_f3a197b26dc88b39:function(t){let e=s(t).cancel();return g(e)},__wbg_catch_66060324c27be6f7:function(t,e){let _=s(t).catch(s(e));return g(_)},__wbg_clearTimeout_113b1cde814ec762:function(t){let e=clearTimeout(p(t));return g(e)},__wbg_clearTimeout_333bba87532ab9d3:function(t){let e=clearTimeout(p(t));return g(e)},__wbg_clearTimeout_47a40e3be01ed7a3:function(){return h(function(t,e){s(t).clearTimeout(p(e));},arguments)},__wbg_close_296263cfe1bb2999:function(){return h(function(t){s(t).close();},arguments)},__wbg_close_388d99468213b286:function(){return h(function(t){s(t).close();},arguments)},__wbg_close_4857e22d08b71356:function(){return h(function(t){s(t).close();},arguments)},__wbg_close_f3365df7ba1b74d3:function(t){s(t).close();},__wbg_code_1cda2855fcd9b009:function(t){return s(t).code},__wbg_code_70beb7b22374d55e:function(t){return s(t).code},__wbg_createDataChannel_122bd3d8aacee49b:function(t,e,_){let r=s(t).createDataChannel(I(e,_));return g(r)},__wbg_crypto_38df2bab126b63dc:function(t){let e=s(t).crypto;return g(e)},__wbg_data_8a04443c1e5a8cd3:function(t){let e=s(t).data;return g(e)},__wbg_dispatchEvent_cc62a6a43d28b01c:function(){return h(function(t,e){return s(t).dispatchEvent(s(e))},arguments)},__wbg_done_6a8439e544ec6206:function(t){return s(t).done},__wbg_enqueue_bbeb09ba0b140f76:function(){return h(function(t,e){s(t).enqueue(s(e));},arguments)},__wbg_entries_4e00eefd3fd54cf1:function(t){let e=s(t).entries();return g(e)},__wbg_entries_5a6a7e7e0df09fe5:function(t){let e=Object.entries(s(t));return g(e)},__wbg_error_6651fee1c71e5da9:function(t){console.error(s(t));},__wbg_error_9a99766f65a03031:function(t,e){console.error(s(t),s(e));},__wbg_error_a6fa202b58aa1cd3:function(t,e){let _,r;try{_=t,r=e,console.error(I(t,e));}finally{n.__wbindgen_export4(_,r,1);}},__wbg_fetch_074561c3e313c86f:function(t){let e=fetch(s(t));return g(e)},__wbg_fetch_22858a12fcf93152:function(t,e){let _=s(t).fetch(s(e));return g(_)},__wbg_from_8a57180716c586ee:function(t){let e=Array.from(s(t));return g(e)},__wbg_getRandomValues_76dfc69825c9c552:function(){return h(function(t,e){globalThis.crypto.getRandomValues(A(t,e));},arguments)},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return h(function(t,e){s(t).getRandomValues(s(e));},arguments)},__wbg_getReader_9facd4f899beac89:function(){return h(function(t){let e=s(t).getReader();return g(e)},arguments)},__wbg_get_44e98e27bda25b5b:function(){return h(function(t,e){let _=Reflect.get(s(t),s(e));return g(_)},arguments)},__wbg_get_4b90d6d8c5deb5d5:function(t,e){let _=s(t)[e>>>0];return g(_)},__wbg_get_52a8a619f7b88df6:function(){return h(function(t,e){let _=Reflect.get(s(t),s(e));return g(_)},arguments)},__wbg_get_done_c21b9933fc9a9e9c:function(t){let e=s(t).done;return u(e)?16777215:e?1:0},__wbg_get_unchecked_46e778e3cec74b5e:function(t,e){let _=s(t)[e>>>0];return g(_)},__wbg_get_value_ad568c7d3db9073f:function(t){let e=s(t).value;return g(e)},__wbg_get_with_ref_key_6412cf3094599694:function(t,e){let _=s(t)[s(e)];return g(_)},__wbg_has_14676d88c1340d2c:function(){return h(function(t,e){return Reflect.has(s(t),s(e))},arguments)},__wbg_headers_5b19cf40627ae54d:function(t){let e=s(t).headers;return g(e)},__wbg_info_a2b5f8a5dae8b26c:function(t){console.info(s(t));},__wbg_instanceof_ArrayBuffer_a581da923203f29f:function(t){let e;try{e=s(t)instanceof ArrayBuffer;}catch{e=false;}return e},__wbg_instanceof_Blob_5c4e145be35f9b1e:function(t){let e;try{e=s(t)instanceof Blob;}catch{e=false;}return e},__wbg_instanceof_Map_7f94c740225003e2:function(t){let e;try{e=s(t)instanceof Map;}catch{e=false;}return e},__wbg_instanceof_Promise_aa24ea31000d4ee6:function(t){let e;try{e=s(t)instanceof Promise;}catch{e=false;}return e},__wbg_instanceof_Response_36a65a969abaa7c6:function(t){let e;try{e=s(t)instanceof Response;}catch{e=false;}return e},__wbg_instanceof_Uint8Array_b6fe1ac89eba107e:function(t){let e;try{e=s(t)instanceof Uint8Array;}catch{e=false;}return e},__wbg_instanceof_Window_9e0fe7d3d1ff4342:function(t){let e;try{e=s(t)instanceof Window;}catch{e=false;}return e},__wbg_isArray_139f48e3c057ede8:function(t){return Array.isArray(s(t))},__wbg_isSafeInteger_c22ccb4af2201fe9:function(t){return Number.isSafeInteger(s(t))},__wbg_iterator_9b36cebf3be7b7cd:function(){return g(Symbol.iterator)},__wbg_length_68a9d5278d084f4f:function(t){return s(t).length},__wbg_length_fb04d16d7bdf6d4c:function(t){return s(t).length},__wbg_log_6614a4effdb4e983:function(t){console.log(s(t));},__wbg_maxRetransmits_dfa0382c31f8e2ca:function(t){let e=s(t).maxRetransmits;return u(e)?16777215:e},__wbg_message_12958526424a887b:function(t,e){let _=s(e).message,r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg_msCrypto_bd5a034af96bcba6:function(t){let e=s(t).msCrypto;return g(e)},__wbg_new_0b303268aa395a38:function(){let t=new Array;return g(t)},__wbg_new_189262ff31890c23:function(){return h(function(){let t=new Headers;return g(t)},arguments)},__wbg_new_20b778a4c5c691c3:function(){let t=new Object;return g(t)},__wbg_new_227d7c05414eb861:function(){let t=new Error;return g(t)},__wbg_new_24739629d416f982:function(){return h(function(){let t=new AbortController;return g(t)},arguments)},__wbg_new_5fae30e6b23db8df:function(t,e){let _=new Error(I(t,e));return g(_)},__wbg_new_883c0db065f06efd:function(){return g(new Map)},__wbg_new_a3e5112401a82338:function(){return h(function(t,e){let _=new WebSocket(I(t,e));return g(_)},arguments)},__wbg_new_b06772b280cc6e52:function(t){let e=new Uint8Array(s(t));return g(e)},__wbg_new_from_slice_bb2d1778c0b87eb1:function(t,e){let _=new Uint8Array(A(t,e));return g(_)},__wbg_new_typed_90c3f6c29ba36d19:function(t,e){try{var _={a:t,b:e},r=(a,w)=>{let d=_.a;_.a=0;try{return xt(d,_.b,a,w)}finally{_.a=d;}};let o=new Promise(r);return g(o)}finally{_.a=0;}},__wbg_new_with_byte_offset_and_length_9e1e664fe1a5d385:function(t,e,_){let r=new Uint8Array(s(t),e>>>0,_>>>0);return g(r)},__wbg_new_with_configuration_3a96aa953ca17197:function(){return h(function(t){let e=new RTCPeerConnection(s(t));return g(e)},arguments)},__wbg_new_with_event_init_dict_bd850674488710b1:function(){return h(function(t,e,_){let r=new CustomEvent(I(t,e),s(_));return g(r)},arguments)},__wbg_new_with_into_underlying_sink_2596343f9b6c8e58:function(t){let e=new WritableStream(N.__wrap(t));return g(e)},__wbg_new_with_into_underlying_source_fd904252f385f59c:function(t,e){let _=new ReadableStream(O.__wrap(t),p(e));return g(_)},__wbg_new_with_length_4b57a7a5dc67221c:function(t){let e=new Uint8Array(t>>>0);return g(e)},__wbg_new_with_str_and_init_df876572184fe639:function(){return h(function(t,e,_){let r=new Request(I(t,e),s(_));return g(r)},arguments)},__wbg_new_with_str_sequence_505a4829cc247e79:function(){return h(function(t,e,_){let r=new WebSocket(I(t,e),s(_));return g(r)},arguments)},__wbg_next_8cb028b6ba50743f:function(){return h(function(t){let e=s(t).next();return g(e)},arguments)},__wbg_next_cfd0b146c9538df8:function(t){let e=s(t).next;return g(e)},__wbg_node_84ea875411254db1:function(t){let e=s(t).node;return g(e)},__wbg_now_bce4dc999095ea77:function(){return Date.now()},__wbg_now_e7c6795a7f81e10f:function(t){return s(t).now()},__wbg_parse_a5c06e19bc1187fd:function(t,e){return Date.parse(I(t,e))},__wbg_peerunistream_new:function(t){let e=B.__wrap(t);return g(e)},__wbg_performance_3fcf6e32a7e1ed0a:function(t){let e=s(t).performance;return g(e)},__wbg_process_44c7a14e11e9f69e:function(t){let e=s(t).process;return g(e)},__wbg_protocol_28aaef5ea42981d6:function(t,e){let _=s(e).protocol,r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg_prototypesetcall_956c7493c68e29b4:function(t,e,_){Uint8Array.prototype.set.call(A(t,e),s(_));},__wbg_push_ceb8ef046afb2041:function(t,e){return s(t).push(s(e))},__wbg_queueMicrotask_4698f900840e3286:function(t){queueMicrotask(s(t));},__wbg_queueMicrotask_477a5533c7100338:function(t){let e=s(t).queueMicrotask;return g(e)},__wbg_randomFillSync_6c25eac9869eb53c:function(){return h(function(t,e){s(t).randomFillSync(p(e));},arguments)},__wbg_read_8426c146431f2905:function(t){let e=s(t).read();return g(e)},__wbg_readyState_25243ad6ce649774:function(t){return s(t).readyState},__wbg_reason_4ec455bac79b33ce:function(t,e){let _=s(e).reason,r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg_releaseLock_188846ef719acb10:function(t){s(t).releaseLock();},__wbg_removeEventListener_016c1d24523b4730:function(){return h(function(t,e,_,r){s(t).removeEventListener(I(e,_),s(r));},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return h(function(){let t=module.require;return g(t)},arguments)},__wbg_resolve_0183de2e8c6b1d54:function(t){let e=Promise.resolve(s(t));return g(e)},__wbg_respond_3cdb4cf32683fd79:function(){return h(function(t,e){s(t).respond(e>>>0);},arguments)},__wbg_send_77521d09456dd693:function(){return h(function(t,e,_){s(t).send(A(e,_));},arguments)},__wbg_send_99d049cae69c53cc:function(){return h(function(t,e,_){s(t).send(A(e,_));},arguments)},__wbg_send_bac9d3dc4f21ef28:function(){return h(function(t,e,_){s(t).send(I(e,_));},arguments)},__wbg_setTimeout_3a808dd861dd3c12:function(t,e){let _=setTimeout(s(t),e);return g(_)},__wbg_setTimeout_6613a51400c1bf9f:function(){return h(function(t,e,_){let r=s(t).setTimeout(p(e),_);return g(r)},arguments)},__wbg_setTimeout_ef24d2fc3ad97385:function(){return h(function(t,e){let _=setTimeout(s(t),e);return g(_)},arguments)},__wbg_set_5f806304fb633ab3:function(t,e,_){let r=s(t).set(s(e),s(_));return g(r)},__wbg_set_6be42768c690e380:function(t,e,_){s(t)[p(e)]=p(_);},__wbg_set_86698c227e5b9dad:function(t,e,_){s(t).set(A(e,_));},__wbg_set_a6ba3ac0e634b822:function(){return h(function(t,e,_){return Reflect.set(s(t),s(e),s(_))},arguments)},__wbg_set_binaryType_07905e4563fcd9b2:function(t,e){s(t).binaryType=kt[e];},__wbg_set_binaryType_8c2dd2cf1cfc2e28:function(t,e){s(t).binaryType=ht[e];},__wbg_set_body_d1153b16a2b95ca1:function(t,e){s(t).body=s(e);},__wbg_set_bufferedAmountLowThreshold_8969a2db2c745257:function(t,e){s(t).bufferedAmountLowThreshold=e>>>0;},__wbg_set_cache_5a01a8b5e6ca6cf2:function(t,e){s(t).cache=yt[e];},__wbg_set_credentials_e9120ed88b1fc0b8:function(t,e){s(t).credentials=It[e];},__wbg_set_da33c120a6584674:function(t,e,_){s(t)[e>>>0]=p(_);},__wbg_set_detail_c7af5edea934390b:function(t,e){s(t).detail=s(e);},__wbg_set_handle_event_6147c38b782c7b42:function(t,e){s(t).handleEvent=s(e);},__wbg_set_headers_877ed41890d28af2:function(t,e){s(t).headers=s(e);},__wbg_set_high_water_mark_77da20c49668427d:function(t,e){s(t).highWaterMark=e;},__wbg_set_method_b4ede299b2064f37:function(t,e,_){s(t).method=I(e,_);},__wbg_set_mode_d6c2e1991aa963c6:function(t,e){s(t).mode=vt[e];},__wbg_set_onbufferedamountlow_b695487bdd219f98:function(t,e){s(t).onbufferedamountlow=s(e);},__wbg_set_onclose_9cb5c3372e16c192:function(t,e){s(t).onclose=s(e);},__wbg_set_onclose_f8bec1cbeb64aa93:function(t,e){s(t).onclose=s(e);},__wbg_set_onerror_190fe67e911ebf28:function(t,e){s(t).onerror=s(e);},__wbg_set_onmessage_4d57c4ddab951294:function(t,e){s(t).onmessage=s(e);},__wbg_set_onmessage_96337495f0bfb796:function(t,e){s(t).onmessage=s(e);},__wbg_set_onopen_3e2bf6b11d434c2d:function(t,e){s(t).onopen=s(e);},__wbg_set_signal_9022b5aa06a6ce5b:function(t,e){s(t).signal=s(e);},__wbg_signal_41dd1a8913cd0b7d:function(t){let e=s(t).signal;return g(e)},__wbg_stack_3b0d974bbf31e44f:function(t,e){let _=s(e).stack,r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg_static_accessor_GLOBAL_60a4124bab7dcc9a:function(){let t=typeof global>"u"?null:global;return u(t)?0:g(t)},__wbg_static_accessor_GLOBAL_THIS_95ca6460658b5d13:function(){let t=typeof globalThis>"u"?null:globalThis;return u(t)?0:g(t)},__wbg_static_accessor_SELF_4c95f759a91e9aae:function(){let t=typeof self>"u"?null:self;return u(t)?0:g(t)},__wbg_static_accessor_WINDOW_44b435597f9e9ee7:function(){let t=typeof window>"u"?null:window;return u(t)?0:g(t)},__wbg_status_9e6505cfa3e73a7c:function(t){return s(t).status},__wbg_subarray_42216645a367cd7a:function(t,e,_){let r=s(t).subarray(e>>>0,_>>>0);return g(r)},__wbg_then_254bab9b266a77a5:function(t,e,_){let r=s(t).then(s(e),s(_));return g(r)},__wbg_then_3ea18602c6a5123b:function(t,e){let _=s(t).then(s(e));return g(_)},__wbg_url_72c67c175685a054:function(t,e){let _=s(e).url,r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg_url_d0b8042af0d1bbba:function(t,e){let _=s(e).url,r=c(_,n.__wbindgen_export,n.__wbindgen_export2),o=i;x().setInt32(t+4,o,true),x().setInt32(t+0,r,true);},__wbg_value_3d3defe09fb1ffca:function(t){let e=s(t).value;return g(e)},__wbg_versions_276b2795b1c6a219:function(t){let e=s(t).versions;return g(e)},__wbg_view_15fa5865c6b336e3:function(t){let e=s(t).view;return u(e)?0:g(e)},__wbg_warn_633bacc13ba7e6c3:function(t){console.warn(s(t));},__wbg_wasClean_f17429d064911939:function(t){return s(t).wasClean},__wbindgen_cast_0000000000000001:function(t,e){let _=F(t,e,gt);return g(_)},__wbindgen_cast_0000000000000002:function(t,e){let _=F(t,e,ft);return g(_)},__wbindgen_cast_0000000000000003:function(t,e){let _=F(t,e,dt);return g(_)},__wbindgen_cast_0000000000000004:function(t,e){let _=F(t,e,ut);return g(_)},__wbindgen_cast_0000000000000005:function(t,e){let _=F(t,e,lt);return g(_)},__wbindgen_cast_0000000000000006:function(t,e){let _=F(t,e,bt);return g(_)},__wbindgen_cast_0000000000000007:function(t,e){let _=F(t,e,at);return g(_)},__wbindgen_cast_0000000000000008:function(t,e){let _=Ft(t,e,pt);return g(_)},__wbindgen_cast_0000000000000009:function(t,e){let _=F(t,e,wt);return g(_)},__wbindgen_cast_000000000000000a:function(t){return g(t)},__wbindgen_cast_000000000000000b:function(t){return g(t)},__wbindgen_cast_000000000000000c:function(t,e){let _=A(t,e);return g(_)},__wbindgen_cast_000000000000000d:function(t,e){let _=I(t,e);return g(_)},__wbindgen_cast_000000000000000e:function(t){let e=BigInt.asUintN(64,t);return g(e)},__wbindgen_cast_000000000000000f:function(t,e){var _=A(t,e).slice();return n.__wbindgen_export4(t,e*1,1),g(_)},__wbindgen_object_clone_ref:function(t){let e=s(t);return g(e)},__wbindgen_object_drop_ref:function(t){p(t);}}}}function bt(b,t){n.__wasm_bindgen_func_elem_21377(b,t);}function at(b,t){n.__wasm_bindgen_func_elem_22509(b,t);}function pt(b,t){n.__wasm_bindgen_func_elem_22573(b,t);}function wt(b,t){n.__wasm_bindgen_func_elem_30578(b,t);}function gt(b,t,e){n.__wasm_bindgen_func_elem_21580(b,t,g(e));}function dt(b,t,e){n.__wasm_bindgen_func_elem_18950(b,t,g(e));}function ut(b,t,e){n.__wasm_bindgen_func_elem_4004(b,t,g(e));}function lt(b,t,e){n.__wasm_bindgen_func_elem_23242(b,t,g(e));}function ft(b,t,e){try{let o=n.__wbindgen_add_to_stack_pointer(-16);n.__wasm_bindgen_func_elem_30728(o,b,t,g(e));var _=x().getInt32(o+0,!0),r=x().getInt32(o+4,!0);if(r)throw p(_)}finally{n.__wbindgen_add_to_stack_pointer(16);}}function xt(b,t,e,_){n.__wasm_bindgen_func_elem_30730(b,t,g(e),g(_));}var ht=["blob","arraybuffer"],mt=["bytes"],yt=["default","no-store","reload","no-cache","force-cache","only-if-cached"],It=["omit","same-origin","include"],vt=["same-origin","no-cors","cors","navigate"],kt=["arraybuffer","blob"],$=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_bistream_free(b,1)),Rt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_intounderlyingbytesource_free(b,1)),K=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_intounderlyingsink_free(b,1)),J=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_intounderlyingsource_free(b,1)),Y=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_peerunistream_free(b,1)),Q=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_wasmclient_free(b,1)),Z=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbg_wasmconnection_free(b,1));function g(b){W===C.length&&C.push(C.length+1);let t=W;return W=C[t],C[t]=b,t}var G=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(b=>n.__wbindgen_export5(b.a,b.b));function H(b){let t=typeof b;if(t=="number"||t=="boolean"||b==null)return `${b}`;if(t=="string")return `"${b}"`;if(t=="symbol"){let r=b.description;return r==null?"Symbol":`Symbol(${r})`}if(t=="function"){let r=b.name;return typeof r=="string"&&r.length>0?`Function(${r})`:"Function"}if(Array.isArray(b)){let r=b.length,o="[";r>0&&(o+=H(b[0]));for(let a=1;a<r;a++)o+=", "+H(b[a]);return o+="]",o}let e=/\[object ([^\]]+)\]/.exec(toString.call(b)),_;if(e&&e.length>1)_=e[1];else return toString.call(b);if(_=="Object")try{return "Object("+JSON.stringify(b)+")"}catch{return "Object"}return b instanceof Error?`${b.name}: ${b.message}
|
|
2
|
-
${b.stack}`:_}function Ct(b){b<1028||(C[b]=W,W=b);}function At(b,t){b=b>>>0;let e=x(),_=[];for(let r=b;r<b+4*t;r+=4)_.push(p(e.getUint32(r,true)));return _}function A(b,t){return b=b>>>0,T().subarray(b/1,b/1+t)}var P=null;function x(){return (P===null||P.buffer.detached===true||P.buffer.detached===void 0&&P.buffer!==n.memory.buffer)&&(P=new DataView(n.memory.buffer)),P}function I(b,t){return Pt(b>>>0,t)}var M=null;function T(){return (M===null||M.byteLength===0)&&(M=new Uint8Array(n.memory.buffer)),M}function s(b){return C[b]}function h(b,t){try{return b.apply(this,t)}catch(e){n.__wbindgen_export3(g(e));}}var C=new Array(1024).fill(void 0);C.push(void 0,null,true,false);var W=C.length;function u(b){return b==null}function Ft(b,t,e){let _={a:b,b:t,cnt:1},r=(...o)=>{_.cnt++;try{return e(_.a,_.b,...o)}finally{r._wbg_cb_unref();}};return r._wbg_cb_unref=()=>{--_.cnt===0&&(n.__wbindgen_export5(_.a,_.b),_.a=0,G.unregister(_));},G.register(r,_,_),r}function F(b,t,e){let _={a:b,b:t,cnt:1},r=(...o)=>{_.cnt++;let a=_.a;_.a=0;try{return e(a,_.b,...o)}finally{_.a=a,r._wbg_cb_unref();}};return r._wbg_cb_unref=()=>{--_.cnt===0&&(n.__wbindgen_export5(_.a,_.b),_.a=0,G.unregister(_));},G.register(r,_,_),r}function k(b,t){let e=t(b.length*1,1)>>>0;return T().set(b,e/1),i=b.length,e}function tt(b,t){let e=t(b.length*4,4)>>>0,_=x();for(let r=0;r<b.length;r++)_.setUint32(e+4*r,g(b[r]),true);return i=b.length,e}function c(b,t,e){if(e===void 0){let w=j.encode(b),d=t(w.length,1)>>>0;return T().subarray(d,d+w.length).set(w),i=w.length,d}let _=b.length,r=t(_,1)>>>0,o=T(),a=0;for(;a<_;a++){let w=b.charCodeAt(a);if(w>127)break;o[r+a]=w;}if(a!==_){a!==0&&(b=b.slice(a)),r=e(r,_,_=a+b.length*3,1)>>>0;let w=T().subarray(r+a,r+_),d=j.encodeInto(b,w);a+=d.written,r=e(r,_,a,1)>>>0;}return i=a,r}function p(b){let t=s(b);return Ct(b),t}var z=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});z.decode();var St=2146435072,X=0;function Pt(b,t){return X+=t,X>=St&&(z=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),z.decode(),X=t),z.decode(T().subarray(b,b+t))}var j=new TextEncoder;"encodeInto"in j||(j.encodeInto=function(b,t){let e=j.encode(b);return t.set(e),{read:b.length,written:e.length}});var i=0,n;function nt(b,t){return n=b.exports,P=null,M=null,n.__wbindgen_start(),n}async function Mt(b,t){if(typeof Response=="function"&&b instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(b,t)}catch(r){if(b.ok&&e(b.type)&&b.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let _=await b.arrayBuffer();return await WebAssembly.instantiate(_,t)}else {let _=await WebAssembly.instantiate(b,t);return _ instanceof WebAssembly.Instance?{instance:_,module:b}:_}function e(_){switch(_){case "basic":case "cors":case "default":return true}return false}}function jt(b){if(n!==void 0)return n;b!==void 0&&(Object.getPrototypeOf(b)===Object.prototype?{module:b}=b:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=et();b instanceof WebAssembly.Module||(b=new WebAssembly.Module(b));let e=new WebAssembly.Instance(b,t);return nt(e)}async function qt(b){if(n!==void 0)return n;b!==void 0&&(Object.getPrototypeOf(b)===Object.prototype?{module_or_path:b}=b:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),b===void 0&&(b=new URL("openrtc_bg.wasm",import.meta.url));let t=et();(typeof b=="string"||typeof Request=="function"&&b instanceof Request||typeof URL=="function"&&b instanceof URL)&&(b=fetch(b));let{instance:e,module:_}=await Mt(await b,t);return nt(e)}export{q as BiStream,L as IntoUnderlyingByteSource,N as IntoUnderlyingSink,O as IntoUnderlyingSource,B as PeerUniStream,U as WasmClient,D as WasmConnection,qt as default,jt as initSync,Wt as start};
|