@poolse/sdk 2.9.0 → 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
  });
@@ -1622,6 +1631,248 @@ var UsersResource = class {
1622
1631
  }
1623
1632
  };
1624
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
+
1625
1876
  // src/resources/ice-servers.ts
1626
1877
  var IceServersResource = class {
1627
1878
  constructor(client) {
@@ -1890,6 +2141,8 @@ var Poolse = class {
1890
2141
  realtime;
1891
2142
  /** STUN/TURN servers for WebRTC — see `IceServersResource`. */
1892
2143
  iceServers;
2144
+ /** SFU credentials for a call's media — see `CallTokensResource`. */
2145
+ callTokens;
1893
2146
  resolved;
1894
2147
  tokenCache;
1895
2148
  constructor(config) {
@@ -1907,6 +2160,7 @@ var Poolse = class {
1907
2160
  this.attachments = new AttachmentsResource(this.rest, cachedConfig.fetch);
1908
2161
  this.users = new UsersResource(cachedConfig);
1909
2162
  this.iceServers = new IceServersResource(this.rest);
2163
+ this.callTokens = new CallTokensResource(this.rest);
1910
2164
  this.realtime = new PoolseRealtime(cachedConfig, this.tokenCache, {
1911
2165
  ...this.resolved.wsUrl !== void 0 ? { wsUrl: this.resolved.wsUrl } : {},
1912
2166
  socketPath: this.resolved.socketPath,
@@ -1916,6 +2170,27 @@ var Poolse = class {
1916
2170
  iceServersProvider: async () => (await this.iceServers.list()).ice_servers
1917
2171
  });
1918
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))
2192
+ });
2193
+ }
1919
2194
  /**
1920
2195
  * Tear down the SDK: close the WebSocket, drop all channels.
1921
2196
  * No-op for REST — fetch() doesn't keep persistent state.
@@ -1928,12 +2203,14 @@ var Poolse = class {
1928
2203
  };
1929
2204
 
1930
2205
  // src/version.ts
1931
- var version = "2.9.0";
2206
+ var version = "2.10.0";
1932
2207
 
1933
2208
  exports.ApiError = ApiError;
1934
2209
  exports.AttachmentHandle = AttachmentHandle;
1935
2210
  exports.AttachmentsResource = AttachmentsResource;
1936
2211
  exports.AuthError = AuthError;
2212
+ exports.CallRoom = CallRoom;
2213
+ exports.CallTokensResource = CallTokensResource;
1937
2214
  exports.CallsResource = CallsResource;
1938
2215
  exports.ConversationChannel = ConversationChannel;
1939
2216
  exports.ConversationHandle = ConversationHandle;