openrtc 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +11 -8
  2. package/dist/{DelegatingRuntimeAdapter-fgz5OPQx.d.ts → DelegatingRuntimeAdapter-BkLR3TNN.d.ts} +33 -31
  3. package/dist/{ITransport-UNOXiRJD.d.ts → ITransport-yaruAmx3.d.ts} +48 -84
  4. package/dist/{IpcRuntimeAdapter-CI3vCzk0.d.ts → IpcRuntimeAdapter-DDKeQ6UC.d.ts} +6 -6
  5. package/dist/WasmBridge-DVQ2YPRB.js +1 -0
  6. package/dist/{assembly-CLdwe5T-.d.ts → assembly-BTzwQuwI.d.ts} +67 -74
  7. package/dist/{capabilities-BUe5YldR.d.ts → capabilities-BwzPe51I.d.ts} +19 -19
  8. package/dist/chunk-2IRNZN3N.js +1 -0
  9. package/dist/chunk-4MLJXEVV.js +2 -0
  10. package/dist/chunk-AJQVMVYW.js +1 -0
  11. package/dist/chunk-BOS554IK.js +2 -0
  12. package/dist/chunk-DI5VSZ2T.js +2 -0
  13. package/dist/chunk-F4BJ72HN.js +1 -0
  14. package/dist/{chunk-LRT5GEGH.js → chunk-FKEKINIM.js} +2 -2
  15. package/dist/chunk-GND6UW37.js +1 -0
  16. package/dist/{chunk-Z2WVSXPW.js → chunk-HUG5AX7R.js} +1 -1
  17. package/dist/chunk-LN4ALFT6.js +1 -0
  18. package/dist/chunk-NXM5ZGHD.js +2 -0
  19. package/dist/chunk-OUFHVLDQ.js +2 -0
  20. package/dist/chunk-SUWCBTBQ.js +1 -0
  21. package/dist/chunk-UGZJJQPM.js +3 -0
  22. package/dist/chunk-ZA44REGI.js +2 -0
  23. package/dist/controlPlane-JJFURVOX.js +1 -0
  24. package/dist/{OpenRTCShared.d.ts → coreClient.d.ts} +61 -66
  25. package/dist/coreClient.js +1 -0
  26. package/dist/{deviceEnrollment-33NZEARB.js → deviceEnrollment-Z2EHP2EX.js} +1 -1
  27. package/dist/deviceKey-Y35WSEQQ.js +1 -0
  28. package/dist/deviceProfile-CR2C7OYR.js +2 -0
  29. package/dist/index.d.ts +30 -30
  30. package/dist/index.js +1 -1
  31. package/dist/{ipc-CflAVodw.d.ts → ipc-CPnNwv6f.d.ts} +3 -3
  32. package/dist/ipcFactory-DQFK65VE.js +1 -0
  33. package/dist/openrtc-INQDCF23.js +2 -0
  34. package/dist/openrtc_bg.wasm +0 -0
  35. package/dist/runtime/WasmRuntimeAdapter.d.ts +4 -4
  36. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  37. package/dist/runtime/device-status.d.ts +10 -10
  38. package/dist/runtime/device-status.js +1 -1
  39. package/dist/runtime/factories.d.ts +8 -8
  40. package/dist/runtime/factories.js +1 -1
  41. package/dist/runtime/index.d.ts +50 -50
  42. package/dist/runtime/index.js +1 -1
  43. package/dist/testing.d.ts +29 -28
  44. package/dist/testing.js +1 -1
  45. package/dist/transport/index.d.ts +24 -24
  46. package/dist/transport/index.js +1 -1
  47. package/dist/{types-DhmY9hBy.d.ts → types-C4TIUgOJ.d.ts} +74 -70
  48. package/dist/{types-l3m3GrOe.d.ts → types-D67HlF0p.d.ts} +58 -102
  49. package/package.json +2 -6
  50. package/dist/OpenRTCShared.js +0 -1
  51. package/dist/WasmBridge-P5646IVR.js +0 -1
  52. package/dist/chunk-45WBH7E3.js +0 -1
  53. package/dist/chunk-5OTF7W2N.js +0 -3
  54. package/dist/chunk-7FPG3MFF.js +0 -2
  55. package/dist/chunk-AG2F6MOB.js +0 -1
  56. package/dist/chunk-CWGKLGJZ.js +0 -1
  57. package/dist/chunk-HIXXBEWX.js +0 -1
  58. package/dist/chunk-IKZ33R7R.js +0 -2
  59. package/dist/chunk-KJTJLLJE.js +0 -2
  60. package/dist/chunk-QCPSLUKO.js +0 -1
  61. package/dist/chunk-VBUDERMM.js +0 -2
  62. package/dist/chunk-XPL7PUBW.js +0 -2
  63. package/dist/chunk-Y35AKFCM.js +0 -1
  64. package/dist/chunk-ZQF5KSOK.js +0 -2
  65. package/dist/controlPlane-YAMXWHAF.js +0 -1
  66. package/dist/deviceKey-SBNKLVYF.js +0 -1
  67. package/dist/deviceProfile-3BEQZLJF.js +0 -2
  68. package/dist/ipcFactory-JTMNUTZI.js +0 -1
  69. package/dist/native.d.ts +0 -15
  70. package/dist/native.js +0 -1
  71. package/dist/openrtc-JUV7TOTL.js +0 -2
  72. /package/dist/{deviceManagement-PHY5TIOS.js → deviceManagement-SUMBRXXC.js} +0 -0
  73. /package/dist/{deviceRoster-VZA3TQOR.js → deviceRoster-EUF6BBF5.js} +0 -0
@@ -1,6 +1,6 @@
1
- import { a as RuntimePeerState, j as RuntimeConnectionStateSnapshot, c as RuntimePeerReadinessSnapshot, b as RuntimePeerConnectOptions, C as Connection, f as RuntimeIncomingStream, v as RuntimeClientOptions, z as RuntimeAuthIdentity, A as AuthContext, q as RuntimeLocalDeviceInfo, r as RuntimeLocalDeviceProfile, I as IrohBrowserProtocolStore, w as IrohNamespaceDescriptor, x as IrohMutationReceipt, y as IrohDocEntry, h as RuntimeDevice, m as RuntimeManagedSessionOptions, n as RuntimeManagedSession, o as RuntimeDeviceStatusSnapshot, p as RuntimeDeviceConnectOptions, B as RuntimeSession, t as RuntimeJoinRoomOptions, u as RuntimeRoomMember, D as RuntimeConnectionTarget, g as RuntimeScopedChannelOptions, i as RuntimeScopedLogicalChannel, e as RuntimePeerStreamOptions, s as RuntimeRawConnection, R as RuntimeChannelDescriptor, E as RuntimePresenceLoopOptions, d as RuntimePeerHealth, k as RuntimeApplicationPayloadReadinessOptions, l as RuntimeConnectionEvent } from './types-l3m3GrOe.js';
2
- import { G as GrantScope, I as ISignalingBackend, e as ConnectDeviceHooks, f as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, d as PeerSessionSnapshot, R as ResolvedPeerIdentity, a6 as AppLimits, N as NativeConnectParams, s as NativeConnectResult, E as ExplicitFileDataSendParams } from './ITransport-UNOXiRJD.js';
3
- import { R as RuntimeCapabilities, a as RuntimeCapabilityProfile } from './capabilities-BUe5YldR.js';
1
+ import { R as RuntimePeerState, g as ConnectionState, b as PeerReadiness, P as PeerConnectOptions, a as Connection, I as IncomingStream, o as RuntimeClientOptions, r as RuntimeAuthIdentity, A as AuthContext, L as LocalDeviceInfo, l as DeviceProfile, B as BrowserProtocolStore, N as NamespaceDescriptor, p as IrohMutationReceipt, q as IrohDocEntry, e as RuntimeDevice, M as ManagedOptions, j as ManagedSession, D as DeviceStatus, k as DeviceConnectOptions, s as RuntimeSession, J as JoinRoomOptions, n as RuntimeRoomMember, t as ConnectionTarget, S as ScopedChannelOptions, f as ScopedLogicalChannel, d as PeerStreamOptions, m as RawConnection, C as ChannelDescriptor, u as PresenceLoopOptions, c as RuntimePeerHealth, h as ReadinessOptions, i as ConnectionEvent } from './types-D67HlF0p.js';
2
+ import { G as GrantScope, I as ISignalingBackend, f as ConnectDeviceHooks, g as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, d as PeerSessionSnapshot, e as ResolvedPeerIdentity, a6 as AppLimits, N as NativeConnectParams, t as NativeConnectResult, E as ExplicitFileDataSendParams } from './ITransport-yaruAmx3.js';
3
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-BwzPe51I.js';
4
4
 
5
5
  /**
6
6
  * Coalesced peer reconciliation scheduler and full reconcile orchestration.
@@ -26,7 +26,7 @@ interface SessionOptions {
26
26
  */
27
27
  scope: string;
28
28
  /**
29
- * When true, watchPeerStates / onConnectionStateChange deliver events for
29
+ * When true, watchPeerStates / onStateChange deliver events for
30
30
  * ALL peers, not just those scoped to this session. Useful for the default
31
31
  * 'user-device' session that legitimately needs the full peer picture.
32
32
  * Default: false.
@@ -54,23 +54,23 @@ interface Session {
54
54
  * Subscribe to connection-state events filtered to this session's scope.
55
55
  * Returns the unsubscribe function (may be async for WASM bridge compat).
56
56
  */
57
- onConnectionStateChange(callback: (state: RuntimeConnectionStateSnapshot) => void): (() => void) | Promise<() => void>;
57
+ onStateChange(callback: (state: ConnectionState) => void): (() => void) | Promise<() => void>;
58
58
  /** Async snapshot of peers matching this session's scope. */
59
59
  listConnectedPeers(): RuntimePeerState[];
60
60
  /** Peer readiness for a specific peer ID (scope-filtered). */
61
- getPeerReadiness(peerId: string): Promise<RuntimePeerReadinessSnapshot>;
61
+ getPeerReadiness(peerId: string): Promise<PeerReadiness>;
62
62
  /**
63
63
  * Connect to a peer via ticket or device ID, tagging the connection with
64
64
  * this session's scope.
65
65
  */
66
- connectPeer(options: RuntimePeerConnectOptions): Promise<Connection>;
66
+ connectPeer(options: PeerConnectOptions): Promise<Connection>;
67
67
  /** Disconnect a peer within this session's scope only. */
68
68
  disconnectPeer(peerId: string): Promise<void>;
69
69
  /**
70
70
  * Subscribe to incoming streams from peers whose scope matches this
71
71
  * session. Streams from other scopes are not delivered.
72
72
  */
73
- onIncomingStream(callback: (stream: RuntimeIncomingStream) => void): () => void;
73
+ onIncomingStream(callback: (stream: IncomingStream) => void): () => void;
74
74
  /** Tear down all subscriptions and disconnect scope-tagged connections. */
75
75
  dispose(): void;
76
76
  }
@@ -80,7 +80,7 @@ interface Session {
80
80
  * (`docs/plans/openrtc-auth-connection-remediation-plan.md`).
81
81
  *
82
82
  * `DriveGrantActorHandle` is the historical implementation behind the public
83
- * `ScopedConnectionActorHandle` alias. It is a TypeScript observer-side dial
83
+ * `ConnectionActor` alias. It is a TypeScript observer-side dial
84
84
  * coalescer for scoped protocol routes such as drive-grant guests and
85
85
  * trusted-device drive-view. It mirrors the intended Rust actor shape but is
86
86
  * not backed by the Rust actor today. With one handle per `(scope, peerNodeId)`
@@ -95,7 +95,7 @@ interface Session {
95
95
  * end-to-end. What it does today:
96
96
  *
97
97
  * - `DriveGrantConnectionPipeline` and trusted-device drive-view acquisition call
98
- * `runtimeClient.getScopedConnectionActor(scope, peerNodeId).ensureReady()`,
98
+ * `runtimeClient.connectionActor(scope, peerNodeId).ensureReady()`,
99
99
  * then perform their existing `connectPeer` call inside the handle-owned
100
100
  * `dial` function. Multiple concurrent observers for the same key thus
101
101
  * coalesce to one `connectPeer` call.
@@ -197,12 +197,6 @@ declare class DriveGrantActorHandle {
197
197
  * QUIC stream layer.
198
198
  */
199
199
  openLogicalChannel(label: string): Promise<DriveGrantLogicalChannelHandle>;
200
- /**
201
- * Test/Phase-4 helper: returns the label without invoking the
202
- * unimplemented wire format, so observers can prove their request
203
- * shape round-trips today.
204
- */
205
- openLogicalChannelTestStub(label: string): Promise<DriveGrantLogicalChannelHandle>;
206
200
  /**
207
201
  * Idempotent shutdown. Subsequent `ensureReady()` rejects with
208
202
  * `shutdown`; subsequent `shutdown()` is a no-op.
@@ -224,7 +218,7 @@ declare class DriveGrantActorRegistry {
224
218
  size(): number;
225
219
  }
226
220
 
227
- interface RuntimePolicySnapshot {
221
+ interface PolicySnapshot {
228
222
  managedSession: {
229
223
  nativeStartRetryWindowMs: number;
230
224
  nativeStartRetryMinDelayMs: number;
@@ -251,8 +245,8 @@ interface RuntimePolicySnapshot {
251
245
  ephemeralDeviceIdTtlMs: number;
252
246
  };
253
247
  }
254
- declare const OPENRTC_RUNTIME_POLICY: RuntimePolicySnapshot;
255
- declare function getRuntimePolicy(): RuntimePolicySnapshot;
248
+ declare const RUNTIME_POLICY: PolicySnapshot;
249
+ declare function getRuntimePolicy(): PolicySnapshot;
256
250
 
257
251
  /**
258
252
  * RuntimeClient is the primary application-facing API.
@@ -287,7 +281,7 @@ declare class RuntimeClient {
287
281
  private readonly deviceManager;
288
282
  private readonly peerManager;
289
283
  private readonly connectionController;
290
- private readonly nativeApplicationStreamConsumer;
284
+ private readonly nativeStreamConsumer;
291
285
  private managedSessionKey;
292
286
  private managedSessionUserId;
293
287
  private managedSessionOptions;
@@ -324,7 +318,7 @@ declare class RuntimeClient {
324
318
  private scheduleManagedReconciliationFollowups;
325
319
  private stopManagedReconciliation;
326
320
  private notifyManagedReconciliation;
327
- reconcileNativeManagedSession(reason?: string): Promise<void>;
321
+ syncNativeSession(reason?: string): Promise<void>;
328
322
  notifyNetworkChange(reason?: string): Promise<void>;
329
323
  private connectionStateSnapshotKey;
330
324
  private runNativeStartLoop;
@@ -341,10 +335,10 @@ declare class RuntimeClient {
341
335
  localNodeId?: string;
342
336
  userId?: string;
343
337
  }>;
344
- getPeerReconciliationStats(): Readonly<PeerReconciliationStats>;
345
- getRuntimePolicy(): RuntimePolicySnapshot;
346
- getRuntimeCapabilities(): RuntimeCapabilities;
347
- getCapabilityProfile(): RuntimeCapabilityProfile;
338
+ reconciliationStats(): Readonly<PeerReconciliationStats>;
339
+ getRuntimePolicy(): PolicySnapshot;
340
+ capabilities(): RuntimeCapabilities;
341
+ getCapabilityProfile(): CapabilityProfile;
348
342
  start(options?: {
349
343
  clearSessionTokens?: boolean;
350
344
  }): Promise<void>;
@@ -352,14 +346,14 @@ declare class RuntimeClient {
352
346
  getNodeId(): Promise<string>;
353
347
  getNodeIdFromTicket(ticket: string): Promise<string | null>;
354
348
  getLocalDeviceId(): Promise<string | null>;
355
- getLocalDeviceInfo(): Promise<RuntimeLocalDeviceInfo | null>;
356
- getLocalDeviceProfile(options?: {
349
+ getLocalDeviceInfo(): Promise<LocalDeviceInfo | null>;
350
+ localDeviceProfile(options?: {
357
351
  deviceName?: string;
358
352
  localDeviceId?: string | null;
359
353
  platform?: 'native' | 'web';
360
354
  userId?: string | null;
361
- }): Promise<RuntimeLocalDeviceProfile>;
362
- updateLocalDeviceName(deviceName: string): Promise<RuntimeLocalDeviceInfo | null>;
355
+ }): Promise<DeviceProfile>;
356
+ updateDeviceName(deviceName: string): Promise<LocalDeviceInfo | null>;
363
357
  getManagedNodeId(options?: {
364
358
  initializeIfMissing?: boolean;
365
359
  }): Promise<string | null>;
@@ -368,11 +362,11 @@ declare class RuntimeClient {
368
362
  * browser endpoint. The host store supplies durable IndexedDB operations;
369
363
  * no second endpoint, router, presence loop, or reconnect owner is created.
370
364
  */
371
- initializeIrohProtocols(store: IrohBrowserProtocolStore): Promise<void>;
365
+ initIrohProtocols(store: BrowserProtocolStore): Promise<void>;
372
366
  createIrohNamespace(options?: {
373
367
  generation?: number;
374
368
  shareRevision?: number;
375
- }): Promise<IrohNamespaceDescriptor>;
369
+ }): Promise<NamespaceDescriptor>;
376
370
  importIrohTicket(ticket: string, options?: {
377
371
  generation?: number;
378
372
  shareRevision?: number;
@@ -392,7 +386,7 @@ declare class RuntimeClient {
392
386
  }>;
393
387
  queryIrohNamespace(namespaceId: string, keyPrefix?: Uint8Array<ArrayBuffer>): Promise<IrohDocEntry[]>;
394
388
  hydrateIrohBlob(contentHash: string): Promise<void>;
395
- acknowledgeIrohOutbox(operationId: string): Promise<void>;
389
+ acknowledgeOutbox(operationId: string): Promise<void>;
396
390
  flushIrohProtocols(): Promise<void>;
397
391
  private persistentIrohProtocolBackend;
398
392
  private assertProtocolCounter;
@@ -414,7 +408,7 @@ declare class RuntimeClient {
414
408
  * remains the sole owner of the native/WASM admission registry. Restricted
415
409
  * grants should always include their server-issued expiry.
416
410
  */
417
- registerAdmissionToken(input: {
411
+ registerToken(input: {
418
412
  token: string;
419
413
  scope: GrantScope;
420
414
  maxConnections?: number;
@@ -454,14 +448,14 @@ declare class RuntimeClient {
454
448
  */
455
449
  updateFriendTicket(friendTicket: string | null): Promise<void>;
456
450
  getEndpointTicket(): Promise<string>;
457
- startManagedSession(options: RuntimeManagedSessionOptions): Promise<RuntimeManagedSession>;
451
+ startManagedSession(options: ManagedOptions): Promise<ManagedSession>;
458
452
  stopManagedSession(options?: {
459
453
  preserveBackendSession?: boolean;
460
454
  }): Promise<void>;
461
455
  private stopManagedSessionInternal;
462
456
  private rotateManagedUserDeviceGrant;
463
457
  listDevices(): Promise<RuntimeDevice[]>;
464
- listDevicesWithStatus(): Promise<RuntimeDeviceStatusSnapshot[]>;
458
+ listDeviceStatus(): Promise<DeviceStatus[]>;
465
459
  updateDevice(deviceId: string, updates: {
466
460
  deviceName?: string;
467
461
  capabilities?: RuntimeDevice['capabilities'];
@@ -469,8 +463,8 @@ declare class RuntimeClient {
469
463
  }): Promise<void>;
470
464
  deleteDevice(deviceId: string): Promise<void>;
471
465
  watchDevices(callback: (devices: RuntimeDevice[]) => void): () => void;
472
- watchDevicesWithStatus(callback: (devices: RuntimeDeviceStatusSnapshot[]) => void): () => void;
473
- connectDeviceWithRetry(device: RuntimeDevice, hooks: ConnectDeviceHooks, options: ConnectDeviceOptions): Promise<ConnectDeviceResult>;
466
+ watchDeviceStatus(callback: (devices: DeviceStatus[]) => void): () => void;
467
+ connectWithRetry(device: RuntimeDevice, hooks: ConnectDeviceHooks, options: ConnectDeviceOptions): Promise<ConnectDeviceResult>;
474
468
  /**
475
469
  * Runtime-owned device connect flow used by product code.
476
470
  * Rust owns the actual managed dial policy. This wrapper only:
@@ -478,17 +472,17 @@ declare class RuntimeClient {
478
472
  * - forwards the request to the active runtime adapter
479
473
  * - refreshes peer state and invokes optional app callbacks
480
474
  */
481
- connectDevice(device: RuntimeDevice, options: RuntimeDeviceConnectOptions): Promise<ConnectDeviceResult>;
475
+ connectDevice(device: RuntimeDevice, options: DeviceConnectOptions): Promise<ConnectDeviceResult>;
482
476
  watchPeerStates(callback: (peers: RuntimePeerState[]) => void): () => void;
483
477
  watchPeerLifecycle(callback: (peers: RuntimePeerState[]) => void): () => void;
484
478
  getPeerState(id: string): RuntimePeerState | undefined;
485
- resolvePeerConnectionRecords(id: string): Promise<ManagedConnectionRecord[]>;
479
+ resolvePeerRecords(id: string): Promise<ManagedConnectionRecord[]>;
486
480
  getPeerSession(id: string): Promise<PeerSessionSnapshot | null>;
487
481
  listPeerSessions(): Promise<PeerSessionSnapshot[]>;
488
482
  waitForConnectedPeer(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
489
- getPeerReadiness(id: string, timeoutMs?: number): Promise<RuntimePeerReadinessSnapshot>;
483
+ getPeerReadiness(id: string, timeoutMs?: number): Promise<PeerReadiness>;
490
484
  resolvePeerIdentity(id: string): Promise<ResolvedPeerIdentity>;
491
- resolveIncomingStreamPeer(remoteNodeId: string): Promise<ResolvedPeerIdentity>;
485
+ resolveStreamPeer(remoteNodeId: string): Promise<ResolvedPeerIdentity>;
492
486
  listConnectedPeers(): RuntimePeerState[];
493
487
  addPeerScope(id: string, scope?: string): RuntimePeerState | undefined;
494
488
  releasePeerScope(id: string, scope?: string): RuntimePeerState | undefined;
@@ -498,14 +492,14 @@ declare class RuntimeClient {
498
492
  subscribeSessions(localDeviceId: string, callback: (session: RuntimeSession) => void | Promise<void>): Promise<() => void>;
499
493
  getAppLimits(): AppLimits;
500
494
  createRoom(roomId?: string): Promise<string>;
501
- joinRoom(roomId: string, options?: RuntimeJoinRoomOptions): Promise<Connection[]>;
495
+ joinRoom(roomId: string, options?: JoinRoomOptions): Promise<Connection[]>;
502
496
  leaveRoom(roomId: string): Promise<void>;
503
497
  getRoomMembers(roomId: string): Promise<RuntimeRoomMember[]>;
504
498
  watchRoom(roomId: string, callback: (members: RuntimeRoomMember[]) => void): () => void;
505
499
  /** @deprecated Use connect() (no-arg) for lifecycle, or connectTo() for peer connections */
506
- connectByTicket(target: RuntimeConnectionTarget): Promise<Connection>;
507
- connectPeer(options: RuntimePeerConnectOptions): Promise<Connection>;
508
- connectScopedChannel(options: RuntimeScopedChannelOptions): Promise<RuntimeScopedLogicalChannel>;
500
+ connectByTicket(target: ConnectionTarget): Promise<Connection>;
501
+ connectPeer(options: PeerConnectOptions): Promise<Connection>;
502
+ connectScopedChannel(options: ScopedChannelOptions): Promise<ScopedLogicalChannel>;
509
503
  /**
510
504
  * Returns the per-`{scope, peerNodeId}` observer-side coalescer that
511
505
  * participating scoped guest callers (such as DriveViewClient) use. The
@@ -522,7 +516,7 @@ declare class RuntimeClient {
522
516
  * only with a narrow `dial` callback that delegates back through
523
517
  * `connectPeer`; the runtime `Client` remains the peer lifecycle owner.
524
518
  */
525
- getScopedConnectionActor(key: DriveGrantConnectionKey | {
519
+ connectionActor(key: DriveGrantConnectionKey | {
526
520
  scope: string;
527
521
  peerNodeId: string;
528
522
  }, options?: {
@@ -540,7 +534,7 @@ declare class RuntimeClient {
540
534
  * router/disconnect handler to the connection object) can
541
535
  * supply their own `dial` here. The actor's coalescer still
542
536
  * ensures only one `dial(key)` runs even with N concurrent
543
- * `getScopedConnectionActor(...).ensureReady()` callers — this just
537
+ * `connectionActor(...).ensureReady()` callers — this just
544
538
  * lets the caller decide what "dial" means.
545
539
  */
546
540
  dial?: (key: DriveGrantConnectionKey) => Promise<void>;
@@ -549,40 +543,40 @@ declare class RuntimeClient {
549
543
  private scopedDialCandidateIds;
550
544
  private hasManualDisconnectSuppression;
551
545
  /** Shuts down every scoped observer handle during managed-session teardown. */
552
- shutdownScopedConnectionActors(): Promise<void>;
553
- openPeerBi(id: string, options?: RuntimePeerStreamOptions): Promise<{
546
+ shutdownActors(): Promise<void>;
547
+ openPeerBi(id: string, options?: PeerStreamOptions): Promise<{
554
548
  connection: Connection;
555
549
  readable: ReadableStream<Uint8Array>;
556
550
  writable: WritableStream<Uint8Array>;
557
551
  }>;
558
- openPeerNativeBi(id: string, label: string, options?: RuntimePeerStreamOptions): Promise<{
552
+ openPeerNativeBi(id: string, label: string, options?: PeerStreamOptions): Promise<{
559
553
  connection: Connection;
560
554
  readable: ReadableStream<Uint8Array>;
561
555
  writable: WritableStream<Uint8Array>;
562
556
  }>;
563
557
  /** Like openPeerBi but skips the settled_ready requirement — usable for latency probes. */
564
- openPeerBiTransportOnly(id: string, options?: RuntimePeerStreamOptions): Promise<{
558
+ openPeerBiRaw(id: string, options?: PeerStreamOptions): Promise<{
565
559
  connection: Connection;
566
560
  readable: ReadableStream<Uint8Array>;
567
561
  writable: WritableStream<Uint8Array>;
568
562
  }>;
569
- openPeerUni(id: string, options?: RuntimePeerStreamOptions): Promise<{
563
+ openPeerUni(id: string, options?: PeerStreamOptions): Promise<{
570
564
  connection: Connection;
571
565
  writable: WritableStream<Uint8Array>;
572
566
  }>;
573
567
  private waitForBrowserApplicationCrypto;
574
568
  connectToDevice(params: NativeConnectParams): Promise<NativeConnectResult>;
575
- connectRaw(target: RuntimeConnectionTarget): Promise<RuntimeRawConnection>;
569
+ connectRaw(target: ConnectionTarget): Promise<RawConnection>;
576
570
  openBi(nodeId: string): Promise<{
577
571
  readable: ReadableStream<Uint8Array>;
578
572
  writable: WritableStream<Uint8Array>;
579
573
  }>;
580
574
  openUni(nodeId: string): Promise<WritableStream<Uint8Array>>;
581
- onIncomingStream(callback: (stream: RuntimeIncomingStream) => boolean | void): () => void;
582
- registerChannel(descriptor: RuntimeChannelDescriptor): void;
575
+ onIncomingStream(callback: (stream: IncomingStream) => boolean | void): () => void;
576
+ registerChannel(descriptor: ChannelDescriptor): void;
583
577
  unregisterChannel(channelId: string): void;
584
- listChannels(): RuntimeChannelDescriptor[];
585
- onIncomingChannelStream(channelId: string, callback: (stream: RuntimeIncomingStream) => boolean | void): () => void;
578
+ listChannels(): ChannelDescriptor[];
579
+ onChannelStream(channelId: string, callback: (stream: IncomingStream) => boolean | void): () => void;
586
580
  /** @deprecated Use named channels or the optional `openrtc-file-transfer` package. */
587
581
  sendExplicitFilePath(connectionId: string, filePath: string, transferId?: string): Promise<string>;
588
582
  /** @deprecated Use named channels or the optional `openrtc-file-transfer` package. */
@@ -591,7 +585,7 @@ declare class RuntimeClient {
591
585
  getTransferHistory(limit?: number): Promise<Array<[string, unknown]>>;
592
586
  /** @deprecated Transfer history belongs to the consumer application. */
593
587
  deleteTransferJob(jobId: string): Promise<void>;
594
- startPresenceLoop(options?: RuntimePresenceLoopOptions): Promise<void>;
588
+ startPresenceLoop(options?: PresenceLoopOptions): Promise<void>;
595
589
  updatePresence(options?: {
596
590
  isOnline?: boolean;
597
591
  ttlMs?: number;
@@ -608,20 +602,20 @@ declare class RuntimeClient {
608
602
  isConnected(nodeId: string): Promise<boolean>;
609
603
  disconnectNode(nodeId: string): Promise<void>;
610
604
  disconnectDevice(deviceId: string): Promise<void>;
611
- setAutoConnectExcluded(deviceId: string, excluded: boolean): Promise<void>;
605
+ excludeAutoConnect(deviceId: string, excluded: boolean): Promise<void>;
612
606
  disconnectPeer(id: string, scope?: string): Promise<void>;
613
607
  forceDisconnectPeer(id: string): Promise<void>;
614
608
  getPeerHealth(id: string): Promise<RuntimePeerHealth>;
615
- getConnectionStates(): Promise<RuntimeConnectionStateSnapshot[]>;
609
+ getConnectionStates(): Promise<ConnectionState[]>;
616
610
  /**
617
611
  * Subscribe to raw backend connection diagnostics.
618
612
  *
619
613
  * This compatibility surface intentionally does not drive peer lifecycle or
620
614
  * UI readiness; use watchPeerStates() for the reducer-owned lifecycle view.
621
615
  */
622
- onConnectionStateChange(callback: (state: RuntimeConnectionStateSnapshot) => void): Promise<() => void> | (() => void);
616
+ onStateChange(callback: (state: ConnectionState) => void): Promise<() => void> | (() => void);
623
617
  getConnections(): Connection[];
624
- getApplicationReadyConnections(options?: RuntimeApplicationPayloadReadinessOptions): Connection[];
618
+ readyConnections(options?: ReadinessOptions): Connection[];
625
619
  onConnection(callback: (connection: Connection) => void): () => void;
626
620
  onDisconnection(callback: (connection: Connection) => void): () => void;
627
621
  /**
@@ -630,8 +624,8 @@ declare class RuntimeClient {
630
624
  * so Iroh, WebRTC, and MoQ share one intake path.
631
625
  */
632
626
  onMessage(callback: (connection: Connection, message: unknown) => void): () => void;
633
- onConnectionEvent(callback: (event: RuntimeConnectionEvent) => void): () => void;
634
- forceReconnectSnapshot(): void;
627
+ onConnectionEvent(callback: (event: ConnectionEvent) => void): () => void;
628
+ forceReconnect(): void;
635
629
  /** Single-call lifecycle: combines initialize() + start() */
636
630
  connect(): Promise<void>;
637
631
  /** Disconnect from the runtime (alias for stop()) */
@@ -665,24 +659,24 @@ declare class RuntimeClient {
665
659
  getDevices(): Promise<RuntimeDevice[]>;
666
660
  /** Device subscription with optional status enrichment */
667
661
  onDevices(callback: (devices: RuntimeDevice[]) => void): () => void;
668
- onDevices(callback: (devices: RuntimeDeviceStatusSnapshot[]) => void, options: {
662
+ onDevices(callback: (devices: DeviceStatus[]) => void, options: {
669
663
  status: true;
670
664
  }): () => void;
671
665
  /** Alias for getTicket — returns an invite/ticket string */
672
666
  getInvite(): Promise<string>;
673
667
  /** Connect to a peer by device ID or options */
674
- connectTo(options: RuntimePeerConnectOptions): Promise<Connection>;
668
+ connectTo(options: PeerConnectOptions): Promise<Connection>;
675
669
  /** Alias for waitForConnectedPeer */
676
670
  waitFor(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
677
671
  /** Open a stream to a peer (default: bidirectional) */
678
- openStream(id: string, options?: RuntimePeerStreamOptions & {
672
+ openStream(id: string, options?: PeerStreamOptions & {
679
673
  direction?: 'bi' | 'send';
680
674
  }): Promise<{
681
675
  connection: Connection;
682
676
  readable?: ReadableStream<Uint8Array>;
683
677
  writable: WritableStream<Uint8Array>;
684
678
  }>;
685
- openChannelStream(channelId: string, id: string, options?: RuntimePeerStreamOptions & {
679
+ openChannelStream(channelId: string, id: string, options?: PeerStreamOptions & {
686
680
  direction?: 'bi' | 'send';
687
681
  }): Promise<{
688
682
  connection: Connection;
@@ -690,8 +684,7 @@ declare class RuntimeClient {
690
684
  writable: WritableStream<Uint8Array>;
691
685
  }>;
692
686
  /** Alias for onIncomingStream */
693
- onStream(callback: (stream: RuntimeIncomingStream) => boolean | void): () => void;
694
- onChannelStream(channelId: string, callback: (stream: RuntimeIncomingStream) => boolean | void): () => void;
687
+ onStream(callback: (stream: IncomingStream) => boolean | void): () => void;
695
688
  /** Alias for watchRoom */
696
689
  onRoomChange(roomId: string, callback: (members: RuntimeRoomMember[]) => void): () => void;
697
690
  /**
@@ -736,10 +729,10 @@ interface PlutoRuntimeAssembly<TBackend extends RuntimeAdapterWithAuth = Runtime
736
729
  initializeIfMissing?: boolean;
737
730
  }): Promise<string | null>;
738
731
  getRuntimeStatus(): Promise<any>;
739
- listDevicesWithStatus(): Promise<any>;
740
- watchDevicesWithStatus(callback: (devices: any[]) => void): () => void;
732
+ listDeviceStatus(): Promise<any>;
733
+ watchDeviceStatus(callback: (devices: any[]) => void): () => void;
741
734
  connectDevice(device: any, options: any): Promise<any>;
742
- setAutoConnectExcluded(deviceId: string, excluded: boolean): Promise<void>;
735
+ excludeAutoConnect(deviceId: string, excluded: boolean): Promise<void>;
743
736
  }
744
737
 
745
- export { DriveGrantActorError as D, OPENRTC_RUNTIME_POLICY as O, type PeerReconciliationStats as P, type RuntimePolicySnapshot as R, RuntimeClient as a, type PlutoRuntimeAssembly as b, type RuntimeFactoryOptions as c, type DriveGrantActorErrorKind as d, DriveGrantActorHandle as e, type DriveGrantActorHandleOptions as f, DriveGrantActorRegistry as g, type DriveGrantActorState as h, type DriveGrantClose as i, type DriveGrantDial as j, type DriveGrantConnectionKey as k, type DriveGrantLogicalChannelHandle as l, type DriveGrantPreferredTransport as m, getRuntimePolicy as n, driveGrantConnectionKey as o, driveGrantConnectionKeyToString as p };
738
+ export { DriveGrantActorHandle as D, type PolicySnapshot as P, RuntimeClient as R, type PeerReconciliationStats as a, type PlutoRuntimeAssembly as b, type RuntimeFactoryOptions as c, DriveGrantActorError as d, type DriveGrantActorErrorKind as e, type DriveGrantConnectionKey as f, type DriveGrantActorHandleOptions as g, type DriveGrantActorState as h, DriveGrantActorRegistry as i, type DriveGrantClose as j, type DriveGrantDial as k, type DriveGrantLogicalChannelHandle as l, type DriveGrantPreferredTransport as m, RUNTIME_POLICY as n, driveGrantConnectionKey as o, driveGrantConnectionKeyToString as p, getRuntimePolicy as q };
@@ -1,4 +1,4 @@
1
- import { c as ProtocolName, T as TransportOptimization } from './ITransport-UNOXiRJD.js';
1
+ import { c as ProtocolName, R as RouteOptimization } from './ITransport-yaruAmx3.js';
2
2
 
3
3
  type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
4
4
  interface RuntimeCapabilities {
@@ -40,7 +40,7 @@ interface RuntimeCapabilities {
40
40
  wasm: boolean;
41
41
  };
42
42
  }
43
- interface RuntimeCapabilityProfile {
43
+ interface CapabilityProfile {
44
44
  environment: 'web' | 'native' | 'unknown';
45
45
  transports: {
46
46
  quic: boolean;
@@ -58,39 +58,39 @@ interface RuntimeCapabilityProfile {
58
58
  };
59
59
  nativeProtocols: RuntimeCapabilities['nativeProtocols'];
60
60
  }
61
- interface NativeRuntimeTransportFeatureStatus {
61
+ interface TransportStatus {
62
62
  compiled?: boolean;
63
63
  enabled?: boolean;
64
64
  }
65
- interface NativeRuntimeStatusSnapshot {
65
+ interface NativeRuntimeStatus {
66
66
  ready?: boolean;
67
67
  nodeId?: string | null;
68
68
  node_id?: string | null;
69
69
  transport?: {
70
- irohQuic?: NativeRuntimeTransportFeatureStatus;
71
- irohLan?: NativeRuntimeTransportFeatureStatus;
72
- webRtc?: NativeRuntimeTransportFeatureStatus;
73
- webRtcLan?: NativeRuntimeTransportFeatureStatus;
74
- moq?: NativeRuntimeTransportFeatureStatus;
75
- ble?: NativeRuntimeTransportFeatureStatus;
70
+ irohQuic?: TransportStatus;
71
+ irohLan?: TransportStatus;
72
+ webRtc?: TransportStatus;
73
+ webRtcLan?: TransportStatus;
74
+ moq?: TransportStatus;
75
+ ble?: TransportStatus;
76
76
  irohRelayOnly?: boolean;
77
77
  irohRelayTransportPolicy?: string | null;
78
78
  routePriority?: ProtocolName[];
79
- optimizeFor?: TransportOptimization;
79
+ optimizeFor?: RouteOptimization;
80
80
  };
81
81
  }
82
- declare const BROWSER_WASM_RUNTIME_CAPABILITIES: RuntimeCapabilities;
82
+ declare const BROWSER_CAPABILITIES: RuntimeCapabilities;
83
83
  /**
84
84
  * The small host surface that browser WebRTC capability reporting needs.
85
85
  *
86
86
  * This is deliberately a feature check only: capability reporting must not
87
87
  * create a peer connection, probe ICE, or influence route ownership.
88
88
  */
89
- interface BrowserRuntimeCapabilityHost {
89
+ interface CapabilityHost {
90
90
  RTCPeerConnection?: unknown;
91
91
  }
92
- declare const NATIVE_IPC_RUNTIME_CAPABILITIES: RuntimeCapabilities;
93
- declare function cloneRuntimeCapabilities(capabilities: RuntimeCapabilities): RuntimeCapabilities;
92
+ declare const NATIVE_CAPABILITIES: RuntimeCapabilities;
93
+ declare function cloneCapabilities(capabilities: RuntimeCapabilities): RuntimeCapabilities;
94
94
  /**
95
95
  * Returns browser/WASM capabilities for a concrete JavaScript host.
96
96
  *
@@ -98,8 +98,8 @@ declare function cloneRuntimeCapabilities(capabilities: RuntimeCapabilities): Ru
98
98
  * requires the browser primitive to exist at runtime. Passing the host keeps
99
99
  * the resolver deterministic in SSR and test environments.
100
100
  */
101
- declare function runtimeCapabilitiesForBrowserHost(host?: BrowserRuntimeCapabilityHost | null | undefined): RuntimeCapabilities;
102
- declare function runtimeCapabilitiesFromNativeStatus(status: NativeRuntimeStatusSnapshot | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
103
- declare function runtimeCapabilityProfile(capabilities: RuntimeCapabilities): RuntimeCapabilityProfile;
101
+ declare function browserCapabilities(host?: CapabilityHost | null | undefined): RuntimeCapabilities;
102
+ declare function statusCapabilities(status: NativeRuntimeStatus | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
103
+ declare function capabilityProfile(capabilities: RuntimeCapabilities): CapabilityProfile;
104
104
 
105
- export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type RuntimeCapabilityProfile as a, type BrowserRuntimeCapabilityHost as b, type NativeRuntimeStatusSnapshot as c, type NativeRuntimeTransportFeatureStatus as d, type RuntimeAdapterKind as e, cloneRuntimeCapabilities as f, runtimeCapabilitiesFromNativeStatus as g, runtimeCapabilityProfile as h, runtimeCapabilitiesForBrowserHost as r };
105
+ export { BROWSER_CAPABILITIES as B, type CapabilityProfile as C, NATIVE_CAPABILITIES as N, type RuntimeCapabilities as R, type TransportStatus as T, type CapabilityHost as a, type NativeRuntimeStatus as b, type RuntimeAdapterKind as c, browserCapabilities as d, capabilityProfile as e, cloneCapabilities as f, statusCapabilities as s };
@@ -0,0 +1 @@
1
+ import {a,b as b$2}from'./chunk-ZA44REGI.js';import {a as a$1}from'./chunk-DUY34MGT.js';import {b as b$1}from'./chunk-NRXEG5GQ.js';var L={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":299532e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var b=new WeakMap;function B(o){let e=b.get(o);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function K(o){let e=o?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function f(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var N=/^[A-Za-z0-9_.:@-]{1,160}$/,$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function j(o){let e=typeof o=="string"?o.trim():"";if(!N.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return $.test(t)?t:e}function W(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,j(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function U(o){let e=typeof o=="string"?o.trim():"";if(!N.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function k(o){let e=b$2(o.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var D=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},R=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:(L[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let s={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(s),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let s=this.options?.warnAtSessionCreditsUsd;!this.warned&&s!==void 0&&this.total>=s&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:s,kind:"warning"}));}},G=32,q=4096;function _(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}function P(o,e,t,i){let n=JSON.stringify({__openrtc:2,kind:o,name:e,value:t,...i?{gossip:i}:{}});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function z(o){if(!o||typeof o!="object"||o instanceof Uint8Array)return null;let e=o,t=e.__openrtc===2&&(e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null;if(!t?.gossip)return t;let{gossip:i}=t;return typeof i.id=="string"&&i.id.length>0&&i.id.length<=384&&typeof i.originPeerId=="string"&&i.originPeerId.length>0&&i.originPeerId.length<=256&&(i.targetPeerId===void 0||typeof i.targetPeerId=="string"&&i.targetPeerId.length>0&&i.targetPeerId.length<=256)&&Number.isSafeInteger(i.hops)&&i.hops>=0&&i.hops<=G?t:null}var T=class{constructor(e,t=false){this.client=e;this.gossipFanout=t;this.connections=new Map;this.connectionListeners=new Set;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.seenGossipMessages=new Set;this.seenGossipOrder=[];this.stopMessage=e.onMessage((i,n)=>this.receive(i,n)),this.stopConnection=e.onConnection(i=>this.add(i)),this.stopDisconnection=e.onDisconnection(i=>this.remove(i)),e.getConnections().forEach(i=>this.add(i));}state(e){if(this.gossipFanout)throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=_(e);return {set:i=>{let n=P("state",t,i);this.localState.set(t,n);for(let{raw:s}of this.connections.values())this.sendState(s,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let s=(r,a)=>i({peerId:r,value:a});n.add(s);for(let[r,a]of this.remoteState)a.has(t)&&i({peerId:r,value:a.get(t)});return ()=>n?.delete(s)}}}channel(e){let t=_(e),i=n=>P("channel",t,n);return {send:async n=>{let s=i(n);if(!this.gossipFanout){await Promise.all([...this.connections.values()].map(({raw:r})=>r.send(s)));return}await this.sendGossip("channel",t,n);},sendTo:async(n,s)=>{let r=[...this.connections.values()].find(a=>a.view.peerId===n);if(r){await r.raw.send(i(s));return}if(!this.gossipFanout)throw new Error(`[OpenRTC] Peer '${n}' is not connected.`);await this.sendGossip("channel",t,s,n);},onMessage:n=>{let s=this.channelListeners.get(t);s||this.channelListeners.set(t,s=new Set);let r=(a,c)=>n({peerId:a,message:c});return s.add(r),()=>s?.delete(r)}}}onConnection(e){this.connectionListeners.add(e);for(let{view:t}of this.connections.values())e(t);return ()=>this.connectionListeners.delete(e)}close(){this.stopMessage(),this.stopConnection(),this.stopDisconnection();for(let e of this.stateSenders.values())for(let t of e.values())t.close();for(let e of [...this.connections.values()])this.remove(e.raw);this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),this.seenGossipMessages.clear(),this.seenGossipOrder.splice(0,this.seenGossipOrder.length);}add(e){if(this.connections.has(e.id))return;let t=e.remoteNodeId||e.id,i={id:e.id,peerId:t,send:n=>e.send(n),onMessage:n=>{let s=this.rawListeners.get(e.id);s||this.rawListeners.set(e.id,s=new Set);let r=n;return s.add(r),()=>s?.delete(r)},onClose:n=>{let s=this.closeListeners.get(e.id);return s||this.closeListeners.set(e.id,s=new Set),s.add(n),()=>s?.delete(n)}};this.connections.set(e.id,{raw:e,view:i});for(let n of this.connectionListeners)n(i);for(let[n,s]of this.localState)this.sendState(e,n,s);}remove(e){let t=this.connections.get(e.id);if(!t)return;this.connections.delete(e.id);let i=this.stateSenders.get(e);if(i){for(let s of i.values())s.close();this.stateSenders.delete(e);}for(let s of this.closeListeners.get(e.id)??[])s();this.closeListeners.delete(e.id),this.rawListeners.delete(e.id);let n=this.remoteState.get(t.view.peerId);if(n){for(let s of n.keys())for(let r of this.stateListeners.get(s)??[])r(t.view.peerId,null);this.remoteState.delete(t.view.peerId);}}receive(e,t){this.add(e);let i=z(t);if(!i){for(let r of this.rawListeners.get(e.id)??[])r(t);return}if(i.gossip){if(!this.rememberGossipMessage(i.gossip.id))return;let r=!i.gossip.targetPeerId||i.gossip.targetPeerId===e.localNodeId;if(i.gossip.hops<G){let a=P(i.kind,i.name,i.value,{...i.gossip,hops:i.gossip.hops+1});Promise.allSettled([...this.connections.values()].filter(({raw:c})=>c.id!==e.id).map(({raw:c})=>c.send(a)));}if(!r)return}let n=i.gossip?.originPeerId??this.connections.get(e.id)?.view.peerId??e.remoteNodeId??e.id;if(i.kind==="channel"){for(let r of this.channelListeners.get(i.name)??[])r(n,i.value);return}let s=this.remoteState.get(n);s||this.remoteState.set(n,s=new Map),s.set(i.name,i.value);for(let r of this.stateListeners.get(i.name)??[])r(n,i.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let s=n.get(t);s||(s=new a$1(r=>e.send(r)),n.set(t,s)),s.send(i).catch(()=>{});}async sendGossip(e,t,i,n){let s=[...this.connections.values()];if(s.length===0)return;let r=s[0].raw.localNodeId,a=`${r}:${crypto.randomUUID()}`;this.rememberGossipMessage(a);let c=P(e,t,i,{id:a,originPeerId:r,...n?{targetPeerId:n}:{},hops:0});await Promise.all(s.map(({raw:l})=>l.send(c)));}rememberGossipMessage(e){if(this.seenGossipMessages.has(e))return false;if(this.seenGossipMessages.add(e),this.seenGossipOrder.push(e),this.seenGossipOrder.length>q){let t=this.seenGossipOrder.shift();t&&this.seenGossipMessages.delete(t);}return true}},w=class{constructor(e,t,i,n,s=false){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.gossipFanout=s;this.closed=false;b.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}async close(){if(!this.closed){this.closed=true,this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{b.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new T(this.client,this.gossipFanout))}},g=class extends w{constructor(t,i,n,s){super("devices",t,i,n);this.roster=s;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let r=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=v=>(this.roster.reconcileLiveSnapshot(v),v),h=async()=>this.roster.mergeDevices(d(await r())),p=async()=>this.roster.mergeStatus(await a()),u=v=>c(I=>v(this.roster.mergeDevices(d(I)))),y=v=>l(I=>v(this.roster.mergeStatus(I))),m=Object.create(i);Object.defineProperties(m,{listDevices:{value:h,enumerable:false},listDeviceStatus:{value:p,enumerable:false},watchDevices:{value:u,enumerable:false},watchDeviceStatus:{value:y,enumerable:false},devices:{value:{...i.devices,list:h,listWithStatus:p,watch:u,watchWithStatus:y},enumerable:true}}),b.set(this,m),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},A=class extends w{constructor(t,i,n,s){super("space",t,i,n);this.delivery=s;this.kind="space";this.leave=()=>this.close();}},S=class extends w{constructor(t,i,n,s,r,a=false){super("room",t,i,n,a);this.membership=s;this.onLeave=r;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},E=class extends w{constructor(t,i,n,s){super("ticket",t,i,n);this.token=s;this.kind="ticket";}},M=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new D;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof g&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=U(e),s=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,s,n);for(let r of this.handles)r instanceof g&&r.removeEnrolledDevice(n);n===s&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();for(let n of this.handles)n instanceof g&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${f(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let i=t.access??"capability";return this.activateOnce(`room:${f(e)}`,JSON.stringify({access:i,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),i==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${f(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=K(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new R(e.usage);}makeControlPlane(e){return Promise.all([import('./controlPlane-JJFURVOX.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-Y35WSEQQ.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-Y35WSEQQ.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let s=this.activations.get(e);if(s){if(s.fingerprint!==t||s.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return s.promise}let r={fingerprint:t,auth:i},a=n().then(c=>(r.handle=c,c)).catch(c=>{throw this.activations.get(e)===r&&this.activations.delete(e),c});return r.promise=a,this.activations.set(e,r),a}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):W(this.appTag);return U(e)}runtimeOptions(e){let t=this.options.transports,i=t?.privacy==="relay-only";if(i&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");let n=i?b$1(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,nativeStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationGateway:{endpoint:(this.internals.endpoints??a).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:i?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:typeof t?.webrtc=="object"?i?{...t.webrtc,privacyMode:true,useTurn:true,useDefaultIceServers:false}:t.webrtc:t?.webrtc===true?i?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:n},transportPriority:n}}async activate(e){let t=e.controlPlane??await this.controlPlane(),i={relay:this.options.transports?.relay===true,moq:!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},n=e.source,s=null,r=()=>({userId:e.principalId,token:n.token,tokenProvider:async()=>n.token,expiresAtMs:n.expiresAtMs}),a=this.runtimeOptions({avenue:e.source.avenue,grantProvider:t.grantProvider(e.source,{maxPeers:e.maxPeers,features:i,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async d=>{n={...n,...d},await s?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:e.kind==="room"&&e.advancedFanout===true,deviceName:e.deviceName,devicePlatform:e.devicePlatform}),[c,{wrapAssembly:l}]=await Promise.all([this.internals.runtimeFactory(a),import('./coreClient.js')]);s=l(c,this.internals.platform==="native"?"native":"web"),await s.setAuth(r()),this.channels.attach(s,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await s.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(d){throw this.channels.detach(s),await s.advanced.runtime.shutdown().catch(()=>{}),d}return this.usage.record("coordination.connection.open"),s}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let i=await this.deviceId(),{resolveDeviceProfile:n}=await import('./deviceProfile-CR2C7OYR.js'),s=n(e.profile,this.internals.platform==="native"?"native":"web"),r=await this.controlPlane(),a=await r.deviceCertificate(t,i,void 0,s),c=await this.activate({kind:"devices",id:a.principalId,source:a.source,principalId:a.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:s.name,devicePlatform:s.platform,deviceMetadata:s.metadata}),l;try{l=await r.listEnrolledDevices(t,i);}catch(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}let{AuthenticatedDeviceRoster:d}=await import('./deviceRoster-EUF6BBF5.js'),h;return h=new g(a.principalId,c,()=>{this.channels.detach(c),this.onClosed(h);},new d(l)),this.handles.add(h),h}async joinSpace(e,t={}){this.assertOpen();let i=f(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),s=await n.capability("space",i,t.maxPeers,t.advancedFanout),r=String(b$2(s.token).principalId),a=await this.activate({kind:"space",id:i,source:s,principalId:r,deviceId:k(s),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new A(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async joinRoom(e,t={}){this.assertOpen();let i=f(e),n=t.membership??"ephemeral",s=t.access??"capability";if(n==="durable"&&s!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(s==="authenticated"){let d=t.auth??this.options.auth;if(!d)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let h=await this.deviceId(),p=await this.controlPlane(),u=await p.deviceCertificate(d,h,{kind:"room",id:i});n==="durable"&&await p.durableRoomMembership(u.source,i,"join");let y;try{y=await this.activate({kind:"room",id:i,source:u.source,principalId:u.principalId,deviceId:h,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(v){throw n==="durable"&&await p.durableRoomMembership(u.source,i,"leave").catch(()=>{}),v}let m;return m=new S(i,y,()=>{this.channels.detach(y),this.onClosed(m);},n,n==="durable"?async()=>{await p.durableRoomMembership(u.source,i,"leave");}:void 0,t.advancedFanout===true),this.handles.add(m),m}let r=await(await this.controlPlane()).capability("room",i,t.maxPeers,t.advancedFanout),a=String(b$2(r.token).principalId),c=await this.activate({kind:"room",id:i,source:r,principalId:a,deviceId:k(r),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new S(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral",void 0,t.advancedFanout===true),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=f(e),n=await(await this.controlPlane()).capability("ticket",i,t.maxPeers,t.advancedFanout),s=String(b$2(n.token).principalId),r=await this.activate({kind:"ticket",id:i,source:n,principalId:s,deviceId:k(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),a;return a=new E(i,r,()=>{this.channels.detach(r),this.onClosed(a);},n.token),this.handles.add(a),a}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear();}}}};function Q(o,e){return new M(o,e)}export{B as a,Q as b};
@@ -0,0 +1,2 @@
1
+ var s=new Map;function a(e){let r=new Uint8Array(e),t="";for(let o of r)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function l(e){let r=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return a(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function d(){return a(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function c(){return typeof indexedDB>"u"?null:new Promise((e,r)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error);})}async function g(e){let r=await c().catch(()=>null);if(!r)return s.get(e)??null;try{return await new Promise((t,o)=>{let n=r.transaction("keys","readonly").objectStore("keys").get(e);n.onsuccess=()=>t(n.result??null),n.onerror=()=>o(n.error);})}finally{r.close();}}async function f(e,r){let t=await c().catch(()=>null);if(!t){s.set(e,r);return}try{await new Promise((o,n)=>{let i=t.transaction("keys","readwrite").objectStore("keys").put(r,e);i.onsuccess=()=>o(),i.onerror=()=>n(i.error);});}finally{t.close();}}async function p(e){s.delete(e);let r=await c().catch(()=>null);if(r)try{await new Promise((t,o)=>{let n=r.transaction("keys","readwrite").objectStore("keys").delete(e);n.onsuccess=()=>t(),n.onerror=()=>o(n.error);});}finally{r.close();}}async function m(e){let r=await g(e);if(r)return r;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await f(e,t),t}async function y(e){let r=await crypto.subtle.exportKey("jwk",e.publicKey),t=await l(r);return {publicKeyJwk:r,thumbprint:t,async proof(o){let n=d(),i=Math.floor(Date.now()/1e3),u=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(o(n,i)));return {publicKeyJwk:r,signature:a(u),nonce:n,issuedAt:i}}}}async function v(){return y(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}var w={async getOrCreate(e){return y(await m(e))},delete:p};
2
+ export{l as a,v as b,w as c};
@@ -0,0 +1 @@
1
+ var n={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",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",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"},i=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;}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 t=E(r);return t.retryable?t.plane==="coordination"||t.plane==="transport"||t.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}}};function b(e){let a=E(e);return {errorCode:a.code,retryable:a.retryable,errorPlane:a.plane}}function o(e,a,r){let t=c(e);return new i({code:e,message:a,retryable:r.retryable??t.retryable,plane:r.plane??t.plane,cause:r.cause,generation:r.generation,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,revision:r.revision})}function c(e){switch(e){case n.AUTH_NOT_READY:case n.AUTH_EXPIRED:case n.AUTH_DEVICE_REENROLLMENT_REQUIRED:return {retryable:true,plane:"auth"};case n.AUTH_DENIED:return {retryable:false,plane:"auth"};case n.ADMISSION_DENIED:case n.ADMISSION_SCOPE_MISMATCH:return {retryable:false,plane:"admission"};case n.BUDGET_EXCEEDED:return {retryable:false,plane:"budget"};case n.BUDGET_STALE:case n.BUDGET_RENEWAL_REQUIRED:return {retryable:true,plane:"budget"};case n.COORDINATION_DISCONNECTED:case n.COORDINATION_RATE_LIMITED:case n.COORDINATION_SERVICE_UNAVAILABLE:return {retryable:true,plane:"coordination"};case n.COORDINATION_PROTOCOL:return {retryable:false,plane:"coordination"};case n.TRANSPORT_DIAL_EXHAUSTED:case n.TRANSPORT_UNAVAILABLE:case n.TRANSPORT_TICKET_MISSING:return {retryable:true,plane:"transport"};case n.DELIVERY_NOT_READY:return {retryable:true,plane:"delivery"};case n.INTERNAL:default:return {retryable:false,plane:"internal"}}}function E(e){if(i.is(e))return e instanceof i?e:new i({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});if(typeof e=="object"&&e!==null){let r=e,t=typeof r.code=="string"?r.code:"",l=typeof r.message=="string"?r.message:e instanceof Error?e.message:String(e),s=typeof r.retryable=="boolean"?r.retryable:void 0;if(t){let u=T(t,l,s);if(u)return u}if(typeof r.name=="string"&&r.name==="CoordinationConnectError")return o(n.COORDINATION_DISCONNECTED,l,{retryable:s??true,plane:"coordination",cause:e});if(typeof r.name=="string"&&r.name==="CoordinationGatewayProtocolError")return o(t||n.COORDINATION_PROTOCOL,l,{retryable:s??false,plane:d(t),cause:e})}let a=e instanceof Error?e.message:String(e??"unknown error");return p(a,e)}function T(e,a,r){let t=e.trim().toLowerCase();return t==="unauthenticated"||t==="functions/unauthenticated"||t==="auth/unauthorized"||t.includes("permission-denied")?o(n.AUTH_DENIED,a,{retryable:false,plane:"auth"}):t==="budget-renewal-required"||t==="budget/renewal-required"?o(n.BUDGET_RENEWAL_REQUIRED,a,{retryable:r??true,plane:"budget"}):t.includes("resource-exhausted")||t.includes("budget")||t==="budget-exceeded"||t==="insufficient-budget"?t.includes("stale")||/stale-budget/i.test(a)?o(n.BUDGET_STALE,a,{retryable:r??true,plane:"budget"}):o(n.BUDGET_EXCEEDED,a,{retryable:false,plane:"budget"}):t.includes("rate-limit")||t==="rate_limited"||t==="too-many-requests"?o(n.COORDINATION_RATE_LIMITED,a,{retryable:r??true,plane:"coordination"}):t.includes("admission")||t==="permission-denied"||t==="session-token-denied"?o(n.ADMISSION_DENIED,a,{retryable:false,plane:"admission"}):t.includes("scope")?o(n.ADMISSION_SCOPE_MISMATCH,a,{retryable:false,plane:"admission"}):t.includes("disconnect")||t.includes("unavailable")||t==="aborted"?o(n.COORDINATION_DISCONNECTED,a,{retryable:r??true,plane:"coordination"}):t.startsWith("coordination/")||t.includes("protocol")?o(e,a,{retryable:r??false,plane:d(e)}):null}function d(e){let a=e.trim().toLowerCase();return a.includes("budget")?"budget":a.includes("auth")?"auth":a.includes("admission")||a.includes("scope")?"admission":(a.includes("rate"),"coordination")}function p(e,a){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)?o(n.AUTH_NOT_READY,e,{retryable:true,plane:"auth",cause:a}):/missing endpoint ticket|ticket missing/i.test(e)?o(n.TRANSPORT_TICKET_MISSING,e,{retryable:true,plane:"transport",cause:a}):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(e)?o(n.TRANSPORT_DIAL_EXHAUSTED,e,{retryable:true,plane:"transport",cause:a}):/stale[- ]budget/i.test(e)?o(n.BUDGET_STALE,e,{retryable:true,plane:"budget",cause:a}):/budget|credit|quota|limit\s*exceeded/i.test(e)?o(n.BUDGET_EXCEEDED,e,{retryable:false,plane:"budget",cause:a}):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(e)?o(n.ADMISSION_DENIED,e,{retryable:false,plane:"admission",cause:a}):/not\s+application-routable|not[- ]ready|settledReady/i.test(e)?o(n.DELIVERY_NOT_READY,e,{retryable:true,plane:"delivery",cause:a}):/gateway|coordination|websocket|signaling/i.test(e)?o(n.COORDINATION_DISCONNECTED,e,{retryable:true,plane:"coordination",cause:a}):o(n.INTERNAL,e,{retryable:false,plane:"internal",cause:a})}export{n as a,i as b,b as c,o as d,E as e};
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-4MLJXEVV.js';function u(){let r=crypto.getRandomValues(new Uint8Array(24)),e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(r){if(!r||typeof r!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=r;if(e.kty!=="OKP"||e.crv!=="Ed25519"||typeof e.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.x)||e.d!==void 0)throw new Error("[OpenRTC] Native host returned an invalid Ed25519 public key.");return {kty:"OKP",crv:"Ed25519",x:e.x}}function y(r){return {async readSecureRecord(e,t){return r.invoke("openrtc_read_secure_record",{appTag:e,key:t})},async writeSecureRecord(e,t,n){await r.invoke("openrtc_write_secure_record",{appTag:e,key:t,value:n});},async deleteSecureRecord(e,t){await r.invoke("openrtc_delete_secure_record",{appTag:e,key:t});},async delete(e){await r.invoke("openrtc_delete_device_key",{appTag:e});},async getOrCreate(e){let t=d(await r.invoke("openrtc_device_public_key",{appTag:e})),n=await a(t);return {publicKeyJwk:t,thumbprint:n,async proof(s){let o=u(),c=Math.floor(Date.now()/1e3),i=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:s(o,c)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(i))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:t,signature:i,nonce:o,issuedAt:c}}}}}}
2
+ export{y as a};