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