@poolse/sdk 2.25.0 → 3.0.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 +34 -0
- package/LICENSE +206 -21
- package/README.md +2 -2
- package/dist/index.cjs +6 -691
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -431
- package/dist/index.d.ts +22 -431
- package/dist/index.js +7 -687
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -103,640 +103,21 @@ var AuthError = class extends ApiError {
|
|
|
103
103
|
}
|
|
104
104
|
};
|
|
105
105
|
|
|
106
|
-
// src/voice/calls.ts
|
|
107
|
-
function toMedia(value) {
|
|
108
|
-
return value === "video" ? "video" : "audio";
|
|
109
|
-
}
|
|
110
|
-
var CallsResource = class {
|
|
111
|
-
/** Resolves the user channel lazily — it may not be joined yet. */
|
|
112
|
-
getChannel;
|
|
113
|
-
incoming = /* @__PURE__ */ new Set();
|
|
114
|
-
accepted = /* @__PURE__ */ new Set();
|
|
115
|
-
declined = /* @__PURE__ */ new Set();
|
|
116
|
-
busy = /* @__PURE__ */ new Set();
|
|
117
|
-
cancelled = /* @__PURE__ */ new Set();
|
|
118
|
-
ended = /* @__PURE__ */ new Set();
|
|
119
|
-
bound = false;
|
|
120
|
-
constructor(getChannel) {
|
|
121
|
-
this.getChannel = getChannel;
|
|
122
|
-
}
|
|
123
|
-
// ── placing and answering ──────────────────────────────────────────
|
|
124
|
-
/**
|
|
125
|
-
* Ring every other member of a conversation. Resolves once the server
|
|
126
|
-
* has fanned the invite out, with the minted call id and who was rung
|
|
127
|
-
* — not when anyone answers; that arrives via {@link onAccepted}.
|
|
128
|
-
*/
|
|
129
|
-
invite(conversationId, media = "audio") {
|
|
130
|
-
return this.request("call:invite", {
|
|
131
|
-
conversation_id: conversationId,
|
|
132
|
-
media
|
|
133
|
-
}).then((reply) => ({
|
|
134
|
-
callId: reply.call_id,
|
|
135
|
-
conversationId: reply.conversation_id,
|
|
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)
|
|
141
|
-
}));
|
|
142
|
-
}
|
|
143
|
-
/**
|
|
144
|
-
* Answer a ringing call. This only tells the caller you picked up —
|
|
145
|
-
* join the voice room yourself to actually connect audio.
|
|
146
|
-
*/
|
|
147
|
-
async accept(call) {
|
|
148
|
-
await this.request("call:accept", {
|
|
149
|
-
call_id: call.callId,
|
|
150
|
-
conversation_id: call.conversationId,
|
|
151
|
-
caller_user_id: call.callerUserId
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
/** Reject a ringing call without joining the room. */
|
|
155
|
-
async decline(call) {
|
|
156
|
-
await this.request("call:decline", {
|
|
157
|
-
call_id: call.callId,
|
|
158
|
-
conversation_id: call.conversationId,
|
|
159
|
-
caller_user_id: call.callerUserId
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Tell the caller you are already on another call.
|
|
164
|
-
*
|
|
165
|
-
* Distinct from {@link decline}: nobody chose anything, so clients
|
|
166
|
-
* send this automatically when a ring arrives mid-call. `useCalls`
|
|
167
|
-
* does it for you.
|
|
168
|
-
*/
|
|
169
|
-
async markBusy(call) {
|
|
170
|
-
await this.request("call:busy", {
|
|
171
|
-
call_id: call.callId,
|
|
172
|
-
conversation_id: call.conversationId,
|
|
173
|
-
caller_user_id: call.callerUserId
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* End a call that is already connected.
|
|
178
|
-
*
|
|
179
|
-
* Distinct from {@link cancel}, which withdraws an unanswered invite.
|
|
180
|
-
* Without this a connected call has no end signal, so hanging up
|
|
181
|
-
* leaves the other side sitting in the room with a call screen it has
|
|
182
|
-
* no reason to close.
|
|
183
|
-
*/
|
|
184
|
-
async hangUp(call) {
|
|
185
|
-
await this.request("call:hangup", {
|
|
186
|
-
call_id: call.callId,
|
|
187
|
-
conversation_id: call.conversationId
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
/** Withdraw an invite you placed — hung up before anyone answered. */
|
|
191
|
-
async cancel(call) {
|
|
192
|
-
await this.request("call:cancel", {
|
|
193
|
-
call_id: call.callId,
|
|
194
|
-
conversation_id: call.conversationId
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
// ── subscriptions ──────────────────────────────────────────────────
|
|
198
|
-
/** Somebody is ringing you. */
|
|
199
|
-
onIncoming(fn) {
|
|
200
|
-
this.bind();
|
|
201
|
-
this.incoming.add(fn);
|
|
202
|
-
return () => this.incoming.delete(fn);
|
|
203
|
-
}
|
|
204
|
-
/** Your outbound call was answered — join the room now. */
|
|
205
|
-
onAccepted(fn) {
|
|
206
|
-
this.bind();
|
|
207
|
-
this.accepted.add(fn);
|
|
208
|
-
return () => this.accepted.delete(fn);
|
|
209
|
-
}
|
|
210
|
-
/** Your outbound call was rejected. */
|
|
211
|
-
onDeclined(fn) {
|
|
212
|
-
this.bind();
|
|
213
|
-
this.declined.add(fn);
|
|
214
|
-
return () => this.declined.delete(fn);
|
|
215
|
-
}
|
|
216
|
-
/** The person you called is already on another call. */
|
|
217
|
-
onBusy(fn) {
|
|
218
|
-
this.bind();
|
|
219
|
-
this.busy.add(fn);
|
|
220
|
-
return () => this.busy.delete(fn);
|
|
221
|
-
}
|
|
222
|
-
/** The other side ended a connected call. */
|
|
223
|
-
onEnded(fn) {
|
|
224
|
-
this.bind();
|
|
225
|
-
this.ended.add(fn);
|
|
226
|
-
return () => this.ended.delete(fn);
|
|
227
|
-
}
|
|
228
|
-
/** An inbound ring was withdrawn before you answered. */
|
|
229
|
-
onCancelled(fn) {
|
|
230
|
-
this.bind();
|
|
231
|
-
this.cancelled.add(fn);
|
|
232
|
-
return () => this.cancelled.delete(fn);
|
|
233
|
-
}
|
|
234
|
-
// ── internals ──────────────────────────────────────────────────────
|
|
235
|
-
/**
|
|
236
|
-
* One Phoenix binding per event regardless of listener count; we fan
|
|
237
|
-
* out ourselves, matching how the conversation channels do it.
|
|
238
|
-
*/
|
|
239
|
-
bind() {
|
|
240
|
-
if (this.bound) return;
|
|
241
|
-
this.bound = true;
|
|
242
|
-
const channel = this.getChannel();
|
|
243
|
-
channel.on("call:incoming", (p) => {
|
|
244
|
-
const call = {
|
|
245
|
-
callId: p.call_id,
|
|
246
|
-
conversationId: p.conversation_id,
|
|
247
|
-
callerUserId: p.caller_user_id,
|
|
248
|
-
media: toMedia(p.media)
|
|
249
|
-
};
|
|
250
|
-
this.incoming.forEach((l) => l(call));
|
|
251
|
-
});
|
|
252
|
-
channel.on("call:accepted", (p) => {
|
|
253
|
-
const call = {
|
|
254
|
-
callId: p.call_id,
|
|
255
|
-
conversationId: p.conversation_id,
|
|
256
|
-
userId: p.user_id
|
|
257
|
-
};
|
|
258
|
-
this.accepted.forEach((l) => l(call));
|
|
259
|
-
});
|
|
260
|
-
channel.on("call:declined", (p) => {
|
|
261
|
-
const call = {
|
|
262
|
-
callId: p.call_id,
|
|
263
|
-
conversationId: p.conversation_id,
|
|
264
|
-
userId: p.user_id
|
|
265
|
-
};
|
|
266
|
-
this.declined.forEach((l) => l(call));
|
|
267
|
-
});
|
|
268
|
-
channel.on("call:busy", (p) => {
|
|
269
|
-
const call = {
|
|
270
|
-
callId: p.call_id,
|
|
271
|
-
conversationId: p.conversation_id,
|
|
272
|
-
userId: p.user_id
|
|
273
|
-
};
|
|
274
|
-
this.busy.forEach((l) => l(call));
|
|
275
|
-
});
|
|
276
|
-
channel.on("call:ended", (p) => {
|
|
277
|
-
const call = {
|
|
278
|
-
callId: p.call_id,
|
|
279
|
-
conversationId: p.conversation_id,
|
|
280
|
-
userId: p.user_id
|
|
281
|
-
};
|
|
282
|
-
this.ended.forEach((l) => l(call));
|
|
283
|
-
});
|
|
284
|
-
channel.on("call:cancelled", (p) => {
|
|
285
|
-
const call = {
|
|
286
|
-
callId: p.call_id,
|
|
287
|
-
conversationId: p.conversation_id,
|
|
288
|
-
callerUserId: p.caller_user_id
|
|
289
|
-
};
|
|
290
|
-
this.cancelled.forEach((l) => l(call));
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
request(event, payload) {
|
|
294
|
-
return new Promise((resolve, reject) => {
|
|
295
|
-
this.getChannel().push(event, payload).receive("ok", (reply) => resolve(reply)).receive(
|
|
296
|
-
"error",
|
|
297
|
-
(reply) => reject(new PoolseError(`${event} rejected: ${reply?.reason ?? "unknown"}`))
|
|
298
|
-
).receive("timeout", () => reject(new PoolseError(`${event} timed out`)));
|
|
299
|
-
});
|
|
300
|
-
}
|
|
301
|
-
};
|
|
302
|
-
|
|
303
|
-
// src/voice/webrtc-browser.ts
|
|
304
|
-
function isWebRtcAvailable() {
|
|
305
|
-
return typeof globalThis !== "undefined" && typeof globalThis.RTCPeerConnection === "function";
|
|
306
|
-
}
|
|
307
|
-
function createBrowserWebRtcAdapter() {
|
|
308
|
-
return {
|
|
309
|
-
createPeerConnection(iceServers) {
|
|
310
|
-
return new RTCPeerConnection({
|
|
311
|
-
iceServers
|
|
312
|
-
});
|
|
313
|
-
},
|
|
314
|
-
async getUserMedia() {
|
|
315
|
-
const stream = await navigator.mediaDevices.getUserMedia({
|
|
316
|
-
audio: { echoCancellation: true, noiseSuppression: true }
|
|
317
|
-
});
|
|
318
|
-
return stream;
|
|
319
|
-
},
|
|
320
|
-
playRemoteStream(_peerId, stream) {
|
|
321
|
-
const el = document.createElement("audio");
|
|
322
|
-
el.autoplay = true;
|
|
323
|
-
el.style.display = "none";
|
|
324
|
-
el.srcObject = stream;
|
|
325
|
-
document.body.appendChild(el);
|
|
326
|
-
void el.play().catch(() => {
|
|
327
|
-
});
|
|
328
|
-
return () => {
|
|
329
|
-
el.srcObject = null;
|
|
330
|
-
el.remove();
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
};
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
// src/voice/voice-room.ts
|
|
337
|
-
var DEFAULT_ICE_SERVERS = [{ urls: "stun:stun.l.google.com:19302" }];
|
|
338
|
-
var SPEAKING_THRESHOLD = 0.02;
|
|
339
|
-
var SPEAKING_RELEASE_MS = 350;
|
|
340
|
-
var SPEAKING_POLL_MS = 100;
|
|
341
|
-
var VoiceRoom = class {
|
|
342
|
-
conversationId;
|
|
343
|
-
socket;
|
|
344
|
-
webrtc;
|
|
345
|
-
iceServers;
|
|
346
|
-
iceServersProvider;
|
|
347
|
-
detectSpeaking;
|
|
348
|
-
channel = null;
|
|
349
|
-
localStream = null;
|
|
350
|
-
selfId = null;
|
|
351
|
-
status = "idle";
|
|
352
|
-
muted = false;
|
|
353
|
-
peers = /* @__PURE__ */ new Map();
|
|
354
|
-
sinks = /* @__PURE__ */ new Map();
|
|
355
|
-
/** Candidates that landed before their offer/answer did. */
|
|
356
|
-
pendingIce = /* @__PURE__ */ new Map();
|
|
357
|
-
roster = /* @__PURE__ */ new Map();
|
|
358
|
-
/**
|
|
359
|
-
* How many callers currently hold this room open.
|
|
360
|
-
*
|
|
361
|
-
* `PoolseRealtime` hands out ONE room per conversation, so a call
|
|
362
|
-
* screen and an always-on voice bar for the same conversation share
|
|
363
|
-
* this instance — which is correct, since a user is in one audio
|
|
364
|
-
* session, not two. Without counting, whichever of them tore down
|
|
365
|
-
* first would cut the audio out from under the other.
|
|
366
|
-
*/
|
|
367
|
-
holders = 0;
|
|
368
|
-
speakingTimer = null;
|
|
369
|
-
stopSpeakingDetection = null;
|
|
370
|
-
statusListeners = /* @__PURE__ */ new Set();
|
|
371
|
-
rosterListeners = /* @__PURE__ */ new Set();
|
|
372
|
-
errorListeners = /* @__PURE__ */ new Set();
|
|
373
|
-
constructor(conversationId, socket, opts = {}) {
|
|
374
|
-
this.conversationId = conversationId;
|
|
375
|
-
this.socket = socket;
|
|
376
|
-
this.webrtc = opts.webrtc ?? createBrowserWebRtcAdapter();
|
|
377
|
-
this.iceServers = opts.iceServers ?? DEFAULT_ICE_SERVERS;
|
|
378
|
-
this.iceServersProvider = opts.iceServersProvider ?? null;
|
|
379
|
-
this.detectSpeaking = opts.detectSpeaking ?? true;
|
|
380
|
-
}
|
|
381
|
-
// ── observation ────────────────────────────────────────────────────
|
|
382
|
-
getStatus() {
|
|
383
|
-
return this.status;
|
|
384
|
-
}
|
|
385
|
-
isMuted() {
|
|
386
|
-
return this.muted;
|
|
387
|
-
}
|
|
388
|
-
/** Everyone in the room, oldest join first. */
|
|
389
|
-
getParticipants() {
|
|
390
|
-
return [...this.roster.values()].map((p) => ({ ...p, isSelf: p.userId === this.selfId })).sort((a, b) => a.joinedAt - b.joinedAt || a.userId.localeCompare(b.userId));
|
|
391
|
-
}
|
|
392
|
-
onStatus(fn) {
|
|
393
|
-
this.statusListeners.add(fn);
|
|
394
|
-
return () => this.statusListeners.delete(fn);
|
|
395
|
-
}
|
|
396
|
-
onParticipants(fn) {
|
|
397
|
-
this.rosterListeners.add(fn);
|
|
398
|
-
return () => this.rosterListeners.delete(fn);
|
|
399
|
-
}
|
|
400
|
-
onError(fn) {
|
|
401
|
-
this.errorListeners.add(fn);
|
|
402
|
-
return () => this.errorListeners.delete(fn);
|
|
403
|
-
}
|
|
404
|
-
// ── lifecycle ──────────────────────────────────────────────────────
|
|
405
|
-
/** Acquire the mic, join the channel, and start negotiating. */
|
|
406
|
-
async join() {
|
|
407
|
-
if (this.channel) {
|
|
408
|
-
this.holders += 1;
|
|
409
|
-
return;
|
|
410
|
-
}
|
|
411
|
-
this.holders += 1;
|
|
412
|
-
this.setStatus("connecting");
|
|
413
|
-
await this.resolveIceServers();
|
|
414
|
-
try {
|
|
415
|
-
this.localStream = await this.webrtc.getUserMedia();
|
|
416
|
-
} catch (err) {
|
|
417
|
-
this.holders = Math.max(0, this.holders - 1);
|
|
418
|
-
this.setStatus("error");
|
|
419
|
-
this.emitError(new Error(`microphone unavailable: ${String(err)}`));
|
|
420
|
-
throw err;
|
|
421
|
-
}
|
|
422
|
-
const channel = this.socket.channel(`voice:conversation:${this.conversationId}`, {});
|
|
423
|
-
this.channel = channel;
|
|
424
|
-
this.bindChannel(channel);
|
|
425
|
-
await new Promise((resolve, reject) => {
|
|
426
|
-
channel.join().receive("ok", () => {
|
|
427
|
-
channel.push("voice:join", { muted: false, speaking: false });
|
|
428
|
-
resolve();
|
|
429
|
-
}).receive("error", (reply) => {
|
|
430
|
-
const err = new Error(`voice join rejected: ${reply?.reason ?? "unknown"}`);
|
|
431
|
-
this.setStatus("error");
|
|
432
|
-
this.emitError(err);
|
|
433
|
-
this.teardown();
|
|
434
|
-
reject(err);
|
|
435
|
-
}).receive("timeout", () => {
|
|
436
|
-
const err = new Error("voice join timed out");
|
|
437
|
-
this.setStatus("error");
|
|
438
|
-
this.emitError(err);
|
|
439
|
-
this.teardown();
|
|
440
|
-
reject(err);
|
|
441
|
-
});
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
/** Announce departure, then drop every peer connection and the mic. */
|
|
445
|
-
leave() {
|
|
446
|
-
if (this.holders > 0) this.holders -= 1;
|
|
447
|
-
if (this.holders > 0) return;
|
|
448
|
-
this.channel?.push("voice:leave", {});
|
|
449
|
-
this.teardown();
|
|
450
|
-
this.setStatus("idle");
|
|
451
|
-
}
|
|
452
|
-
/** Mute or unmute the local mic. Returns the new muted state. */
|
|
453
|
-
setMuted(muted) {
|
|
454
|
-
this.muted = muted;
|
|
455
|
-
for (const track of this.localStream?.getAudioTracks() ?? []) {
|
|
456
|
-
track.enabled = !muted;
|
|
457
|
-
}
|
|
458
|
-
this.channel?.push(muted ? "voice:mute" : "voice:unmute", { muted });
|
|
459
|
-
if (this.selfId) {
|
|
460
|
-
const self = this.roster.get(this.selfId);
|
|
461
|
-
if (self) this.roster.set(this.selfId, { ...self, muted, speaking: false });
|
|
462
|
-
this.emitRoster();
|
|
463
|
-
}
|
|
464
|
-
return this.muted;
|
|
465
|
-
}
|
|
466
|
-
toggleMute() {
|
|
467
|
-
return this.setMuted(!this.muted);
|
|
468
|
-
}
|
|
469
|
-
// ── channel wiring ─────────────────────────────────────────────────
|
|
470
|
-
bindChannel(channel) {
|
|
471
|
-
channel.on("voice:presence_state", (state) => {
|
|
472
|
-
this.roster.clear();
|
|
473
|
-
for (const [userId, entry] of Object.entries(state ?? {})) {
|
|
474
|
-
const meta = entry?.metas?.[0] ?? {};
|
|
475
|
-
this.roster.set(userId, {
|
|
476
|
-
userId,
|
|
477
|
-
muted: meta.mute_state ?? false,
|
|
478
|
-
speaking: meta.speaking_state ?? false,
|
|
479
|
-
joinedAt: meta.joined_at ?? 0
|
|
480
|
-
});
|
|
481
|
-
}
|
|
482
|
-
this.emitRoster();
|
|
483
|
-
for (const userId of this.roster.keys()) {
|
|
484
|
-
if (userId !== this.selfId) this.startNegotiation(userId);
|
|
485
|
-
}
|
|
486
|
-
});
|
|
487
|
-
channel.on("voice:joined", (payload) => {
|
|
488
|
-
const userId = payload?.user_id;
|
|
489
|
-
if (!userId) return;
|
|
490
|
-
if (!this.selfId) {
|
|
491
|
-
this.selfId = userId;
|
|
492
|
-
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
493
|
-
this.setStatus("connected");
|
|
494
|
-
if (this.detectSpeaking && this.localStream) {
|
|
495
|
-
this.startSpeakingDetection(this.localStream);
|
|
496
|
-
}
|
|
497
|
-
this.emitRoster();
|
|
498
|
-
return;
|
|
499
|
-
}
|
|
500
|
-
if (userId === this.selfId) return;
|
|
501
|
-
if (!this.roster.has(userId)) {
|
|
502
|
-
this.roster.set(userId, { userId, muted: false, speaking: false, joinedAt: Date.now() });
|
|
503
|
-
this.emitRoster();
|
|
504
|
-
}
|
|
505
|
-
this.startNegotiation(userId);
|
|
506
|
-
});
|
|
507
|
-
channel.on("voice:left", (payload) => {
|
|
508
|
-
const userId = payload?.user_id;
|
|
509
|
-
if (!userId) return;
|
|
510
|
-
this.closePeer(userId);
|
|
511
|
-
this.roster.delete(userId);
|
|
512
|
-
this.emitRoster();
|
|
513
|
-
});
|
|
514
|
-
channel.on("voice:mute", (payload) => {
|
|
515
|
-
this.patchParticipant(payload?.user_id, { muted: payload?.muted ?? false });
|
|
516
|
-
});
|
|
517
|
-
channel.on("voice:active_speaker", (payload) => {
|
|
518
|
-
this.patchParticipant(payload?.user_id, { speaking: payload?.speaking ?? false });
|
|
519
|
-
});
|
|
520
|
-
channel.on("voice:signal", (payload) => {
|
|
521
|
-
void this.handleSignal(payload);
|
|
522
|
-
});
|
|
523
|
-
channel.on("voice:error", (payload) => {
|
|
524
|
-
this.emitError(new Error(`voice error: ${payload?.reason ?? "unknown"}`));
|
|
525
|
-
});
|
|
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
|
-
}
|
|
544
|
-
// ── negotiation ────────────────────────────────────────────────────
|
|
545
|
-
/**
|
|
546
|
-
* Glare control: both sides learn about each other simultaneously, so
|
|
547
|
-
* without a rule both would offer at once. The lexicographically lower
|
|
548
|
-
* user id offers and the higher answers — deterministic, no extra
|
|
549
|
-
* round trip.
|
|
550
|
-
*/
|
|
551
|
-
shouldOffer(peerId) {
|
|
552
|
-
return this.selfId != null && this.selfId < peerId;
|
|
553
|
-
}
|
|
554
|
-
startNegotiation(peerId) {
|
|
555
|
-
const pc = this.ensurePeer(peerId);
|
|
556
|
-
if (!this.shouldOffer(peerId)) return;
|
|
557
|
-
void (async () => {
|
|
558
|
-
try {
|
|
559
|
-
const offer = await pc.createOffer();
|
|
560
|
-
await pc.setLocalDescription(offer);
|
|
561
|
-
this.sendSignal("offer", peerId, { sdp: offer.sdp });
|
|
562
|
-
} catch (err) {
|
|
563
|
-
this.emitError(new Error(`offer to ${peerId} failed: ${String(err)}`));
|
|
564
|
-
}
|
|
565
|
-
})();
|
|
566
|
-
}
|
|
567
|
-
ensurePeer(peerId) {
|
|
568
|
-
const existing = this.peers.get(peerId);
|
|
569
|
-
if (existing) return existing;
|
|
570
|
-
const pc = this.webrtc.createPeerConnection(this.iceServers);
|
|
571
|
-
if (this.localStream) {
|
|
572
|
-
for (const track of this.localStream.getTracks()) {
|
|
573
|
-
pc.addTrack(track, this.localStream);
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
pc.onicecandidate = (event) => {
|
|
577
|
-
if (!event.candidate) return;
|
|
578
|
-
this.sendSignal("ice-candidate", peerId, event.candidate);
|
|
579
|
-
};
|
|
580
|
-
pc.ontrack = (event) => {
|
|
581
|
-
const stream = event.streams[0];
|
|
582
|
-
if (!stream) return;
|
|
583
|
-
this.sinks.get(peerId)?.();
|
|
584
|
-
this.sinks.set(peerId, this.webrtc.playRemoteStream(peerId, stream));
|
|
585
|
-
};
|
|
586
|
-
this.peers.set(peerId, pc);
|
|
587
|
-
return pc;
|
|
588
|
-
}
|
|
589
|
-
async handleSignal(payload) {
|
|
590
|
-
const from = payload["from_user_id"];
|
|
591
|
-
const type = payload["type"];
|
|
592
|
-
if (!from || !type || from === this.selfId) return;
|
|
593
|
-
const target = payload["target_user_id"];
|
|
594
|
-
if (target && target !== this.selfId) return;
|
|
595
|
-
const data = payload["data"] ?? {};
|
|
596
|
-
const pc = this.ensurePeer(from);
|
|
597
|
-
try {
|
|
598
|
-
if (type === "offer") {
|
|
599
|
-
await pc.setRemoteDescription({ type: "offer", sdp: data["sdp"] });
|
|
600
|
-
await this.flushIce(pc, from);
|
|
601
|
-
const answer = await pc.createAnswer();
|
|
602
|
-
await pc.setLocalDescription(answer);
|
|
603
|
-
this.sendSignal("answer", from, { sdp: answer.sdp });
|
|
604
|
-
} else if (type === "answer") {
|
|
605
|
-
await pc.setRemoteDescription({ type: "answer", sdp: data["sdp"] });
|
|
606
|
-
await this.flushIce(pc, from);
|
|
607
|
-
} else if (type === "ice-candidate") {
|
|
608
|
-
const candidate = data;
|
|
609
|
-
if (!pc.remoteDescription) {
|
|
610
|
-
const queued = this.pendingIce.get(from) ?? [];
|
|
611
|
-
queued.push(candidate);
|
|
612
|
-
this.pendingIce.set(from, queued);
|
|
613
|
-
} else {
|
|
614
|
-
await pc.addIceCandidate(candidate);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
} catch (err) {
|
|
618
|
-
this.emitError(new Error(`signal (${type}) from ${from} failed: ${String(err)}`));
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
async flushIce(pc, peerId) {
|
|
622
|
-
const queued = this.pendingIce.get(peerId);
|
|
623
|
-
if (!queued?.length) return;
|
|
624
|
-
this.pendingIce.delete(peerId);
|
|
625
|
-
for (const candidate of queued) {
|
|
626
|
-
try {
|
|
627
|
-
await pc.addIceCandidate(candidate);
|
|
628
|
-
} catch {
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
/**
|
|
633
|
-
* Every signal body travels under `data` — the server's
|
|
634
|
-
* `validate_signal_data/1` rejects the push outright when that key is
|
|
635
|
-
* missing or empty, and a rejected signal is never relayed.
|
|
636
|
-
*/
|
|
637
|
-
sendSignal(type, targetUserId, data) {
|
|
638
|
-
this.channel?.push("voice:signal", { type, target_user_id: targetUserId, data });
|
|
639
|
-
}
|
|
640
|
-
// ── speaking detection ─────────────────────────────────────────────
|
|
641
|
-
startSpeakingDetection(stream) {
|
|
642
|
-
const Ctor = globalThis.AudioContext;
|
|
643
|
-
if (!Ctor) return;
|
|
644
|
-
const ctx = new Ctor();
|
|
645
|
-
const source = ctx.createMediaStreamSource(stream);
|
|
646
|
-
const analyser = ctx.createAnalyser();
|
|
647
|
-
analyser.fftSize = 512;
|
|
648
|
-
source.connect(analyser);
|
|
649
|
-
const buf = new Float32Array(analyser.fftSize);
|
|
650
|
-
let speaking = false;
|
|
651
|
-
let lastLoud = 0;
|
|
652
|
-
this.speakingTimer = setInterval(() => {
|
|
653
|
-
analyser.getFloatTimeDomainData(buf);
|
|
654
|
-
let sum = 0;
|
|
655
|
-
for (const v of buf) sum += v * v;
|
|
656
|
-
const rms = Math.sqrt(sum / buf.length);
|
|
657
|
-
const now = Date.now();
|
|
658
|
-
if (!this.muted && rms > SPEAKING_THRESHOLD) lastLoud = now;
|
|
659
|
-
const next = !this.muted && now - lastLoud < SPEAKING_RELEASE_MS;
|
|
660
|
-
if (next === speaking) return;
|
|
661
|
-
speaking = next;
|
|
662
|
-
this.channel?.push("voice:active_speaker", { speaking });
|
|
663
|
-
this.patchParticipant(this.selfId ?? void 0, { speaking });
|
|
664
|
-
}, SPEAKING_POLL_MS);
|
|
665
|
-
this.stopSpeakingDetection = () => {
|
|
666
|
-
void ctx.close().catch(() => {
|
|
667
|
-
});
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
// ── teardown & emit ────────────────────────────────────────────────
|
|
671
|
-
closePeer(peerId) {
|
|
672
|
-
const pc = this.peers.get(peerId);
|
|
673
|
-
if (pc) {
|
|
674
|
-
pc.onicecandidate = null;
|
|
675
|
-
pc.ontrack = null;
|
|
676
|
-
pc.onconnectionstatechange = null;
|
|
677
|
-
pc.close();
|
|
678
|
-
this.peers.delete(peerId);
|
|
679
|
-
}
|
|
680
|
-
this.sinks.get(peerId)?.();
|
|
681
|
-
this.sinks.delete(peerId);
|
|
682
|
-
this.pendingIce.delete(peerId);
|
|
683
|
-
}
|
|
684
|
-
teardown() {
|
|
685
|
-
this.holders = 0;
|
|
686
|
-
for (const peerId of [...this.peers.keys()]) this.closePeer(peerId);
|
|
687
|
-
if (this.speakingTimer) clearInterval(this.speakingTimer);
|
|
688
|
-
this.speakingTimer = null;
|
|
689
|
-
this.stopSpeakingDetection?.();
|
|
690
|
-
this.stopSpeakingDetection = null;
|
|
691
|
-
for (const track of this.localStream?.getTracks() ?? []) track.stop();
|
|
692
|
-
this.localStream = null;
|
|
693
|
-
this.channel?.leave();
|
|
694
|
-
this.channel = null;
|
|
695
|
-
this.selfId = null;
|
|
696
|
-
this.muted = false;
|
|
697
|
-
this.roster.clear();
|
|
698
|
-
this.emitRoster();
|
|
699
|
-
}
|
|
700
|
-
patchParticipant(userId, patch) {
|
|
701
|
-
if (!userId) return;
|
|
702
|
-
const current = this.roster.get(userId);
|
|
703
|
-
if (!current) return;
|
|
704
|
-
this.roster.set(userId, { ...current, ...patch });
|
|
705
|
-
this.emitRoster();
|
|
706
|
-
}
|
|
707
|
-
setStatus(status) {
|
|
708
|
-
if (this.status === status) return;
|
|
709
|
-
this.status = status;
|
|
710
|
-
this.statusListeners.forEach((l) => l(status));
|
|
711
|
-
}
|
|
712
|
-
emitRoster() {
|
|
713
|
-
const snapshot = this.getParticipants();
|
|
714
|
-
this.rosterListeners.forEach((l) => l(snapshot));
|
|
715
|
-
}
|
|
716
|
-
emitError(err) {
|
|
717
|
-
this.errorListeners.forEach((l) => l(err));
|
|
718
|
-
}
|
|
719
|
-
};
|
|
720
|
-
|
|
721
106
|
// src/realtime/realtime.ts
|
|
722
107
|
var PoolseRealtime = class {
|
|
723
108
|
config;
|
|
724
109
|
tokenCache;
|
|
725
110
|
socketPath;
|
|
726
|
-
iceServersProvider;
|
|
727
111
|
wsUrl;
|
|
728
112
|
socket = null;
|
|
729
113
|
conversations = /* @__PURE__ */ new Map();
|
|
730
|
-
voiceRooms = /* @__PURE__ */ new Map();
|
|
731
114
|
userChannel = null;
|
|
732
|
-
callsResource = null;
|
|
733
115
|
status = "idle";
|
|
734
116
|
statusListeners = /* @__PURE__ */ new Set();
|
|
735
117
|
constructor(config, tokenCache, opts = {}) {
|
|
736
118
|
this.config = config;
|
|
737
119
|
this.tokenCache = tokenCache;
|
|
738
120
|
this.socketPath = opts.socketPath ?? "/socket";
|
|
739
|
-
this.iceServersProvider = opts.iceServersProvider ?? null;
|
|
740
121
|
this.wsUrl = opts.wsUrl ?? deriveWsUrl(config.apiUrl);
|
|
741
122
|
}
|
|
742
123
|
/** Current connection status. */
|
|
@@ -800,8 +181,6 @@ var PoolseRealtime = class {
|
|
|
800
181
|
}
|
|
801
182
|
/** Close the socket and tear down every joined channel. */
|
|
802
183
|
disconnect() {
|
|
803
|
-
for (const room of this.voiceRooms.values()) room.leave();
|
|
804
|
-
this.voiceRooms.clear();
|
|
805
184
|
this.setStatus("closed");
|
|
806
185
|
this.conversations.forEach((c) => c._destroy());
|
|
807
186
|
this.conversations.clear();
|
|
@@ -846,42 +225,6 @@ var PoolseRealtime = class {
|
|
|
846
225
|
handle._join();
|
|
847
226
|
return handle;
|
|
848
227
|
}
|
|
849
|
-
/**
|
|
850
|
-
* Voice room for a conversation — the Discord-style surface. Call
|
|
851
|
-
* `join()` on the returned handle to acquire the mic and connect;
|
|
852
|
-
* reusing the same id returns the same room rather than opening a
|
|
853
|
-
* second one.
|
|
854
|
-
*
|
|
855
|
-
* Ringing somebody who hasn't joined is a separate concern; see
|
|
856
|
-
* `poolse.calls`.
|
|
857
|
-
*/
|
|
858
|
-
voice(conversationId, opts = {}) {
|
|
859
|
-
const existing = this.voiceRooms.get(conversationId);
|
|
860
|
-
if (existing) return existing;
|
|
861
|
-
this.connect();
|
|
862
|
-
if (!this.socket) {
|
|
863
|
-
throw new PoolseError("socket not initialised \u2014 call connect() first");
|
|
864
|
-
}
|
|
865
|
-
const room = new VoiceRoom(conversationId, this.socket, {
|
|
866
|
-
...this.iceServersProvider ? { iceServersProvider: this.iceServersProvider } : {},
|
|
867
|
-
...opts
|
|
868
|
-
});
|
|
869
|
-
this.voiceRooms.set(conversationId, room);
|
|
870
|
-
return room;
|
|
871
|
-
}
|
|
872
|
-
/**
|
|
873
|
-
* Call invitations for a user — the WhatsApp-style surface. Rides the
|
|
874
|
-
* `user:<id>` topic, the one channel a client is always joined to, so
|
|
875
|
-
* a ring reaches somebody who hasn't opened a voice room yet.
|
|
876
|
-
*
|
|
877
|
-
* Takes the user id explicitly, mirroring `user(userId)`; the SDK
|
|
878
|
-
* never assumes whose token it is holding.
|
|
879
|
-
*/
|
|
880
|
-
calls(userId) {
|
|
881
|
-
if (this.callsResource) return this.callsResource;
|
|
882
|
-
this.callsResource = new CallsResource(() => this.user(userId)._channel());
|
|
883
|
-
return this.callsResource;
|
|
884
|
-
}
|
|
885
228
|
/** Drop a conversation handle and leave the channel. */
|
|
886
229
|
leave(conversationId) {
|
|
887
230
|
const handle = this.conversations.get(conversationId);
|
|
@@ -1034,8 +377,9 @@ var UserChannel = class {
|
|
|
1034
377
|
this.channel = channel;
|
|
1035
378
|
}
|
|
1036
379
|
/**
|
|
1037
|
-
* The underlying Phoenix channel, for
|
|
1038
|
-
*
|
|
380
|
+
* The underlying Phoenix channel, for hosts that listen to events the
|
|
381
|
+
* handle has no method for (a native call host forwards
|
|
382
|
+
* `call:ring_ended` / `call:finished` to its call core).
|
|
1039
383
|
*
|
|
1040
384
|
* @internal
|
|
1041
385
|
*/
|
|
@@ -1814,8 +1158,7 @@ var CallRoom = class {
|
|
|
1814
1158
|
* livekit-client does NOT play remote audio for you on the web — that
|
|
1815
1159
|
* is what `@livekit/components-react`'s `<RoomAudioRenderer />` exists
|
|
1816
1160
|
* to do. Without this a call connects, the roster is right, video
|
|
1817
|
-
* flows, and nobody hears anything.
|
|
1818
|
-
* this (see `webrtc-browser.ts`); the SFU path has to as well.
|
|
1161
|
+
* flows, and nobody hears anything.
|
|
1819
1162
|
*
|
|
1820
1163
|
* Empty on React Native, where there is no DOM and LiveKit routes
|
|
1821
1164
|
* audio through the native audio session instead.
|
|
@@ -2230,22 +1573,6 @@ var CallRoom = class {
|
|
|
2230
1573
|
}
|
|
2231
1574
|
};
|
|
2232
1575
|
|
|
2233
|
-
// src/resources/ice-servers.ts
|
|
2234
|
-
var IceServersResource = class {
|
|
2235
|
-
constructor(client) {
|
|
2236
|
-
this.client = client;
|
|
2237
|
-
}
|
|
2238
|
-
client;
|
|
2239
|
-
/** GET /v1/ice-servers */
|
|
2240
|
-
list(signal) {
|
|
2241
|
-
return this.client.request({
|
|
2242
|
-
method: "GET",
|
|
2243
|
-
path: "/v1/ice-servers",
|
|
2244
|
-
...signal ? { signal } : {}
|
|
2245
|
-
});
|
|
2246
|
-
}
|
|
2247
|
-
};
|
|
2248
|
-
|
|
2249
1576
|
// src/rest-client.ts
|
|
2250
1577
|
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET"]);
|
|
2251
1578
|
var RestClient = class {
|
|
@@ -2501,8 +1828,6 @@ var Poolse = class {
|
|
|
2501
1828
|
* `config.wsUrl`.
|
|
2502
1829
|
*/
|
|
2503
1830
|
realtime;
|
|
2504
|
-
/** STUN/TURN servers for WebRTC — see `IceServersResource`. */
|
|
2505
|
-
iceServers;
|
|
2506
1831
|
/** SFU credentials for a call's media — see `CallTokensResource`. */
|
|
2507
1832
|
callTokens;
|
|
2508
1833
|
/** Whether a call is running on a conversation — for a Join banner. */
|
|
@@ -2525,17 +1850,12 @@ var Poolse = class {
|
|
|
2525
1850
|
this.messages = new MessagesResource(this.rest);
|
|
2526
1851
|
this.attachments = new AttachmentsResource(this.rest, cachedConfig.fetch);
|
|
2527
1852
|
this.users = new UsersResource(cachedConfig);
|
|
2528
|
-
this.iceServers = new IceServersResource(this.rest);
|
|
2529
1853
|
this.callTokens = new CallTokensResource(this.rest);
|
|
2530
1854
|
this.liveCalls = new LiveCallsResource(this.rest);
|
|
2531
1855
|
this.rooms = new RoomsResource(this.rest);
|
|
2532
1856
|
this.realtime = new PoolseRealtime(cachedConfig, this.tokenCache, {
|
|
2533
1857
|
...this.resolved.wsUrl !== void 0 ? { wsUrl: this.resolved.wsUrl } : {},
|
|
2534
|
-
socketPath: this.resolved.socketPath
|
|
2535
|
-
// Re-fetched on every room join rather than cached here: TURN
|
|
2536
|
-
// credentials expire, and a stale one is rejected silently — the
|
|
2537
|
-
// call connects and carries no media.
|
|
2538
|
-
iceServersProvider: async () => (await this.iceServers.list()).ice_servers
|
|
1858
|
+
socketPath: this.resolved.socketPath
|
|
2539
1859
|
});
|
|
2540
1860
|
}
|
|
2541
1861
|
/**
|
|
@@ -2571,7 +1891,7 @@ var Poolse = class {
|
|
|
2571
1891
|
};
|
|
2572
1892
|
|
|
2573
1893
|
// src/version.ts
|
|
2574
|
-
var version = "
|
|
1894
|
+
var version = "3.0.0";
|
|
2575
1895
|
|
|
2576
1896
|
// src/call-log.ts
|
|
2577
1897
|
function parseCallLogBody(body) {
|
|
@@ -2736,6 +2056,6 @@ function formatCallLogPreview(preview, currentUserId) {
|
|
|
2736
2056
|
return "Call";
|
|
2737
2057
|
}
|
|
2738
2058
|
|
|
2739
|
-
export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallRoom, CallTokensResource,
|
|
2059
|
+
export { ApiError, AttachmentHandle, AttachmentsResource, AuthError, CallRoom, CallTokensResource, ConversationChannel, ConversationHandle, ConversationMessages, ConversationsResource, DevicesResource, LiveCallsResource, MeResource, MessageHandle, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, PoolseError, PoolseRealtime, RateLimitedError, RoomsResource, UserChannel, UsersResource, callLogDisplayFor, describeCallLog, formatCallDuration, formatCallLogPreview, isCallLogMessage, isMessageVisibleTo, parseCallLog, parseCallLogBody, safeUuid, version };
|
|
2740
2060
|
//# sourceMappingURL=index.js.map
|
|
2741
2061
|
//# sourceMappingURL=index.js.map
|