openrtc 2.8.2 → 2.8.4

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 (64) hide show
  1. package/dist/{Connection-DnZeUt3p.d.ts → Connection-BU8g28lx.d.ts} +3 -1
  2. package/dist/{DelegatingRuntimeAdapter-DtNdkP9H.d.ts → DelegatingRuntimeAdapter-DXeVrxQJ.d.ts} +2 -2
  3. package/dist/{IpcRuntimeAdapter-BSartqkw.d.ts → IpcRuntimeAdapter-CytWufhU.d.ts} +2 -2
  4. package/dist/WasmBridge-6R3LRMUA.js +1 -0
  5. package/dist/{assembly-CMe7xj2N.d.ts → assembly-CJjfcYrA.d.ts} +24 -2
  6. package/dist/{capabilities-CsnXfI4b.d.ts → capabilities-BOyxv_kT.d.ts} +1 -1
  7. package/dist/chunk-577A77JB.js +2 -0
  8. package/dist/{chunk-ISTROQQJ.js → chunk-67RYEH6T.js} +1 -1
  9. package/dist/{chunk-HDGSSJGQ.js → chunk-ESBROG6S.js} +1 -1
  10. package/dist/{chunk-VGG7KR7S.js → chunk-KSIYKQR6.js} +1 -1
  11. package/dist/chunk-OC4VXLX7.js +1 -0
  12. package/dist/{chunk-H6BF3HGG.js → chunk-ODOJMY4Z.js} +1 -1
  13. package/dist/{chunk-4KY4I6W5.js → chunk-S3U4WUZ2.js} +1 -1
  14. package/dist/chunk-TWIZQT6M.js +1 -0
  15. package/dist/{chunk-FKOOMOD5.js → chunk-WC6AHTD7.js} +1 -1
  16. package/dist/{chunk-NHIANLEM.js → chunk-WD2FZUOM.js} +1 -1
  17. package/dist/{chunk-UPWTSOR7.js → chunk-WD47V4PK.js} +2 -2
  18. package/dist/chunk-XXSKL76B.js +2 -0
  19. package/dist/controlPlane-C5RUPLAM.js +1 -0
  20. package/dist/coreClient.d.ts +3 -3
  21. package/dist/{deviceEnrollment-2UW67OPP.js → deviceEnrollment-27EVK3E3.js} +1 -1
  22. package/dist/index.d.ts +26 -7
  23. package/dist/index.js +1 -1
  24. package/dist/ipcFactory-XWA7RXHB.js +1 -0
  25. package/dist/native.d.ts +5 -5
  26. package/dist/native.js +1 -1
  27. package/dist/node.d.ts +6 -6
  28. package/dist/node.js +2 -2
  29. package/dist/openrtc-EGNQXXVW.js +2 -0
  30. package/dist/openrtc_bg.wasm +0 -0
  31. package/dist/{room-XOMUNWSD.js → room-VVZXY3M2.js} +1 -1
  32. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  33. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  34. package/dist/runtime/device-status.d.ts +1 -1
  35. package/dist/runtime/factories.d.ts +26 -5
  36. package/dist/runtime/factories.js +1 -1
  37. package/dist/runtime/index.d.ts +10 -9
  38. package/dist/runtime/index.js +1 -1
  39. package/dist/server-browser.d.ts +4 -4
  40. package/dist/server.d.ts +4 -4
  41. package/dist/server.js +1 -1
  42. package/dist/service-node.d.ts +4 -4
  43. package/dist/service-node.js +1 -1
  44. package/dist/testing/native.d.ts +4 -4
  45. package/dist/testing/native.js +1 -1
  46. package/dist/testing.d.ts +4 -4
  47. package/dist/testing.js +1 -1
  48. package/dist/transport/index.d.ts +2 -2
  49. package/dist/{types-CJ5FGAyJ.d.ts → types-ldAq2oqi.d.ts} +11 -2
  50. package/native/darwin-arm64/openrtc-node-host +0 -0
  51. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  52. package/native/darwin-x64/openrtc-node-host +0 -0
  53. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  54. package/native/linux-x64/openrtc-node-host +0 -0
  55. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  56. package/package.json +1 -1
  57. package/dist/WasmBridge-6DUJ5P2C.js +0 -1
  58. package/dist/chunk-4R5BLX2U.js +0 -2
  59. package/dist/chunk-DUY34MGT.js +0 -1
  60. package/dist/chunk-JQBYZHKY.js +0 -1
  61. package/dist/chunk-YDC7W5NL.js +0 -2
  62. package/dist/controlPlane-GRIKNHDP.js +0 -1
  63. package/dist/ipcFactory-TBF2Z736.js +0 -1
  64. package/dist/openrtc-6SOVNCB2.js +0 -2
@@ -854,6 +854,8 @@ interface BackendConnectionState {
854
854
  transportState?: string;
855
855
  protocolState?: string;
856
856
  routable?: boolean;
857
+ /** Rust-authenticated application scopes carried by this logical peer. */
858
+ scopes?: PeerScope[];
857
859
  activeTransport?: ProtocolName;
858
860
  parallelTransport?: ProtocolName | null;
859
861
  readinessState?: string;
@@ -1659,4 +1661,4 @@ declare class Connection {
1659
1661
  private close;
1660
1662
  }
1661
1663
 
1662
- export { type ManagedConnectionRecord as $, type DeviceProfile as A, type RawConnection as B, type ChannelDescriptor$1 as C, type DeviceStatus as D, type EffectiveRoomArchitecture as E, type RuntimeRoomMember as F, type GrantScope as G, type AuthContext as H, type IncomingStream as I, type JoinRoomOptions$1 as J, type RuntimeClientOptions as K, type LocalDeviceInfo$1 as L, type ManagedOptions as M, type ServiceErrorMetadata as N, type DiscoveryMode as O, type PlutoIrohConfiguration as P, type AuthMode as Q, type RoomArchitectureMode as R, type ServiceErrorObservation as S, type SignalingMode as T, type ClientOptions as U, type ExplicitFileDataSendParams as V, type ISignalingBackend as W, type RuntimeIdentity as X, type RoomMember as Y, type Device as Z, type DeviceStatusSnapshot as _, type RoomArchitectureReason as a, type RuntimeAuthContext as a$, type SignalingEnvelope as a0, type DeviceEvent as a1, type DesiredPeerProjection as a2, type SignalingSession as a3, type SessionEvent as a4, type LocalDeviceInfo as a5, type NativeManagedSessionStartResult as a6, type BackendPeerBiStream as a7, type BackendPeerUniStream as a8, type PortableMediaPublish as a9, type AppLimits as aA, type ConnectionTarget as aB, type PresenceLoopOptions as aC, type SignalingOptions as aD, type JoinRoomOptions as aE, type ChannelMetadata as aF, type RoomCreationMode as aG, type ProtocolCapabilityMap as aH, type ScanningLoopOptions as aI, type ScanningLoopHandle as aJ, type RuntimeBootstrapOptions as aK, type RuntimeBootstrapResult as aL, type ApplicationPayloadReadinessOptions as aM, type ManagedApplicationRouteOptions as aN, type PeerState as aO, type PeerScope as aP, type PeerHealth as aQ, type ChannelDescriptor as aR, type JoinRequest as aS, type AutoConnectPolicy as aT, type ChannelFraming as aU, type ConnectionStatus as aV, type DevicePresence as aW, type PayloadRouteOptions as aX, type PeerLifecycleStatus$1 as aY, type PeerSessionSnapshot$1 as aZ, type PresencePolicy as a_, type PortableMediaPublicationStart as aa, type PortableMediaSample as ab, type PortableMediaChunk as ac, type PortableMediaControl as ad, type NativeConnectParams as ae, type NativeConnectResult as af, type BackendConnectionState as ag, type NativePeerDataEvent as ah, type CoordinationGatewayGrantRequest as ai, type CoordinationGatewayGrant as aj, type BrowserWasmRuntimeModule as ak, type BrowserProtocolStore as al, type NamespaceDescriptor as am, type IrohMutationReceipt as an, type IrohDocEntry as ao, type CoordinationSignalingStore as ap, type ManagedRoomMessage as aq, type CoreClientBridgeHost as ar, type RouteDescriptor as as, type PayloadCrypto as at, type CryptoStreams as au, type CryptoBiStream as av, type RouteFamily as aw, type RouteKind as ax, type RuntimeAuthIdentity as ay, type RuntimeSession as az, type RoomArchitectureSnapshot as b, type RuntimePeerScope as b0, type SessionKind as b1, type SessionPlatform as b2, type RoomAuthorityAssignment as c, type PlutoRTCConfiguration as d, type PlutoMoQConfiguration as e, type RouteOptimization as f, type ProtocolName as g, type RuntimePeerState as h, type PeerConnectOptions as i, Connection as j, type PeerSessionSnapshot as k, type PeerReadiness as l, type RuntimePeerHealth as m, type ResolvedPeerIdentity as n, type PeerStreamOptions as o, type ScopedChannelOptions as p, type RuntimeDevice as q, type ScopedLogicalChannel as r, type ConnectionState as s, type ReadinessOptions as t, type ConnectionEvent as u, type ManagedSession as v, type DeviceConnectOptions as w, type ConnectDeviceResult as x, type ConnectDeviceHooks as y, type ConnectDeviceOptions as z };
1664
+ export { type SignalingEnvelope as $, type DeviceProfile as A, type RawConnection as B, type ChannelDescriptor$1 as C, type DeviceStatus as D, type EffectiveRoomArchitecture as E, type RuntimeRoomMember as F, type GrantScope as G, type AuthContext as H, type IncomingStream as I, type JoinRoomOptions$1 as J, type RuntimeClientOptions as K, type LocalDeviceInfo$1 as L, type ManagedOptions as M, type DiscoveryMode as N, type AuthMode as O, type PlutoIrohConfiguration as P, type SignalingMode as Q, type RoomArchitectureMode as R, type ServiceErrorObservation as S, type ClientOptions as T, type ExplicitFileDataSendParams as U, type ISignalingBackend as V, type RuntimeIdentity as W, type RoomMember as X, type Device as Y, type DeviceStatusSnapshot as Z, type ManagedConnectionRecord as _, type RoomArchitectureReason as a, type RuntimeAuthContext as a$, type DeviceEvent as a0, type DesiredPeerProjection as a1, type SignalingSession as a2, type SessionEvent as a3, type LocalDeviceInfo as a4, type NativeManagedSessionStartResult as a5, type BackendPeerBiStream as a6, type BackendPeerUniStream as a7, type PortableMediaPublish as a8, type PortableMediaPublicationStart as a9, type AppLimits as aA, type ConnectionTarget as aB, type PresenceLoopOptions as aC, type SignalingOptions as aD, type JoinRoomOptions as aE, type ChannelMetadata as aF, type RoomCreationMode as aG, type ProtocolCapabilityMap as aH, type ScanningLoopOptions as aI, type ScanningLoopHandle as aJ, type RuntimeBootstrapOptions as aK, type RuntimeBootstrapResult as aL, type ApplicationPayloadReadinessOptions as aM, type ManagedApplicationRouteOptions as aN, type PeerState as aO, type PeerScope as aP, type PeerHealth as aQ, type ChannelDescriptor as aR, type JoinRequest as aS, type AutoConnectPolicy as aT, type ChannelFraming as aU, type ConnectionStatus as aV, type DevicePresence as aW, type PayloadRouteOptions as aX, type PeerLifecycleStatus$1 as aY, type PeerSessionSnapshot$1 as aZ, type PresencePolicy as a_, type PortableMediaSample as aa, type PortableMediaChunk as ab, type PortableMediaControl as ac, type NativeConnectParams as ad, type NativeConnectResult as ae, type BackendConnectionState as af, type NativePeerDataEvent as ag, type ServiceErrorMetadata as ah, type CoordinationGatewayGrantRequest as ai, type CoordinationGatewayGrant as aj, type BrowserWasmRuntimeModule as ak, type BrowserProtocolStore as al, type NamespaceDescriptor as am, type IrohMutationReceipt as an, type IrohDocEntry as ao, type CoordinationSignalingStore as ap, type ManagedRoomMessage as aq, type CoreClientBridgeHost as ar, type RouteDescriptor as as, type PayloadCrypto as at, type CryptoStreams as au, type CryptoBiStream as av, type RouteFamily as aw, type RouteKind as ax, type RuntimeAuthIdentity as ay, type RuntimeSession as az, type RoomArchitectureSnapshot as b, type RuntimePeerScope as b0, type SessionKind as b1, type SessionPlatform as b2, type RoomAuthorityAssignment as c, type PlutoRTCConfiguration as d, type PlutoMoQConfiguration as e, type RouteOptimization as f, type ProtocolName as g, type RuntimePeerState as h, type PeerConnectOptions as i, Connection as j, type PeerSessionSnapshot as k, type PeerReadiness as l, type RuntimePeerHealth as m, type ResolvedPeerIdentity as n, type PeerStreamOptions as o, type ScopedChannelOptions as p, type RuntimeDevice as q, type ScopedLogicalChannel as r, type ConnectionState as s, type ReadinessOptions as t, type ConnectionEvent as u, type ManagedSession as v, type DeviceConnectOptions as w, type ConnectDeviceResult as x, type ConnectDeviceHooks as y, type ConnectDeviceOptions as z };
@@ -1,5 +1,5 @@
1
- import { O as DiscoveryMode, Q as AuthMode, T as SignalingMode, U as ClientOptions, V as ExplicitFileDataSendParams, W as ISignalingBackend, X as RuntimeIdentity, H as AuthContext, Y as RoomMember, Z as Device, _ as DeviceStatusSnapshot, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, $ as ManagedConnectionRecord, a0 as SignalingEnvelope, a1 as DeviceEvent, a2 as DesiredPeerProjection, a3 as SignalingSession, a4 as SessionEvent, a5 as LocalDeviceInfo, a6 as NativeManagedSessionStartResult, g as ProtocolName, G as GrantScope, a7 as BackendPeerBiStream, a8 as BackendPeerUniStream, a9 as PortableMediaPublish, aa as PortableMediaPublicationStart, ab as PortableMediaSample, ac as PortableMediaChunk, ad as PortableMediaControl, ae as NativeConnectParams, af as NativeConnectResult, ag as BackendConnectionState, ah as NativePeerDataEvent } from './Connection-DnZeUt3p.js';
2
- import { R as RuntimeCapabilities } from './capabilities-CsnXfI4b.js';
1
+ import { N as DiscoveryMode, O as AuthMode, Q as SignalingMode, T as ClientOptions, U as ExplicitFileDataSendParams, V as ISignalingBackend, W as RuntimeIdentity, H as AuthContext, X as RoomMember, Y as Device, Z as DeviceStatusSnapshot, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, _ as ManagedConnectionRecord, $ as SignalingEnvelope, a0 as DeviceEvent, a1 as DesiredPeerProjection, a2 as SignalingSession, a3 as SessionEvent, a4 as LocalDeviceInfo, a5 as NativeManagedSessionStartResult, g as ProtocolName, G as GrantScope, a6 as BackendPeerBiStream, a7 as BackendPeerUniStream, a8 as PortableMediaPublish, a9 as PortableMediaPublicationStart, aa as PortableMediaSample, ab as PortableMediaChunk, ac as PortableMediaControl, ad as NativeConnectParams, ae as NativeConnectResult, af as BackendConnectionState, ag as NativePeerDataEvent } from './Connection-BU8g28lx.js';
2
+ import { R as RuntimeCapabilities } from './capabilities-BOyxv_kT.js';
3
3
 
4
4
  /** Host-neutral configuration shared by browser/WASM and native/IPC adapters. */
5
5
  interface RuntimeBridgeOptions {
@@ -1,6 +1,6 @@
1
- import { R as RuntimeBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-DtNdkP9H.js';
1
+ import { R as RuntimeBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-DXeVrxQJ.js';
2
2
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
3
- import { S as ServiceErrorObservation, ag as BackendConnectionState, ah as NativePeerDataEvent, Z as Device } from './Connection-DnZeUt3p.js';
3
+ import { S as ServiceErrorObservation, af as BackendConnectionState, ag as NativePeerDataEvent, Y as Device } from './Connection-BU8g28lx.js';
4
4
 
5
5
  /**
6
6
  * Root-client owner for the one native WebView projection.
@@ -0,0 +1 @@
1
+ export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-ODOJMY4Z.js';import'./chunk-AYHD4X2R.js';import'./chunk-WD47V4PK.js';import'./chunk-XMYBBLYK.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import'./chunk-67RYEH6T.js';import'./chunk-CNAW5BZ3.js';import'./chunk-CCCYE3XN.js';import'./chunk-577A77JB.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';
@@ -1,5 +1,5 @@
1
- import { h as RuntimePeerState, s as ConnectionState, l as PeerReadiness, i as PeerConnectOptions, j as Connection, I as IncomingStream, G as GrantScope, K as RuntimeClientOptions, W as ISignalingBackend, ay as RuntimeAuthIdentity, H as AuthContext, g as ProtocolName, L as LocalDeviceInfo, A as DeviceProfile, al as BrowserProtocolStore, am as NamespaceDescriptor, an as IrohMutationReceipt, ao as IrohDocEntry, q as RuntimeDevice, M as ManagedOptions, v as ManagedSession, D as DeviceStatus, y as ConnectDeviceHooks, z as ConnectDeviceOptions, x as ConnectDeviceResult, w as DeviceConnectOptions, $ as ManagedConnectionRecord, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, az as RuntimeSession, aA as AppLimits, J as JoinRoomOptions, F as RuntimeRoomMember, aB as ConnectionTarget, p as ScopedChannelOptions, r as ScopedLogicalChannel, o as PeerStreamOptions, ae as NativeConnectParams, af as NativeConnectResult, B as RawConnection, C as ChannelDescriptor, V as ExplicitFileDataSendParams, aC as PresenceLoopOptions, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, m as RuntimePeerHealth, t as ReadinessOptions, u as ConnectionEvent } from './Connection-DnZeUt3p.js';
2
- import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CsnXfI4b.js';
1
+ import { h as RuntimePeerState, s as ConnectionState, l as PeerReadiness, i as PeerConnectOptions, j as Connection, I as IncomingStream, G as GrantScope, K as RuntimeClientOptions, V as ISignalingBackend, ay as RuntimeAuthIdentity, H as AuthContext, g as ProtocolName, L as LocalDeviceInfo, A as DeviceProfile, al as BrowserProtocolStore, am as NamespaceDescriptor, an as IrohMutationReceipt, ao as IrohDocEntry, ae as NativeConnectResult, q as RuntimeDevice, M as ManagedOptions, v as ManagedSession, D as DeviceStatus, y as ConnectDeviceHooks, z as ConnectDeviceOptions, x as ConnectDeviceResult, w as DeviceConnectOptions, _ as ManagedConnectionRecord, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, az as RuntimeSession, aA as AppLimits, J as JoinRoomOptions, F as RuntimeRoomMember, aB as ConnectionTarget, p as ScopedChannelOptions, r as ScopedLogicalChannel, o as PeerStreamOptions, ad as NativeConnectParams, B as RawConnection, C as ChannelDescriptor, U as ExplicitFileDataSendParams, aC as PresenceLoopOptions, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, m as RuntimePeerHealth, t as ReadinessOptions, u as ConnectionEvent } from './Connection-BU8g28lx.js';
2
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-BOyxv_kT.js';
3
3
 
4
4
  /**
5
5
  * Coalesced peer reconciliation scheduler and full reconcile orchestration.
@@ -294,6 +294,14 @@ declare class RuntimeClient {
294
294
  private managedSessionOptions;
295
295
  private managedSessionTransition;
296
296
  private managedSessionStartInFlight;
297
+ private readonly ticketMeshMessageStops;
298
+ private readonly ticketMeshInviteStops;
299
+ private readonly ticketMeshInvites;
300
+ private readonly ticketMeshInviteListeners;
301
+ private readonly activeTicketMeshes;
302
+ private readonly ticketMeshUnconfirmedStarts;
303
+ private readonly ticketMeshStarts;
304
+ private readonly ticketMeshCloseInFlight;
297
305
  private browserInitialization;
298
306
  private terminalShutdown;
299
307
  private readonly managedReconciliationTasks;
@@ -416,6 +424,20 @@ declare class RuntimeClient {
416
424
  * @param maxConnections 0 = unlimited.
417
425
  */
418
426
  getTicketWithToken(grantScope: GrantScope, maxConnections?: number): Promise<string>;
427
+ issueTicketInvite(id: string, maxPeers: number, mesh: boolean): Promise<string>;
428
+ issueTicketMesh(id: string, maxPeers: number): Promise<string>;
429
+ joinTicketMesh(invitation: string): Promise<string>;
430
+ closeTicketMesh(id: string): Promise<void>;
431
+ ticketMeshIssuerNode(id: string): Promise<string>;
432
+ watchTicketMeshInvite(id: string, callback: (invitation: string) => void): () => void;
433
+ private publishTicketMeshInvite;
434
+ private assertTicketMeshStartAvailable;
435
+ private recoverUnconfirmedTicketMeshStart;
436
+ private rollbackTicketMeshStart;
437
+ private releaseTicketMeshProjection;
438
+ private listenForTicketMeshFrames;
439
+ private runTicketMeshAction;
440
+ connectTicketInvite(invitation: string): Promise<NativeConnectResult>;
419
441
  /**
420
442
  * Register a product-issued admission token with the active runtime.
421
443
  *
@@ -1,4 +1,4 @@
1
- import { g as ProtocolName, f as RouteOptimization } from './Connection-DnZeUt3p.js';
1
+ import { g as ProtocolName, f as RouteOptimization } from './Connection-BU8g28lx.js';
2
2
 
3
3
  type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
4
4
  type CapabilityMaturity = 'stable' | 'preview' | 'support-only' | 'unavailable';
@@ -0,0 +1,2 @@
1
+ var u={CREDIT_EXHAUSTED:"credit-exhausted",APP_BUDGET_EXHAUSTED:"app-budget-exhausted",APP_RATE_LIMITED:"app-rate-limited",PRINCIPAL_RATE_LIMITED:"principal-rate-limited",EDGE_RATE_LIMITED:"edge-rate-limited",PROVIDER_SAFETY_PAUSED:"provider-safety-paused",USAGE_PRICE_STALE:"usage-price-stale",RELAY_BUDGET_EXHAUSTED:"relay-budget-exhausted",ROOM_CAPACITY_EXCEEDED:"room-capacity-exceeded"},C={"edge-rate-exceeded":{code:u.EDGE_RATE_LIMITED,scope:"ip"},"route-rate-exceeded":{code:u.EDGE_RATE_LIMITED,scope:"avenue"}};function D(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(C,t)?C[t]:void 0}function T(e){return E(e)?{code:e}:D(e)}var S=new Set(Object.values(u));function E(e){return typeof e=="string"&&S.has(e)}var g="https://openrtc-docs.web.app/openrtc/api/errors";function s(e){let t=e,r={documentationUrl:g};typeof t.scope=="string"&&["account","app","principal","ip","avenue","platform"].includes(t.scope)&&(r.scope=t.scope),typeof t.operation=="string"&&/^[a-z0-9.-]{1,100}$/.test(t.operation)&&(r.operation=t.operation),typeof t.requestId=="string"&&/^[A-Za-z0-9_.:-]{1,160}$/.test(t.requestId)&&(r.requestId=t.requestId);for(let n of ["retryAfterMs","resetAt"])Number.isSafeInteger(t[n])&&Number(t[n])>=0&&(r[n]=Number(t[n]));return r}var o={...u,AUTH_NOT_READY:"auth/not-ready",AUTH_DENIED:"auth/denied",AUTH_EXPIRED:"auth/expired",AUTH_DEVICE_REENROLLMENT_REQUIRED:"auth/device-reenrollment-required",ADMISSION_DENIED:"admission/denied",ADMISSION_SCOPE_MISMATCH:"admission/scope-mismatch",TICKET_INVITE_INVALID:"admission/ticket-invite-invalid",TICKET_MESH_INVALID_OPTIONS:"admission/ticket-mesh-invalid-options",TICKET_MESH_CAPACITY_EXCEEDED:"admission/ticket-mesh-capacity-exceeded",TICKET_MESH_ALREADY_ACTIVE:"admission/ticket-mesh-already-active",ROOM_ARCHITECTURE_UNAVAILABLE:"room-architecture-unavailable",BUDGET_EXCEEDED:"budget/exceeded",BUDGET_STALE:"budget/stale",BUDGET_RENEWAL_REQUIRED:"budget/renewal-required",COORDINATION_DISCONNECTED:"coordination/disconnected",COORDINATION_PROTOCOL:"coordination/protocol",COORDINATION_RATE_LIMITED:"coordination/rate-limited",COORDINATION_SERVICE_UNAVAILABLE:"coordination/service-unavailable",TICKET_MESH_UNAVAILABLE:"coordination/ticket-mesh-unavailable",TRANSPORT_DIAL_EXHAUSTED:"transport/dial-exhausted",TRANSPORT_UNAVAILABLE:"transport/unavailable",TRANSPORT_TICKET_MISSING:"transport/ticket-missing",DELIVERY_NOT_READY:"delivery/not-ready",INTERNAL:"internal/error"},a=class e extends Error{constructor(r){super(r.message);this.name="RTCError";r.cause!==void 0&&(this.cause=r.cause),this.code=r.code,this.retryable=r.retryable,this.plane=r.plane,this.generation=r.generation,this.transportGeneration=r.transportGeneration,this.routeGeneration=r.routeGeneration,this.revision=r.revision,E(r.code)&&Object.assign(this,s(r));}static is(r){return r instanceof e||typeof r=="object"&&r!==null&&r.name==="RTCError"&&typeof r.code=="string"&&typeof r.retryable=="boolean"&&typeof r.plane=="string"}static shouldAppRetry(r){let n=b(r);return n.retryable?n.plane==="coordination"||n.plane==="transport"||n.plane==="auth":false}toJSON(){return {name:this.name,code:this.code,message:this.message,retryable:this.retryable,plane:this.plane,generation:this.generation??null,transportGeneration:this.transportGeneration??null,routeGeneration:this.routeGeneration??null,revision:this.revision??null,...E(this.code)?s(this):{}}}};function w(e){let t=b(e);return {errorCode:t.code,retryable:t.retryable,errorPlane:t.plane,...E(t.code)?s(t):{}}}function d(e,t,r){let n=f(e);return new a({code:e,message:t,retryable:r.retryable??n.retryable,plane:r.plane??n.plane,cause:r.cause,generation:r.generation,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,revision:r.revision,...s(r)})}function f(e){if(String(e).endsWith("-rate-limited"))return {retryable:true,plane:"coordination"};if(e===o.ROOM_CAPACITY_EXCEEDED||e===o.ROOM_ARCHITECTURE_UNAVAILABLE)return {retryable:false,plane:"admission"};let t=String(e).split("/",1)[0],r=E(e)?"budget":["auth","admission","budget","coordination","transport","delivery"].includes(t)?t:"internal";return {retryable:r==="transport"||r==="delivery"||r==="auth"&&e!==o.AUTH_DENIED||r==="coordination"&&e!==o.COORDINATION_PROTOCOL||r==="budget"&&[o.USAGE_PRICE_STALE,o.BUDGET_STALE,o.BUDGET_RENEWAL_REQUIRED].includes(e),plane:r}}function i(e,t,r){return new a({code:e,message:t,...f(e),cause:r})}function b(e){if(a.is(e))return e instanceof a?e:new a({code:e.code,message:e.message||String(e),retryable:e.retryable,plane:e.plane,cause:e,generation:e.generation,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,revision:e.revision,...s(e)});if(typeof e=="object"&&e!==null){let r=e,n=typeof r.code=="string"?r.code:"",l=typeof r.message=="string"?r.message:typeof r.error=="string"?r.error:e instanceof Error?e.message:String(e),R=typeof r.retryable=="boolean"?r.retryable:void 0,y=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:null,I=y&&T(y.code),A=T(n),p=I?y:A?e:null,c=I||A;if(p&&c)return new a({...f(c.code),code:c.code,message:l,cause:e,retryable:typeof p.retryable=="boolean"?p.retryable:!!c.scope,...s(p),...c.scope?{scope:c.scope}:{}});if(n){let _=h(n,l,R);if(_)return _}if(typeof r.name=="string"&&r.name==="CoordinationConnectError")return d(o.COORDINATION_DISCONNECTED,l,{retryable:R??true,plane:"coordination",cause:e});if(typeof r.name=="string"&&r.name==="CoordinationGatewayProtocolError")return d(n||o.COORDINATION_PROTOCOL,l,{retryable:R??false,plane:O(n),cause:e})}let t=e instanceof Error?e.message:String(e??"unknown error");return m(t,e)}function h(e,t,r){let n=e.trim().toLowerCase();return n===o.ROOM_ARCHITECTURE_UNAVAILABLE?i(o.ROOM_ARCHITECTURE_UNAVAILABLE,t):n==="unauthenticated"||n==="functions/unauthenticated"||n==="auth/unauthorized"||n.includes("permission-denied")?i(o.AUTH_DENIED,t):n==="budget-renewal-required"||n==="budget/renewal-required"?d(o.BUDGET_RENEWAL_REQUIRED,t,{retryable:r??true,plane:"budget"}):n.includes("resource-exhausted")||n.includes("budget")||n==="budget-exceeded"||n==="insufficient-budget"?n.includes("stale")||/stale-budget/i.test(t)?d(o.BUDGET_STALE,t,{retryable:r??true,plane:"budget"}):i(o.BUDGET_EXCEEDED,t):n.includes("rate-limit")||n==="rate_limited"||n==="too-many-requests"?d(o.COORDINATION_RATE_LIMITED,t,{retryable:r??true,plane:"coordination"}):n.includes("admission")||n==="permission-denied"||n==="session-token-denied"?i(o.ADMISSION_DENIED,t):n.includes("scope")?i(o.ADMISSION_SCOPE_MISMATCH,t):n.includes("disconnect")||n.includes("unavailable")||n==="aborted"?d(o.COORDINATION_DISCONNECTED,t,{retryable:r??true,plane:"coordination"}):n.startsWith("coordination/")||n.includes("protocol")?d(e,t,{retryable:r??false,plane:O(e)}):null}function O(e){let t=e.trim().toLowerCase();return t.includes("budget")?"budget":t.includes("auth")?"auth":t.includes("admission")||t.includes("scope")?"admission":"coordination"}function m(e,t){return /auth(?:entication)?\s*(?:not ready|pending|missing)/i.test(e)||/token\s*(?:not ready|pending|missing)/i.test(e)||/awaiting[- ]auth/i.test(e)?i(o.AUTH_NOT_READY,e,t):/missing endpoint ticket|ticket missing/i.test(e)?i(o.TRANSPORT_TICKET_MISSING,e,t):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(e)?i(o.TRANSPORT_DIAL_EXHAUSTED,e,t):/stale[- ]budget/i.test(e)?i(o.BUDGET_STALE,e,t):/budget|credit|quota|limit\s*exceeded/i.test(e)?i(o.BUDGET_EXCEEDED,e,t):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(e)?i(o.ADMISSION_DENIED,e,t):/not\s+application-routable|not[- ]ready|settledReady/i.test(e)?i(o.DELIVERY_NOT_READY,e,t):/gateway|coordination|websocket|signaling/i.test(e)?i(o.COORDINATION_DISCONNECTED,e,t):i(o.INTERNAL,e,t)}
2
+ export{D as a,T as b,E as c,s as d,o as e,a as f,w as g,d as h,b as i};
@@ -1 +1 @@
1
- import {b,d}from'./chunk-4R5BLX2U.js';function l(n,c){if(!n||typeof n!="object")return null;let r=n,t=r.details&&typeof r.details=="object"?r.details:null,i=t&&b(t.code),o=i?t:r,e=i||b(o.code);return e?Object.freeze({...d(o),...e.scope?{scope:e.scope}:{},code:e.code,retryable:typeof o.retryable=="boolean"?o.retryable:!!e.scope,avenue:Object.freeze({kind:c.kind,id:c.id})}):null}export{l as a};
1
+ import {b,d}from'./chunk-577A77JB.js';function l(n,c){if(!n||typeof n!="object")return null;let r=n,t=r.details&&typeof r.details=="object"?r.details:null,i=t&&b(t.code),o=i?t:r,e=i||b(o.code);return e?Object.freeze({...d(o),...e.scope?{scope:e.scope}:{},code:e.code,retryable:typeof o.retryable=="boolean"?o.retryable:!!e.scope,avenue:Object.freeze({kind:c.kind,id:c.id})}):null}export{l as a};
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-ZA44REGI.js';import {c,a,i,d}from'./chunk-4R5BLX2U.js';function b(s){return {irohRelay:s.irohRelay===true||s.irohRelay===void 0&&s.relay!==false,managedTurn:s.managedTurn===true}}var M=1440*6e4,w=class extends Error{constructor(r,n,a){super(r);this.status=n;this.reason=a;this.name="RTCError";let t=[502,503,504].includes(n),o=a==="device-reenrollment-auth-required";this.code=o?"auth/device-reenrollment-required":t?"coordination/service-unavailable":n===429?"coordination/rate-limited":n===401?"auth/expired":n===403?"admission/denied":"internal/error",this.retryable=o||t,this.plane=o||n===401?"auth":t||n===429?"coordination":n===403?"admission":"internal";}};function T(s){return !(s instanceof w)||s.status!==403?false:s.reason==="device-certificate-stale"||s.reason==="device-certificate-revoked"?true:!s.reason&&s.message==="Device certificate is revoked or stale."}function P(s,e,r){return `openrtc:v2:device-certificate:${s}:${e}:${r}`}function C(s,e){return `openrtc:v2:device-session:${s}:${e}`}async function G(s,e,r){let n=new TextEncoder().encode(`openrtc:v2:session\0${s}\0${e}\0${r}`),a=new Uint8Array(await crypto.subtle.digest("SHA-256",n)),t="";for(let o of a)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function k(s){let e=s.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=atob(r);return Uint8Array.from(n,a=>a.charCodeAt(0))}function f(s){let e="";for(let r of s)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function B(s,e,r,n,a){if(typeof s.token!="string"||typeof s.expiresAtMs!="number"||s.expiresAtMs<=Date.now()+M||!s.signingPublicJwk||s.signingPublicJwk.kty!=="OKP"||s.signingPublicJwk.crv!=="Ed25519"||typeof s.signingPublicJwk.x!="string")return null;let t=s.token.split(".");if(t.length!==3)return null;let o,i;try{o=JSON.parse(new TextDecoder().decode(k(t[0]))),i=b$1(s.token);}catch{return null}if(o.alg!=="EdDSA"||s.signingPublicJwk.kid&&o.kid!==s.signingPublicJwk.kid)return null;try{let y=await crypto.subtle.importKey("jwk",s.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},y,k(t[2]),new TextEncoder().encode(`${t[0]}.${t[1]}`)))return null}catch{return null}let c=typeof i.principalId=="string"?i.principalId:"",l=Number(i.iat),u=Number(i.exp);if(i.iss!=="openrtc"||i.aud!=="openrtc:v2:gateway-grant"||i.typ!=="device-certificate"||i.appTag!==e||!c||a!==void 0&&c!==a||typeof i.principalKey!="string"||i.principalKey.length===0||i.deviceId!==r||i.deviceKeyThumbprint!==n||typeof i.jti!="string"||i.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||l>=u||u*1e3!==s.expiresAtMs)return null;let d=b(i);return {token:s.token,expiresAtMs:s.expiresAtMs,principalId:c,signingPublicJwk:s.signingPublicJwk,enrolled:false,...d}}async function J(s,e,r,n,a){try{let t=P(e,r,n),o=s.readSecureRecord?await s.readSecureRecord(e,t):globalThis.localStorage?.getItem(t);if(!o)return null;let i=JSON.parse(o),c=await B(i,e,n,a,r);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:r,signingPublicJwk:c.signingPublicJwk}:null}catch(t){if(s.readSecureRecord)throw t;return null}}async function O(s,e,r,n,a){try{let t=C(e,n),o=s.readSecureRecord?await s.readSecureRecord(r,t):globalThis.localStorage?.getItem(t);return o?await B(JSON.parse(o),r,n,a):null}catch(t){if(s.readSecureRecord)throw t;return null}}async function _(s,e,r,n,a){try{let t=P(e,r,n),o=JSON.stringify(a);s.writeSecureRecord?await s.writeSecureRecord(e,t,o):globalThis.localStorage?.setItem(t,o);}catch(t){if(s.writeSecureRecord)throw t}}async function $(s,e,r,n,a){try{let t=C(r,n),o=JSON.stringify({token:a.token,expiresAtMs:a.expiresAtMs,principalId:a.principalId,signingPublicJwk:a.signingPublicJwk});s.writeSecureRecord?await s.writeSecureRecord(e,t,o):globalThis.localStorage?.setItem(t,o);}catch(t){if(s.writeSecureRecord)throw t}}async function A(s,e,r,n,a){try{let t=P(e,r,n);if(s.deleteSecureRecord?await s.deleteSecureRecord(e,t):globalThis.localStorage?.removeItem(t),a){let o=C(a,n);s.deleteSecureRecord?await s.deleteSecureRecord(e,o):globalThis.localStorage?.removeItem(o);}}catch(t){if(s.deleteSecureRecord)throw t}}function x(s){return `${s}_${crypto.randomUUID()}`}function U(s){if(s instanceof TypeError)return true;if(!s||typeof s!="object")return false;let e=Reflect.get(s,"name");return e==="TimeoutError"||e==="AbortError"}async function j(s,e){let r=new TextEncoder().encode(`${s}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",r))].map(a=>a.toString(16).padStart(2,"0")).join("")}var K=class{constructor(e,r,n,a,t={},o){this.apiKey=e;this.endpoints=r;this.keyProvider=n;this.attestation=a;this.events=t;this.botVerification=o;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let r=this.authEpochs.get(e);if(r)return r;let n={generation:0,devices:new Map};return this.authEpochs.set(e,n),e.subscribe&&(n.unsubscribe=e.subscribe(a=>{a?.type==="principal-changed"&&(n.generation+=1,n.devices.clear(),n.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),n}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async deviceSigningPublicKey(){return (await this.key()).publicKeyJwk}async signDeviceBytes(e){return (await this.key()).sign(e)}async resolveBroadcastAccess(e,r){if(!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e)||e.length>32768)throw new Error("Broadcast grant is invalid.");if(r&&r.byteLength!==32)throw new Error("Broadcast publisher verification key is invalid.");let n=await this.key(),a=f(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))),t=r?f(r):"",o=await n.proof((u,d)=>["openrtc:v2:broadcast-access",this.apiKey,a,t,u,d].join(":")),i=await this.post("/v2/broadcasts",{action:"access",grant:e,...t?{publicationVerifyingKey:t}:{},deviceProof:o});if(i.grant!==e)throw new Error("Broadcast access grant mismatch.");let c=k(i.issuerPublicKey);if(c.byteLength!==32)throw new Error("Broadcast issuer key is invalid.");let l=new URL(i.relay?.relayUrl);if(l.protocol!=="https:"||l.username||l.password)throw new Error("Broadcast relay URL is invalid.");if(typeof i.relay.token!="string"||!/^[A-Za-z0-9._-]{16,16384}$/.test(i.relay.token)||typeof i.relay.namespace!="string"||!/^[A-Za-z0-9._/-]{1,512}$/.test(i.relay.namespace))throw new Error("Broadcast relay allocation is invalid.");return {token:e,issuerPublicKey:c,signBindingChallenge:async u=>{if(!(u instanceof Uint8Array)||u.byteLength>2048)throw new Error("Broadcast binding challenge is invalid.");return k(await n.sign(u))},relay:{relayUrl:l.toString(),token:i.relay.token,namespace:i.relay.namespace}}}async manageBroadcast(e){let r=await this.deviceCertificate(e.auth,e.deviceId),n=e.grant??"",a=e.invite??"",t=e.create,o=e.invitation,i=t?f(t.publisher.verificationKey):o?.publicationVerificationKey?f(o.publicationVerificationKey):"",c=t?{maxPublishers:t.maxPublishers,maxSubscribers:t.maxSubscribers,maxBitrateBps:t.maxBitrateBps,maxDurationSeconds:t.maxDurationSeconds,maxEgressBytes:t.maxEgressBytes}:void 0,l=t?{bitrateBps:t.publisherBitrateBps,durationSeconds:t.maxDurationSeconds,reservedEgressBytes:t.reservedEgressBytes}:o?{role:o.role,sourceSlot:o.sourceSlot??"",bitrateBps:o.bitrateBps,durationSeconds:o.durationSeconds,reservedEgressBytes:o.reservedEgressBytes}:void 0,u=f(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({action:e.action,grant:n,invite:a,publicationKey:i,sourceSlot:t?.sourceSlot??o?.sourceSlot??"host-a",limits:c,reservation:l}))))),y=await(await this.key()).proof((v,g)=>["openrtc:v2:broadcast-manage",r.source.token,e.action,u,v,g].join(":")),p=await this.post("/v2/broadcasts",{action:e.action,deviceId:e.deviceId,deviceCertificate:r.source.token,deviceProof:y,...n?{grant:n}:{},...a?{invite:a}:{},...i?{publicationVerifyingKey:i}:{},...t?{sourceSlot:t.sourceSlot??"host-a",limits:c,reservation:l}:{},...o?{invitation:{...l,publicationVerifyingKey:i}}:{}});if(e.action==="create"||e.action==="renew"){if(typeof p.grant!="string"||!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.grant))throw new Error("Managed broadcast grant is invalid.");return p.grant}if(e.action==="invite"){if(typeof p.invite!="string"||!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.invite))throw new Error("Managed broadcast invitation is invalid.");return p.invite}if(e.action==="accept"){if(typeof p.grant!="string"||!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.grant))throw new Error("Managed broadcast accepted grant is invalid.");return p.grant}}async post(e,r){let n=x("request"),a$1=JSON.stringify({apiKey:this.apiKey,...r}),t=null;for(let o=0;o<2;o+=1)try{let i$1=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":n},body:a$1,signal:AbortSignal.timeout(15e3)});if(i$1.ok)return i$1.json();let c$1=`OpenRTC request failed (${i$1.status}).`,l,u;try{let y=await i$1.json();typeof y.error=="string"&&(c$1=y.error.slice(0,256)),typeof y.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(y.reason)&&(l=y.reason),(c(y.code)||a(y.code))&&(u=i({...d(y),code:y.code,message:c$1,retryable:y.retryable}));}catch{}let d$1=u?Object.assign(u,{status:i$1.status,reason:l}):new w(c$1,i$1.status,l);if(t=d$1,!u&&o===0&&[502,503,504].includes(i$1.status))continue;throw d$1}catch(i){if(t=i,o===0&&U(i))continue;throw i}throw t instanceof Error?t:new Error("OpenRTC request failed.")}async capability(e,r,n,a=false,t,o){this.before("capability.issue");let i=e==="space"?await j(this.apiKey,r):r,l=await(await this.key()).proof((p,v)=>["openrtc:v2:capability",this.apiKey,e,i,p,v].join(":")),u=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,d=await this.post("/v2/capabilities",{avenue:{kind:e,id:i},deviceProof:l,...n?{maxPeers:n}:{},...a?{advancedFanout:true}:{},...e==="room"&&t?{architecture:t}:{},...e==="room"&&o?{roomDelivery:o}:{},...u?{turnstileToken:u}:{}});this.record("capability.issue");let y={type:"capability",token:d.capability,avenue:e==="ticket"?{kind:"session",id:i}:d.avenue,expiresAtMs:d.expiresAt*1e3,...b(d)};return y.renew=()=>this.capability(e,r,n,a,t,o),y}async deviceCertificate(e,r,n,a,t){if(this.keyProvider.persistence==="session")throw new Error("[OpenRTC] Durable browser device enrollment requires trust.browserPersistence: persistent. Select it explicitly before creating the client; session keys cannot enroll retained devices.");let o=this.authEpoch(e),i=o.devices.get(r)??{};if(o.devices.set(r,i),t&&i.current&&i.current.token!==t.token)return this.deviceCertificateResult(e,r,n,a,{...i.current,enrolled:false});if(!t&&i.current&&i.current.expiresAtMs>Date.now()+M)return this.deviceCertificateResult(e,r,n,a,{...i.current,enrolled:false});if(!i.inFlight){let l=o.generation;t&&(i.current=void 0,i.recoverRevokedEnrollment=true);let u=t?A(this.keyProvider,this.appTag,t.principalId,r,o.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(e,r,o.sessionKeyHash,a,true)):this.resolveAuthenticatedDevice(e,r,o,a,i.recoverRevokedEnrollment===true);i.inFlight=u.then(d=>{if(o.generation!==l)throw new Error("The OpenRTC authentication identity changed during enrollment.");return i.recoverRevokedEnrollment=false,i.current=d,d}).finally(()=>{i.inFlight=void 0;});}let c=await i.inFlight;return this.deviceCertificateResult(e,r,n,a,c)}async resolveAuthenticatedDevice(e,r,n,a,t=false){let o=await this.key();if(e.getSessionKey){let i=await e.getSessionKey();if(!i)throw new Error("The OpenRTC auth provider has no active principal.");let c=await G(this.appTag,o.thumbprint,i);n.sessionKeyHash=c;let l=await O(this.keyProvider,c,this.appTag,r,o.thumbprint);if(l)return l}return this.enrollAuthenticatedDevice(e,r,n.sessionKeyHash,a,t)}deviceCertificateResult(e,r,n,a,t){let o={type:"device-certificate",token:t.token,avenue:n??{kind:"user",id:t.principalId},expiresAtMs:t.expiresAtMs,irohRelay:t.irohRelay,managedTurn:t.managedTurn};return o.renew=async()=>(await this.deviceCertificate(e,r,n,a)).source,o.recoverRejectedCertificate=async()=>(await this.deviceCertificate(e,r,n,a,t)).source,{principalId:t.principalId,source:o,enrolled:t.enrolled}}async enrollAuthenticatedDevice(e,r,n,a,t=false){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let o=async(v,g)=>{let m=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:v,deviceId:r,...{}});if(!m)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:m,deviceId:r,...e.providerId?{providerId:e.providerId}:{}})},i;try{i=await o(!1);}catch(v){if(!(v instanceof w)||v.status!==401)throw v;i=await o(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let c=await this.key(),l=await J(this.keyProvider,this.appTag,i.principalId,r,c.thumbprint);if(l)return {...l,principalId:i.principalId,enrolled:false,...b(i)};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let{enrollDevice:u}=await import('./deviceEnrollment-2UW67OPP.js'),d=await u({apiKey:this.apiKey,appTag:this.appTag,auth:e,attestation:this.attestation,deviceId:r,identity:i,key:c,profile:a,recoverRevokedEnrollment:t||i.deviceRecoveryAuthorized===true,post:(v,g)=>this.post(v,g),recordAssertionExchange:()=>this.record("identity.assertion.exchange")});i=d.identity;let y=d.enrollment;this.record("device.enroll"),this.attestation&&this.record("security.attestation.verify");let p={principalId:i.principalId,token:y.deviceCertificate,expiresAtMs:y.expiresAt*1e3,signingPublicJwk:y.signingPublicJwk,enrolled:true,...b(i)};return await _(this.keyProvider,this.appTag,i.principalId,r,{token:p.token,expiresAtMs:p.expiresAtMs,signingPublicJwk:p.signingPublicJwk}),n&&await $(this.keyProvider,this.appTag,n,r,p),p}async listEnrolledDevices(e,r){let n=await this.deviceCertificate(e,r);return (await this.deviceManagement(n.source,r,"list")).devices??[]}async revokeDevice(e,r,n){let a=await this.deviceCertificate(e,r);if(await this.deviceManagement(a.source,r,"revoke",n),n===r){let t=this.authEpoch(e);await A(this.keyProvider,this.appTag,a.principalId,r,t.sessionKeyHash),t.devices.delete(r),await this.deleteDeviceKey();}}async revokeAllDevices(e,r,n){let a=await this.deviceCertificate(e,r);await this.deviceManagement(a.source,r,"revoke-all",void 0,n);let t=this.authEpoch(e);await A(this.keyProvider,this.appTag,a.principalId,r,t.sessionKeyHash),t.devices.delete(r),n?await this.deviceCertificate(e,r):(t.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,r,n,a,t=false){let o=n==="revoke"?"device.revoke":n==="revoke-all"?"identity.revoke-all":null;o&&this.before(o);let{manageDevice:i}=await import('./deviceManagement-SUMBRXXC.js'),c=await i({source:e,currentDeviceId:r,action:n,targetDeviceId:a,exceptCurrent:t,key:()=>this.key(),post:l=>this.post("/v2/devices/manage",l),isStale:T});return o&&this.record(o),c}async durableRoomMembership(e,r,n){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(n==="join"?"room.join":"room.leave");let a=b$1(e.token),t=String(a.jti??""),i=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",t,n,r,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:n,roomId:r,deviceCertificate:e.token,deviceProof:i}),this.record(n==="join"?"room.join":"room.leave");}grantProvider(e,r={}){let n=Promise.resolve(),a=e;return t=>{let o=n.then(async()=>{let i=false;a.expiresAtMs<=Date.now()+3e5&&a.renew&&(a=await a.renew(),i=true);let c=t.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),t.refreshGrant&&this.before("coordination.credential.refresh");let l=async d=>{let y=b$1(d.token),p=String(y.jti??""),g=await(await this.key()).proof((m,I)=>["openrtc:v2:gateway-grant",p,t.avenue.kind,t.avenue.id,t.runtimeInstanceId,m,I].join(":"));return this.post("/v2/gateway/grants",{credentialType:d.type,credential:d.token,avenue:t.avenue,runtimeInstanceId:t.runtimeInstanceId,ticketFingerprint:t.ticketFingerprint,deviceProof:g,...t.refreshGrant?{refreshGrant:t.refreshGrant}:{},...r.maxPeers?{maxPeers:r.maxPeers}:{},...r.features?{features:r.features}:{},...t.avenue.kind==="room"&&r.architecture?{architecture:r.architecture}:{},...t.avenue.kind==="room"&&r.roomDelivery?{roomDelivery:r.roomDelivery}:{},...d.type==="device-certificate"&&r.deviceProfile?{deviceProfile:r.deviceProfile}:{}})},u;try{u=await l(a);}catch(d){if(!T(d))throw d;let y=await a.recoverRejectedCertificate?.();if(!y)throw d;a=y,i=true,u=await l(a);}return this.record(c),t.refreshGrant&&this.record("coordination.credential.refresh"),i&&await r.onSourceRenewed?.({token:a.token,expiresAtMs:a.expiresAtMs}),u});return n=o.then(()=>{},()=>{}),o}}turnProvider(e){let r=x("relay"),n=null,a=null;return async()=>{if(n&&n.expiresAtMs>Date.now()+5*6e4)return n;if(a)return a;let t=(async()=>{let o=e(),i=b$1(o.token),c=String(i.jti??""),u=await(await this.key()).proof((y,p)=>["openrtc:v2:relay-turn",c,r,y,p].join(":")),d=await this.post("/v2/relay/turn",{credentialType:o.type,credential:o.token,sessionId:r,deviceProof:u});return n=d,d})();a=t;try{return await t}finally{a===t&&(a=null);}}}};
1
+ import {b as b$1}from'./chunk-ZA44REGI.js';import {c,a,i,d}from'./chunk-577A77JB.js';function b(s){return {irohRelay:s.irohRelay===true||s.irohRelay===void 0&&s.relay!==false,managedTurn:s.managedTurn===true}}var M=1440*6e4,w=class extends Error{constructor(r,n,a){super(r);this.status=n;this.reason=a;this.name="RTCError";let t=[502,503,504].includes(n),o=a==="device-reenrollment-auth-required";this.code=o?"auth/device-reenrollment-required":t?"coordination/service-unavailable":n===429?"coordination/rate-limited":n===401?"auth/expired":n===403?"admission/denied":"internal/error",this.retryable=o||t,this.plane=o||n===401?"auth":t||n===429?"coordination":n===403?"admission":"internal";}};function T(s){return !(s instanceof w)||s.status!==403?false:s.reason==="device-certificate-stale"||s.reason==="device-certificate-revoked"?true:!s.reason&&s.message==="Device certificate is revoked or stale."}function P(s,e,r){return `openrtc:v2:device-certificate:${s}:${e}:${r}`}function C(s,e){return `openrtc:v2:device-session:${s}:${e}`}async function G(s,e,r){let n=new TextEncoder().encode(`openrtc:v2:session\0${s}\0${e}\0${r}`),a=new Uint8Array(await crypto.subtle.digest("SHA-256",n)),t="";for(let o of a)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function k(s){let e=s.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=atob(r);return Uint8Array.from(n,a=>a.charCodeAt(0))}function f(s){let e="";for(let r of s)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function B(s,e,r,n,a){if(typeof s.token!="string"||typeof s.expiresAtMs!="number"||s.expiresAtMs<=Date.now()+M||!s.signingPublicJwk||s.signingPublicJwk.kty!=="OKP"||s.signingPublicJwk.crv!=="Ed25519"||typeof s.signingPublicJwk.x!="string")return null;let t=s.token.split(".");if(t.length!==3)return null;let o,i;try{o=JSON.parse(new TextDecoder().decode(k(t[0]))),i=b$1(s.token);}catch{return null}if(o.alg!=="EdDSA"||s.signingPublicJwk.kid&&o.kid!==s.signingPublicJwk.kid)return null;try{let y=await crypto.subtle.importKey("jwk",s.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},y,k(t[2]),new TextEncoder().encode(`${t[0]}.${t[1]}`)))return null}catch{return null}let c=typeof i.principalId=="string"?i.principalId:"",l=Number(i.iat),u=Number(i.exp);if(i.iss!=="openrtc"||i.aud!=="openrtc:v2:gateway-grant"||i.typ!=="device-certificate"||i.appTag!==e||!c||a!==void 0&&c!==a||typeof i.principalKey!="string"||i.principalKey.length===0||i.deviceId!==r||i.deviceKeyThumbprint!==n||typeof i.jti!="string"||i.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||l>=u||u*1e3!==s.expiresAtMs)return null;let d=b(i);return {token:s.token,expiresAtMs:s.expiresAtMs,principalId:c,signingPublicJwk:s.signingPublicJwk,enrolled:false,...d}}async function J(s,e,r,n,a){try{let t=P(e,r,n),o=s.readSecureRecord?await s.readSecureRecord(e,t):globalThis.localStorage?.getItem(t);if(!o)return null;let i=JSON.parse(o),c=await B(i,e,n,a,r);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:r,signingPublicJwk:c.signingPublicJwk}:null}catch(t){if(s.readSecureRecord)throw t;return null}}async function O(s,e,r,n,a){try{let t=C(e,n),o=s.readSecureRecord?await s.readSecureRecord(r,t):globalThis.localStorage?.getItem(t);return o?await B(JSON.parse(o),r,n,a):null}catch(t){if(s.readSecureRecord)throw t;return null}}async function _(s,e,r,n,a){try{let t=P(e,r,n),o=JSON.stringify(a);s.writeSecureRecord?await s.writeSecureRecord(e,t,o):globalThis.localStorage?.setItem(t,o);}catch(t){if(s.writeSecureRecord)throw t}}async function $(s,e,r,n,a){try{let t=C(r,n),o=JSON.stringify({token:a.token,expiresAtMs:a.expiresAtMs,principalId:a.principalId,signingPublicJwk:a.signingPublicJwk});s.writeSecureRecord?await s.writeSecureRecord(e,t,o):globalThis.localStorage?.setItem(t,o);}catch(t){if(s.writeSecureRecord)throw t}}async function A(s,e,r,n,a){try{let t=P(e,r,n);if(s.deleteSecureRecord?await s.deleteSecureRecord(e,t):globalThis.localStorage?.removeItem(t),a){let o=C(a,n);s.deleteSecureRecord?await s.deleteSecureRecord(e,o):globalThis.localStorage?.removeItem(o);}}catch(t){if(s.deleteSecureRecord)throw t}}function x(s){return `${s}_${crypto.randomUUID()}`}function U(s){if(s instanceof TypeError)return true;if(!s||typeof s!="object")return false;let e=Reflect.get(s,"name");return e==="TimeoutError"||e==="AbortError"}async function j(s,e){let r=new TextEncoder().encode(`${s}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",r))].map(a=>a.toString(16).padStart(2,"0")).join("")}var K=class{constructor(e,r,n,a,t={},o){this.apiKey=e;this.endpoints=r;this.keyProvider=n;this.attestation=a;this.events=t;this.botVerification=o;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let r=this.authEpochs.get(e);if(r)return r;let n={generation:0,devices:new Map};return this.authEpochs.set(e,n),e.subscribe&&(n.unsubscribe=e.subscribe(a=>{a?.type==="principal-changed"&&(n.generation+=1,n.devices.clear(),n.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),n}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async deviceSigningPublicKey(){return (await this.key()).publicKeyJwk}async signDeviceBytes(e){return (await this.key()).sign(e)}async resolveBroadcastAccess(e,r){if(!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e)||e.length>32768)throw new Error("Broadcast grant is invalid.");if(r&&r.byteLength!==32)throw new Error("Broadcast publisher verification key is invalid.");let n=await this.key(),a=f(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))),t=r?f(r):"",o=await n.proof((u,d)=>["openrtc:v2:broadcast-access",this.apiKey,a,t,u,d].join(":")),i=await this.post("/v2/broadcasts",{action:"access",grant:e,...t?{publicationVerifyingKey:t}:{},deviceProof:o});if(i.grant!==e)throw new Error("Broadcast access grant mismatch.");let c=k(i.issuerPublicKey);if(c.byteLength!==32)throw new Error("Broadcast issuer key is invalid.");let l=new URL(i.relay?.relayUrl);if(l.protocol!=="https:"||l.username||l.password)throw new Error("Broadcast relay URL is invalid.");if(typeof i.relay.token!="string"||!/^[A-Za-z0-9._-]{16,16384}$/.test(i.relay.token)||typeof i.relay.namespace!="string"||!/^[A-Za-z0-9._/-]{1,512}$/.test(i.relay.namespace))throw new Error("Broadcast relay allocation is invalid.");return {token:e,issuerPublicKey:c,signBindingChallenge:async u=>{if(!(u instanceof Uint8Array)||u.byteLength>2048)throw new Error("Broadcast binding challenge is invalid.");return k(await n.sign(u))},relay:{relayUrl:l.toString(),token:i.relay.token,namespace:i.relay.namespace}}}async manageBroadcast(e){let r=await this.deviceCertificate(e.auth,e.deviceId),n=e.grant??"",a=e.invite??"",t=e.create,o=e.invitation,i=t?f(t.publisher.verificationKey):o?.publicationVerificationKey?f(o.publicationVerificationKey):"",c=t?{maxPublishers:t.maxPublishers,maxSubscribers:t.maxSubscribers,maxBitrateBps:t.maxBitrateBps,maxDurationSeconds:t.maxDurationSeconds,maxEgressBytes:t.maxEgressBytes}:void 0,l=t?{bitrateBps:t.publisherBitrateBps,durationSeconds:t.maxDurationSeconds,reservedEgressBytes:t.reservedEgressBytes}:o?{role:o.role,sourceSlot:o.sourceSlot??"",bitrateBps:o.bitrateBps,durationSeconds:o.durationSeconds,reservedEgressBytes:o.reservedEgressBytes}:void 0,u=f(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({action:e.action,grant:n,invite:a,publicationKey:i,sourceSlot:t?.sourceSlot??o?.sourceSlot??"host-a",limits:c,reservation:l}))))),y=await(await this.key()).proof((v,g)=>["openrtc:v2:broadcast-manage",r.source.token,e.action,u,v,g].join(":")),p=await this.post("/v2/broadcasts",{action:e.action,deviceId:e.deviceId,deviceCertificate:r.source.token,deviceProof:y,...n?{grant:n}:{},...a?{invite:a}:{},...i?{publicationVerifyingKey:i}:{},...t?{sourceSlot:t.sourceSlot??"host-a",limits:c,reservation:l}:{},...o?{invitation:{...l,publicationVerifyingKey:i}}:{}});if(e.action==="create"||e.action==="renew"){if(typeof p.grant!="string"||!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.grant))throw new Error("Managed broadcast grant is invalid.");return p.grant}if(e.action==="invite"){if(typeof p.invite!="string"||!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.invite))throw new Error("Managed broadcast invitation is invalid.");return p.invite}if(e.action==="accept"){if(typeof p.grant!="string"||!/^orb1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p.grant))throw new Error("Managed broadcast accepted grant is invalid.");return p.grant}}async post(e,r){let n=x("request"),a$1=JSON.stringify({apiKey:this.apiKey,...r}),t=null;for(let o=0;o<2;o+=1)try{let i$1=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":n},body:a$1,signal:AbortSignal.timeout(15e3)});if(i$1.ok)return i$1.json();let c$1=`OpenRTC request failed (${i$1.status}).`,l,u;try{let y=await i$1.json();typeof y.error=="string"&&(c$1=y.error.slice(0,256)),typeof y.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(y.reason)&&(l=y.reason),(c(y.code)||a(y.code))&&(u=i({...d(y),code:y.code,message:c$1,retryable:y.retryable}));}catch{}let d$1=u?Object.assign(u,{status:i$1.status,reason:l}):new w(c$1,i$1.status,l);if(t=d$1,!u&&o===0&&[502,503,504].includes(i$1.status))continue;throw d$1}catch(i){if(t=i,o===0&&U(i))continue;throw i}throw t instanceof Error?t:new Error("OpenRTC request failed.")}async capability(e,r,n,a=false,t,o){this.before("capability.issue");let i=e==="space"?await j(this.apiKey,r):r,l=await(await this.key()).proof((p,v)=>["openrtc:v2:capability",this.apiKey,e,i,p,v].join(":")),u=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,d=await this.post("/v2/capabilities",{avenue:{kind:e,id:i},deviceProof:l,...n?{maxPeers:n}:{},...a?{advancedFanout:true}:{},...e==="room"&&t?{architecture:t}:{},...e==="room"&&o?{roomDelivery:o}:{},...u?{turnstileToken:u}:{}});this.record("capability.issue");let y={type:"capability",token:d.capability,avenue:e==="ticket"?{kind:"session",id:i}:d.avenue,expiresAtMs:d.expiresAt*1e3,...b(d)};return y.renew=()=>this.capability(e,r,n,a,t,o),y}async deviceCertificate(e,r,n,a,t){if(this.keyProvider.persistence==="session")throw new Error("[OpenRTC] Durable browser device enrollment requires trust.browserPersistence: persistent. Select it explicitly before creating the client; session keys cannot enroll retained devices.");let o=this.authEpoch(e),i=o.devices.get(r)??{};if(o.devices.set(r,i),t&&i.current&&i.current.token!==t.token)return this.deviceCertificateResult(e,r,n,a,{...i.current,enrolled:false});if(!t&&i.current&&i.current.expiresAtMs>Date.now()+M)return this.deviceCertificateResult(e,r,n,a,{...i.current,enrolled:false});if(!i.inFlight){let l=o.generation;t&&(i.current=void 0,i.recoverRevokedEnrollment=true);let u=t?A(this.keyProvider,this.appTag,t.principalId,r,o.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(e,r,o.sessionKeyHash,a,true)):this.resolveAuthenticatedDevice(e,r,o,a,i.recoverRevokedEnrollment===true);i.inFlight=u.then(d=>{if(o.generation!==l)throw new Error("The OpenRTC authentication identity changed during enrollment.");return i.recoverRevokedEnrollment=false,i.current=d,d}).finally(()=>{i.inFlight=void 0;});}let c=await i.inFlight;return this.deviceCertificateResult(e,r,n,a,c)}async resolveAuthenticatedDevice(e,r,n,a,t=false){let o=await this.key();if(e.getSessionKey){let i=await e.getSessionKey();if(!i)throw new Error("The OpenRTC auth provider has no active principal.");let c=await G(this.appTag,o.thumbprint,i);n.sessionKeyHash=c;let l=await O(this.keyProvider,c,this.appTag,r,o.thumbprint);if(l)return l}return this.enrollAuthenticatedDevice(e,r,n.sessionKeyHash,a,t)}deviceCertificateResult(e,r,n,a,t){let o={type:"device-certificate",token:t.token,avenue:n??{kind:"user",id:t.principalId},expiresAtMs:t.expiresAtMs,irohRelay:t.irohRelay,managedTurn:t.managedTurn};return o.renew=async()=>(await this.deviceCertificate(e,r,n,a)).source,o.recoverRejectedCertificate=async()=>(await this.deviceCertificate(e,r,n,a,t)).source,{principalId:t.principalId,source:o,enrolled:t.enrolled}}async enrollAuthenticatedDevice(e,r,n,a,t=false){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let o=async(v,g)=>{let m=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:v,deviceId:r,...{}});if(!m)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:m,deviceId:r,...e.providerId?{providerId:e.providerId}:{}})},i;try{i=await o(!1);}catch(v){if(!(v instanceof w)||v.status!==401)throw v;i=await o(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let c=await this.key(),l=await J(this.keyProvider,this.appTag,i.principalId,r,c.thumbprint);if(l)return {...l,principalId:i.principalId,enrolled:false,...b(i)};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let{enrollDevice:u}=await import('./deviceEnrollment-27EVK3E3.js'),d=await u({apiKey:this.apiKey,appTag:this.appTag,auth:e,attestation:this.attestation,deviceId:r,identity:i,key:c,profile:a,recoverRevokedEnrollment:t||i.deviceRecoveryAuthorized===true,post:(v,g)=>this.post(v,g),recordAssertionExchange:()=>this.record("identity.assertion.exchange")});i=d.identity;let y=d.enrollment;this.record("device.enroll"),this.attestation&&this.record("security.attestation.verify");let p={principalId:i.principalId,token:y.deviceCertificate,expiresAtMs:y.expiresAt*1e3,signingPublicJwk:y.signingPublicJwk,enrolled:true,...b(i)};return await _(this.keyProvider,this.appTag,i.principalId,r,{token:p.token,expiresAtMs:p.expiresAtMs,signingPublicJwk:p.signingPublicJwk}),n&&await $(this.keyProvider,this.appTag,n,r,p),p}async listEnrolledDevices(e,r){let n=await this.deviceCertificate(e,r);return (await this.deviceManagement(n.source,r,"list")).devices??[]}async revokeDevice(e,r,n){let a=await this.deviceCertificate(e,r);if(await this.deviceManagement(a.source,r,"revoke",n),n===r){let t=this.authEpoch(e);await A(this.keyProvider,this.appTag,a.principalId,r,t.sessionKeyHash),t.devices.delete(r),await this.deleteDeviceKey();}}async revokeAllDevices(e,r,n){let a=await this.deviceCertificate(e,r);await this.deviceManagement(a.source,r,"revoke-all",void 0,n);let t=this.authEpoch(e);await A(this.keyProvider,this.appTag,a.principalId,r,t.sessionKeyHash),t.devices.delete(r),n?await this.deviceCertificate(e,r):(t.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,r,n,a,t=false){let o=n==="revoke"?"device.revoke":n==="revoke-all"?"identity.revoke-all":null;o&&this.before(o);let{manageDevice:i}=await import('./deviceManagement-SUMBRXXC.js'),c=await i({source:e,currentDeviceId:r,action:n,targetDeviceId:a,exceptCurrent:t,key:()=>this.key(),post:l=>this.post("/v2/devices/manage",l),isStale:T});return o&&this.record(o),c}async durableRoomMembership(e,r,n){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(n==="join"?"room.join":"room.leave");let a=b$1(e.token),t=String(a.jti??""),i=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",t,n,r,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:n,roomId:r,deviceCertificate:e.token,deviceProof:i}),this.record(n==="join"?"room.join":"room.leave");}grantProvider(e,r={}){let n=Promise.resolve(),a=e;return t=>{let o=n.then(async()=>{let i=false;a.expiresAtMs<=Date.now()+3e5&&a.renew&&(a=await a.renew(),i=true);let c=t.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),t.refreshGrant&&this.before("coordination.credential.refresh");let l=async d=>{let y=b$1(d.token),p=String(y.jti??""),g=await(await this.key()).proof((m,I)=>["openrtc:v2:gateway-grant",p,t.avenue.kind,t.avenue.id,t.runtimeInstanceId,m,I].join(":"));return this.post("/v2/gateway/grants",{credentialType:d.type,credential:d.token,avenue:t.avenue,runtimeInstanceId:t.runtimeInstanceId,ticketFingerprint:t.ticketFingerprint,deviceProof:g,...t.refreshGrant?{refreshGrant:t.refreshGrant}:{},...r.maxPeers?{maxPeers:r.maxPeers}:{},...r.features?{features:r.features}:{},...t.avenue.kind==="room"&&r.architecture?{architecture:r.architecture}:{},...t.avenue.kind==="room"&&r.roomDelivery?{roomDelivery:r.roomDelivery}:{},...d.type==="device-certificate"&&r.deviceProfile?{deviceProfile:r.deviceProfile}:{}})},u;try{u=await l(a);}catch(d){if(!T(d))throw d;let y=await a.recoverRejectedCertificate?.();if(!y)throw d;a=y,i=true,u=await l(a);}return this.record(c),t.refreshGrant&&this.record("coordination.credential.refresh"),i&&await r.onSourceRenewed?.({token:a.token,expiresAtMs:a.expiresAtMs}),u});return n=o.then(()=>{},()=>{}),o}}turnProvider(e){let r=x("relay"),n=null,a=null;return async()=>{if(n&&n.expiresAtMs>Date.now()+5*6e4)return n;if(a)return a;let t=(async()=>{let o=e(),i=b$1(o.token),c=String(i.jti??""),u=await(await this.key()).proof((y,p)=>["openrtc:v2:relay-turn",c,r,y,p].join(":")),d=await this.post("/v2/relay/turn",{credentialType:o.type,credential:o.token,sessionId:r,deviceProof:u});return n=d,d})();a=t;try{return await t}finally{a===t&&(a=null);}}}};
2
2
  export{K as a};
@@ -1 +1 @@
1
- import {t}from'./chunk-UPWTSOR7.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 waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(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-WD47V4PK.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 waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(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 @@
1
+ import {h,e}from'./chunk-577A77JB.js';var s="openrtc-ticket-v1.",c=16*1024,d=/^[A-Za-z0-9_.:@-]{1,160}$/;function n(t){return h(e.TICKET_INVITE_INVALID,t,{retryable:false,plane:"admission"})}function a(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw n("[OpenRTC] Invalid ticket invitation encoding.");return atob(t.replace(/-/g,"+").replace(/_/g,"/"))}function g(t){if(typeof t.id!="string"||!d.test(t.id)||!Number.isSafeInteger(t.maxPeers)||t.maxPeers<2||t.maxPeers>8||typeof t.mesh!="boolean"||typeof t.ticket!="string"||!t.ticket||t.ticket.length>c)throw n("[OpenRTC] Invalid ticket invitation.");let i=t.ticket.lastIndexOf(".");if(i<1)throw n("[OpenRTC] Ticket invitation has no endpoint grant.");let e;try{e=JSON.parse(a(t.ticket.slice(i+1)));}catch{throw n("[OpenRTC] Ticket invitation has an invalid endpoint grant.")}if(!e||typeof e!="object"||Array.isArray(e)||e.s!==`ticket:${t.id}`||typeof e.t!="string"||!e.t||e.m!==0||typeof e.h!="string"||!e.h||typeof e.e!="number"||!Number.isSafeInteger(e.e)||e.e<=Date.now()||e.a!=="openrtc:endpoint-ticket:v1"||typeof e.n!="string"||!e.n)throw n("[OpenRTC] Ticket invitation grant does not match its avenue.");return t}function u(t){if(t.length>c||!t.startsWith(s))throw n("[OpenRTC] Invalid ticket invitation format.");let i;try{i=JSON.parse(a(t.slice(s.length)));}catch{throw n("[OpenRTC] Invalid ticket invitation body.")}if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(e=>!["id","ticket","max_peers","mesh"].includes(e)))throw n("[OpenRTC] Invalid ticket invitation body.");return g({id:i.id,ticket:i.ticket,maxPeers:i.max_peers,mesh:i.mesh})}var l=class{constructor(i){this.transmit=i;this.pending=null;this.running=false;this.closedError=null;}send(i){return this.closedError?Promise.reject(this.closedError):new Promise((e,p)=>{this.pending&&this.pending.resolve(),this.pending={payload:i.slice(),resolve:e,reject:p},this.pump();})}close(i=new Error("Latest-state channel is closed.")){this.closedError=i;let e=this.pending;this.pending=null,e?.reject(i);}pump(){this.running||this.closedError||(this.running=true,(async()=>{for(;this.pending&&!this.closedError;){let i=this.pending;this.pending=null;try{await this.transmit(i.payload),i.resolve();}catch(e){i.reject(e);}}})().finally(()=>{this.running=false,this.pending&&!this.closedError&&this.pump();}));}};export{l as a,u as b};