openrtc 2.5.3 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/{Connection-CovQdc8E.d.ts → Connection-CQdRHqjO.d.ts} +36 -1
  2. package/dist/{DelegatingRuntimeAdapter-3ykiNvyh.d.ts → DelegatingRuntimeAdapter-B8ubDv86.d.ts} +2 -2
  3. package/dist/{IpcRuntimeAdapter-BkM_1HyL.d.ts → IpcRuntimeAdapter-D4vIpOre.d.ts} +16 -6
  4. package/dist/WasmBridge-W3GRBTTZ.js +1 -0
  5. package/dist/{assembly-C235UKSS.d.ts → assembly-D9vP5Q6M.d.ts} +2 -2
  6. package/dist/{capabilities-CdZpAKvE.d.ts → capabilities-BgxJVk9q.d.ts} +1 -1
  7. package/dist/chunk-4R5BLX2U.js +2 -0
  8. package/dist/{chunk-WMA4OMJL.js → chunk-5KN6YOM6.js} +1 -1
  9. package/dist/chunk-BEYBIRAN.js +2 -0
  10. package/dist/chunk-C7UBBRYW.js +2 -0
  11. package/dist/{chunk-CHT46RA7.js → chunk-DOI7F3VQ.js} +1 -1
  12. package/dist/{chunk-4CC6YIGG.js → chunk-FQB3VTOC.js} +1 -1
  13. package/dist/chunk-GQWHEDGU.js +2 -0
  14. package/dist/chunk-HQ6ANBIU.js +1 -0
  15. package/dist/chunk-ISTROQQJ.js +1 -0
  16. package/dist/chunk-NHIANLEM.js +1 -0
  17. package/dist/{chunk-P5GCLQHS.js → chunk-V7E4OUN5.js} +1 -1
  18. package/dist/controlPlane-T3TOHY3D.js +1 -0
  19. package/dist/coreClient.d.ts +3 -3
  20. package/dist/deviceEnrollment-2UW67OPP.js +2 -0
  21. package/dist/index.d.ts +24 -7
  22. package/dist/index.js +1 -1
  23. package/dist/ipcFactory-ZEHQMCEM.js +1 -0
  24. package/dist/native.d.ts +5 -5
  25. package/dist/native.js +1 -1
  26. package/dist/node.d.ts +8 -5
  27. package/dist/node.js +2 -2
  28. package/dist/{openrtc-KERRTMSG.js → openrtc-R6EPOY3N.js} +1 -1
  29. package/dist/openrtc_bg.wasm +0 -0
  30. package/dist/{room-2MUFAJ4M.js → room-Z6F46KMH.js} +1 -1
  31. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  32. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  33. package/dist/runtime/device-status.d.ts +1 -1
  34. package/dist/runtime/factories.d.ts +5 -5
  35. package/dist/runtime/factories.js +1 -1
  36. package/dist/runtime/index.d.ts +9 -9
  37. package/dist/runtime/index.js +1 -1
  38. package/dist/server-browser.d.ts +4 -4
  39. package/dist/server.d.ts +4 -4
  40. package/dist/server.js +1 -1
  41. package/dist/service-node.d.ts +4 -4
  42. package/dist/service-node.js +1 -1
  43. package/dist/testing/native.d.ts +4 -4
  44. package/dist/testing/native.js +1 -1
  45. package/dist/testing.d.ts +4 -4
  46. package/dist/testing.js +1 -1
  47. package/dist/transport/index.d.ts +2 -2
  48. package/dist/{types-C6SMXBzJ.d.ts → types-jxyrOzCw.d.ts} +7 -1
  49. package/native/darwin-arm64/openrtc-node-host +0 -0
  50. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  51. package/native/darwin-x64/openrtc-node-host +0 -0
  52. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  53. package/native/linux-x64/openrtc-node-host +0 -0
  54. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  55. package/package.json +1 -1
  56. package/dist/WasmBridge-LP7FHTHZ.js +0 -1
  57. package/dist/chunk-25CN4MLA.js +0 -2
  58. package/dist/chunk-42TNJH5S.js +0 -1
  59. package/dist/chunk-4J4F32QT.js +0 -1
  60. package/dist/chunk-BFN3AVHA.js +0 -2
  61. package/dist/chunk-N6LGTNUI.js +0 -1
  62. package/dist/chunk-VC7TGJFS.js +0 -2
  63. package/dist/controlPlane-IIPEJ77Q.js +0 -1
  64. package/dist/deviceEnrollment-ZQZ2WP5H.js +0 -2
  65. package/dist/ipcFactory-2WMR4PH6.js +0 -1
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-25CN4MLA.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function M(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var _=class _{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(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 i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,_.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};_.PRESENCE_LEASE_MS=15*6e4;var R=_;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-KERRTMSG.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=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:M(i),tokenFingerprint:M(r),tokenSuffixFingerprint:M(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),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(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(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()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.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(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.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:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;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 n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,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(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.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}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=E(w,S,{requireFinish:true}).getWriter(),T=false;try{await C.write(y);let P=new Uint8Array(await i.arrayBuffer());for(let b=0;b<P.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=P.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,P.byteLength));await C.write(ie);}}catch(P){throw T=true,P}finally{try{await C.close();}catch(P){if(!T)throw P}finally{C.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
1
+ import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-GQWHEDGU.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function M(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var _=class _{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(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 i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,_.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};_.PRESENCE_LEASE_MS=15*6e4;var R=_;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-R6EPOY3N.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=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:M(i),tokenFingerprint:M(r),tokenSuffixFingerprint:M(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),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(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(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()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.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(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.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:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;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 n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,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(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.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}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=E(w,S,{requireFinish:true}).getWriter(),T=false;try{await C.write(y);let P=new Uint8Array(await i.arrayBuffer());for(let b=0;b<P.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=P.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,P.byteLength));await C.write(ie);}}catch(P){throw T=true,P}finally{try{await C.close();}catch(P){if(!T)throw P}finally{C.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
@@ -0,0 +1 @@
1
+ export{a as ControlPlane}from'./chunk-BEYBIRAN.js';export{a as PRODUCTION_ENDPOINTS,b as decodeClaims}from'./chunk-ZA44REGI.js';import'./chunk-4R5BLX2U.js';
@@ -1,6 +1,6 @@
1
- import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-C235UKSS.js';
2
- import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, p as RuntimeDevice, q as ScopedLogicalChannel, r as ConnectionState, s as ReadinessOptions, t as ConnectionEvent, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, v as DeviceConnectOptions, w as ConnectDeviceResult, x as ConnectDeviceHooks, y as ConnectDeviceOptions, L as LocalDeviceInfo, z as DeviceProfile, A as RawConnection, J as JoinRoomOptions, B as RuntimeRoomMember, G as GrantScope, F as AuthContext, H as RuntimeClientOptions } from './Connection-CovQdc8E.js';
3
- import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CdZpAKvE.js';
1
+ import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-D9vP5Q6M.js';
2
+ import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, p as ScopedChannelOptions, q as RuntimeDevice, r as ScopedLogicalChannel, s as ConnectionState, t as ReadinessOptions, u as ConnectionEvent, M as ManagedOptions, v as ManagedSession, D as DeviceStatus, w as DeviceConnectOptions, x as ConnectDeviceResult, y as ConnectDeviceHooks, z as ConnectDeviceOptions, L as LocalDeviceInfo, A as DeviceProfile, B as RawConnection, J as JoinRoomOptions, F as RuntimeRoomMember, G as GrantScope, H as AuthContext, K as RuntimeClientOptions } from './Connection-CQdRHqjO.js';
3
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-BgxJVk9q.js';
4
4
 
5
5
  type ChannelConnectOptions = Omit<ScopedChannelOptions, 'scope' | 'deviceId' | 'ticket'> & {
6
6
  /**
@@ -0,0 +1,2 @@
1
+ import {h,e}from'./chunk-4R5BLX2U.js';function v(e){return e.status===403&&e.reason==="device-enrollment-revoked"}async function p(e$1){let r=e$1.identity,a=async(o=false,t=e$1.recoverRevokedEnrollment)=>{let n=await e$1.key.proof((d,l)=>["openrtc:v2:device-enroll",e$1.appTag,r.principalId,e$1.deviceId,d,l].join(":")),i=e$1.attestation?{kind:e$1.attestation.kind,...await e$1.attestation.getEvidence({challenge:`openrtc:v2:attestation:${e$1.appTag}:${r.principalId}:${e$1.deviceId}:${n.nonce}`,apiKey:e$1.apiKey})}:void 0;return e$1.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:e$1.deviceId,deviceProof:n,...e$1.profile?.name||e$1.profile?.platform?{deviceProfile:{...e$1.profile.name?{name:e$1.profile.name}:{},...e$1.profile.platform?{platform:e$1.profile.platform}:{}}}:{},...t?{recoverRevokedEnrollment:true}:{},...o?{recoverDeviceKey:true}:{},...i?{attestation:i}:{}})};try{return {identity:r,enrollment:await a()}}catch(o){let t=o;if(!(t instanceof Error))throw o;if(v(t)){if(r.deviceRecoveryAuthorized===false)throw h(e.AUTH_DEVICE_REENROLLMENT_REQUIRED,"This device was removed. Sign in again to authorize re-enrollment.",{retryable:true,plane:"auth",cause:o});return {identity:r,enrollment:await a(false,true)}}if(t.status!==412||t.reason!=="device-key-recovery-required")throw o;let n=await e$1.auth.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:true,deviceId:e$1.deviceId,recoveryReason:"device-key-rotation"});if(!n)throw new Error("The OpenRTC auth provider returned no assertion.");let i=await e$1.post("/v2/assertions/exchange",{assertion:n,...e$1.auth.providerId?{providerId:e$1.auth.providerId}:{}});if(e$1.recordAssertionExchange(),i.principalId!==r.principalId)throw new Error("The authenticated principal changed during device-key recovery.");return r=i,{identity:r,enrollment:await a(true)}}}
2
+ export{p as enrollDevice};
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
2
- import { O as Options, C as Client } from './types-C6SMXBzJ.js';
3
- export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a6 as UsageUpdate, a7 as UsageWarning } from './types-C6SMXBzJ.js';
2
+ import { O as Options, C as Client } from './types-jxyrOzCw.js';
3
+ export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a6 as UsageUpdate, a7 as UsageWarning } from './types-jxyrOzCw.js';
4
+ import { N as ServiceErrorMetadata } from './Connection-CQdRHqjO.js';
5
+ export { S as ServiceErrorObservation } from './Connection-CQdRHqjO.js';
4
6
  import './coreClient.js';
5
- import './assembly-C235UKSS.js';
6
- import './Connection-CovQdc8E.js';
7
- import './capabilities-CdZpAKvE.js';
7
+ import './assembly-D9vP5Q6M.js';
8
+ import './capabilities-BgxJVk9q.js';
8
9
 
9
10
  /**
10
11
  * Create a lazy OpenRTC 2.0 browser client. Construction validates only local
@@ -27,6 +28,7 @@ declare namespace OpenRTC {
27
28
  * - Dead-letter `admission`, `budget`, security/ACL, and non-retryable auth.
28
29
  * - Error codes annotate projection; they never own dial, presence, or settlement.
29
30
  */
31
+
30
32
  type ErrorPlane = 'coordination' | 'admission' | 'transport' | 'auth' | 'budget' | 'delivery' | 'internal';
31
33
  declare const ERROR_CODES: {
32
34
  readonly AUTH_NOT_READY: "auth/not-ready";
@@ -50,9 +52,18 @@ declare const ERROR_CODES: {
50
52
  readonly TRANSPORT_TICKET_MISSING: "transport/ticket-missing";
51
53
  readonly DELIVERY_NOT_READY: "delivery/not-ready";
52
54
  readonly INTERNAL: "internal/error";
55
+ readonly CREDIT_EXHAUSTED: "credit-exhausted";
56
+ readonly APP_BUDGET_EXHAUSTED: "app-budget-exhausted";
57
+ readonly APP_RATE_LIMITED: "app-rate-limited";
58
+ readonly PRINCIPAL_RATE_LIMITED: "principal-rate-limited";
59
+ readonly EDGE_RATE_LIMITED: "edge-rate-limited";
60
+ readonly PROVIDER_SAFETY_PAUSED: "provider-safety-paused";
61
+ readonly USAGE_PRICE_STALE: "usage-price-stale";
62
+ readonly RELAY_BUDGET_EXHAUSTED: "relay-budget-exhausted";
63
+ readonly ROOM_CAPACITY_EXCEEDED: "room-capacity-exceeded";
53
64
  };
54
65
  type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES] | (string & {});
55
- interface ErrorOptions {
66
+ interface ErrorOptions extends ServiceErrorMetadata {
56
67
  code: ErrorCode;
57
68
  message: string;
58
69
  retryable: boolean;
@@ -64,6 +75,12 @@ interface ErrorOptions {
64
75
  revision?: number;
65
76
  }
66
77
  declare class RTCError extends Error {
78
+ readonly scope?: ServiceErrorMetadata['scope'];
79
+ readonly operation?: string;
80
+ readonly requestId?: string;
81
+ readonly retryAfterMs?: number;
82
+ readonly resetAt?: number;
83
+ readonly documentationUrl?: string;
67
84
  readonly name: string;
68
85
  readonly code: ErrorCode;
69
86
  readonly retryable: boolean;
@@ -78,7 +95,7 @@ declare class RTCError extends Error {
78
95
  static shouldAppRetry(error: unknown): boolean;
79
96
  toJSON(): Record<string, unknown>;
80
97
  }
81
- interface ErrorProjection {
98
+ interface ErrorProjection extends ServiceErrorMetadata {
82
99
  errorCode?: ErrorCode;
83
100
  retryable?: boolean;
84
101
  errorPlane?: ErrorPlane;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-4J4F32QT.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-42TNJH5S.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function y(a){return i(a,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:t}]=await Promise.all([import('./BrowserManagedBroadcastHost-ARCP5MGJ.js'),import('./WasmBridge-LP7FHTHZ.js')]),r=t().then(async n=>(await n.initWasm(),n.start(),new n.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>r})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}y.native=function(a$2,e=d()){let o=new a;return i(a$2,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new r(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let r=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:r,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:()=>o.close(),deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:r}=await import('./ipcFactory-2WMR4PH6.js');return r(t,e,o)}})};export{y as OpenRTC};
1
+ import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-NHIANLEM.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-ISTROQQJ.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-HQ6ANBIU.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';export{e as ERROR_CODES,f as RTCError,i as classifyError,h as createError,g as projectError}from'./chunk-4R5BLX2U.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function y(a){return i(a,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:t}]=await Promise.all([import('./BrowserManagedBroadcastHost-ARCP5MGJ.js'),import('./WasmBridge-W3GRBTTZ.js')]),r=t().then(async n=>(await n.initWasm(),n.start(),new n.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>r})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}y.native=function(a$2,e=d()){let o=new a;return i(a$2,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new r(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let r=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:r,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:()=>o.close(),deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:r}=await import('./ipcFactory-ZEHQMCEM.js');return r(t,e,o)}})};export{y as OpenRTC};
@@ -0,0 +1 @@
1
+ import {a as a$2}from'./chunk-5KN6YOM6.js';import {s}from'./chunk-C7UBBRYW.js';import'./chunk-BGWJHPBC.js';import'./chunk-FQB3VTOC.js';import'./chunk-GQWHEDGU.js';import {a as a$1}from'./chunk-XMYBBLYK.js';import'./chunk-TYZS5LXQ.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-NHIANLEM.js';import'./chunk-72NEEJQG.js';import'./chunk-ISTROQQJ.js';import'./chunk-CNAW5BZ3.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-4R5BLX2U.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t=a$1(p);return a$2(t,new s({...t,bridge:n,projectionBroker:m}))}export{l as createIpcClient};
package/dist/native.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { O as Options, C as Client } from './types-C6SMXBzJ.js';
2
- export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-C6SMXBzJ.js';
1
+ import { O as Options, C as Client } from './types-jxyrOzCw.js';
2
+ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-jxyrOzCw.js';
3
3
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
4
- export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CovQdc8E.js';
4
+ export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CQdRHqjO.js';
5
5
  import './coreClient.js';
6
- import './assembly-C235UKSS.js';
7
- import './capabilities-CdZpAKvE.js';
6
+ import './assembly-D9vP5Q6M.js';
7
+ import './capabilities-BgxJVk9q.js';
8
8
 
9
9
  /**
10
10
  * Native-only OpenRTC entrypoint for Tauri and other IPC-backed frontends.
package/dist/native.js CHANGED
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-4J4F32QT.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-42TNJH5S.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function u(p,t=d()){let r=new a;return i(p,{platform:"native",broadcastHostFactory:async e=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new o(t,e)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async e=>{let o=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:e.trustDomain,deviceId:e.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:e.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let e=await t.invoke("get_rtc_local_device_info");return String(e?.deviceId??"")},runtimeFactory:async e=>{let{createIpcClient:o}=await import('./ipcFactory-2WMR4PH6.js');return o(e,t,r)}})}export{u as OpenRTC};
1
+ import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-NHIANLEM.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-ISTROQQJ.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-HQ6ANBIU.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-4R5BLX2U.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function u(p,t=d()){let r=new a;return i(p,{platform:"native",broadcastHostFactory:async e=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new o(t,e)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async e=>{let o=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:e.trustDomain,deviceId:e.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:e.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let e=await t.invoke("get_rtc_local_device_info");return String(e?.deviceId??"")},runtimeFactory:async e=>{let{createIpcClient:o}=await import('./ipcFactory-ZEHQMCEM.js');return o(e,t,r)}})}export{u as OpenRTC};
package/dist/node.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import { O as Options, C as Client } from './types-C6SMXBzJ.js';
2
- export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-C6SMXBzJ.js';
1
+ import { O as Options, C as Client } from './types-jxyrOzCw.js';
2
+ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-jxyrOzCw.js';
3
3
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
4
+ import { S as ServiceErrorObservation } from './Connection-CQdRHqjO.js';
5
+ export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CQdRHqjO.js';
4
6
  import { AuthorityAssignmentInput, AuthorityInterestAssignment } from './service-node.js';
5
- export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CovQdc8E.js';
6
7
  import './coreClient.js';
7
- import './assembly-C235UKSS.js';
8
- import './capabilities-CdZpAKvE.js';
8
+ import './assembly-D9vP5Q6M.js';
9
+ import './capabilities-BgxJVk9q.js';
9
10
 
10
11
  interface NodeServiceNodeOptions {
11
12
  apiKey: string;
@@ -30,6 +31,8 @@ interface NodeServiceNodeOptions {
30
31
  /** OpenRTC repository root containing crates/openrtc/Cargo.toml. */
31
32
  sourceRoot?: string;
32
33
  startupTimeoutMs?: number;
34
+ /** Historical service-denial observations from the Rust gateway owner. */
35
+ onServiceError?: (error: ServiceErrorObservation) => void;
33
36
  }
34
37
  interface NodeServiceConnection {
35
38
  /** Rust-owned stable logical connection identity. */
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-4J4F32QT.js';import {c}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i,b as b$1,a as a$2}from'./chunk-42TNJH5S.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';import {spawn}from'child_process';import {constants}from'fs';import {access,readFile}from'fs/promises';import {isAbsolute,resolve,dirname}from'path';import {fileURLToPath}from'url';import {isDeepStrictEqual}from'util';import {randomUUID,verify,createHash}from'crypto';var N=1,M=24*1024,H=96*1024,I=128*1024,C=64*1024,W=256,Z=256,x=3e4,ee=/^[A-Za-z0-9_.:@-]+$/,te=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,oe=1;function re(o){return Buffer.from(JSON.stringify({schema:o.schema,kind:o.kind,platform:o.platform,arch:o.arch,rustTarget:o.rustTarget,sourceCommit:o.sourceCommit,sourceDigest:o.sourceDigest,binarySha256:o.binarySha256,protocol:o.protocol,signingKeySha256:o.signingKeySha256,signatureAlgorithm:o.signatureAlgorithm}),"utf8")}async function ne(o,e,t){let[r,n,s]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(o,"native","openrtc-node-host-signing-public.pem"))]).catch(()=>{throw new Error("[OpenRTC] Packaged Node host provenance is incomplete.")}),i;try{i=JSON.parse(n.toString("utf8"));}catch{throw new Error("[OpenRTC] Packaged Node host manifest is invalid.")}let c=u=>createHash("sha256").update(u).digest("hex"),l={"darwin-arm64":"aarch64-apple-darwin","darwin-x64":"x86_64-apple-darwin","linux-x64":"x86_64-unknown-linux-gnu"}[`${process.platform}-${process.arch}`];if(!(i!=null&&l!==void 0&&i.schema===oe&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===l&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===c(r)&&i.signingKeySha256===c(s)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,re(i),s,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function $(o){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!te.test(e)&&(!o||!t?.includes(o))))}function m(o,e){queueMicrotask(()=>{try{o(e);}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function G(o){let e=/^\d{1,20}$/;return typeof o.transportStableId!="string"||!e.test(o.transportStableId)||!e.test(o.transportGeneration)||!e.test(o.routeGeneration)?null:{transportStableId:o.transportStableId,transportGeneration:o.transportGeneration,routeGeneration:o.routeGeneration}}function ie(o,e){return o.transportStableId===e.transportStableId&&o.transportGeneration===e.transportGeneration&&o.routeGeneration===e.routeGeneration}function f(o,e,t=160){let r=o.trim();if(!r||r.length>t||!ee.test(r))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return r}function v(o,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(o)||o<1||o>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return o}function se(o){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(o.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(o.secretKey)||o.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...o.shardIds].map(t=>f(t,"shardId",80)).sort();if(e.length<1||e.length>64||new Set(e).size!==e.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");if(!isAbsolute(o.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return o.maxPeers!==void 0&&v(o.maxPeers,"maxPeers",50),o.startupTimeoutMs!==void 0&&v(o.startupTimeoutMs,"startupTimeoutMs",12e4),{...o,serviceId:f(o.serviceId,"serviceId",80),generation:v(o.generation,"generation"),shardIds:e,deviceId:f(o.deviceId,"deviceId"),deviceName:o.deviceName?.trim()||"OpenRTC Node service"}}async function y(o){try{return await access(o,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function L(o,e,t,r,n){return new Promise((s,i)=>{let c=spawn(o,e,{cwd:t,env:$(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),l=Buffer.alloc(0),a=(p,F)=>Buffer.concat([p,F]).subarray(-I);c.stdout.on("data",p=>{d=a(d,p);}),c.stderr.on("data",p=>{l=a(l,p);});let u=setTimeout(()=>{c.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${o}.`));},r);c.once("error",p=>{clearTimeout(u),i(p);}),c.once("exit",p=>{clearTimeout(u),p===0?s(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${l.toString("utf8").trim().slice(-4096)}`));});})}async function q(o){let e=o.binaryPath||process.env.OPENRTC_NODE_HOST_BINARY;if(e){if(!isAbsolute(e)||!await y(e))throw new Error("[OpenRTC] Node host binaryPath must name an executable absolute path.");return {command:e,args:[...o.binaryArgs??[]]}}if(o.buildFromSource){let s=o.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!s||!isAbsolute(s))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(s,"crates/openrtc/Cargo.toml"),c=resolve(s,"target");await L("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",c],s,12e4,o.secretKey);let d=resolve(c,"debug",`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(d))throw new Error("[OpenRTC] local Node host build did not produce an executable.");return {command:d,args:[]}}let t=resolve(dirname(fileURLToPath(import.meta.url)),".."),r=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(r,`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(n))throw new Error(`[OpenRTC] This package has no Node host for ${process.platform}-${process.arch}. Install a supported OpenRTC package, set OPENRTC_NODE_HOST_BINARY, or use buildFromSource with sourceRoot.`);return await ne(t,r,n),{command:n,args:[]}}async function U(o,e){let t=await L(o.command,[...o.args,"--protocol-info"],process.cwd(),12e4,e),r=JSON.parse(t);if(r.protocolVersion!==N||r.lifecycleOwner!=="rust-peer-session"||r.maxConfigBytes!==M||r.maxCommandBytes!==H||r.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return r}var S=class{constructor(e,t,r){this.options=e;this.roomId=t;this.onEvent=r;this.child=null;this.childClosed=Promise.resolve();this.output=Buffer.alloc(0);this.stderr=Buffer.alloc(0);this.pending=new Map;this.writeQueue=Promise.resolve();this.stopped=false;this.closing=null;}async start(){let e=await q(this.options),t=await U(e,this.options.secretKey),r=new Promise((n,s)=>{let i=spawn(e.command,[...e.args],{env:$(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(l=>i.once("close",()=>l()));let c=setTimeout(()=>{s(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??x),d=l=>{clearTimeout(c),s(this.failure(l.message)),this.failAll(this.failure(l.message));};i.once("error",d),i.stderr.on("data",l=>{this.stderr=Buffer.concat([this.stderr,l]).subarray(-4096);}),i.stdout.on("data",l=>{try{for(let a of this.parse(l)){if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&a.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:a.snapshot.connectionId,deviceId:a.snapshot.deviceId,state:a.snapshot.state,routable:a.snapshot.routable,transportStableId:a.transportStableId,transportGeneration:a.transportGeneration,routeGeneration:a.routeGeneration}),a.type==="ready"){if(a.protocolVersion!==N||a.roomId!==this.roomId||a.deviceId!==this.options.deviceId||!isDeepStrictEqual(a.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(c),n();}this.dispatch(a);}}catch(a){d(a instanceof Error?a:new Error(String(a))),i.kill();}}),i.once("exit",(l,a)=>{clearTimeout(c),this.stopped=true;let u=this.failure(`Node host exited (${l??a??"unknown"})`);this.onEvent({type:"host-exit",error:u}),d(u);});});await this.writeLine({protocolVersion:N,apiKey:this.options.apiKey,secretKey:this.options.secretKey,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:this.options.deviceId,roomId:this.roomId,deviceName:this.options.deviceName,stateDirectory:this.options.stateDirectory,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false},M),await r;}async request(e,t){if(!this.child||this.stopped||!this.child.stdin.writable)throw new Error("[OpenRTC] Node host is closed.");if(this.pending.size>=W)throw new Error("[OpenRTC] Node host has too many pending requests.");let r=randomUUID(),n=new Promise((s,i)=>{let c=setTimeout(()=>{this.pending.delete(r),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},x);this.pending.set(r,{resolve:s,reject:i,timer:c});});try{await this.writeLine({type:e,id:r,...t},H);}catch(s){let i=this.pending.get(r);throw i&&clearTimeout(i.timer),this.pending.delete(r),this.failure(s instanceof Error?s.message:String(s))}return n}close(){return this.closing??(this.closing=this.stop())}async stop(){if(!this.child)return;let e=this.child;try{this.stopped||await this.request("shutdown",{});}finally{e.stdin.end();let t=setTimeout(()=>e.kill("SIGTERM"),2e3),r=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(r);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>I&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let r=this.output.indexOf(10);if(r<0)break;if(r>I)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,r).toString("utf8").trim();this.output=this.output.subarray(r+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let r=`${JSON.stringify(e)}
2
- `;if(Buffer.byteLength(r,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((s,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(r,c=>{c?i(c):s();});}));return this.writeQueue=n.catch(()=>{}),n}dispatch(e){if(e.type!=="response"){this.onEvent(e);return}let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(this.failure(e.error||"Node host request failed")));}failure(e){let t=s=>s.split(this.options.secretKey).join("[REDACTED]"),r=t(e),n=t(this.stderr.toString("utf8")).trim();return new Error(`[OpenRTC] ${r}.${n?` Host stderr: ${n}`:""}`)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},E=class{constructor(e,t,r,n,s){this.id=e;this.peerId=t;this.host=r;this.nativeGeneration=n;this.capabilityKey=s;this.messages=new Set;this.closeListeners=new Set;this.queued=[];this.isClosed=false;}async send(e){if(this.isClosed)throw new Error("[OpenRTC] Connection is closed.");let t=ae(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$2("raw","message",e,this.capabilityKey));await this.host.request("send",{connectionId:this.id,payloadBase64:t.toString("base64")});}onMessage(e){let t=e;this.messages.add(t);for(let r of this.queued.splice(0))m(t,r);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?m(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===Z&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)m(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)m(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ie(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t){this.id=e;this.host=t;this.kind="room";this.listeners=new Set;this.connections=new Map;this.closed=false;}publishAssignment(e){if(this.closed)return Promise.reject(new Error("[OpenRTC] Service room is closed."));let t=(e.priorityDeviceIds??[]).map(n=>f(n,"priorityDeviceId")),r=(e.relevantEntityIds??[]).map(n=>f(n,"relevantEntityId"));return t.length>8||r.length>32||new Set(t).size!==t.length||new Set(r).size!==r.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:f(e.subjectDeviceId,"subjectDeviceId"),shardId:f(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:r,ttlMs:e.ttlMs===void 0?void 0:v(e.ttlMs,"ttlMs",12e4)})}onConnection(e){this.listeners.add(e);for(let t of this.connections.values())m(e,t);return ()=>this.listeners.delete(e)}project(e){if(this.closed)return;if(e.type==="host-exit"){this.closed=true;for(let d of this.connections.values())d.close();this.connections.clear(),this.listeners.clear();return}if(e.type==="peer-message"){let d=this.connections.get(e.connectionId),l=G(e);if(d&&l&&d.accepts(l)){let a=ce(e.payloadBase64),u=b$1(a);u?u.capability===`room:${this.id}`&&u.kind==="raw"&&d.receive(u.value):d.receive(a);}return}if(e.type!=="connection-state")return;let t=e.snapshot,r=G(e);if(typeof t.connectionId!="string"||!r)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(r)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(r);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let c=new E(t.connectionId,i,this.host,r,`room:${this.id}`);this.connections.set(c.id,c);for(let d of this.listeners)m(d,c);}async close(){if(this.closed)return this.host.close();this.closed=true;for(let e of this.connections.values())e.close();this.connections.clear(),this.listeners.clear(),await this.host.close();}};function ae(o){let e;if(o instanceof Uint8Array)e=Buffer.from(o);else if(o instanceof ArrayBuffer)e=Buffer.from(o);else if(typeof o=="string")e=Buffer.from(o,"utf8");else {let t=JSON.stringify(o);if(t===void 0)throw new TypeError("[OpenRTC] Message must be a string, bytes, or JSON value.");e=Buffer.from(t,"utf8");}if(e.length>C)throw new RangeError("[OpenRTC] Message exceeds the Node host payload limit.");return e}function ce(o){let e=Buffer.from(o,"base64");if(e.length>C)throw new Error("[OpenRTC] Node host returned an oversized application payload.");try{let t=new TextDecoder("utf-8",{fatal:!0}).decode(e);try{return JSON.parse(t)}catch{return t}}catch{return new Uint8Array(e)}}var b=class{constructor(e){this.listeners=new Set;this.roomPromise=null;this.roomId=null;this.closed=false;this.closing=null;this.options=se(e);}onConnection(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");return this.listeners.add(e),()=>this.listeners.delete(e)}listen(e){return this.closed?Promise.reject(new Error("[OpenRTC] ServiceNode is closed.")):(e=f(e,"roomId"),this.roomId&&this.roomId!==e?Promise.reject(new Error("[OpenRTC] A Node ServiceNode owns exactly one room.")):this.roomPromise?this.roomPromise:(this.roomId=e,this.roomPromise=this.open(e),this.roomPromise))}close(){return this.closing??(this.closing=this.stop())}async stop(){this.closed=true,await(await this.roomPromise?.catch(()=>null))?.close(),this.listeners.clear();}async open(e){let t,r=new S(this.options,e,n=>t?.project(n));t=new T(e,r);try{return await r.start(),t.onConnection(n=>{for(let s of this.listeners)m(s,{room:t,connection:n});}),t}catch(n){throw await r.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function de(o){let e=await q(o);return U(e)}function Ee(o,e){let t=c(e,"openrtc/node"),r=new a;return i(o,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:s}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new s(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let s=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:s,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let n=await t.invoke("get_rtc_local_device_info");return String(n?.deviceId??"")},runtimeFactory:async n=>{let{createIpcClient:s}=await import('./ipcFactory-2WMR4PH6.js');return s(n,t,r)}})}export{Ee as OpenRTC,b as ServiceNode,de as inspectNodeHost};
1
+ import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-NHIANLEM.js';import {c}from'./chunk-72NEEJQG.js';import {a as a$3}from'./chunk-ISTROQQJ.js';import'./chunk-NDR2ANQB.js';import {i,b as b$1,a as a$4}from'./chunk-HQ6ANBIU.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import {a as a$2,c as c$1,d,i as i$1,f as f$1}from'./chunk-4R5BLX2U.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';import {spawn}from'child_process';import {constants}from'fs';import {access,readFile}from'fs/promises';import {isAbsolute,resolve,dirname}from'path';import {fileURLToPath}from'url';import {isDeepStrictEqual}from'util';import {randomUUID,verify,createHash}from'crypto';var N=1,F=24*1024,U=96*1024,E=128*1024,C=64*1024,ne=256,ie=256,L=3e4,se=/^[A-Za-z0-9_.:@-]+$/,ae=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,ce=1;function de(r){return Buffer.from(JSON.stringify({schema:r.schema,kind:r.kind,platform:r.platform,arch:r.arch,rustTarget:r.rustTarget,sourceCommit:r.sourceCommit,sourceDigest:r.sourceDigest,binarySha256:r.binarySha256,protocol:r.protocol,signingKeySha256:r.signingKeySha256,signatureAlgorithm:r.signatureAlgorithm}),"utf8")}async function le(r,e,t){let[o,n,a]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(r,"native","openrtc-node-host-signing-public.pem"))]).catch(()=>{throw new Error("[OpenRTC] Packaged Node host provenance is incomplete.")}),i;try{i=JSON.parse(n.toString("utf8"));}catch{throw new Error("[OpenRTC] Packaged Node host manifest is invalid.")}let c=s=>createHash("sha256").update(s).digest("hex"),l={"darwin-arm64":"aarch64-apple-darwin","darwin-x64":"x86_64-apple-darwin","linux-x64":"x86_64-unknown-linux-gnu"}[`${process.platform}-${process.arch}`];if(!(i!=null&&l!==void 0&&i.schema===ce&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===l&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===c(o)&&i.signingKeySha256===c(a)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,de(i),a,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function z(r){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!ae.test(e)&&(!r||!t?.includes(r))))}function f(r,e){queueMicrotask(()=>{try{let t=r(e);t&&typeof t.then=="function"&&t.catch(()=>{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}});}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function $(r){let e=/^\d{1,20}$/;return typeof r.transportStableId!="string"||!e.test(r.transportStableId)||!e.test(r.transportGeneration)||!e.test(r.routeGeneration)?null:{transportStableId:r.transportStableId,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration}}function ue(r,e){return r.transportStableId===e.transportStableId&&r.transportGeneration===e.transportGeneration&&r.routeGeneration===e.routeGeneration}function m(r,e,t=160){let o=r.trim();if(!o||o.length>t||!se.test(o))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return o}function v(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function pe(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(r.secretKey)||r.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...r.shardIds].map(t=>m(t,"shardId",80)).sort();if(e.length<1||e.length>64||new Set(e).size!==e.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");if(!isAbsolute(r.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return r.maxPeers!==void 0&&v(r.maxPeers,"maxPeers",50),r.startupTimeoutMs!==void 0&&v(r.startupTimeoutMs,"startupTimeoutMs",12e4),{...r,serviceId:m(r.serviceId,"serviceId",80),generation:v(r.generation,"generation"),shardIds:e,deviceId:m(r.deviceId,"deviceId"),deviceName:r.deviceName?.trim()||"OpenRTC Node service"}}async function y(r){try{return await access(r,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function V(r,e,t,o,n){return new Promise((a,i)=>{let c=spawn(r,e,{cwd:t,env:z(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),l=Buffer.alloc(0),u=(p,Y)=>Buffer.concat([p,Y]).subarray(-E);c.stdout.on("data",p=>{d=u(d,p);}),c.stderr.on("data",p=>{l=u(l,p);});let s=setTimeout(()=>{c.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${r}.`));},o);c.once("error",p=>{clearTimeout(s),i(p);}),c.once("exit",p=>{clearTimeout(s),p===0?a(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${l.toString("utf8").trim().slice(-4096)}`));});})}async function J(r){let e=r.binaryPath||process.env.OPENRTC_NODE_HOST_BINARY;if(e){if(!isAbsolute(e)||!await y(e))throw new Error("[OpenRTC] Node host binaryPath must name an executable absolute path.");return {command:e,args:[...r.binaryArgs??[]]}}if(r.buildFromSource){let a=r.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!a||!isAbsolute(a))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(a,"crates/openrtc/Cargo.toml"),c=resolve(a,"target");await V("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",c],a,12e4,r.secretKey);let d=resolve(c,"debug",`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(d))throw new Error("[OpenRTC] local Node host build did not produce an executable.");return {command:d,args:[]}}let t=resolve(dirname(fileURLToPath(import.meta.url)),".."),o=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(o,`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(n))throw new Error(`[OpenRTC] This package has no Node host for ${process.platform}-${process.arch}. Install a supported OpenRTC package, set OPENRTC_NODE_HOST_BINARY, or use buildFromSource with sourceRoot.`);return await le(t,o,n),{command:n,args:[]}}async function X(r,e){let t=await V(r.command,[...r.args,"--protocol-info"],process.cwd(),12e4,e),o=JSON.parse(t);if(o.protocolVersion!==N||o.lifecycleOwner!=="rust-peer-session"||o.maxConfigBytes!==F||o.maxCommandBytes!==U||o.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return o}var I=class{constructor(e,t,o){this.options=e;this.roomId=t;this.onEvent=o;this.child=null;this.childClosed=Promise.resolve();this.output=Buffer.alloc(0);this.stderr=Buffer.alloc(0);this.pending=new Map;this.writeQueue=Promise.resolve();this.stopped=false;this.closing=null;}async start(){let e=await J(this.options),t=await X(e,this.options.secretKey),o=new Promise((n,a)=>{let i=spawn(e.command,[...e.args],{env:z(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(u=>i.once("close",()=>u()));let c,d=setTimeout(()=>{a(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??L),l=u=>{clearTimeout(d);let s=f$1.is(u)?u:this.failure(u.message);a(s),this.failAll(s);};i.once("error",l),i.stderr.on("data",u=>{this.stderr=Buffer.concat([this.stderr,u]).subarray(-4096);}),i.stdout.on("data",u=>{try{for(let s of this.parse(u)){if(s.type==="failure"){c=this.failure(s.error,s.serviceError),l(c);continue}if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&s.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:s.snapshot.connectionId,deviceId:s.snapshot.deviceId,state:s.snapshot.state,routable:s.snapshot.routable,transportStableId:s.transportStableId,transportGeneration:s.transportGeneration,routeGeneration:s.routeGeneration}),s.type==="ready"){if(s.protocolVersion!==N||s.roomId!==this.roomId||s.deviceId!==this.options.deviceId||!isDeepStrictEqual(s.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(d),n();}this.dispatch(s);}}catch(s){l(s instanceof Error?s:new Error(String(s))),i.kill();}}),i.once("exit",(u,s)=>{clearTimeout(d),this.stopped=true;let p=c??this.failure(`Node host exited (${u??s??"unknown"})`);this.onEvent({type:"host-exit",error:p}),l(p);});});await this.writeLine({protocolVersion:N,apiKey:this.options.apiKey,secretKey:this.options.secretKey,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:this.options.deviceId,roomId:this.roomId,deviceName:this.options.deviceName,stateDirectory:this.options.stateDirectory,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false},F),await o;}async request(e,t){if(!this.child||this.stopped||!this.child.stdin.writable)throw new Error("[OpenRTC] Node host is closed.");if(this.pending.size>=ne)throw new Error("[OpenRTC] Node host has too many pending requests.");let o=randomUUID(),n=new Promise((a,i)=>{let c=setTimeout(()=>{this.pending.delete(o),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},L);this.pending.set(o,{resolve:a,reject:i,timer:c});});try{await this.writeLine({type:e,id:o,...t},U);}catch(a){let i=this.pending.get(o);throw i&&clearTimeout(i.timer),this.pending.delete(o),this.failure(a instanceof Error?a.message:String(a))}return n}close(){return this.closing??(this.closing=this.stop())}async stop(){if(!this.child)return;let e=this.child;try{this.stopped||await this.request("shutdown",{});}finally{e.stdin.end();let t=setTimeout(()=>e.kill("SIGTERM"),2e3),o=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(o);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>E&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let o=this.output.indexOf(10);if(o<0)break;if(o>E)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,o).toString("utf8").trim();this.output=this.output.subarray(o+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let o=`${JSON.stringify(e)}
2
+ `;if(Buffer.byteLength(o,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((a,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(o,c=>{c?i(c):a();});}));return this.writeQueue=n.catch(()=>{}),n}dispatch(e){if(e.type!=="response"){this.onEvent(e);return}let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(this.failure(e.error||"Node host request failed",e.serviceError)));}failure(e,t){let o=c=>c.split(this.options.secretKey).join("[REDACTED]"),n=o(e),a=o(this.stderr.toString("utf8")).trim(),i=`[OpenRTC] ${n}.${a?` Host stderr: ${a}`:""}`;if(t&&typeof t=="object"&&!Array.isArray(t)){let c=t,d$1=a$2(c.code);if(c$1(c.code)||d$1){let l=d(c);return i$1({...l,requestId:l.requestId?o(l.requestId):void 0,code:c.code,retryable:typeof c.retryable=="boolean"?c.retryable:!!d$1,message:i})}}return new Error(i)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},S=class{constructor(e,t,o,n,a){this.id=e;this.peerId=t;this.host=o;this.nativeGeneration=n;this.capabilityKey=a;this.messages=new Set;this.closeListeners=new Set;this.queued=[];this.isClosed=false;}async send(e){if(this.isClosed)throw new Error("[OpenRTC] Connection is closed.");let t=he(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$4("raw","message",e,this.capabilityKey));await this.host.request("send",{connectionId:this.id,payloadBase64:t.toString("base64")});}onMessage(e){let t=e;this.messages.add(t);for(let o of this.queued.splice(0))f(t,o);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?f(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===ie&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)f(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)f(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ue(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t,o){this.id=e;this.host=t;this.onServiceError=o;this.kind="room";this.listeners=new Set;this.connections=new Map;this.closed=false;}publishAssignment(e){if(this.closed)return Promise.reject(new Error("[OpenRTC] Service room is closed."));let t=(e.priorityDeviceIds??[]).map(n=>m(n,"priorityDeviceId")),o=(e.relevantEntityIds??[]).map(n=>m(n,"relevantEntityId"));return t.length>8||o.length>32||new Set(t).size!==t.length||new Set(o).size!==o.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:m(e.subjectDeviceId,"subjectDeviceId"),shardId:m(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:o,ttlMs:e.ttlMs===void 0?void 0:v(e.ttlMs,"ttlMs",12e4)})}onConnection(e){this.listeners.add(e);for(let t of this.connections.values())f(e,t);return ()=>this.listeners.delete(e)}project(e){if(this.closed)return;if(e.type==="host-exit"){this.closed=true;for(let d of this.connections.values())d.close();this.connections.clear(),this.listeners.clear();return}if(e.type==="service-error"){let d=e.avenue;if(!d||typeof d!="object"||Array.isArray(d))return;let l=d;if(l.kind!=="room"||l.id!==this.id||typeof e.runtimeInstanceId!="string"||e.runtimeInstanceId.trim().length===0)return;let u=a$3(e.serviceError,{kind:"room",id:this.id});u&&this.onServiceError&&f(()=>{if(!this.closed)return this.onServiceError?.(u)},void 0);return}if(e.type==="peer-message"){let d=this.connections.get(e.connectionId),l=$(e);if(d&&l&&d.accepts(l)){let u=fe(e.payloadBase64),s=b$1(u);s?s.capability===`room:${this.id}`&&s.kind==="raw"&&d.receive(s.value):d.receive(u);}return}if(e.type!=="connection-state")return;let t=e.snapshot,o=$(e);if(typeof t.connectionId!="string"||!o)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(o)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(o);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let c=new S(t.connectionId,i,this.host,o,`room:${this.id}`);this.connections.set(c.id,c);for(let d of this.listeners)f(d,c);}async close(){if(this.closed)return this.host.close();this.closed=true;for(let e of this.connections.values())e.close();this.connections.clear(),this.listeners.clear(),await this.host.close();}};function he(r){let e;if(r instanceof Uint8Array)e=Buffer.from(r);else if(r instanceof ArrayBuffer)e=Buffer.from(r);else if(typeof r=="string")e=Buffer.from(r,"utf8");else {let t=JSON.stringify(r);if(t===void 0)throw new TypeError("[OpenRTC] Message must be a string, bytes, or JSON value.");e=Buffer.from(t,"utf8");}if(e.length>C)throw new RangeError("[OpenRTC] Message exceeds the Node host payload limit.");return e}function fe(r){let e=Buffer.from(r,"base64");if(e.length>C)throw new Error("[OpenRTC] Node host returned an oversized application payload.");try{let t=new TextDecoder("utf-8",{fatal:!0}).decode(e);try{return JSON.parse(t)}catch{return t}}catch{return new Uint8Array(e)}}var b=class{constructor(e){this.listeners=new Set;this.roomPromise=null;this.roomId=null;this.closed=false;this.closing=null;this.options=pe(e);}onConnection(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");return this.listeners.add(e),()=>this.listeners.delete(e)}listen(e){return this.closed?Promise.reject(new Error("[OpenRTC] ServiceNode is closed.")):(e=m(e,"roomId"),this.roomId&&this.roomId!==e?Promise.reject(new Error("[OpenRTC] A Node ServiceNode owns exactly one room.")):this.roomPromise?this.roomPromise:(this.roomId=e,this.roomPromise=this.open(e),this.roomPromise))}close(){return this.closing??(this.closing=this.stop())}async stop(){this.closed=true,await(await this.roomPromise?.catch(()=>null))?.close(),this.listeners.clear();}async open(e){let t,o=new I(this.options,e,n=>t?.project(n));t=new T(e,o,this.options.onServiceError);try{return await o.start(),t.onConnection(n=>{for(let a of this.listeners)f(a,{room:t,connection:n});}),t}catch(n){throw await o.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function me(r){let e=await J(r);return X(e)}function ke(r,e){let t=c(e,"openrtc/node"),o=new a;return i(r,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:a}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new a(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let a=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:a,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>o.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let n=await t.invoke("get_rtc_local_device_info");return String(n?.deviceId??"")},runtimeFactory:async n=>{let{createIpcClient:a}=await import('./ipcFactory-ZEHQMCEM.js');return a(n,t,o)}})}export{ke as OpenRTC,b as ServiceNode,me as inspectNodeHost};