@poolse/sdk 2.8.4 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -104,6 +104,9 @@ var AuthError = class extends ApiError {
104
104
  };
105
105
 
106
106
  // src/voice/calls.ts
107
+ function toMedia(value) {
108
+ return value === "video" ? "video" : "audio";
109
+ }
107
110
  var CallsResource = class {
108
111
  /** Resolves the user channel lazily — it may not be joined yet. */
109
112
  getChannel;
@@ -123,13 +126,18 @@ var CallsResource = class {
123
126
  * has fanned the invite out, with the minted call id and who was rung
124
127
  * — not when anyone answers; that arrives via {@link onAccepted}.
125
128
  */
126
- invite(conversationId) {
129
+ invite(conversationId, media = "audio") {
127
130
  return this.request("call:invite", {
128
- conversation_id: conversationId
131
+ conversation_id: conversationId,
132
+ media
129
133
  }).then((reply) => ({
130
134
  callId: reply.call_id,
131
135
  conversationId: reply.conversation_id,
132
- calleeUserIds: reply.callee_user_ids ?? []
136
+ calleeUserIds: reply.callee_user_ids ?? [],
137
+ // Echoed by the server rather than assumed, so an older deployment
138
+ // that ignores the field is reflected honestly instead of leaving
139
+ // the UI promising video it will not get.
140
+ media: toMedia(reply.media)
133
141
  }));
134
142
  }
135
143
  /**
@@ -236,7 +244,8 @@ var CallsResource = class {
236
244
  const call = {
237
245
  callId: p.call_id,
238
246
  conversationId: p.conversation_id,
239
- callerUserId: p.caller_user_id
247
+ callerUserId: p.caller_user_id,
248
+ media: toMedia(p.media)
240
249
  };
241
250
  this.incoming.forEach((l) => l(call));
242
251
  });
@@ -334,6 +343,7 @@ var VoiceRoom = class {
334
343
  socket;
335
344
  webrtc;
336
345
  iceServers;
346
+ iceServersProvider;
337
347
  detectSpeaking;
338
348
  channel = null;
339
349
  localStream = null;
@@ -365,6 +375,7 @@ var VoiceRoom = class {
365
375
  this.socket = socket;
366
376
  this.webrtc = opts.webrtc ?? createBrowserWebRtcAdapter();
367
377
  this.iceServers = opts.iceServers ?? DEFAULT_ICE_SERVERS;
378
+ this.iceServersProvider = opts.iceServersProvider ?? null;
368
379
  this.detectSpeaking = opts.detectSpeaking ?? true;
369
380
  }
370
381
  // ── observation ────────────────────────────────────────────────────
@@ -399,6 +410,7 @@ var VoiceRoom = class {
399
410
  }
400
411
  this.holders += 1;
401
412
  this.setStatus("connecting");
413
+ await this.resolveIceServers();
402
414
  try {
403
415
  this.localStream = await this.webrtc.getUserMedia();
404
416
  } catch (err) {
@@ -512,6 +524,23 @@ var VoiceRoom = class {
512
524
  this.emitError(new Error(`voice error: ${payload?.reason ?? "unknown"}`));
513
525
  });
514
526
  }
527
+ /**
528
+ * Refresh ICE servers from the provider, if there is one.
529
+ *
530
+ * Never throws. A room that refused to connect because the ICE
531
+ * endpoint was briefly unreachable would be a worse outcome than one
532
+ * that connects without TURN — which is exactly how calls behaved
533
+ * before TURN existed, and works on most networks.
534
+ */
535
+ async resolveIceServers() {
536
+ if (!this.iceServersProvider) return;
537
+ try {
538
+ const servers = await this.iceServersProvider();
539
+ if (servers.length > 0) this.iceServers = servers;
540
+ } catch (err) {
541
+ this.emitError(new Error(`ice servers unavailable, continuing without: ${String(err)}`));
542
+ }
543
+ }
515
544
  // ── negotiation ────────────────────────────────────────────────────
516
545
  /**
517
546
  * Glare control: both sides learn about each other simultaneously, so
@@ -694,6 +723,7 @@ var PoolseRealtime = class {
694
723
  config;
695
724
  tokenCache;
696
725
  socketPath;
726
+ iceServersProvider;
697
727
  wsUrl;
698
728
  socket = null;
699
729
  conversations = /* @__PURE__ */ new Map();
@@ -706,6 +736,7 @@ var PoolseRealtime = class {
706
736
  this.config = config;
707
737
  this.tokenCache = tokenCache;
708
738
  this.socketPath = opts.socketPath ?? "/socket";
739
+ this.iceServersProvider = opts.iceServersProvider ?? null;
709
740
  this.wsUrl = opts.wsUrl ?? deriveWsUrl(config.apiUrl);
710
741
  }
711
742
  /** Current connection status. */
@@ -831,7 +862,10 @@ var PoolseRealtime = class {
831
862
  if (!this.socket) {
832
863
  throw new PoolseError("socket not initialised \u2014 call connect() first");
833
864
  }
834
- const room = new VoiceRoom(conversationId, this.socket, opts);
865
+ const room = new VoiceRoom(conversationId, this.socket, {
866
+ ...this.iceServersProvider ? { iceServersProvider: this.iceServersProvider } : {},
867
+ ...opts
868
+ });
835
869
  this.voiceRooms.set(conversationId, room);
836
870
  return room;
837
871
  }
@@ -1595,6 +1629,264 @@ var UsersResource = class {
1595
1629
  }
1596
1630
  };
1597
1631
 
1632
+ // src/resources/call-tokens.ts
1633
+ var CallTokensResource = class {
1634
+ constructor(client) {
1635
+ this.client = client;
1636
+ }
1637
+ client;
1638
+ /**
1639
+ * POST /v1/conversations/:conversationId/call-token
1640
+ *
1641
+ * Resolves `null` when the deployment has no SFU configured (503).
1642
+ * That is deliberately not an error — the caller falls back to the
1643
+ * peer-to-peer mesh, which is how every call worked before the SFU
1644
+ * existed. A 403 still throws: that one really is a refusal.
1645
+ */
1646
+ async create(conversationId, signal) {
1647
+ try {
1648
+ return await this.client.request({
1649
+ method: "POST",
1650
+ path: `/v1/conversations/${encodeURIComponent(conversationId)}/call-token`,
1651
+ ...signal ? { signal } : {}
1652
+ });
1653
+ } catch (err) {
1654
+ if (err instanceof ApiError && err.status === 503) return null;
1655
+ throw err;
1656
+ }
1657
+ }
1658
+ };
1659
+
1660
+ // src/voice/call-room.ts
1661
+ var CallRoom = class {
1662
+ livekit;
1663
+ tokenProvider;
1664
+ startWithVideo;
1665
+ startMuted;
1666
+ room = null;
1667
+ status = "idle";
1668
+ selfId = null;
1669
+ // Reference counted like VoiceRoom: a call screen and a roster can
1670
+ // both hold the same call, and the second holder must not open a
1671
+ // second SFU connection or tear the first one down on leaving.
1672
+ holders = 0;
1673
+ statusListeners = /* @__PURE__ */ new Set();
1674
+ participantListeners = /* @__PURE__ */ new Set();
1675
+ errorListeners = /* @__PURE__ */ new Set();
1676
+ /** Bound once so `off()` in teardown removes the same references. */
1677
+ onRoomChange = () => this.emitParticipants();
1678
+ constructor(opts) {
1679
+ this.livekit = opts.livekit;
1680
+ this.tokenProvider = opts.tokenProvider;
1681
+ this.startWithVideo = opts.video ?? false;
1682
+ this.startMuted = opts.muted ?? false;
1683
+ }
1684
+ // ── observation ─────────────────────────────────────────────────────
1685
+ getStatus() {
1686
+ return this.status;
1687
+ }
1688
+ onStatus(fn) {
1689
+ this.statusListeners.add(fn);
1690
+ return () => this.statusListeners.delete(fn);
1691
+ }
1692
+ onParticipants(fn) {
1693
+ this.participantListeners.add(fn);
1694
+ return () => this.participantListeners.delete(fn);
1695
+ }
1696
+ onError(fn) {
1697
+ this.errorListeners.add(fn);
1698
+ return () => this.errorListeners.delete(fn);
1699
+ }
1700
+ getParticipants() {
1701
+ if (!this.room) return [];
1702
+ const self = this.toParticipant(this.room.localParticipant, true);
1703
+ const others = [...this.room.remoteParticipants.values()].map(
1704
+ (p) => this.toParticipant(p, false)
1705
+ );
1706
+ return [self, ...others];
1707
+ }
1708
+ // ── lifecycle ───────────────────────────────────────────────────────
1709
+ /**
1710
+ * Connect to the SFU.
1711
+ *
1712
+ * Resolves `true` once media is flowing, `false` when the deployment
1713
+ * has no SFU — the caller should fall back to the mesh rather than
1714
+ * treat that as a failed call.
1715
+ */
1716
+ async join() {
1717
+ if (this.room) {
1718
+ this.holders += 1;
1719
+ return true;
1720
+ }
1721
+ this.holders += 1;
1722
+ this.setStatus("connecting");
1723
+ let connection;
1724
+ try {
1725
+ connection = await this.tokenProvider();
1726
+ } catch (err) {
1727
+ this.holders = Math.max(0, this.holders - 1);
1728
+ this.setStatus("error");
1729
+ const error = new Error(`call token unavailable: ${String(err)}`);
1730
+ this.emitError(error);
1731
+ throw error;
1732
+ }
1733
+ if (!connection) {
1734
+ this.holders = Math.max(0, this.holders - 1);
1735
+ this.setStatus("idle");
1736
+ return false;
1737
+ }
1738
+ const room = new this.livekit.Room({
1739
+ // Let LiveKit drop video layers before it drops the call. On a
1740
+ // phone leaving wifi this is the difference between the picture
1741
+ // degrading and the call ending.
1742
+ adaptiveStream: true,
1743
+ dynacast: true
1744
+ });
1745
+ this.room = room;
1746
+ this.bind(room);
1747
+ try {
1748
+ await room.connect(connection.url, connection.token);
1749
+ this.selfId = room.localParticipant.identity;
1750
+ await room.localParticipant.setMicrophoneEnabled(!this.startMuted);
1751
+ if (this.startWithVideo) await room.localParticipant.setCameraEnabled(true);
1752
+ this.setStatus("connected");
1753
+ this.emitParticipants();
1754
+ return true;
1755
+ } catch (err) {
1756
+ this.holders = Math.max(0, this.holders - 1);
1757
+ this.setStatus("error");
1758
+ const error = new Error(`call media failed: ${String(err)}`);
1759
+ this.emitError(error);
1760
+ await this.teardown();
1761
+ throw error;
1762
+ }
1763
+ }
1764
+ /** Release one holder; disconnects once none are left. */
1765
+ leave() {
1766
+ this.holders = Math.max(0, this.holders - 1);
1767
+ if (this.holders > 0) return;
1768
+ void this.teardown();
1769
+ }
1770
+ // ── media controls ──────────────────────────────────────────────────
1771
+ /**
1772
+ * Turn the camera on or off mid-call.
1773
+ *
1774
+ * Off genuinely stops publishing rather than sending black frames, so
1775
+ * the capture indicator goes out and the uplink is freed. LiveKit
1776
+ * renegotiates underneath.
1777
+ */
1778
+ async setCameraEnabled(enabled) {
1779
+ await this.withLocal((local) => local.setCameraEnabled(enabled), "camera");
1780
+ }
1781
+ /** Mute or unmute the microphone. */
1782
+ async setMicrophoneEnabled(enabled) {
1783
+ await this.withLocal((local) => local.setMicrophoneEnabled(enabled), "microphone");
1784
+ }
1785
+ isCameraEnabled() {
1786
+ return this.room?.localParticipant.isCameraEnabled ?? false;
1787
+ }
1788
+ isMicrophoneEnabled() {
1789
+ return this.room?.localParticipant.isMicrophoneEnabled ?? false;
1790
+ }
1791
+ // ── internals ───────────────────────────────────────────────────────
1792
+ async withLocal(fn, what) {
1793
+ const room = this.room;
1794
+ if (!room) return;
1795
+ try {
1796
+ await fn(room.localParticipant);
1797
+ this.emitParticipants();
1798
+ } catch (err) {
1799
+ this.emitError(new Error(`could not change ${what}: ${String(err)}`));
1800
+ }
1801
+ }
1802
+ bind(room) {
1803
+ const { RoomEvent } = this.livekit;
1804
+ for (const event of [
1805
+ RoomEvent["ParticipantConnected"],
1806
+ RoomEvent["ParticipantDisconnected"],
1807
+ RoomEvent["TrackSubscribed"],
1808
+ RoomEvent["TrackUnsubscribed"],
1809
+ RoomEvent["TrackMuted"],
1810
+ RoomEvent["TrackUnmuted"],
1811
+ RoomEvent["LocalTrackPublished"],
1812
+ RoomEvent["LocalTrackUnpublished"],
1813
+ RoomEvent["ActiveSpeakersChanged"],
1814
+ RoomEvent["ParticipantNameChanged"]
1815
+ ]) {
1816
+ if (event) room.on(event, this.onRoomChange);
1817
+ }
1818
+ const disconnected = RoomEvent["Disconnected"];
1819
+ if (disconnected) {
1820
+ room.on(disconnected, () => {
1821
+ this.setStatus("idle");
1822
+ this.emitParticipants();
1823
+ });
1824
+ }
1825
+ }
1826
+ toParticipant(participant, isSelf) {
1827
+ const cameraSource = this.livekit.Track.Source["Camera"] ?? "camera";
1828
+ const publication = participant.getTrackPublication(cameraSource);
1829
+ const live = publication && !publication.isMuted && publication.track ? publication : null;
1830
+ const videoTrack = live?.track ?? null;
1831
+ return {
1832
+ userId: participant.identity,
1833
+ name: participant.name,
1834
+ isSelf,
1835
+ micEnabled: participant.isMicrophoneEnabled ?? false,
1836
+ cameraEnabled: participant.isCameraEnabled ?? false,
1837
+ speaking: participant.isSpeaking ?? false,
1838
+ videoTrack,
1839
+ videoTrackRef: live ? { participant, publication: live, source: cameraSource } : null
1840
+ };
1841
+ }
1842
+ async teardown() {
1843
+ const room = this.room;
1844
+ this.room = null;
1845
+ this.selfId = null;
1846
+ this.holders = 0;
1847
+ if (room) {
1848
+ try {
1849
+ await room.disconnect();
1850
+ } catch {
1851
+ }
1852
+ }
1853
+ this.setStatus("idle");
1854
+ this.emitParticipants();
1855
+ }
1856
+ setStatus(status) {
1857
+ if (this.status === status) return;
1858
+ this.status = status;
1859
+ for (const fn of this.statusListeners) fn(status);
1860
+ }
1861
+ emitParticipants() {
1862
+ const participants = this.getParticipants();
1863
+ for (const fn of this.participantListeners) fn(participants);
1864
+ }
1865
+ emitError(error) {
1866
+ for (const fn of this.errorListeners) fn(error);
1867
+ }
1868
+ /** The local participant's poolse user id, once connected. */
1869
+ getSelfId() {
1870
+ return this.selfId;
1871
+ }
1872
+ };
1873
+
1874
+ // src/resources/ice-servers.ts
1875
+ var IceServersResource = class {
1876
+ constructor(client) {
1877
+ this.client = client;
1878
+ }
1879
+ client;
1880
+ /** GET /v1/ice-servers */
1881
+ list(signal) {
1882
+ return this.client.request({
1883
+ method: "GET",
1884
+ path: "/v1/ice-servers",
1885
+ ...signal ? { signal } : {}
1886
+ });
1887
+ }
1888
+ };
1889
+
1598
1890
  // src/rest-client.ts
1599
1891
  var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET"]);
1600
1892
  var RestClient = class {
@@ -1845,6 +2137,10 @@ var Poolse = class {
1845
2137
  * `config.wsUrl`.
1846
2138
  */
1847
2139
  realtime;
2140
+ /** STUN/TURN servers for WebRTC — see `IceServersResource`. */
2141
+ iceServers;
2142
+ /** SFU credentials for a call's media — see `CallTokensResource`. */
2143
+ callTokens;
1848
2144
  resolved;
1849
2145
  tokenCache;
1850
2146
  constructor(config) {
@@ -1861,9 +2157,36 @@ var Poolse = class {
1861
2157
  this.messages = new MessagesResource(this.rest);
1862
2158
  this.attachments = new AttachmentsResource(this.rest, cachedConfig.fetch);
1863
2159
  this.users = new UsersResource(cachedConfig);
2160
+ this.iceServers = new IceServersResource(this.rest);
2161
+ this.callTokens = new CallTokensResource(this.rest);
1864
2162
  this.realtime = new PoolseRealtime(cachedConfig, this.tokenCache, {
1865
2163
  ...this.resolved.wsUrl !== void 0 ? { wsUrl: this.resolved.wsUrl } : {},
1866
- socketPath: this.resolved.socketPath
2164
+ socketPath: this.resolved.socketPath,
2165
+ // Re-fetched on every room join rather than cached here: TURN
2166
+ // credentials expire, and a stale one is rejected silently — the
2167
+ // call connects and carries no media.
2168
+ iceServersProvider: async () => (await this.iceServers.list()).ice_servers
2169
+ });
2170
+ }
2171
+ /**
2172
+ * A call's media, carried by the SFU.
2173
+ *
2174
+ * Media only — ringing, presence, roster and mute state stay on
2175
+ * poolse's own channels, and a client joins both. See {@link CallRoom}.
2176
+ *
2177
+ * `livekit` is your app's `livekit-client` import. This package cannot
2178
+ * import it for you: tsup rewrites `require()` into `__require()`,
2179
+ * which Metro cannot follow, so a dependency required from in here is
2180
+ * absent from every React Native bundle.
2181
+ *
2182
+ * import * as livekit from 'livekit-client';
2183
+ * const call = poolse.call(conversationId, { livekit, video: true });
2184
+ * const usingSfu = await call.join(); // false = no SFU, use the mesh
2185
+ */
2186
+ call(conversationId, opts) {
2187
+ return new CallRoom({
2188
+ ...opts,
2189
+ tokenProvider: opts.tokenProvider ?? (() => this.callTokens.create(conversationId))
1867
2190
  });
1868
2191
  }
1869
2192
  /**
@@ -1878,8 +2201,8 @@ var Poolse = class {
1878
2201
  };
1879
2202
 
1880
2203
  // src/version.ts
1881
- var version = "2.8.4";
2204
+ var version = "2.10.0";
1882
2205
 
1883
- export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallsResource, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, DevicesResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, UserChannel, UsersResource, VoiceRoom, createBrowserWebRtcAdapter, isWebRtcAvailable, safeUuid, version };
2206
+ export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallRoom, CallTokensResource, CallsResource, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, DevicesResource, IceServersResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, UserChannel, UsersResource, VoiceRoom, createBrowserWebRtcAdapter, isWebRtcAvailable, safeUuid, version };
1884
2207
  //# sourceMappingURL=index.js.map
1885
2208
  //# sourceMappingURL=index.js.map