openrtc 2.5.1 → 2.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +21 -1
  2. package/dist/NativeManagedBroadcastHost-WCQ6TPUU.js +1 -0
  3. package/dist/{WasmBridge-ZXBCXBBM.js → WasmBridge-LWMCETW4.js} +1 -1
  4. package/dist/{assembly-DvfsYFCL.d.ts → assembly-LOFcpH3S.d.ts} +2 -1
  5. package/dist/{chunk-FEF3DPPB.js → chunk-6Q2LAXM4.js} +1 -1
  6. package/dist/chunk-AAZPQQXX.js +2 -0
  7. package/dist/chunk-CNAW5BZ3.js +2 -0
  8. package/dist/{chunk-Z4KJHIV5.js → chunk-EFTDXE6M.js} +1 -1
  9. package/dist/chunk-FB5M6GIW.js +2 -0
  10. package/dist/chunk-J7NBMQQA.js +2 -0
  11. package/dist/{chunk-EIJNERKZ.js → chunk-PLIWPC45.js} +1 -1
  12. package/dist/chunk-TZLNKQNJ.js +1 -0
  13. package/dist/coreClient.d.ts +1 -1
  14. package/dist/{dist-XO466BRG.js → dist-FIVA6EPA.js} +0 -18
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/ipcFactory-PDVLUG2W.js +1 -0
  18. package/dist/native.d.ts +1 -1
  19. package/dist/native.js +1 -1
  20. package/dist/node.d.ts +5 -1
  21. package/dist/node.js +2 -2
  22. package/dist/openrtc-SQF7H4ZE.js +2 -0
  23. package/dist/openrtc_bg.wasm +0 -0
  24. package/dist/room-A2FMQRNZ.js +1 -0
  25. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  26. package/dist/runtime/factories.d.ts +1 -1
  27. package/dist/runtime/factories.js +1 -1
  28. package/dist/runtime/index.d.ts +2 -2
  29. package/dist/runtime/index.js +1 -1
  30. package/dist/server-browser.d.ts +1 -1
  31. package/dist/server.d.ts +1 -1
  32. package/dist/server.js +1 -1
  33. package/dist/service-node.d.ts +2 -1
  34. package/dist/service-node.js +1 -1
  35. package/dist/testing/native.d.ts +1 -1
  36. package/dist/testing/native.js +1 -1
  37. package/dist/testing.d.ts +3 -1
  38. package/dist/testing.js +1 -1
  39. package/native/darwin-arm64/openrtc-node-host +0 -0
  40. package/native/darwin-arm64/openrtc-node-host.manifest.json +20 -0
  41. package/native/darwin-x64/openrtc-node-host +0 -0
  42. package/native/darwin-x64/openrtc-node-host.manifest.json +20 -0
  43. package/native/linux-x64/openrtc-node-host +0 -0
  44. package/native/linux-x64/openrtc-node-host.manifest.json +20 -0
  45. package/native/openrtc-node-host-signing-public.pem +3 -0
  46. package/package.json +3 -2
  47. package/dist/chunk-2K47N3QP.js +0 -2
  48. package/dist/chunk-GHAJW6SZ.js +0 -2
  49. package/dist/chunk-GTHSRQ7Y.js +0 -2
  50. package/dist/chunk-Z54XUIKZ.js +0 -1
  51. package/dist/ipcFactory-PRAJ7JP7.js +0 -1
  52. package/dist/openrtc-VCS6V3AN.js +0 -2
  53. package/dist/room-ULZ2FGWV.js +0 -1
package/README.md CHANGED
@@ -152,19 +152,39 @@ service.onConnection(({ connection }) => {
152
152
  await service.listen('world-42');
153
153
  ```
154
154
 
155
+ `maxPeers` counts everyone in the room, including the service. Node defaults to
156
+ eight; set a value from 1 through 50 explicitly when needed. Your app's approved
157
+ limit and available credits still apply, so a larger request can be denied.
158
+ Browser and standalone Rust grant requests may omit the value to use app policy.
159
+ These limits are not a promise of 50 simultaneous server connections or a
160
+ replacement for the remaining authority acceptance tests.
161
+
155
162
  The released package must contain the signed native artifact for the current
156
163
  `process.platform`/`process.arch`; a missing artifact fails closed. A reviewed
157
164
  source checkout can instead opt into `buildFromSource: true` with an absolute
158
165
  `sourceRoot`. The developer secret is sent only over the child's stdin, and
159
166
  the Node layer only demultiplexes bounded application messages and authority
160
167
  assignments. The Rust peer-session actor remains the sole lifecycle owner.
168
+ `connection.peerId` is the admitted remote endpoint ID, not an app account or
169
+ durable device ID. Room access alone does not grant those identities. Keep
170
+ `stateDirectory` across process restarts to retain the host's private keys.
171
+ Await `service.close()` before reusing that directory; it waits for the host
172
+ process to finish, not just acknowledge shutdown.
173
+ JSON and string messages use the same room-scoped envelope as browser
174
+ `Connection.send`; `onMessage` receives the application value, not the envelope.
175
+ Messages explicitly addressed to another room are discarded. Node byte payloads
176
+ (`Uint8Array`/`ArrayBuffer`) retain the lower-level native byte contract; use
177
+ JSON values for portable browser/Node application messages.
161
178
  This preview Node facade intentionally owns one room and exposes only
162
179
  message-oriented `send`/`onMessage`/`onClose` plus assignment publication; it
163
180
  does not yet claim the browser facade's streams, media, or full Room
164
181
  namespaces. Browser resolution of `openrtc/node` fails closed; browser code
165
182
  uses WASM plus delegated grants through `openrtc/service-node`. Native Rust
166
183
  uses `ControlPlane::join_authority_room` directly and does not require
167
- JavaScript.
184
+ JavaScript. Its `RoomAuthority::compose_client(builder)` method binds the
185
+ dedicated service-room client to the existing Rust peer-session owner before
186
+ endpoint initialization. Native hosts publish a room-scoped compound ticket;
187
+ attaching the signaling backend alone is not service startup.
168
188
 
169
189
  The authority surface remains preview-only until signed prebuilt artifacts and
170
190
  source-bound browser, Node, and native Rust authority E2E lanes pass.
@@ -0,0 +1 @@
1
+ import {b as b$1,a}from'./chunk-LLZT3MR6.js';import'./chunk-JPBW67B3.js';var p=64,w=50;function l(n,e){if(n instanceof Uint8Array)return n.slice();if(n instanceof ArrayBuffer)return new Uint8Array(n.slice(0));if(Array.isArray(n)&&n.every(r=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(n);throw new Error(`[OpenRTC] ${e} returned invalid binary data.`)}var u=class{constructor(e,r,t,i,o){this.bridge=e;this.handleId=r;this.onFailure=o;this.incoming=null;this.incomingWriters=new Map;this.sources=new Map;this.timer=null;this.closed=false;let s=i[0]??"",c={beginOpenRtcMediaPublication:async a=>{let d=await this.bridge.invoke("begin_openrtc_broadcast_publication",{handleId:this.handleId,sourceSlot:s,publicationId:a.publicationId||null,kind:a.kind,codec:a.codec,clockRate:a.clockRate,codedWidth:a.codedWidth??null,codedHeight:a.codedHeight??null,channels:a.channels??null});return {...d,control:l(d.control??[],"broadcast publication")}},encodeOpenRtcMediaSample:async a=>{if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");return await this.bridge.invokeRaw("publish_openrtc_broadcast_sample",a.payload,{"x-openrtc-broadcast-handle-id":this.handleId,"x-openrtc-publication-id":a.publicationId,"x-openrtc-timestamp-us":String(a.timestampUs),"x-openrtc-duration-us":String(a.durationUs),"x-openrtc-keyframe":String(a.keyframe),"x-openrtc-discardable":String(a.discardable)}),new Uint8Array},pauseOpenRtcMediaPublication:async a=>{await this.bridge.invoke("pause_openrtc_broadcast_publication",{handleId:this.handleId,publicationId:a});},retireOpenRtcMediaPublication:async a=>{await this.bridge.invoke("retire_openrtc_broadcast_publication",{handleId:this.handleId,publicationId:a});},retireOpenRtcMediaReceiver:async(a,d)=>{await this.bridge.invoke("retire_openrtc_broadcast_receiver",{handleId:this.handleId,publicationId:a,mediaGeneration:d});},decodeOpenRtcMediaControl:a=>this.decodeControl(a),decodeOpenRtcMediaChunk:a=>this.decodeChunk(a)},v={createBidirectionalStream:async()=>({protocol:"openrtc-media/1",readable:new ReadableStream({start(a){a.close();}}),writable:new WritableStream})};if(this.media=new b$1(v,c,(a,d)=>(this.incoming=d,()=>{this.incoming=null;})),["owner","publisher","processor"].includes(t)&&!s)throw new Error("[OpenRTC] Broadcast publisher grant has no source slot.");this.scheduleReceive(0);}addTrack(e,r){return this.media.addTrack(e,r)}removeTrack(e){return this.media.removeTrack(e)}onTrack(e){return this.media.onTrack(r=>e({...r,source:{id:this.sources.get(r.receiver.id)??"unknown"}}))}senders(){return this.media.senders()}receivers(){return this.media.receivers()}async close(){this.closed||(this.closed=true,this.timer&&clearTimeout(this.timer),this.timer=null,await Promise.all([...this.incomingWriters.values()].map(({writer:e})=>e.close().catch(()=>{}))),this.incomingWriters.clear(),this.sources.clear(),await this.media.close());}scheduleReceive(e){this.closed||(this.timer=setTimeout(()=>{this.receive();},e));}async receive(){if(!this.closed)try{let e=await this.bridge.invoke("receive_openrtc_broadcast_media",{handleId:this.handleId,max:p});for(let r of e)await this.accept(r);this.scheduleReceive(e.length===p?0:w);}catch(e){this.closed||this.onFailure(e);}}async accept(e){let r=e.publicationId;if(this.sources.set(r,e.sourceSlot),e.control){let i=this.incomingWriters.get(r);if(e.controlType==="stop"){i?.generation===e.mediaGeneration&&(this.incomingWriters.delete(r),await i.writer.close().catch(()=>{})),this.sources.delete(r);return}if(e.controlType!=="publish"||i&&i.generation>=e.mediaGeneration)return;i&&await i.writer.close().catch(()=>{});let o=new TransformStream,s=o.writable.getWriter();this.incomingWriters.set(r,{generation:e.mediaGeneration,writer:s}),this.incoming?.({peerId:e.sourceSlot,protocol:"openrtc-media/1",readable:o.readable,writable:new WritableStream}),await s.write(a(l(e.control,"broadcast control")));return}if(!e.media)return;let t=this.incomingWriters.get(r);!t||t.generation!==e.mediaGeneration||await t.writer.write(a(l(e.media,"broadcast media")));}async decodeControl(e){if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");return this.bridge.invokeRaw("decode_openrtc_media_control",e,{})}async decodeChunk(e){if(!this.bridge.invokeRaw)throw new Error("[OpenRTC] Native broadcast requires binary IPC.");let r=l(await this.bridge.invokeRaw("decode_openrtc_media_chunk",e,{}),"decode_openrtc_media_chunk");if(r.byteLength<4)throw new Error("[OpenRTC] Native media metadata is truncated.");let i=4+new DataView(r.buffer,r.byteOffset,4).getUint32(0,false);if(i>r.byteLength)throw new Error("[OpenRTC] Native media metadata is invalid.");return {...JSON.parse(new TextDecoder().decode(r.subarray(4,i))),payload:r.slice(i)}}},b=class{constructor(e,r){this.bridge=e;this.context=r;this.sessions=new Set;this.publishers=new Set;}open(e){return this.openNative(e)}async create(e){let r=e.auth??this.context.defaultAuth;if(!r)throw new Error("Managed broadcast creation requires authenticated control-plane access.");let t=await this.context.manage({action:"create",deviceId:await this.context.deviceId(),auth:r,create:e});if(!t)throw new Error("Managed broadcast creation returned no grant.");return t}async preparePublisher(){let e=await this.bridge.invoke("prepare_openrtc_broadcast_publisher"),r=l(e.verificationKey,"broadcast publisher");if(!e.handle||r.byteLength!==32)throw e.handle&&await this.bridge.invoke("release_openrtc_broadcast_publisher",{handle:e.handle}).catch(()=>{}),new Error("[OpenRTC] Native broadcast publisher is invalid.");let t=false,i={verificationKey:r,open:o=>{if(t)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.openNative(o,e.handle)},close:async()=>{t||(t=true,this.publishers.delete(i),await this.bridge.invoke("release_openrtc_broadcast_publisher",{handle:e.handle}));}};return this.publishers.add(i),i}renew(e,r){return this.manage("renew",r,{grant:e})}invite(e,r,t){return this.manage("invite",t,{grant:e,invitation:r})}accept(e,r){return this.manage("accept",r,{invite:e})}async revoke(e,r,t){await this.manage("revoke",t,{grant:e,invite:r});}async leave(e,r){await this.manage("leave",r,{grant:e});}async closeGrant(e,r){await this.manage("close",r,{grant:e});}async close(){await Promise.all([...this.sessions].map(e=>e.close())),await Promise.all([...this.publishers].map(e=>e.close()));}async manage(e,r,t){let i=r??this.context.defaultAuth;if(!i)throw new Error(`Managed broadcast ${e} requires authenticated control-plane access.`);return this.context.manage({action:e,deviceId:await this.context.deviceId(),auth:i,...t})}async openNative(e,r){let t=await this.bridge.invoke("open_openrtc_broadcast",{grantToken:e,issuerPublicKey:null,publisherSignerHandle:r??null,nowMs:Date.now()}),i=t.state,o=false,s=new u(this.bridge,t.handleId,t.role,t.sourceSlots??[],()=>{i="failed";}),c={id:t.id,role:t.role,get state(){return i},media:s,getStats:()=>this.bridge.invoke("get_openrtc_broadcast_stats",{handleId:t.handleId}),close:async()=>{o||(o=true,i="closed",await s.close(),await this.bridge.invoke("close_openrtc_broadcast",{handleId:t.handleId}),this.sessions.delete(c));}};return this.sessions.add(c),c}};export{b as NativeManagedBroadcastHost};
@@ -1 +1 @@
1
- export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-EIJNERKZ.js';import'./chunk-AYHD4X2R.js';import'./chunk-GTHSRQ7Y.js';import'./chunk-XTYALGJN.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';
1
+ export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-PLIWPC45.js';import'./chunk-AYHD4X2R.js';import'./chunk-AAZPQQXX.js';import'./chunk-XTYALGJN.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';
@@ -313,6 +313,7 @@ declare class RuntimeClient {
313
313
  private resolveManagedSessionUserId;
314
314
  private resolveManagedAutoConnectEnabled;
315
315
  private resolveManagedPresenceEnabled;
316
+ private resolveManagedTicketScope;
316
317
  private getEffectiveRuntimeUserId;
317
318
  private fetchAndApplyAppLimits;
318
319
  private resolvePeerStreamTarget;
@@ -466,7 +467,7 @@ declare class RuntimeClient {
466
467
  preserveBackendSession?: boolean;
467
468
  }): Promise<void>;
468
469
  private stopManagedSessionInternal;
469
- private rotateManagedUserDeviceGrant;
470
+ private rotateManagedGrant;
470
471
  listDevices(): Promise<RuntimeDevice[]>;
471
472
  listDeviceStatus(): Promise<DeviceStatus[]>;
472
473
  updateDevice(deviceId: string, updates: {
@@ -1 +1 @@
1
- import {t}from'./chunk-GTHSRQ7Y.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
1
+ import {t}from'./chunk-AAZPQQXX.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
@@ -0,0 +1,2 @@
1
+ import {b as b$1,d,l}from'./chunk-OT7IPLZE.js';import {a,c,e}from'./chunk-N6LGTNUI.js';import*as D from'tweetnacl';function _t(){throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an AuthProvider; legacy runtimes must import openrtc/auth explicitly.");}var Me="openrtc-trust";var re="identity",R="managed-room-keys",I="managed-room-state";function Ee(){if(typeof globalThis.indexedDB>"u")throw new Error("[OpenRTC] Managed rooms require durable IndexedDB storage.");return globalThis.indexedDB}function _e(){return new Promise((t,e)=>{let n=Ee().open(Me,2);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(re)||i.createObjectStore(re),i.objectStoreNames.contains(R)||i.createObjectStore(R),i.objectStoreNames.contains(I)||i.createObjectStore(I);},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("managed room database failed")),n.onblocked=()=>e(new Error("managed room database upgrade is blocked"));})}function F(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>n(t.error??new Error("managed room storage failed"));})}function T(t){return new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error??new Error("managed room storage failed")),t.onabort=()=>n(t.error??new Error("managed room storage aborted"));})}function ke(t,e,n){return `${t}:${e}:${n}`}function De(t,e){return `${t}:${e}`}function oe(t){return new TextEncoder().encode(`openrtc-managed-room-state-v1:${t}`)}async function xe(t,e){let n=t.transaction(R,"readonly"),i=T(n),r=await F(n.objectStore(R).get(e));if(await i,r)return r;let o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},false,["encrypt","decrypt"]),a=t.transaction(R,"readwrite"),s=T(a);a.objectStore(R).add(o,e);try{return await s,o}catch{let c=t.transaction(R,"readonly"),d=T(c),l=await F(c.objectStore(R).get(e));if(await d,!l)throw new Error("[OpenRTC] Managed room wrapping key could not be persisted.");return l}}function Ge(t){let e=t;return e?.schemaVersion===1&&e.wrappedKey instanceof Uint8Array&&e.wrappingNonce instanceof Uint8Array&&e.wrappingNonce.byteLength===12&&(e.sealedState===void 0||e.sealedState instanceof Uint8Array)?e:null}async function W(t,e,n){let i=await _e(),r=ke(t,e,n);try{let o=await xe(i,De(t,e)),a=i.transaction(I,"readonly"),s=T(a),c=Ge(await F(a.objectStore(I).get(r)));await s;let d,l;if(c){let u=await crypto.subtle.decrypt({name:"AES-GCM",iv:c.wrappingNonce,additionalData:oe(r)},o,c.wrappedKey).catch(()=>{throw new Error("[OpenRTC] Managed room state key authentication failed.")});if(d=new Uint8Array(u),d.byteLength!==32)throw new Error("[OpenRTC] Managed room state key is invalid.");l=c;}else {d=crypto.getRandomValues(new Uint8Array(32));let u=crypto.getRandomValues(new Uint8Array(12)),v=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:u,additionalData:oe(r)},o,d));l={schemaVersion:1,wrappingNonce:u,wrappedKey:v};let y=i.transaction(I,"readwrite"),m=T(y);y.objectStore(I).add(l,r),await m;}return {wrappingKey:d,sealedState:l.sealedState,async persist(u){if(!(u instanceof Uint8Array)||u.byteLength===0)throw new Error("[OpenRTC] Managed room sealed state is invalid.");let v=i.transaction(I,"readwrite"),y=T(v);v.objectStore(I).put({...l,sealedState:u},r),await y,l={...l,sealedState:u};},close(){d.fill(0),i.close();}}}catch(o){throw i.close(),o}}var Ne=3e4,Ke=5*6e4,Le=3e4,He=100,Ue=48*1024,se=12,Be=10*6e4,je=5*6e4,L=15e3,ze=15e3,Fe=1e3,ae=250;function ce(t){let e=[...new Set(t.map(n=>String(n??"").trim().toLowerCase()).filter(Boolean))].sort();if(e.length>ae)throw new Error(`Coordination excluded-peer set exceeds ${ae} devices.`);return e}var We="openrtc.v2",qe="openrtc.auth.";function de(t){try{let e=t.split(".")[1];if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),i=JSON.parse(globalThis.atob(n));return typeof i.jti=="string"&&i.jti.length>0?i.jti:null}catch{return null}}var h=class extends Error{constructor(n,i,r){super(n);this.retryable=i;this.gatewayCode=r;this.name="CoordinationConnectError";this.code=a.COORDINATION_DISCONNECTED;this.plane="coordination";}},H=class extends Error{constructor(n,i,r){let o=e({code:n,message:i,retryable:r});super(`Coordination gateway ${n}: ${i}`);this.name="CoordinationGatewayProtocolError";this.code=o.code||n||a.COORDINATION_PROTOCOL,this.retryable=r,this.plane=o.plane;}};function le(t){return t instanceof h&&/\bstale-budget\b/i.test(t.message)}function _(t){if(!t||typeof t!="object")return false;let e=t;return e.gatewayCode==="credential-revoked"||e.code==="credential-revoked"||e.reason==="device-certificate-revoked"}function ue(t){if(_(t))return true;if(typeof t!="object"||t===null)return false;let e=t;if(e.retryable===false)return true;let n=e.status??e.statusCode,i=typeof n=="number"?n:Number.NaN;if(Number.isInteger(i)&&i>=400&&i<500&&![408,425,429].includes(i))return true;let r=String(e.code??"");return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(r)}function $e(t){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(t*(.75+e[0]/4294967295*.5)))}function f(t){if(typeof crypto.randomUUID=="function")return `${t}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${t}:${n}`}async function Ve(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),n="";for(let i of new Uint8Array(e))n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function E(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error("[OpenRTC] Managed room payload encoding is invalid.");let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e.padEnd(Math.ceil(e.length/4)*4,"="));return Uint8Array.from(n,i=>i.charCodeAt(0))}function Je(t,e,n){let i=new URL(t);if(i.search||i.hash||i.username||i.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(i.protocol==="https:")i.protocol="wss:";else if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol!=="wss:"&&i.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return i.pathname=`${i.pathname.replace(/\/+$/,"")}/v${n}/connect/${e}`,i.toString()}function pe(t){let e=new URL(t);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var U=class t{constructor(e){this.options=e;this.runtimeInstanceId=f("runtime");this.socket=null;this.socketReady=false;this.activeGrantToken=null;this.activeGrantJti=null;this.activeAvenue=null;this.activeGrantExpiresAtMs=0;this.activeGrantProtocolVersion=1;this.leaseRefreshMode="off";this.pendingLeaseRefreshKey=null;this.authenticationRefreshTail=Promise.resolve();this.authenticationRefreshes=new Map;this.connectPromise=null;this.desiredPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.sparseMembers=new Map;this.sparseRoutes=new Map;this.pendingMembershipPageSnapshot=null;this.sparseTopologyRevision=0;this.roomArchitectureSnapshot=null;this.roomAuthorityAssignment=null;this.roomAuthorityAssignmentExpiry=null;this.roomEncryptionEpoch=0;this.managedWasmClient=null;this.peerAdmissionRuntime=null;this.peerAdmissionScope=null;this.peerAdmissionRevision=0;this.managedStateProvider=W;this.managedState=null;this.managedInitialization=null;this.managedActions=Promise.resolve();this.managedPublishQueue=[];this.managedPublishScheduled=false;this.managedMessageListeners=new Set;this.deviceListeners=new Set;this.architectureListeners=new Set;this.authorityAssignmentListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectOutageStartedAtMs=null;this.reconnectCircuitOpen=false;this.hostAvailable=true;this.connectionReadyWaiters=new Set;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;this.credentialRevoked=false;if(this.initialExcludedPeers=ce(e.initialExcludedPeers??[]),this.desiredExcludedPeers=[...this.initialExcludedPeers],e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let n=new URL(e.gateway.endpoint),i=n.hostname==="127.0.0.1"||n.hostname==="localhost"||n.hostname==="[::1]",r=n.protocol==="https:"||n.protocol==="wss:",o=e.gateway.testingAllowInsecureLoopback===true&&i&&(n.protocol==="http:"||n.protocol==="ws:");if(!r&&!o)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(n.username||n.password||n.search||n.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,n,i,r,o,a){let s=this.desiredPresence;if(i&&this.options.roomArchitecture==="authority"){let l=this.options.avenueOverride;if(l?.kind!=="room"||!this.peerAdmissionRuntime)throw new Error("[OpenRTC] Authority rooms require Rust peer admission support.");let u=`v2:room:${l.id}`;this.peerAdmissionRuntime.__requireScopePeerAdmission(u),this.peerAdmissionScope=u;}this.desiredPresence={localNodeId:e,ticket:n,online:i,ttlMs:r,metadata:o,deviceName:a?.trim()||this.options.getDefaultDeviceName()},(!s||s.localNodeId!==e||s.ticket!==n||s.online!==i||s.ttlMs!==r||s.metadata!==o||s.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);let d=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(l){if(!(l instanceof h)||!l.retryable)throw l;await this.waitForConnectionReady();}this.appliedPresenceRevision>=d||(s&&s.ticket!==n&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:f("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,d));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:f("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<ze)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}setHostAvailability(e){let n=e.available&&!this.hostAvailable;this.hostAvailable=e.available;for(let i of this.roomConnections.values())i.setHostAvailability(e);for(let i of this.friendConnections.values())i.setHostAvailability(e);if(!e.available){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}n&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(i=>this.scheduleReconnect(i));}async updateDevice(e,n){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=n;if(n.excludedPeers!==void 0){let r=ce(n.excludedPeers);this.desiredExcludedPeers=r,i={...n,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:f("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let n=new t({...this.options,credentialPurpose:"device-control"});try{await n.deleteDevice(e);}finally{n.stopAuthActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:f("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,n){let i=r=>e(n?r.filter(o=>o.nodeId!==n):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected().catch(()=>{}),()=>this.deviceListeners.delete(i)}onRoomArchitectureChange(e){return this.architectureListeners.add(e),this.roomArchitectureSnapshot&&e({...this.roomArchitectureSnapshot}),()=>this.architectureListeners.delete(e)}onRoomAuthorityAssignmentChange(e){return this.authorityAssignmentListeners.add(e),e(this.roomAuthorityAssignmentSnapshot()),()=>this.authorityAssignmentListeners.delete(e)}async publishAuthorityAssignment(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"authority.assignment.publish",idempotencyKey:f("authority-assignment"),assignment:e.assignment,signature:e.signature});}setWasmClient(e){this.setManagedRoomRuntime(e,W);}setManagedRoomRuntime(e,n){let i=e;this.peerAdmissionRuntime=i&&typeof i.__requireScopePeerAdmission=="function"&&typeof i.__updateScopePeerAdmission=="function"?i:null;let r=e;this.managedWasmClient=r&&typeof r.__initManagedRoomGroup=="function"&&typeof r.__handleManagedRoomPreparePage=="function"&&typeof r.__handleManagedRoomArtifactChunk=="function"&&typeof r.__sealManagedRoomPayload=="function"&&typeof r.__openManagedRoomPayload=="function"&&typeof r.__forgetManagedRoomGroup=="function"?r:null,this.managedStateProvider=n,this.roomArchitectureSnapshot?.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}onManagedRoomMessage(e){return this.managedMessageListeners.add(e),()=>this.managedMessageListeners.delete(e)}async publishManagedRoomMessage(e){return new Promise((n,i)=>{this.managedPublishQueue.push({input:e,resolve:n,reject:i}),!this.managedPublishScheduled&&(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));})}async subscribeDevices(){let e=null;return new ReadableStream({start:n=>{e=n,this.deviceStreams.add(n);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&n.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:f("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,n){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:f("session-update"),sessionId:this.unscopedId(e),session:n,expiresAtMs:typeof n.expiresAt=="number"?n.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let n=null;return new ReadableStream({start:i=>{n=i,this.sessionStreams.add(i);},cancel:()=>{n&&this.sessionStreams.delete(n),n=null;}})}async sendMessage(e,n,i,r){await this.ensureConnected();let o=f("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:n,state:i,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,n){let i=[...new Set(e.map(s=>s.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let s of i)if(s.length>128||s.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,a=[];n(new Map);for(let s of i){if(!s||s===this.options.getCurrentUserId())continue;let c=this.friendConnection(s);a.push(c.onDevicesChange(d=>{r.value||(o.set(s,d.filter(l=>l.online)),n(new Map(o)));}));}return ()=>{r.value=true;for(let s of a)s();for(let s of i)this.friendConnections.get(s)?.stopAuthActivity(),this.friendConnections.delete(s);}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:f("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.credentialRevoked=false,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthActivity(){this.stopped=true,this.reconnectOutageStartedAtMs=null,this.stopSocket(),this.rejectConnectionReadyWaiters(new h("Coordination activity stopped before capability admission completed.",false)),this.desiredExcludedPeers=[...this.initialExcludedPeers];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();this.pendingAcks.clear();for(let e of this.managedPublishQueue.splice(0))e.reject(new Error("[OpenRTC] Managed room activity stopped."));if(this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.managedState){try{this.managedWasmClient?.__forgetManagedRoomGroup(this.managedAvenueKey());}catch{}this.managedState.close(),this.managedState=null;}this.managedInitialization=null,this.managedMessageListeners.clear(),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment=null,this.authorityAssignmentListeners.clear(),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,n,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new t({...this.options,avenueOverride:{kind:"room",id:r}}),o.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(r,o));try{await o.updatePresence(n,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(a){if(!(a instanceof h)||!a.retryable)throw a;await o.waitForConnectionReady();}}async leaveCoordinationRoom(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthActivity(),this.roomConnections.delete(n));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,n){return this.requireRoomConnection(e).onDevicesChange(r=>n(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.credentialRevoked)throw new h("Coordination credential revoked.",false,"credential-revoked");if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new h("Coordination reconnect is parked until the host is foregrounded and online.",true);if(this.reconnectCircuitOpen)throw new h("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new h("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence??this.controlPresence(),n=this.desiredPresenceRevision,i=async()=>{let r=await this.mintGatewayCredential(e,false);await new Promise((o,a)=>{let s=new WebSocket(Je(r.gatewayUrl,r.routeKey,r.protocolVersion),[We,`${qe}${r.token}`]);this.socket=s;let c=false,d=false,l=null,u=()=>{d||s.readyState!==WebSocket.OPEN||(d=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?n:0),clearTimeout(v),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(r.expiresAtMs,r.protocolVersion),this.resolveConnectionReadyWaiters(),o());},v=setTimeout(()=>{s.close(4408,"authentication timeout"),l=new h("Coordination gateway authentication timed out.",true),a(l);},L);s.onopen=()=>{s.send(JSON.stringify({v:1,type:"auth",token:r.token,device:this.gatewayDevice(e)}));},s.onmessage=y=>{let m;try{m=JSON.parse(String(y.data));}catch{s.close(4400,"invalid gateway frame"),d||(clearTimeout(v),a(new Error("Coordination gateway returned an invalid frame.")));return}if(m.type==="ready"&&!c&&(this.activeGrantToken=r.token,this.activeGrantJti=de(r.token),this.activeAvenue=r.avenue,this.activeGrantExpiresAtMs=r.expiresAtMs,this.activeGrantProtocolVersion=r.protocolVersion,this.leaseRefreshMode=m.leaseRefreshMode??"off",c=true),m.type==="error"&&!d){l=new h(`Coordination gateway ${m.code}: ${m.message}`,m.retryable,m.code),clearTimeout(v),a(l),s.close(4403,m.code);return}this.handleFrame(m,s);let Ce=m.type==="roster.snapshot"||m.type==="membership.snapshot"||m.type==="membership.page"&&this.pendingMembershipPageSnapshot===null;c&&(this.options.credentialPurpose==="device-control"||Ce)&&u();},s.onerror=()=>{d||(clearTimeout(v),l??(l=new h("Coordination gateway connection failed.",true)),a(l));},s.onclose=y=>{clearTimeout(v);let m=this.socket===s;m&&y.code===4403&&(!l||_(l))&&this.stopForCredentialRevocation(new h("Coordination credential revoked.",false,"credential-revoked")),d||(l??(l=new h(`Coordination gateway closed (${y.code}) before its initial projection.`,y.code!==4401&&y.code!==4403)),a(l)),this.socket===s&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed.",s),this.rejectPendingAuthRefresh(new h("Coordination gateway closed during credential refresh.",y.code!==4401&&y.code!==4403),s),m&&!this.stopped&&this.desiredPresence&&y.code!==1e3&&!le(l)&&this.scheduleReconnect(l??new h(`Coordination gateway closed (${y.code}).`,y.code!==4401));};});};try{await i();}catch(r){if(!le(r))throw r;await i();}}async mintGatewayCredential(e,n){let r={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await Ve(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:f("credential")},o;try{if(!this.options.gateway.grantProvider)throw new h("OpenRTC 2.0 coordination requires a v2 gateway grant provider.",!1);o=await this.options.gateway.grantProvider({...r,...n&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(s){throw s instanceof h?s:new h(s instanceof Error?s.message:"Coordination credential mint failed.",!ue(s),_(s)?"credential-revoked":void 0)}if(o.protocolVersion!==2)throw new h("Unsupported coordination gateway protocol.",false);let a=pe(this.options.gateway.endpoint);if(pe(o.gatewayUrl)!==a)throw new h("Coordination credential returned an unexpected gateway origin.",false);return o}handleFrame(e,n=this.socket){if(!(n&&n!==this.socket)){if(e.type==="error"&&e.code==="credential-revoked"){let i=new h(`Coordination gateway ${e.code}: ${e.message}`,false,e.code);this.rejectPendingAcks(i.message,n??void 0),this.rejectPendingAuthRefresh(i,n??void 0),this.stopForCredentialRevocation(i);return}if(e.type==="auth.refreshed"){let i=this.pendingAuthRefresh;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve());}else if(e.type==="lease.refreshed"){let i=this.pendingAuthRefresh;if(i&&i.socket===n&&e.idempotencyKey===this.pendingLeaseRefreshKey){if(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=Date.now()){this.rejectPendingAuthRefresh(new h("Coordination lease refresh is already expired or invalid.",false),n);return}clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.activeGrantExpiresAtMs=e.expiresAtMs,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve();}}else if(e.type==="roster.snapshot"){this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.devices.clear();for(let i of e.devices)this.devices.set(i.deviceId,this.toDevice(i));this.emitDevices();}else if(e.type==="membership.snapshot"){this.pendingMembershipPageSnapshot=null,this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let i of e.members)this.sparseMembers.set(i.deviceId,i);this.rebuildSparseDevices();}else if(e.type==="membership.page"){let i=/^[A-Za-z0-9:_-]{1,160}$/.test(e.snapshotId)&&Number.isSafeInteger(e.pageIndex)&&Number.isSafeInteger(e.pageCount)&&Number.isSafeInteger(e.memberCount)&&e.pageIndex>=0&&e.pageCount>=2&&e.pageCount<=50&&e.pageIndex<e.pageCount&&e.memberCount>100&&e.memberCount<=5e3&&e.members.length>0&&e.members.length<=100;e.pageIndex===0&&i&&(this.pendingMembershipPageSnapshot={snapshotId:e.snapshotId,nextPageIndex:0,pageCount:e.pageCount,memberCount:e.memberCount,members:new Map});let r=this.pendingMembershipPageSnapshot;if(!(i&&r!==null&&r.snapshotId===e.snapshotId&&r.nextPageIndex===e.pageIndex&&r.pageCount===e.pageCount&&r.memberCount===e.memberCount&&e.members.every(a=>a.deviceId.length>0&&!r.members.has(a.deviceId)))||!r){n?.close(4400,"invalid membership page");return}for(let a of e.members)r.members.set(a.deviceId,a);if(r.nextPageIndex+=1,r.nextPageIndex===r.pageCount){if(r.members.size!==r.memberCount){n?.close(4400,"incomplete membership pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let a of r.members.values())this.sparseMembers.set(a.deviceId,a);this.pendingMembershipPageSnapshot=null,this.rebuildSparseDevices();}}else if(e.type==="membership.changed")e.operation==="delete"?this.sparseMembers.delete(e.member.deviceId):this.sparseMembers.set(e.member.deviceId,e.member),this.rebuildSparseDevices();else if(e.type==="topology.lease")this.acceptTopologyLease(e.lease);else if(e.type==="authority.assignment")this.acceptAuthorityAssignment(e.assignment,e.signature);else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let i=this.devices.has(e.device.deviceId),r=this.toDevice(e.device);this.devices.set(r.deviceId,r),this.emitDeviceEvents([{type:i?"modified":"added",device:r}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=Fe&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="managed.prepare.page"||e.type==="managed.commit.chunk.received"||e.type==="managed.received")this.enqueueManagedWork(()=>this.handleManagedFrame(e));else if(e.type==="session.changed"){let i=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let r of this.sessionStreams)r.enqueue(i);}else if(e.type==="ack"){let i=this.pendingAcks.get(e.idempotencyKey);i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh?.socket===n&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let r=this.pendingAuthRefresh;clearTimeout(r.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,r.reject(new h(`Coordination gateway ${e.code}: ${e.message}`,e.retryable,e.code));return}let i=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.reject(new H(e.code,e.message,e.retryable)));}}}enqueueManagedWork(e){let n=this.managedActions.then(e);this.managedActions=n.catch(i=>{console.error("[OpenRTC] Managed room owner rejected a gateway frame:",i),this.socket?.close(4400,"managed room state invalid");});}async flushManagedPublishBatch(){let e=this.managedPublishQueue.splice(0,He);if(e.length!==0)try{await this.ensureConnected(),await this.ensureManagedGroupInitialized();let n=this.roomArchitectureSnapshot,i=this.managedWasmClient,r=this.managedState;if(!n||n.effective!=="managed"||n.phase!=="settled"||this.roomEncryptionEpoch<1||!i||!r)throw new Error("[OpenRTC] Managed room encryption is not settled.");let o=[];for(let d of e){let l=await i.__sealManagedRoomPayload(this.managedAvenueKey(),BigInt(n.epoch),BigInt(this.roomEncryptionEpoch),d.input.messageId,d.input.channel,d.input.priority,d.input.zoneId,d.input.payload);o.push({item:d,sealedState:l.sealedState,envelope:{messageId:d.input.messageId,channel:d.input.channel,priority:d.input.priority,scope:d.input.zoneId?{kind:"zone",zoneId:d.input.zoneId}:{kind:"global"},ciphertext:l.payload}});}await r.persist(E(o[o.length-1].sealedState));let a=[],s=0,c=async()=>{if(a.length===0)return;let d=a;a=[],s=0,await this.sendOperation({v:1,type:"managed.publish",idempotencyKey:f("managed-publish"),architectureEpoch:n.epoch,encryptionEpoch:this.roomEncryptionEpoch,batch:d.map(({envelope:l})=>l)});for(let{item:l}of d)l.resolve();};for(let d of o){let l=d.envelope.ciphertext.length;a.length>0&&s+l>Ue&&await c(),a.push(d),s+=l;}await c();}catch(n){for(let i of e)i.reject(n);throw n}finally{this.managedPublishQueue.length>0&&!this.managedPublishScheduled&&(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));}}managedAvenueKey(){let e=this.activeAvenue??this.options.avenueOverride;if(!e||e.kind!=="room"&&e.kind!=="space")throw new Error("[OpenRTC] Managed groups require an active room or space.");return `${e.kind}:${e.id}`}async ensureManagedGroupInitialized(){if(this.managedState)return;if(this.managedInitialization)return this.managedInitialization;let e=this.managedWasmClient;if(!e)throw new Error("[OpenRTC] This browser runtime has no managed-room Rust/WASM owner.");let n=this.managedAvenueKey(),i=(async()=>{let r=await this.managedStateProvider(this.options.appTag,this.options.getLocalDeviceId(),n),o=await e.__initManagedRoomGroup(n,this.options.getLocalDeviceId(),r.wrappingKey,r.sealedState);this.managedState=r,await this.executeManagedGroupActions([o]);})();this.managedInitialization=i;try{await i;}finally{this.managedInitialization===i&&(this.managedInitialization=null);}}async executeManagedGroupActions(e){for(let n of e)if(n.type==="persist-state"){let i=this.managedState;if(!i)throw new Error("[OpenRTC] Managed room state store is unavailable.");await i.persist(E(n.sealedState));}else n.type==="publish-key-package"?await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:f("managed-key-package"),keyPackageHash:n.keyPackageHash,keyPackage:n.keyPackage}):n.type==="request-prepare-page"?await this.sendOperation({v:1,type:"managed.prepare.page.request",idempotencyKey:f("managed-prepare-page"),preparationId:n.preparationId,pageIndex:n.pageIndex}):n.type==="send-artifact-chunk"?await this.sendOperation({v:1,type:"managed.commit.chunk",idempotencyKey:f("managed-artifact"),...n.chunk}):n.type==="acknowledge-commit"&&await this.sendOperation({v:1,type:"managed.commit.ack",idempotencyKey:f("managed-commit-ack"),preparationId:n.preparationId,encryptionEpoch:n.encryptionEpoch,groupIdHash:n.groupIdHash});}async handleManagedFrame(e){await this.ensureManagedGroupInitialized();let n=this.managedWasmClient;if(!n)throw new Error("[OpenRTC] Managed room Rust/WASM owner is unavailable.");let i=this.managedAvenueKey();if(e.type==="managed.prepare.page"){await this.executeManagedGroupActions(await n.__handleManagedRoomPreparePage(i,e));return}if(e.type==="managed.commit.chunk.received"){await this.executeManagedGroupActions(await n.__handleManagedRoomArtifactChunk(i,e));return}let r=this.roomArchitectureSnapshot;if(!r||r.effective!=="managed"||r.phase!=="settled"||e.architectureEpoch!==r.epoch||e.encryptionEpoch!==this.roomEncryptionEpoch)throw new Error("[OpenRTC] Managed room delivery uses a stale room lease.");let o=[],a=null;for(let s of e.batch){let c=s.scope.kind==="zone"?s.scope.zoneId:void 0,d=await n.__openManagedRoomPayload(i,BigInt(e.architectureEpoch),BigInt(e.encryptionEpoch),s.messageId,s.channel,s.priority,c,E(s.ciphertext));a=d.sealedState,o.push({senderId:e.senderDeviceId,messageId:s.messageId,channel:s.channel,priority:s.priority,...c?{zoneId:c}:{},payload:E(d.payload)});}if(a){let s=this.managedState;if(!s)throw new Error("[OpenRTC] Managed room state store is unavailable.");await s.persist(E(a));}for(let s of o)for(let c of this.managedMessageListeners)c(s);}async sendOperation(e){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let n=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(i){if(!(i instanceof H)||i.code!=="budget-renewal-required"&&i.code!==a.BUDGET_RENEWAL_REQUIRED||!i.retryable)throw i;this.budgetRenewalEpoch===n&&await this.renewBudget(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let n=this.socket;if(!n||n.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.get(e.idempotencyKey)?.timer===o&&this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},L);this.pendingAcks.set(e.idempotencyKey,{socket:n,resolve:i,reject:r,timer:o});try{n.send(JSON.stringify(e));}catch(a){clearTimeout(o),this.pendingAcks.delete(e.idempotencyKey),r(a instanceof Error?a:new Error(String(a)));}});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication(true).then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let n=await this.options.resolveSpaceNamespaceId();if(!n)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:n}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}rebuildSparseDevices(){this.devices.clear();for(let e of this.sparseMembers.values()){let n=this.sparseRoutes.get(e.deviceId),i=n?{...e,...n}:{...e,runtimeInstanceId:"",nodeId:"",ticket:""};this.devices.set(e.deviceId,this.toDevice(i));}this.emitDevices();}acceptTopologyLease(e){if(e.topologyRevision<=this.sparseTopologyRevision)return;let n=this.activeAvenue,i=[...e.active,...e.backups],r=i.map(u=>u.deviceId),o=e.schemaVersion===1||this.validArchitectureLease(e.architecture),a=e.schemaVersion===1||this.validGroupEncryptionLease(e.groupEncryption,e.architecture),s=e.schemaVersion===2&&e.architecture.effectiveMode==="authority",c=e.schemaVersion===2?e.admissionPeers:void 0,d=!s||this.peerAdmissionScope!==null&&this.peerAdmissionRuntime!==null&&Array.isArray(c)&&c.length<=50&&new Set(c.map(u=>u.deviceId)).size===c.length&&c.every(u=>this.sparseMembers.get(u.deviceId)?.online&&u.deviceId!==this.options.getLocalDeviceId()&&/^[0-9a-f]{64}$/.test(u.nodeId));if(!((e.schemaVersion===1||e.schemaVersion===2)&&o&&a&&d&&Number.isSafeInteger(e.topologyRevision)&&e.topologyRevision>0&&(this.sparseTopologyRevision===0?e.previousTopologyRevision===void 0:e.previousTopologyRevision===this.sparseTopologyRevision)&&e.grantJti===this.activeGrantJti&&n!==null&&e.avenue.kind===n.kind&&e.avenue.id===n.id&&Number.isSafeInteger(e.expiresAtMs)&&e.expiresAtMs>Date.now()&&e.expiresAtMs<=this.activeGrantExpiresAtMs&&e.active.length<=16&&e.backups.length<=4&&i.length<=20&&new Set(r).size===r.length&&i.every(u=>u.online&&this.sparseMembers.has(u.deviceId)&&u.deviceId!==this.options.getLocalDeviceId()&&u.nodeId.trim().length>0&&u.ticket.trim().length>0))){this.socket?.close(4400,"invalid topology lease");return}if(s)try{this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,e.expiresAtMs,JSON.stringify(c.map(u=>u.nodeId)));}catch{this.socket?.close(4400,"invalid peer admission lease");return}if(e.schemaVersion===2){e.groupEncryption&&(this.roomEncryptionEpoch=e.groupEncryption.epoch);let u={requested:e.architecture.requestedMode,effective:e.architecture.effectiveMode,epoch:e.architecture.epoch,phase:e.architecture.phase,reason:e.architecture.reason,heldCreditsUsd:e.architecture.heldCreditsMicrousd/1e6,quoteExpiresAtMs:e.architecture.quoteExpiresAtMs},v=JSON.stringify(u)!==JSON.stringify(this.roomArchitectureSnapshot);if(this.roomArchitectureSnapshot=u,v)for(let y of this.architectureListeners)y({...u});if(u.effective!=="authority"&&this.roomAuthorityAssignment){this.roomAuthorityAssignmentExpiry&&(clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null),this.roomAuthorityAssignment=null;for(let y of this.authorityAssignmentListeners)y(null);}u.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}this.sparseTopologyRevision=e.topologyRevision,this.sparseRoutes.clear();for(let u of e.active)this.sparseRoutes.set(u.deviceId,{...u,topologyRole:"active",topologyRevision:e.topologyRevision});for(let u of e.backups)this.sparseRoutes.set(u.deviceId,{...u,topologyRole:"backup",topologyRevision:e.topologyRevision});this.rebuildSparseDevices();}acceptAuthorityAssignment(e,n){let i=this.roomAuthorityAssignment,r=this.options.getLocalDeviceId(),o=[e.serviceId,e.subjectDeviceId,e.shardId,...e.priorityDeviceIds,...e.relevantEntityIds];if(i&&e.generation===i.generation&&e.revision===i.revision){if(JSON.stringify({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:e.priorityDeviceIds,relevantEntityIds:e.relevantEntityIds,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs})===JSON.stringify(i))return;this.socket?.close(4400,"invalid authority assignment");return}if(!(e.policyVersion==="room-authority-assignment-v1"&&this.roomArchitectureSnapshot?.effective==="authority"&&e.subjectDeviceId===r&&Number.isSafeInteger(e.generation)&&e.generation>0&&Number.isSafeInteger(e.revision)&&e.revision>0&&Number.isSafeInteger(e.issuedAtMs)&&Number.isSafeInteger(e.expiresAtMs)&&e.issuedAtMs<=Date.now()+3e4&&e.expiresAtMs>Date.now()&&e.expiresAtMs-e.issuedAtMs<=12e4&&e.priorityDeviceIds.length<=8&&e.relevantEntityIds.length<=32&&new Set(e.priorityDeviceIds).size===e.priorityDeviceIds.length&&new Set(e.relevantEntityIds).size===e.relevantEntityIds.length&&o.every(c=>/^[A-Za-z0-9_.:@-]{1,160}$/.test(c))&&/^[A-Za-z0-9_-]{86}$/.test(n)&&(!i||e.generation>i.generation||e.generation===i.generation&&e.revision>i.revision))){this.socket?.close(4400,"invalid authority assignment");return}this.roomAuthorityAssignment=Object.freeze({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:Object.freeze([...e.priorityDeviceIds]),relevantEntityIds:Object.freeze([...e.relevantEntityIds]),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs}),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=setTimeout(()=>{if(this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment?.expiresAtMs===e.expiresAtMs){this.roomAuthorityAssignment=null;for(let c of this.authorityAssignmentListeners)c(null);}},Math.max(0,e.expiresAtMs-Date.now()));for(let c of this.authorityAssignmentListeners)c(this.roomAuthorityAssignmentSnapshot());}roomAuthorityAssignmentSnapshot(){let e=this.roomAuthorityAssignment;return !e||e.expiresAtMs<=Date.now()?null:{...e,priorityDeviceIds:[...e.priorityDeviceIds],relevantEntityIds:[...e.relevantEntityIds]}}validArchitectureLease(e){let n=this.roomArchitectureSnapshot?.epoch??0,i=new Set(["auto","mesh","sparse","managed","authority"]),r=new Set(["mesh","sparse","managed","authority"]),o=new Set(["size","traffic","latency","cost","capacity","manual","recovery"]);return e.policyVersion==="room-architecture-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=n&&(e.epoch===n||n===0||e.previousArchitectureEpoch===n)&&i.has(e.requestedMode)&&r.has(e.effectiveMode)&&(e.phase==="settled"||e.phase==="preparing")&&o.has(e.reason)&&Number.isSafeInteger(e.heldCreditsMicrousd)&&e.heldCreditsMicrousd>=0&&Number.isSafeInteger(e.quoteExpiresAtMs)&&e.quoteExpiresAtMs>0&&(e.reservationId===void 0||/^[A-Za-z0-9:_-]{1,160}$/.test(e.reservationId))}validGroupEncryptionLease(e,n){if(!e)return n.effectiveMode!=="managed"||n.phase==="preparing";let i=this.roomEncryptionEpoch;return e.policyVersion==="room-mls-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=i&&(e.epoch===i||i===0||e.previousEncryptionEpoch===i)&&(e.phase==="preparing"||e.phase==="settled")&&(n.effectiveMode!=="managed"||n.phase!=="settled"||e.phase==="settled")&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(e.committerDeviceId)&&/^[A-Za-z0-9_-]{43}$/.test(e.groupIdHash)}snapshot(e){return [...this.devices.values()].filter(n=>!e||n.nodeId!==e).sort((n,i)=>n.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let n of this.deviceListeners)n(e);}emitDeviceEvents(e){for(let n of this.deviceStreams)n.enqueue(e);}updateLocalDeviceExpiry(e){let n=this.options.getLocalDeviceId(),i=this.devices.get(n);if(!i||i.expiresAt===e)return;let r={...i,expiresAt:e};this.devices.set(n,r),this.emitDeviceEvents([{type:"modified",device:r}]),this.emitDevices();}scheduleAuthRefresh(e,n){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),r=n===2?Ke:Ne,o=i>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!o){this.stopSocket(false),this.scheduleReconnect(new h("Coordination credential crossed a billing boundary.",true));return}(n===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(s=>{this.stopSocket(false),this.scheduleReconnect(s);});},o?i-r:Math.max(1e3,i+1e3));}refreshAuthentication(e=false){let n=`${e?"issue":"refresh"}\0${this.desiredPresence?.ticket??""}`,i=this.authenticationRefreshes.get(n);if(i)return i;let r=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performAuthenticationRefresh(e));this.authenticationRefreshTail=r,this.authenticationRefreshes.set(n,r);let o=()=>{this.authenticationRefreshes.get(n)===r&&this.authenticationRefreshes.delete(n);};return r.then(o,o),r}async performAuthenticationRefresh(e){let n=this.socket,i=this.desiredPresence;if(!n||n.readyState!==WebSocket.OPEN||!this.socketReady||!i)throw new h("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let r=await this.mintGatewayCredential(i,!e);if(this.socket!==n||n.readyState!==WebSocket.OPEN||!this.socketReady)throw new h("Coordination socket changed while minting a credential refresh.",true);let o,a,s=new Promise((d,l)=>{o=d,a=l;}),c=setTimeout(()=>{this.pendingAuthRefresh?.timer===c&&(this.pendingAuthRefresh=null),a(new h("Coordination credential refresh timed out.",true));},L);this.pendingAuthRefresh={socket:n,promise:s,resolve:o,reject:a,timer:c};try{n.send(JSON.stringify({v:1,type:"auth.refresh",token:r.token}));}catch(d){this.rejectPendingAuthRefresh(new h(d instanceof Error?d.message:"Coordination credential refresh send failed.",true),n);}await s,this.activeGrantToken=r.token,this.activeGrantJti=de(r.token),this.activeAvenue=r.avenue,this.activeGrantExpiresAtMs=r.expiresAtMs,this.activeGrantProtocolVersion=r.protocolVersion;}refreshLease(){let e=`lease\0${this.desiredPresence?.ticket??""}`,n=this.authenticationRefreshes.get(e);if(n)return n;let i=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performLeaseRefresh());this.authenticationRefreshTail=i,this.authenticationRefreshes.set(e,i);let r=()=>{this.authenticationRefreshes.get(e)===i&&this.authenticationRefreshes.delete(e);};return i.then(r,r),i}async performLeaseRefresh(){let e=this.socket;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady)throw new h("Coordination socket is unavailable for lease refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let n=f("lease"),i,r,o=new Promise((s,c)=>{i=s,r=c;}),a=setTimeout(()=>{this.pendingAuthRefresh?.timer===a&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),r(new h("Coordination lease refresh timed out.",true));},L);this.pendingLeaseRefreshKey=n,this.pendingAuthRefresh={socket:e,promise:o,resolve:i,reject:r,timer:a};try{e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:n}));}catch(s){this.rejectPendingAuthRefresh(new h(s instanceof Error?s.message:"Coordination lease refresh send failed.",true),e);}try{await o;}catch(s){if(this.stopped||_(s))throw s;await this.performAuthenticationRefresh(true);}}stopForCredentialRevocation(e){return _(e)?(this.credentialRevoked=true,this.reconnectCircuitOpen=true,this.stopAuthActivity(),true):false}scheduleReconnect(e){if(this.stopForCredentialRevocation(e)||this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof h?e.retryable:!ue(e))){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new h("Coordination reconnect circuit is open.",false));return}if(this.reconnectOutageStartedAtMs??(this.reconnectOutageStartedAtMs=Date.now()),!this.hostAvailable)return;let i=Math.min(this.reconnectAttempt,se),r=Date.now()-this.reconnectOutageStartedAtMs>=Be,o=$e(r?je:d(i,250,Le));this.reconnectAttempt=Math.min(i+1,se),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(a=>this.scheduleReconnect(a));},o);}stopSocket(e=true){this.peerAdmissionScope&&this.peerAdmissionRuntime&&this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,0,"[]"),e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null,this.leaseRefreshMode="off",this.pendingLeaseRefreshKey=null,this.rejectPendingAuthRefresh(new h("Coordination credential refresh was canceled.",true));let n=this.socket;this.socket=null,this.socketReady=false,this.activeGrantJti=null,this.activeAvenue=null,this.activeGrantExpiresAtMs=0,this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.pendingMembershipPageSnapshot=null,this.sparseMembers.size>0&&this.rebuildSparseDevices(),n?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new h("Coordination reconnect circuit is unavailable.",false)):new Promise((e,n)=>{this.connectionReadyWaiters.add({resolve:e,reject:n});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let n of this.connectionReadyWaiters)n.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e,n){let i=this.pendingAuthRefresh;!i||n&&i.socket!==n||(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,i.reject(e));}rejectPendingAcks(e,n){for(let[i,r]of this.pendingAcks)n&&r.socket!==n||(clearTimeout(r.timer),r.reject(new Error(e)),this.pendingAcks.delete(i));}unscopedId(e){let n=e.split("::");return n.length===2?n[1]:e}requireRoomConnection(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);if(!i)throw new Error(`Room ${n} is not joined through the coordination gateway.`);return i}friendConnection(e){let n=this.friendConnections.get(e);if(n||(n=new t({...this.options,avenueOverride:{kind:"user",id:e}}),n.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,n)),!n.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");n.desiredPresence={...this.desiredPresence};}return n}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var B=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let n=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>n+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",a=Number(r?.expiresAtMs),s=Date.now();if(!o||!Number.isFinite(a)||a<=s+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let c={token:o,expiresAtMs:a};return this.cached=c,this.refreshRetryUsed=false,this.notify(c),this.scheduleRefresh(c),c})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,n){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(n?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let n of this.listeners)n(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let n=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},n);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};var he=class{constructor(e){this.options=e;this.signaling=null;this.wasmClient=null;this.managedStateProvider=null;this.hostAvailability={available:true,reason:"initial"};this.nativeTrustTokens=e.gateway?new B(e.gateway.nativeTrustTokenProvider):null;}usesGateway(){return !!this.options.gateway}getSignaling(){if(this.options.signalingMode==="ticket-only")throw new Error('[openrtc] Managed signaling is disabled when signalingMode="ticket-only".');if(!this.options.gateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");if(!this.signaling){this.signaling=new U({projectId:this.options.projectId,gateway:this.options.gateway,appTag:this.options.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:this.options.resolveSpaceNamespaceId,getCurrentUserId:this.options.getCurrentUserId,getAuthToken:this.options.getAuthToken,getAppCheckToken:this.options.getAppCheckToken,getLocalDeviceId:this.options.getLocalDeviceId,getDefaultDeviceName:this.options.getDefaultDeviceName,getPlatformType:this.options.getPlatformType,normalizeDevice:this.options.normalizeDevice,avenueOverride:this.options.avenueOverride,roomArchitecture:this.options.roomArchitecture,initialExcludedPeers:this.options.initialExcludedPeers,nativeTrustTokens:this.nativeTrustTokens});let e=this.signaling;this.managedStateProvider?e.setManagedRoomRuntime(this.wasmClient,this.managedStateProvider):e.setWasmClient(this.wasmClient),this.signaling.setHostAvailability?.(this.hostAvailability);}return this.signaling}setWasmClient(e){this.wasmClient=e,this.managedStateProvider=null,this.signaling?.setWasmClient(e);}setManagedRoomRuntime(e,n){this.wasmClient=e,this.managedStateProvider=n,this.signaling?.setManagedRoomRuntime(e,n);}setHostAvailability(e){this.hostAvailability=e,this.signaling?.setHostAvailability?.(e);}async reconnectAfterHostResume(){await this.signaling?.reconnectAfterHostResume?.();}async handleScopeChange(){await this.signaling?.handleScopeChange();}stopAuthActivity(){this.signaling?.stopAuthActivity();}async getNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeNativeTrustToken(e,n){return this.nativeTrustTokens?.subscribe(e,n)??(()=>{})}};function Ye(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function q(t,e,n){if(Ye()){if(typeof n>"u"){console[t](e);return}console[t](e,n);}}function Bt(t,e){q("debug",t,e);}function jt(t,e){q("info",t,e);}function zt(t,e){q("log",t,e);}function ge(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var Qe="[OpenRTC][teardown-trace]";function Xe(){try{let t=globalThis;if(t.OPENRTC_TEARDOWN_TRACE===!0||t.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function qt(t,e={}){console.info(Qe,{kind:t,ts:new Date().toISOString(),...e}),Xe()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:t,stack:new Error(`teardown: ${t}`).stack});}var z="trustedDevice",Ze="plutonium:e2ee:identity:v1",et="plutonium:e2ee:identity:session:v1",tt="openrtc-trust",P="identity",fe="transport-trust:v1",nt=2,ye="managed-room-keys",me="managed-room-state",it=1,b=null,k=null;function S(t){let e=atob(t),n=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return n}function x(t){let e="";for(let n=0;n<t.length;n+=1)e+=String.fromCharCode(t[n]);return btoa(e)}async function $(t){let e=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join("")}function rt(){return typeof sessionStorage>"u"?null:sessionStorage}function ot(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Ze);}catch{}}var j=null;async function ve(){return j||(j=(async()=>{let t=globalThis.crypto?.subtle;if(!t||typeof t.generateKey!="function")return false;try{let e=await t.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),j)}async function st(t){let e=await crypto.subtle.exportKey("raw",t);return new Uint8Array(e)}function at(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function be(){let t=at();return t?new Promise(e=>{let n;try{n=t.open(tt,nt);}catch{e(null);return}n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(P)||i.createObjectStore(P),i.objectStoreNames.contains(ye)||i.createObjectStore(ye),i.objectStoreNames.contains(me)||i.createObjectStore(me);},n.onsuccess=()=>e(n.result),n.onerror=()=>e(null),n.onblocked=()=>e(null);}):Promise.resolve(null)}async function ct(){let t=await be();if(!t)return null;try{return await new Promise(e=>{let r=t.transaction(P,"readonly").objectStore(P).get(fe);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{t.close();}}async function dt(t){let e=await be();if(!e)return false;try{return await new Promise(n=>{let i=e.transaction(P,"readwrite");i.objectStore(P).put(t,fe),i.oncomplete=()=>n(!0),i.onerror=()=>n(!1),i.onabort=()=>n(!1);})}catch{return false}finally{e.close();}}async function we(t,e){let n=await st(t.publicKey),i=await $(n),r=t.privateKey;return {publicKey:n,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let a=await crypto.subtle.sign({name:"Ed25519"},r,S(o));return x(new Uint8Array(a))}}}function lt(t,e,n){let i=t.secretKey;return {publicKey:t.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:n,async signChallenge(r){return ut(r,i)}}}function Yt(t=32){let e=crypto.getRandomValues(new Uint8Array(t));return x(e)}function ut(t,e){let n=D.sign.detached(S(t),e);return x(n)}function pt(t,e,n){try{return D.sign.detached.verify(S(t),S(e),S(n))}catch{return false}}async function Qt(t,e,n){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",S(n),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,S(e),S(t))}catch{}return pt(t,e,n)}function Xt(t){return x(t)}function Zt(t){if(!t||!t.trim())return null;try{let e=JSON.parse(t),n=e&&typeof e=="object"&&!Array.isArray(e)?e[z]:null;if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,a=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!a?null:{version:r,identityPublicKey:o,identityFingerprint:a}}catch{return null}}async function ht(){let t=await vt().catch(()=>null);return t?{version:it,identityPublicKey:x(t.publicKey),identityFingerprint:t.fingerprint}:null}async function en(t){let e=await ht();if(!e)return t??void 0;let n=typeof t=="string"?t.trim():"";if(!n)return JSON.stringify({[z]:e});try{let i=JSON.parse(n);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[z]:e})}catch{}return JSON.stringify({metadata:t,[z]:e})}function gt(){if(typeof window>"u")return null;let t=window.__TAURI_INTERNALS__;return !t||typeof t.invoke!="function"?null:t.invoke.bind(t)}async function yt(){if(typeof window>"u")return null;let t=gt();if(!ge()&&!t)return null;if(!t)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await t("openrtc_get_transport_trust_identity"),n=S(e.publicKeyBase64);if(n.byteLength!==D.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await $(n);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:n,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return t("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let n=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw n.cause=e,n}}function mt(){let t=rt();t&&t.removeItem(et);}async function ft(){if(ot(),mt(),b)return b;let t=await yt();if(t)return b=t,b;if(await ve()){let e=await ct();if(e)return b=await we(e,true),b}return null}async function vt(t={}){let e=await ft();if(e)return e;if(k)return k;let n=bt(t);k=n;try{return await n}finally{k===n&&(k=null);}}async function bt(t){if(b)return b;let e=t.ephemeral===true;if(await ve())try{let n=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await dt(n)),b=await we(n,i),b}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let n=D.sign.keyPair(),i=await $(b$1(n.publicKey));return b=lt(n,i,!1),b}catch{return null}}var wt={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function nn(){return wt}var St={adapter:"browser-wasm",productMaturity:{boundedRooms:"stable",serviceNodes:"preview",offlineEdge:"support-only",broadcast:"preview"},signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:false,irohLan:false,webRtc:true,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},Rt={adapter:"native-ipc",productMaturity:{boundedRooms:"stable",serviceNodes:"unavailable",offlineEdge:"unavailable",broadcast:"unavailable"},signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function Se(t){return {adapter:t.adapter,productMaturity:t.productMaturity?{...t.productMaturity}:void 0,signaling:{...t.signaling},transport:{...t.transport},nativeProtocols:{...t.nativeProtocols},lifecycle:{...t.lifecycle},transfers:{...t.transfers},fallback:{...t.fallback}}}function on(t=globalThis){let e=Se(St),n=typeof t?.RTCPeerConnection=="function";return e.transport.webRtc=n,e}function G(t){return t?.compiled===true&&t.enabled===true}function sn(t,e=false){let n=Se(Rt),i=t?.transport;return n.productMaturity={...n.productMaturity,...t?.productMaturity},i&&(n.transport.irohQuic=G(i.irohQuic),n.transport.irohLan=G(i.irohLan),n.transport.webRtc=G(i.webRtc),n.transport.moq=G(i.moq),n.transport.ble=G(i.ble)),n.transport.wasm=false,n.fallback.wasm=e,n}function an(t){return {environment:t.adapter==="native-ipc"||t.adapter==="tauri-ipc"?"native":t.adapter==="browser-wasm"?"web":"unknown",productMaturity:t.productMaturity?{...t.productMaturity}:void 0,transports:{quic:t.transport.irohQuic,irohRelay:t.transport.irohQuic||t.adapter==="browser-wasm",irohLan:t.transport.irohLan,webRtc:t.transport.webRtc,moq:t.transport.moq,ble:t.transport.ble},lifecycle:{...t.lifecycle},storage:{localFileSystem:t.transfers.explicitFilePath,transferHistory:t.transfers.history},nativeProtocols:{...t.nativeProtocols}}}function Re(t){if(t.errorCode)return t;let e=t.error||t.readinessReason;if(!e)return t;let n=c(e);return {...t,errorCode:n.errorCode,retryable:n.retryable,errorPlane:n.errorPlane}}function C(t){return !t||typeof t!="object"?{}:t instanceof Map?Object.fromEntries(t):t}function V(t){let e=C(t),n=C(e.device);if(!Object.keys(n).length)return e;let i={...n,...e};return delete i.device,i}function p(t,...e){for(let n of e){let i=t[n];if(typeof i=="string"&&i.trim().length>0)return i}}function w(t,...e){for(let n of e){let i=t[n];if(typeof i=="boolean")return i}}function g(t,...e){for(let n of e){let i=t[n];if(typeof i=="number"&&Number.isFinite(i))return i}}function A(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date){let e=t.getTime();return Number.isFinite(e)?e:void 0}if(typeof t=="string"){let e=Date.parse(t);return Number.isFinite(e)?e:void 0}if(t&&typeof t=="object"){let e=t;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let n=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(n!==void 0&&Number.isFinite(n)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function J(...t){let e=t.map(A).filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length?Math.max(...e):void 0}function Y(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ie(t){let e=Y("presenceStatus"in t?t.presenceStatus:void 0),n="presenceUpdatedAt"in t?A(t.presenceUpdatedAt):void 0,i="presenceExpiresAt"in t?A(t.presenceExpiresAt):void 0,r=n??J(t.lastSeenAt,t.updatedAt,t.createdAt),o=i??A(t.expiresAt),a=e;a||(t.online?r!==void 0&&r+3e5<=Date.now()?a="idle":a="online":a="offline");let s=typeof t.ticket=="string"?t.ticket.trim():"",c="connectable"in t&&typeof t.connectable=="boolean"?t.connectable:a==="online"&&s.length>0;return {presenceStatus:a,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:c}}function Ae(t){return l(t)}function M(t,...e){return Ae(p(t,...e))}function N(t){if(!Array.isArray(t))return;let e=Array.from(new Set(t.map(Ae).filter(n=>!!n)));return e.length?e:void 0}function Te(t){let e=C(t),n={webrtc:g(e,"webrtc"),iroh:g(e,"iroh"),irohLan:g(e,"irohLan","iroh_lan"),irohRelay:g(e,"irohRelay","iroh_relay"),ble:g(e,"ble"),moq:g(e,"moq")};return Object.values(n).some(i=>i!==void 0)?n:void 0}function pn(t){return (t.discoveryMode??"space")==="space"&&typeof t.apiKey=="string"&&t.apiKey.trim().length>0&&typeof t.spaceKey=="string"&&t.spaceKey.trim().length>0}function hn(t,e,n){return n?true:(typeof t.appTag=="string"?t.appTag:typeof t.tag=="string"?t.tag:void 0)===e}function It(t,e){let n=V(t),i=p(n,"deviceId","device_id")||e||"",r=p(n,"nodeId","node_id")||"",o=p(n,"ticket")||"";return {deviceId:i,deviceName:p(n,"deviceName","device_name")||"Unknown Device",online:!!n.online,ticket:o,friendTicket:p(n,"friendTicket","friend_ticket"),presenceStatus:Y(p(n,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:g(n,"presenceUpdatedAt","presence_updated_at")??J(n.presenceUpdatedAt,n.presence_updated_at,n.lastSeenAt,n.last_seen_at,n.updatedAt,n.updated_at,n.createdAt,n.created_at),presenceExpiresAt:g(n,"presenceExpiresAt","presence_expires_at")??A(n.presenceExpiresAt??n.presence_expires_at)??A(n.expiresAt??n.expires_at),connectable:w(n,"connectable"),kind:p(n,"kind"),nodeId:r||void 0,devicePublicKeyJwk:n.devicePublicKeyJwk??n.device_public_key_jwk,platformType:p(n,"platformType","platform_type"),capabilities:n.capabilities||void 0,sessionId:p(n,"sessionId","session_id"),userId:p(n,"userId","user_id"),lastSeenAt:n.lastSeenAt??n.last_seen_at,expiresAt:n.expiresAt??n.expires_at,createdAt:n.createdAt??n.created_at,updatedAt:n.updatedAt??n.updated_at,metadata:p(n,"metadata"),excludedPeers:Q(n.excludedPeers??n.excluded_peers),availableTransports:N(n.availableTransports??n.available_transports),transports:N(n.transports),topologyRole:n.topologyRole==="active"||n.topologyRole==="backup"?n.topologyRole:void 0,topologyRevision:Number.isSafeInteger(n.topologyRevision)&&Number(n.topologyRevision)>0?Number(n.topologyRevision):void 0}}function Q(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function At(t){let e=Ie(t);return {...t,...e,connectionStatus:"connectionStatus"in t&&typeof t.connectionStatus=="string"?t.connectionStatus:t.online?"online":"disconnected",settledReady:"settledReady"in t&&typeof t.settledReady=="boolean"?t.settledReady:false,readinessState:"readinessState"in t&&typeof t.readinessState=="string"?t.readinessState:void 0,readinessReason:"readinessReason"in t&&typeof t.readinessReason=="string"?t.readinessReason:void 0,peerHealth:"peerHealth"in t&&typeof t.peerHealth=="string"?t.peerHealth:"unknown",peerId:"peerId"in t&&typeof t.peerId=="string"?t.peerId:void 0,promotionEligible:"promotionEligible"in t&&typeof t.promotionEligible=="boolean"?t.promotionEligible:true,scopes:"scopes"in t?Q(t.scopes):[],connectionId:"connectionId"in t&&typeof t.connectionId=="string"?t.connectionId:void 0,deviceIdHint:"deviceIdHint"in t&&typeof t.deviceIdHint=="string"?t.deviceIdHint:void 0,transportStableId:"transportStableId"in t&&typeof t.transportStableId=="number"?t.transportStableId:"transportStableId"in t?t.transportStableId??null:void 0,transportGeneration:"transportGeneration"in t&&typeof t.transportGeneration=="number"?t.transportGeneration:void 0,routeGeneration:"routeGeneration"in t&&typeof t.routeGeneration=="number"?t.routeGeneration:void 0,activeTransport:"activeTransport"in t?t.activeTransport:void 0,parallelTransport:"parallelTransport"in t?t.parallelTransport:void 0,availableTransports:"availableTransports"in t?N(t.availableTransports):"transports"in t?N(t.transports):void 0,latencyMs:"latencyMs"in t&&typeof t.latencyMs=="number"?t.latencyMs:void 0,latencyByTransport:"latencyByTransport"in t?Te(t.latencyByTransport):void 0}}function O(t,e){return e===void 0?true:e===null?t==null:t==null||t===e}function Pe(t,e){let n=O(t.connectionId,e.connectionId)&&O(t.nodeId,e.nodeId)&&O(t.transportStableId,e.transportStableId)&&O(t.transportGeneration,e.transportGeneration)&&O(t.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:n?o:void 0;return {inheritsSnapshot:n,fields:{connectionId:i(e.connectionId??void 0,t.connectionId),transportStableId:i(e.transportStableId,t.transportStableId),transportGeneration:i(e.transportGeneration,t.transportGeneration),routeGeneration:i(e.routeGeneration,t.routeGeneration),activeTransport:i(e.activeTransport,t.activeTransport),parallelTransport:i(e.parallelTransport,t.parallelTransport),latencyMs:n?t.latencyMs:void 0,latencyByTransport:n?t.latencyByTransport:void 0}}}var Tt={connectionId:void 0,transportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Pt(t,e,n){let i=Pe(t,{connectionId:e.activeConnectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=n?n({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):t.promotionEligible??true;if(!r)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let o=e.status??t.connectionStatus,a=typeof o=="string"?o.trim().toLowerCase():"",s=a==="failed"||a==="closed"||a==="disconnected",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,l=t.settledReady===true||t.readinessState==="routable";if(i.inheritsSnapshot&&l&&!s&&!d)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let u=s?false:d,v=d&&!s&&(a==="connecting"||a==="connected")?"connected":o,y=d?"routable":e.readinessState??(i.inheritsSnapshot?t.readinessState:void 0),m=u?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?t.readinessReason:void 0);return {...t,connectionStatus:v,settledReady:u,readinessState:y,readinessReason:m,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields}}function Ct(t,e){let n=Pe(t,{connectionId:e.connectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:false,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let i=e.status??t.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",a=t.settledReady===true||t.readinessState==="routable",s=e.routable===false;if(n.inheritsSnapshot&&a&&o&&!s)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};if(a&&o)return {...t,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??t.readinessReason,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...Tt,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let c=e.routable===true||e.protocolState==="routable";if(n.inheritsSnapshot&&a&&!o&&!c)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,transportStableId:t.transportStableId??e.transportStableId,transportGeneration:t.transportGeneration??e.transportGeneration,routeGeneration:t.routeGeneration??e.routeGeneration,activeTransport:t.activeTransport??e.activeTransport,parallelTransport:t.parallelTransport===void 0?e.parallelTransport:t.parallelTransport,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};let d=e.transportState==="connected"&&e.health==="healthy",l=o?false:c,u=!o&&(c||d)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,v=l?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(n.inheritsSnapshot?t.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=l?(n.inheritsSnapshot?t.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(n.inheritsSnapshot?t.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...t,connectionStatus:u,settledReady:l,readinessState:v,readinessReason:y,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes}}function Mt(t){let{device:e,session:n=null,peer:i=null,isPromotionEligible:r}=t,o=At(e);return n&&(o=Pt(o,n,r)),i&&(o=Ct(o,i)),Re(o)}function gn(t){let e=V(t),n=It(e),i=Y(p(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ie({...n,...i?{presenceStatus:i}:{},presenceUpdatedAt:g(e,"presenceUpdatedAt","presence_updated_at")??J(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:g(e,"presenceExpiresAt","presence_expires_at")??A(e.presenceExpiresAt??e.presence_expires_at)??A(e.expiresAt??e.expires_at),connectable:w(e,"connectable")}),o={...n,...r,connectionStatus:p(e,"connectionStatus","connection_status")||"disconnected",settledReady:w(e,"settledReady","settled_ready")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,peerHealth:p(e,"peerHealth","peer_health")||"unknown",peerId:p(e,"peerId","peer_id"),scopes:Q(e.scopes),connectionId:p(e,"connectionId","connection_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,activeTransport:M(e,"activeTransport","active_transport"),parallelTransport:M(e,"parallelTransport","parallel_transport")??null,availableTransports:N(e.availableTransports??e.available_transports),latencyMs:g(e,"latencyMs","latency_ms"),latencyByTransport:Te(e.latencyByTransport??e.latency_by_transport)};return Mt({device:o})}function yn(t){let e=V(t);return Re({peerId:p(e,"peerId","peer_id")||"",deviceId:p(e,"deviceId","device_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),nodeId:p(e,"nodeId","node_id"),activeConnectionId:p(e,"activeConnectionId","active_connection_id"),candidates:Array.isArray(e.candidates)?e.candidates.filter(n=>typeof n=="string"):Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(n=>typeof n=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(n=>typeof n=="string"):[],status:p(e,"status")||"disconnected",health:p(e,"health")||"unknown",settledReady:w(e,"settledReady","settled_ready")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,activeTransport:M(e,"activeTransport","active_transport"),parallelTransport:M(e,"parallelTransport","parallel_transport")??null,replacementPending:w(e,"replacementPending","replacement_pending")??void 0,logicalSessionTerminal:w(e,"logicalSessionTerminal","logical_session_terminal")??false,lastTransitionAtMs:g(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,transitionCount:g(e,"transitionCount","transition_count")??void 0,connectTransitions:g(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:g(e,"replacementCount","replacement_count")??void 0,retireCount:g(e,"retireCount","retire_count")??void 0,lastDisconnectReason:p(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:p(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:p(e,"error"),errorCode:p(e,"errorCode","error_code")??void 0,retryable:w(e,"retryable")??void 0,errorPlane:p(e,"errorPlane","error_plane")??void 0})}function mn(t){let e=C(t);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectTransitions:typeof e.connectTransitions=="number"?e.connectTransitions:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function fn(t){let e=C(t);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function Et(t){switch(t){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function vn(t){let e=t.activeConnectionId||t.candidates[0]||null;if(!e)return null;let n=Et(t.status),i=n==="connected"?"connected":n==="connecting"?"connecting":"closed",r=n==="connected"?t.settledReady?"routable":"transport-only":n==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:t.deviceId??null,deviceIdHint:t.deviceIdHint??null,remoteNodeId:t.nodeId??null,state:n,transportState:i,protocolState:r,routable:!!t.settledReady,readinessState:t.readinessState,readinessReason:t.readinessReason,transportGeneration:t.transportGeneration,routeGeneration:t.routeGeneration,transportStableId:t.transportStableId,activeTransport:t.activeTransport,parallelTransport:t.parallelTransport??null,replacementInProgress:t.replacementPending,logicalSessionTerminal:t.logicalSessionTerminal===true,lastTransitionAtMs:t.lastTransitionAtMs,transitionCount:t.transitionCount,connectTransitions:t.connectTransitions,replacementCount:t.replacementCount,retireCount:t.retireCount,lastDisconnectReason:t.lastDisconnectReason??void 0,lastReconnectReason:t.lastReconnectReason??void 0,updatedAt:t.lastSeenAtMs,error:t.error??void 0}}function bn(t){let e=C(t),n=p(e,"connectionId","connection_id");if(!n)return null;let i=p(e,"state")||"connecting",r=g(e,"createdAt","created_at")??g(e,"updatedAt","updated_at")??Date.now(),o=g(e,"updatedAt","updated_at")??r;return {connectionId:n,deviceId:p(e,"deviceId","device_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),remoteNodeId:p(e,"remoteNodeId","remote_node_id"),state:i,transportState:p(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:p(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:w(e,"routable")??false,logicalSessionTerminal:w(e,"logicalSessionTerminal","logical_session_terminal")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:M(e,"activeTransport","active_transport"),parallelTransport:M(e,"parallelTransport","parallel_transport")??null,replacementInProgress:w(e,"replacementInProgress","replacement_in_progress")??void 0,lastTransitionAtMs:g(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:g(e,"transitionCount","transition_count")??void 0,connectTransitions:g(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:g(e,"replacementCount","replacement_count")??void 0,retireCount:g(e,"retireCount","retire_count")??void 0,lastDisconnectReason:p(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:p(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:p(e,"error")??void 0,createdAt:r,updatedAt:o}}function wn(t,e){return t?t.connectionId===e.connectionId&&(t.deviceId??null)===(e.deviceId??null)&&(t.deviceIdHint??null)===(e.deviceIdHint??null)&&(t.remoteNodeId??null)===(e.remoteNodeId??null)&&t.state===e.state&&(t.transportState??null)===(e.transportState??null)&&(t.protocolState??null)===(e.protocolState??null)&&!!t.routable==!!e.routable&&(t.activeTransport??null)===(e.activeTransport??null)&&(t.parallelTransport??null)===(e.parallelTransport??null)&&(t.transportStableId??null)===(e.transportStableId??null)&&(t.transportGeneration??null)===(e.transportGeneration??null)&&(t.routeGeneration??null)===(e.routeGeneration??null)&&!!t.replacementInProgress==!!e.replacementInProgress&&!!t.logicalSessionTerminal==!!e.logicalSessionTerminal&&(t.transitionCount??null)===(e.transitionCount??null)&&(t.connectTransitions??null)===(e.connectTransitions??null)&&(t.replacementCount??null)===(e.replacementCount??null)&&(t.retireCount??null)===(e.retireCount??null)&&(t.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(t.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(t.error??null)===(e.error??null):false}
2
+ export{Mt as A,gn as B,yn as C,mn as D,fn as E,vn as F,bn as G,wn as H,_t as a,he as b,Ye as c,Bt as d,jt as e,zt as f,ge as g,qt as h,Yt as i,Qt as j,Xt as k,Zt as l,en as m,vt as n,wt as o,nn as p,St as q,Rt as r,Se as s,on as t,sn as u,an as v,V as w,pn as x,hn as y,It as z};
@@ -0,0 +1,2 @@
1
+ var N="openrtc:endpoint-ticket:v1";function I(n){let e=n.lastIndexOf(".");return {irohTicket:e>=0?n.slice(0,e):n,tokenSuffix:e>=0?n.slice(e+1):null}}function K(){return y(24)}function Y(n,e,c,a,i){return `${n}.${k(n,e,c,a,i)}`}function R(n,e){let c=A(e);return !c||!D(n,c)?null:c}function k(n,e,c,a,i){return btoa(JSON.stringify({t:e,s:c,m:a,h:S(n),...typeof i=="number"?{e:i}:{},a:N,n:L()})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),c=(4-e.length%4)%4;return JSON.parse(atob(e+"=".repeat(c)))}catch{return null}}function D(n,e){return !(typeof e.h=="string"&&e.h!==S(n)||typeof e.e=="number"&&Number.isFinite(e.e)&&e.e<=Date.now()||typeof e.a=="string"&&e.a!==N||typeof e.n=="string"&&!U(e.n))}function L(){return y(16)}function y(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),c=(4-e.length%4)%4;return atob(e+"=".repeat(c)).length===16}catch{return false}}function s(n,e){return n>>>e|n<<32-e}var w=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function S(n){let e=new TextEncoder().encode(n),c=e.length*8,a=e.length+1;for(;a%64!==56;)a+=1;let i=new Uint8Array(a+8);i.set(e),i[e.length]=128;let p=new DataView(i.buffer);p.setUint32(a,Math.floor(c/4294967296),false),p.setUint32(a+4,c>>>0,false);let r=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],o=new Array(64);for(let d=0;d<i.length;d+=64){for(let t=0;t<16;t+=1)o[t]=p.getUint32(d+t*4,false);for(let t=16;t<64;t+=1){let h=s(o[t-15],7)^s(o[t-15],18)^o[t-15]>>>3,_=s(o[t-2],17)^s(o[t-2],19)^o[t-2]>>>10;o[t]=o[t-16]+h+o[t-7]+_>>>0;}let[x,u,b,m,f,g,l,T]=r;for(let t=0;t<64;t+=1){let h=s(f,6)^s(f,11)^s(f,25),_=f&g^~f&l,E=T+h+_+w[t]+o[t]>>>0,O=s(x,2)^s(x,13)^s(x,22),C=x&u^x&b^u&b,P=O+C>>>0;T=l,l=g,g=f,f=m+E>>>0,m=b,b=u,u=x,x=E+P>>>0;}r[0]=r[0]+x>>>0,r[1]=r[1]+u>>>0,r[2]=r[2]+b>>>0,r[3]=r[3]+m>>>0,r[4]=r[4]+f>>>0,r[5]=r[5]+g>>>0,r[6]=r[6]+l>>>0,r[7]=r[7]+T>>>0;}return r.map(d=>d.toString(16).padStart(8,"0")).join("")}
2
+ export{I as a,K as b,Y as c,R as d};
@@ -1 +1 @@
1
- import {r}from'./chunk-2K47N3QP.js';import {a}from'./chunk-GTHSRQ7Y.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
1
+ import {r}from'./chunk-FB5M6GIW.js';import {a}from'./chunk-AAZPQQXX.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};