@poolse/sdk 2.1.5 → 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.
- package/CHANGELOG.md +159 -159
- package/LICENSE +21 -21
- package/README.md +397 -395
- package/dist/index.cjs +590 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +337 -3
- package/dist/index.d.ts +337 -3
- package/dist/index.js +587 -2
- package/dist/index.js.map +1 -1
- package/package.json +28 -16
package/dist/index.cjs
CHANGED
|
@@ -105,6 +105,545 @@ var AuthError = class extends ApiError {
|
|
|
105
105
|
}
|
|
106
106
|
};
|
|
107
107
|
|
|
108
|
+
// src/voice/calls.ts
|
|
109
|
+
var CallsResource = class {
|
|
110
|
+
/** Resolves the user channel lazily — it may not be joined yet. */
|
|
111
|
+
getChannel;
|
|
112
|
+
incoming = /* @__PURE__ */ new Set();
|
|
113
|
+
accepted = /* @__PURE__ */ new Set();
|
|
114
|
+
declined = /* @__PURE__ */ new Set();
|
|
115
|
+
busy = /* @__PURE__ */ new Set();
|
|
116
|
+
cancelled = /* @__PURE__ */ new Set();
|
|
117
|
+
bound = false;
|
|
118
|
+
constructor(getChannel) {
|
|
119
|
+
this.getChannel = getChannel;
|
|
120
|
+
}
|
|
121
|
+
// ── placing and answering ──────────────────────────────────────────
|
|
122
|
+
/**
|
|
123
|
+
* Ring every other member of a conversation. Resolves once the server
|
|
124
|
+
* has fanned the invite out, with the minted call id and who was rung
|
|
125
|
+
* — not when anyone answers; that arrives via {@link onAccepted}.
|
|
126
|
+
*/
|
|
127
|
+
invite(conversationId) {
|
|
128
|
+
return this.request("call:invite", {
|
|
129
|
+
conversation_id: conversationId
|
|
130
|
+
}).then((reply) => ({
|
|
131
|
+
callId: reply.call_id,
|
|
132
|
+
conversationId: reply.conversation_id,
|
|
133
|
+
calleeUserIds: reply.callee_user_ids ?? []
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Answer a ringing call. This only tells the caller you picked up —
|
|
138
|
+
* join the voice room yourself to actually connect audio.
|
|
139
|
+
*/
|
|
140
|
+
async accept(call) {
|
|
141
|
+
await this.request("call:accept", {
|
|
142
|
+
call_id: call.callId,
|
|
143
|
+
conversation_id: call.conversationId,
|
|
144
|
+
caller_user_id: call.callerUserId
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/** Reject a ringing call without joining the room. */
|
|
148
|
+
async decline(call) {
|
|
149
|
+
await this.request("call:decline", {
|
|
150
|
+
call_id: call.callId,
|
|
151
|
+
conversation_id: call.conversationId,
|
|
152
|
+
caller_user_id: call.callerUserId
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Tell the caller you are already on another call.
|
|
157
|
+
*
|
|
158
|
+
* Distinct from {@link decline}: nobody chose anything, so clients
|
|
159
|
+
* send this automatically when a ring arrives mid-call. `useCalls`
|
|
160
|
+
* does it for you.
|
|
161
|
+
*/
|
|
162
|
+
async markBusy(call) {
|
|
163
|
+
await this.request("call:busy", {
|
|
164
|
+
call_id: call.callId,
|
|
165
|
+
conversation_id: call.conversationId,
|
|
166
|
+
caller_user_id: call.callerUserId
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** Withdraw an invite you placed — hung up before anyone answered. */
|
|
170
|
+
async cancel(call) {
|
|
171
|
+
await this.request("call:cancel", {
|
|
172
|
+
call_id: call.callId,
|
|
173
|
+
conversation_id: call.conversationId
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
// ── subscriptions ──────────────────────────────────────────────────
|
|
177
|
+
/** Somebody is ringing you. */
|
|
178
|
+
onIncoming(fn) {
|
|
179
|
+
this.bind();
|
|
180
|
+
this.incoming.add(fn);
|
|
181
|
+
return () => this.incoming.delete(fn);
|
|
182
|
+
}
|
|
183
|
+
/** Your outbound call was answered — join the room now. */
|
|
184
|
+
onAccepted(fn) {
|
|
185
|
+
this.bind();
|
|
186
|
+
this.accepted.add(fn);
|
|
187
|
+
return () => this.accepted.delete(fn);
|
|
188
|
+
}
|
|
189
|
+
/** Your outbound call was rejected. */
|
|
190
|
+
onDeclined(fn) {
|
|
191
|
+
this.bind();
|
|
192
|
+
this.declined.add(fn);
|
|
193
|
+
return () => this.declined.delete(fn);
|
|
194
|
+
}
|
|
195
|
+
/** The person you called is already on another call. */
|
|
196
|
+
onBusy(fn) {
|
|
197
|
+
this.bind();
|
|
198
|
+
this.busy.add(fn);
|
|
199
|
+
return () => this.busy.delete(fn);
|
|
200
|
+
}
|
|
201
|
+
/** An inbound ring was withdrawn before you answered. */
|
|
202
|
+
onCancelled(fn) {
|
|
203
|
+
this.bind();
|
|
204
|
+
this.cancelled.add(fn);
|
|
205
|
+
return () => this.cancelled.delete(fn);
|
|
206
|
+
}
|
|
207
|
+
// ── internals ──────────────────────────────────────────────────────
|
|
208
|
+
/**
|
|
209
|
+
* One Phoenix binding per event regardless of listener count; we fan
|
|
210
|
+
* out ourselves, matching how the conversation channels do it.
|
|
211
|
+
*/
|
|
212
|
+
bind() {
|
|
213
|
+
if (this.bound) return;
|
|
214
|
+
this.bound = true;
|
|
215
|
+
const channel = this.getChannel();
|
|
216
|
+
channel.on("call:incoming", (p) => {
|
|
217
|
+
const call = {
|
|
218
|
+
callId: p.call_id,
|
|
219
|
+
conversationId: p.conversation_id,
|
|
220
|
+
callerUserId: p.caller_user_id
|
|
221
|
+
};
|
|
222
|
+
this.incoming.forEach((l) => l(call));
|
|
223
|
+
});
|
|
224
|
+
channel.on("call:accepted", (p) => {
|
|
225
|
+
const call = {
|
|
226
|
+
callId: p.call_id,
|
|
227
|
+
conversationId: p.conversation_id,
|
|
228
|
+
userId: p.user_id
|
|
229
|
+
};
|
|
230
|
+
this.accepted.forEach((l) => l(call));
|
|
231
|
+
});
|
|
232
|
+
channel.on("call:declined", (p) => {
|
|
233
|
+
const call = {
|
|
234
|
+
callId: p.call_id,
|
|
235
|
+
conversationId: p.conversation_id,
|
|
236
|
+
userId: p.user_id
|
|
237
|
+
};
|
|
238
|
+
this.declined.forEach((l) => l(call));
|
|
239
|
+
});
|
|
240
|
+
channel.on("call:busy", (p) => {
|
|
241
|
+
const call = {
|
|
242
|
+
callId: p.call_id,
|
|
243
|
+
conversationId: p.conversation_id,
|
|
244
|
+
userId: p.user_id
|
|
245
|
+
};
|
|
246
|
+
this.busy.forEach((l) => l(call));
|
|
247
|
+
});
|
|
248
|
+
channel.on("call:cancelled", (p) => {
|
|
249
|
+
const call = {
|
|
250
|
+
callId: p.call_id,
|
|
251
|
+
conversationId: p.conversation_id,
|
|
252
|
+
callerUserId: p.caller_user_id
|
|
253
|
+
};
|
|
254
|
+
this.cancelled.forEach((l) => l(call));
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
request(event, payload) {
|
|
258
|
+
return new Promise((resolve, reject) => {
|
|
259
|
+
this.getChannel().push(event, payload).receive("ok", (reply) => resolve(reply)).receive(
|
|
260
|
+
"error",
|
|
261
|
+
(reply) => reject(new PoolseError(`${event} rejected: ${reply?.reason ?? "unknown"}`))
|
|
262
|
+
).receive("timeout", () => reject(new PoolseError(`${event} timed out`)));
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
// src/voice/webrtc-browser.ts
|
|
268
|
+
function isWebRtcAvailable() {
|
|
269
|
+
return typeof globalThis !== "undefined" && typeof globalThis.RTCPeerConnection === "function";
|
|
270
|
+
}
|
|
271
|
+
function createBrowserWebRtcAdapter() {
|
|
272
|
+
return {
|
|
273
|
+
createPeerConnection(iceServers) {
|
|
274
|
+
return new RTCPeerConnection({
|
|
275
|
+
iceServers
|
|
276
|
+
});
|
|
277
|
+
},
|
|
278
|
+
async getUserMedia() {
|
|
279
|
+
const stream = await navigator.mediaDevices.getUserMedia({
|
|
280
|
+
audio: { echoCancellation: true, noiseSuppression: true }
|
|
281
|
+
});
|
|
282
|
+
return stream;
|
|
283
|
+
},
|
|
284
|
+
playRemoteStream(_peerId, stream) {
|
|
285
|
+
const el = document.createElement("audio");
|
|
286
|
+
el.autoplay = true;
|
|
287
|
+
el.style.display = "none";
|
|
288
|
+
el.srcObject = stream;
|
|
289
|
+
document.body.appendChild(el);
|
|
290
|
+
void el.play().catch(() => {
|
|
291
|
+
});
|
|
292
|
+
return () => {
|
|
293
|
+
el.srcObject = null;
|
|
294
|
+
el.remove();
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/voice/voice-room.ts
|
|
301
|
+
var DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }];
|
|
302
|
+
var SPEAKING_THRESHOLD = 0.02;
|
|
303
|
+
var SPEAKING_RELEASE_MS = 350;
|
|
304
|
+
var SPEAKING_POLL_MS = 100;
|
|
305
|
+
var VoiceRoom = class {
|
|
306
|
+
conversationId;
|
|
307
|
+
socket;
|
|
308
|
+
webrtc;
|
|
309
|
+
iceServers;
|
|
310
|
+
detectSpeaking;
|
|
311
|
+
channel = null;
|
|
312
|
+
localStream = null;
|
|
313
|
+
selfId = null;
|
|
314
|
+
status = "idle";
|
|
315
|
+
muted = false;
|
|
316
|
+
peers = /* @__PURE__ */ new Map();
|
|
317
|
+
sinks = /* @__PURE__ */ new Map();
|
|
318
|
+
/** Candidates that landed before their offer/answer did. */
|
|
319
|
+
pendingIce = /* @__PURE__ */ new Map();
|
|
320
|
+
roster = /* @__PURE__ */ new Map();
|
|
321
|
+
speakingTimer = null;
|
|
322
|
+
stopSpeakingDetection = null;
|
|
323
|
+
statusListeners = /* @__PURE__ */ new Set();
|
|
324
|
+
rosterListeners = /* @__PURE__ */ new Set();
|
|
325
|
+
errorListeners = /* @__PURE__ */ new Set();
|
|
326
|
+
constructor(conversationId, socket, opts = {}) {
|
|
327
|
+
this.conversationId = conversationId;
|
|
328
|
+
this.socket = socket;
|
|
329
|
+
this.webrtc = opts.webrtc ?? createBrowserWebRtcAdapter();
|
|
330
|
+
this.iceServers = opts.iceServers ?? DEFAULT_ICE_SERVERS;
|
|
331
|
+
this.detectSpeaking = opts.detectSpeaking ?? true;
|
|
332
|
+
}
|
|
333
|
+
// ── observation ────────────────────────────────────────────────────
|
|
334
|
+
getStatus() {
|
|
335
|
+
return this.status;
|
|
336
|
+
}
|
|
337
|
+
isMuted() {
|
|
338
|
+
return this.muted;
|
|
339
|
+
}
|
|
340
|
+
/** Everyone in the room, oldest join first. */
|
|
341
|
+
getParticipants() {
|
|
342
|
+
return [...this.roster.values()].map((p) => ({ ...p, isSelf: p.userId === this.selfId })).sort((a, b) => a.joinedAt - b.joinedAt || a.userId.localeCompare(b.userId));
|
|
343
|
+
}
|
|
344
|
+
onStatus(fn) {
|
|
345
|
+
this.statusListeners.add(fn);
|
|
346
|
+
return () => this.statusListeners.delete(fn);
|
|
347
|
+
}
|
|
348
|
+
onParticipants(fn) {
|
|
349
|
+
this.rosterListeners.add(fn);
|
|
350
|
+
return () => this.rosterListeners.delete(fn);
|
|
351
|
+
}
|
|
352
|
+
onError(fn) {
|
|
353
|
+
this.errorListeners.add(fn);
|
|
354
|
+
return () => this.errorListeners.delete(fn);
|
|
355
|
+
}
|
|
356
|
+
// ── lifecycle ──────────────────────────────────────────────────────
|
|
357
|
+
/** Acquire the mic, join the channel, and start negotiating. */
|
|
358
|
+
async join() {
|
|
359
|
+
if (this.channel) return;
|
|
360
|
+
this.setStatus("connecting");
|
|
361
|
+
try {
|
|
362
|
+
this.localStream = await this.webrtc.getUserMedia();
|
|
363
|
+
} catch (err) {
|
|
364
|
+
this.setStatus("error");
|
|
365
|
+
this.emitError(new Error(`microphone unavailable: ${String(err)}`));
|
|
366
|
+
throw err;
|
|
367
|
+
}
|
|
368
|
+
const channel = this.socket.channel(`voice:conversation:${this.conversationId}`, {});
|
|
369
|
+
this.channel = channel;
|
|
370
|
+
this.bindChannel(channel);
|
|
371
|
+
await new Promise((resolve, reject) => {
|
|
372
|
+
channel.join().receive("ok", () => {
|
|
373
|
+
channel.push("voice:join", { muted: false, speaking: false });
|
|
374
|
+
resolve();
|
|
375
|
+
}).receive("error", (reply) => {
|
|
376
|
+
const err = new Error(`voice join rejected: ${reply?.reason ?? "unknown"}`);
|
|
377
|
+
this.setStatus("error");
|
|
378
|
+
this.emitError(err);
|
|
379
|
+
this.teardown();
|
|
380
|
+
reject(err);
|
|
381
|
+
}).receive("timeout", () => {
|
|
382
|
+
const err = new Error("voice join timed out");
|
|
383
|
+
this.setStatus("error");
|
|
384
|
+
this.emitError(err);
|
|
385
|
+
this.teardown();
|
|
386
|
+
reject(err);
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
/** Announce departure, then drop every peer connection and the mic. */
|
|
391
|
+
leave() {
|
|
392
|
+
this.channel?.push("voice:leave", {});
|
|
393
|
+
this.teardown();
|
|
394
|
+
this.setStatus("idle");
|
|
395
|
+
}
|
|
396
|
+
/** Mute or unmute the local mic. Returns the new muted state. */
|
|
397
|
+
setMuted(muted) {
|
|
398
|
+
this.muted = muted;
|
|
399
|
+
for (const track of this.localStream?.getAudioTracks() ?? []) {
|
|
400
|
+
track.enabled = !muted;
|
|
401
|
+
}
|
|
402
|
+
this.channel?.push(muted ? "voice:mute" : "voice:unmute", { muted });
|
|
403
|
+
if (this.selfId) {
|
|
404
|
+
const self = this.roster.get(this.selfId);
|
|
405
|
+
if (self) this.roster.set(this.selfId, { ...self, muted, speaking: false });
|
|
406
|
+
this.emitRoster();
|
|
407
|
+
}
|
|
408
|
+
return this.muted;
|
|
409
|
+
}
|
|
410
|
+
toggleMute() {
|
|
411
|
+
return this.setMuted(!this.muted);
|
|
412
|
+
}
|
|
413
|
+
// ── channel wiring ─────────────────────────────────────────────────
|
|
414
|
+
bindChannel(channel) {
|
|
415
|
+
channel.on("voice:presence_state", (state) => {
|
|
416
|
+
this.roster.clear();
|
|
417
|
+
for (const [userId, entry] of Object.entries(state ?? {})) {
|
|
418
|
+
const meta = entry?.metas?.[0] ?? {};
|
|
419
|
+
this.roster.set(userId, {
|
|
420
|
+
userId,
|
|
421
|
+
muted: meta.mute_state ?? false,
|
|
422
|
+
speaking: meta.speaking_state ?? false,
|
|
423
|
+
joinedAt: meta.joined_at ?? 0
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
this.emitRoster();
|
|
427
|
+
for (const userId of this.roster.keys()) {
|
|
428
|
+
if (userId !== this.selfId) this.startNegotiation(userId);
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
channel.on("voice:joined", (payload) => {
|
|
432
|
+
const userId = payload?.user_id;
|
|
433
|
+
if (!userId) return;
|
|
434
|
+
if (!this.selfId) {
|
|
435
|
+
this.selfId = userId;
|
|
436
|
+
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
437
|
+
this.setStatus("connected");
|
|
438
|
+
if (this.detectSpeaking && this.localStream) {
|
|
439
|
+
this.startSpeakingDetection(this.localStream);
|
|
440
|
+
}
|
|
441
|
+
this.emitRoster();
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (userId === this.selfId) return;
|
|
445
|
+
if (!this.roster.has(userId)) {
|
|
446
|
+
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
447
|
+
this.emitRoster();
|
|
448
|
+
}
|
|
449
|
+
this.startNegotiation(userId);
|
|
450
|
+
});
|
|
451
|
+
channel.on("voice:left", (payload) => {
|
|
452
|
+
const userId = payload?.user_id;
|
|
453
|
+
if (!userId) return;
|
|
454
|
+
this.closePeer(userId);
|
|
455
|
+
this.roster.delete(userId);
|
|
456
|
+
this.emitRoster();
|
|
457
|
+
});
|
|
458
|
+
channel.on("voice:mute", (payload) => {
|
|
459
|
+
this.patchParticipant(payload?.user_id, { muted: payload?.muted ?? false });
|
|
460
|
+
});
|
|
461
|
+
channel.on("voice:active_speaker", (payload) => {
|
|
462
|
+
this.patchParticipant(payload?.user_id, { speaking: payload?.speaking ?? false });
|
|
463
|
+
});
|
|
464
|
+
channel.on("voice:signal", (payload) => {
|
|
465
|
+
void this.handleSignal(payload);
|
|
466
|
+
});
|
|
467
|
+
channel.on("voice:error", (payload) => {
|
|
468
|
+
this.emitError(new Error(`voice error: ${payload?.reason ?? "unknown"}`));
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
// ── negotiation ────────────────────────────────────────────────────
|
|
472
|
+
/**
|
|
473
|
+
* Glare control: both sides learn about each other simultaneously, so
|
|
474
|
+
* without a rule both would offer at once. The lexicographically lower
|
|
475
|
+
* user id offers and the higher answers — deterministic, no extra
|
|
476
|
+
* round trip.
|
|
477
|
+
*/
|
|
478
|
+
shouldOffer(peerId) {
|
|
479
|
+
return this.selfId != null && this.selfId < peerId;
|
|
480
|
+
}
|
|
481
|
+
startNegotiation(peerId) {
|
|
482
|
+
const pc = this.ensurePeer(peerId);
|
|
483
|
+
if (!this.shouldOffer(peerId)) return;
|
|
484
|
+
void (async () => {
|
|
485
|
+
try {
|
|
486
|
+
const offer = await pc.createOffer();
|
|
487
|
+
await pc.setLocalDescription(offer);
|
|
488
|
+
this.sendSignal("offer", peerId, { sdp: offer.sdp });
|
|
489
|
+
} catch (err) {
|
|
490
|
+
this.emitError(new Error(`offer to ${peerId} failed: ${String(err)}`));
|
|
491
|
+
}
|
|
492
|
+
})();
|
|
493
|
+
}
|
|
494
|
+
ensurePeer(peerId) {
|
|
495
|
+
const existing = this.peers.get(peerId);
|
|
496
|
+
if (existing) return existing;
|
|
497
|
+
const pc = this.webrtc.createPeerConnection(this.iceServers);
|
|
498
|
+
if (this.localStream) {
|
|
499
|
+
for (const track of this.localStream.getTracks()) {
|
|
500
|
+
pc.addTrack(track, this.localStream);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
pc.onicecandidate = (event) => {
|
|
504
|
+
if (!event.candidate) return;
|
|
505
|
+
this.sendSignal("ice-candidate", peerId, event.candidate);
|
|
506
|
+
};
|
|
507
|
+
pc.ontrack = (event) => {
|
|
508
|
+
const stream = event.streams[0];
|
|
509
|
+
if (!stream) return;
|
|
510
|
+
this.sinks.get(peerId)?.();
|
|
511
|
+
this.sinks.set(peerId, this.webrtc.playRemoteStream(peerId, stream));
|
|
512
|
+
};
|
|
513
|
+
this.peers.set(peerId, pc);
|
|
514
|
+
return pc;
|
|
515
|
+
}
|
|
516
|
+
async handleSignal(payload) {
|
|
517
|
+
const from = payload["from_user_id"];
|
|
518
|
+
const type = payload["type"];
|
|
519
|
+
if (!from || !type || from === this.selfId) return;
|
|
520
|
+
const target = payload["target_user_id"];
|
|
521
|
+
if (target && target !== this.selfId) return;
|
|
522
|
+
const data = payload["data"] ?? {};
|
|
523
|
+
const pc = this.ensurePeer(from);
|
|
524
|
+
try {
|
|
525
|
+
if (type === "offer") {
|
|
526
|
+
await pc.setRemoteDescription({ type: "offer", sdp: data["sdp"] });
|
|
527
|
+
await this.flushIce(pc, from);
|
|
528
|
+
const answer = await pc.createAnswer();
|
|
529
|
+
await pc.setLocalDescription(answer);
|
|
530
|
+
this.sendSignal("answer", from, { sdp: answer.sdp });
|
|
531
|
+
} else if (type === "answer") {
|
|
532
|
+
await pc.setRemoteDescription({ type: "answer", sdp: data["sdp"] });
|
|
533
|
+
await this.flushIce(pc, from);
|
|
534
|
+
} else if (type === "ice-candidate") {
|
|
535
|
+
const candidate = data;
|
|
536
|
+
if (!pc.remoteDescription) {
|
|
537
|
+
const queued = this.pendingIce.get(from) ?? [];
|
|
538
|
+
queued.push(candidate);
|
|
539
|
+
this.pendingIce.set(from, queued);
|
|
540
|
+
} else {
|
|
541
|
+
await pc.addIceCandidate(candidate);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
} catch (err) {
|
|
545
|
+
this.emitError(new Error(`signal (${type}) from ${from} failed: ${String(err)}`));
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
async flushIce(pc, peerId) {
|
|
549
|
+
const queued = this.pendingIce.get(peerId);
|
|
550
|
+
if (!queued?.length) return;
|
|
551
|
+
this.pendingIce.delete(peerId);
|
|
552
|
+
for (const candidate of queued) {
|
|
553
|
+
try {
|
|
554
|
+
await pc.addIceCandidate(candidate);
|
|
555
|
+
} catch {
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Every signal body travels under `data` — the server's
|
|
561
|
+
* `validate_signal_data/1` rejects the push outright when that key is
|
|
562
|
+
* missing or empty, and a rejected signal is never relayed.
|
|
563
|
+
*/
|
|
564
|
+
sendSignal(type, targetUserId, data) {
|
|
565
|
+
this.channel?.push("voice:signal", { type, target_user_id: targetUserId, data });
|
|
566
|
+
}
|
|
567
|
+
// ── speaking detection ─────────────────────────────────────────────
|
|
568
|
+
startSpeakingDetection(stream) {
|
|
569
|
+
const Ctor = globalThis.AudioContext;
|
|
570
|
+
if (!Ctor) return;
|
|
571
|
+
const ctx = new Ctor();
|
|
572
|
+
const source = ctx.createMediaStreamSource(stream);
|
|
573
|
+
const analyser = ctx.createAnalyser();
|
|
574
|
+
analyser.fftSize = 512;
|
|
575
|
+
source.connect(analyser);
|
|
576
|
+
const buf = new Float32Array(analyser.fftSize);
|
|
577
|
+
let speaking = false;
|
|
578
|
+
let lastLoud = 0;
|
|
579
|
+
this.speakingTimer = setInterval(() => {
|
|
580
|
+
analyser.getFloatTimeDomainData(buf);
|
|
581
|
+
let sum = 0;
|
|
582
|
+
for (const v of buf) sum += v * v;
|
|
583
|
+
const rms = Math.sqrt(sum / buf.length);
|
|
584
|
+
const now = Date.now();
|
|
585
|
+
if (!this.muted && rms > SPEAKING_THRESHOLD) lastLoud = now;
|
|
586
|
+
const next = !this.muted && now - lastLoud < SPEAKING_RELEASE_MS;
|
|
587
|
+
if (next === speaking) return;
|
|
588
|
+
speaking = next;
|
|
589
|
+
this.channel?.push("voice:active_speaker", { speaking });
|
|
590
|
+
this.patchParticipant(this.selfId ?? void 0, { speaking });
|
|
591
|
+
}, SPEAKING_POLL_MS);
|
|
592
|
+
this.stopSpeakingDetection = () => {
|
|
593
|
+
void ctx.close().catch(() => {
|
|
594
|
+
});
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
// ── teardown & emit ────────────────────────────────────────────────
|
|
598
|
+
closePeer(peerId) {
|
|
599
|
+
const pc = this.peers.get(peerId);
|
|
600
|
+
if (pc) {
|
|
601
|
+
pc.onicecandidate = null;
|
|
602
|
+
pc.ontrack = null;
|
|
603
|
+
pc.onconnectionstatechange = null;
|
|
604
|
+
pc.close();
|
|
605
|
+
this.peers.delete(peerId);
|
|
606
|
+
}
|
|
607
|
+
this.sinks.get(peerId)?.();
|
|
608
|
+
this.sinks.delete(peerId);
|
|
609
|
+
this.pendingIce.delete(peerId);
|
|
610
|
+
}
|
|
611
|
+
teardown() {
|
|
612
|
+
for (const peerId of [...this.peers.keys()]) this.closePeer(peerId);
|
|
613
|
+
if (this.speakingTimer) clearInterval(this.speakingTimer);
|
|
614
|
+
this.speakingTimer = null;
|
|
615
|
+
this.stopSpeakingDetection?.();
|
|
616
|
+
this.stopSpeakingDetection = null;
|
|
617
|
+
for (const track of this.localStream?.getTracks() ?? []) track.stop();
|
|
618
|
+
this.localStream = null;
|
|
619
|
+
this.channel?.leave();
|
|
620
|
+
this.channel = null;
|
|
621
|
+
this.selfId = null;
|
|
622
|
+
this.muted = false;
|
|
623
|
+
this.roster.clear();
|
|
624
|
+
this.emitRoster();
|
|
625
|
+
}
|
|
626
|
+
patchParticipant(userId, patch) {
|
|
627
|
+
if (!userId) return;
|
|
628
|
+
const current = this.roster.get(userId);
|
|
629
|
+
if (!current) return;
|
|
630
|
+
this.roster.set(userId, { ...current, ...patch });
|
|
631
|
+
this.emitRoster();
|
|
632
|
+
}
|
|
633
|
+
setStatus(status) {
|
|
634
|
+
if (this.status === status) return;
|
|
635
|
+
this.status = status;
|
|
636
|
+
this.statusListeners.forEach((l) => l(status));
|
|
637
|
+
}
|
|
638
|
+
emitRoster() {
|
|
639
|
+
const snapshot = this.getParticipants();
|
|
640
|
+
this.rosterListeners.forEach((l) => l(snapshot));
|
|
641
|
+
}
|
|
642
|
+
emitError(err) {
|
|
643
|
+
this.errorListeners.forEach((l) => l(err));
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
|
|
108
647
|
// src/realtime/realtime.ts
|
|
109
648
|
var PoolseRealtime = class {
|
|
110
649
|
config;
|
|
@@ -113,7 +652,9 @@ var PoolseRealtime = class {
|
|
|
113
652
|
wsUrl;
|
|
114
653
|
socket = null;
|
|
115
654
|
conversations = /* @__PURE__ */ new Map();
|
|
655
|
+
voiceRooms = /* @__PURE__ */ new Map();
|
|
116
656
|
userChannel = null;
|
|
657
|
+
callsResource = null;
|
|
117
658
|
status = "idle";
|
|
118
659
|
statusListeners = /* @__PURE__ */ new Set();
|
|
119
660
|
constructor(config, tokenCache, opts = {}) {
|
|
@@ -183,6 +724,8 @@ var PoolseRealtime = class {
|
|
|
183
724
|
}
|
|
184
725
|
/** Close the socket and tear down every joined channel. */
|
|
185
726
|
disconnect() {
|
|
727
|
+
for (const room of this.voiceRooms.values()) room.leave();
|
|
728
|
+
this.voiceRooms.clear();
|
|
186
729
|
this.setStatus("closed");
|
|
187
730
|
this.conversations.forEach((c) => c._destroy());
|
|
188
731
|
this.conversations.clear();
|
|
@@ -227,6 +770,39 @@ var PoolseRealtime = class {
|
|
|
227
770
|
handle._join();
|
|
228
771
|
return handle;
|
|
229
772
|
}
|
|
773
|
+
/**
|
|
774
|
+
* Voice room for a conversation — the Discord-style surface. Call
|
|
775
|
+
* `join()` on the returned handle to acquire the mic and connect;
|
|
776
|
+
* reusing the same id returns the same room rather than opening a
|
|
777
|
+
* second one.
|
|
778
|
+
*
|
|
779
|
+
* Ringing somebody who hasn't joined is a separate concern; see
|
|
780
|
+
* `poolse.calls`.
|
|
781
|
+
*/
|
|
782
|
+
voice(conversationId, opts = {}) {
|
|
783
|
+
const existing = this.voiceRooms.get(conversationId);
|
|
784
|
+
if (existing) return existing;
|
|
785
|
+
this.connect();
|
|
786
|
+
if (!this.socket) {
|
|
787
|
+
throw new PoolseError("socket not initialised \u2014 call connect() first");
|
|
788
|
+
}
|
|
789
|
+
const room = new VoiceRoom(conversationId, this.socket, opts);
|
|
790
|
+
this.voiceRooms.set(conversationId, room);
|
|
791
|
+
return room;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Call invitations for a user — the WhatsApp-style surface. Rides the
|
|
795
|
+
* `user:<id>` topic, the one channel a client is always joined to, so
|
|
796
|
+
* a ring reaches somebody who hasn't opened a voice room yet.
|
|
797
|
+
*
|
|
798
|
+
* Takes the user id explicitly, mirroring `user(userId)`; the SDK
|
|
799
|
+
* never assumes whose token it is holding.
|
|
800
|
+
*/
|
|
801
|
+
calls(userId) {
|
|
802
|
+
if (this.callsResource) return this.callsResource;
|
|
803
|
+
this.callsResource = new CallsResource(() => this.user(userId)._channel());
|
|
804
|
+
return this.callsResource;
|
|
805
|
+
}
|
|
230
806
|
/** Drop a conversation handle and leave the channel. */
|
|
231
807
|
leave(conversationId) {
|
|
232
808
|
const handle = this.conversations.get(conversationId);
|
|
@@ -366,6 +942,15 @@ var UserChannel = class {
|
|
|
366
942
|
this.userId = userId;
|
|
367
943
|
this.channel = channel;
|
|
368
944
|
}
|
|
945
|
+
/**
|
|
946
|
+
* The underlying Phoenix channel, for surfaces that push their own
|
|
947
|
+
* events on this topic (the calls resource does).
|
|
948
|
+
*
|
|
949
|
+
* @internal
|
|
950
|
+
*/
|
|
951
|
+
_channel() {
|
|
952
|
+
return this.channel;
|
|
953
|
+
}
|
|
369
954
|
onMention(fn) {
|
|
370
955
|
if (!this.mentionBound) {
|
|
371
956
|
this.mentionBound = true;
|
|
@@ -1206,12 +1791,13 @@ var Poolse = class {
|
|
|
1206
1791
|
};
|
|
1207
1792
|
|
|
1208
1793
|
// src/version.ts
|
|
1209
|
-
var version = "2.0
|
|
1794
|
+
var version = "2.2.0";
|
|
1210
1795
|
|
|
1211
1796
|
exports.ApiError = ApiError;
|
|
1212
1797
|
exports.AttachmentHandle = AttachmentHandle;
|
|
1213
1798
|
exports.AttachmentsResource = AttachmentsResource;
|
|
1214
1799
|
exports.AuthError = AuthError;
|
|
1800
|
+
exports.CallsResource = CallsResource;
|
|
1215
1801
|
exports.ConversationChannel = ConversationChannel;
|
|
1216
1802
|
exports.ConversationHandle = ConversationHandle;
|
|
1217
1803
|
exports.ConversationMessages = ConversationMessages;
|
|
@@ -1227,6 +1813,9 @@ exports.PoolseRealtime = PoolseRealtime;
|
|
|
1227
1813
|
exports.RateLimitedError = RateLimitedError;
|
|
1228
1814
|
exports.UserChannel = UserChannel;
|
|
1229
1815
|
exports.UsersResource = UsersResource;
|
|
1816
|
+
exports.VoiceRoom = VoiceRoom;
|
|
1817
|
+
exports.createBrowserWebRtcAdapter = createBrowserWebRtcAdapter;
|
|
1818
|
+
exports.isWebRtcAvailable = isWebRtcAvailable;
|
|
1230
1819
|
exports.safeUuid = safeUuid;
|
|
1231
1820
|
exports.version = version;
|
|
1232
1821
|
//# sourceMappingURL=index.cjs.map
|