@stoatx/voice 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +9 -2
- package/dist/index.cjs +233 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +166 -0
- package/dist/index.d.ts +166 -0
- package/dist/index.js +205 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stoatx
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @stoatx/voice
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@stoatx/voice)
|
|
4
|
+
[](https://www.typescriptlang.org/)
|
|
5
|
+
|
|
6
|
+
The shared voice connection and manager behind [`@stoatx/voice-node`](https://www.npmjs.com/package/@stoatx/voice-node) and [`@stoatx/voice-browser`](https://www.npmjs.com/package/@stoatx/voice-browser). You don't need to install it yourself: install the package for your platform instead.
|
|
7
|
+
|
|
8
|
+
## License
|
|
9
|
+
|
|
10
|
+
MIT © [Stoatx / Stoatx Team]
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
BaseVoiceConnection: () => BaseVoiceConnection,
|
|
24
|
+
BaseVoiceManager: () => BaseVoiceManager
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
|
|
28
|
+
// src/VoiceConnection.ts
|
|
29
|
+
var import_events = require("events");
|
|
30
|
+
var BaseVoiceConnection = class extends import_events.EventEmitter {
|
|
31
|
+
/** The voice channel's ID. */
|
|
32
|
+
channelId;
|
|
33
|
+
/** The ID of the server the channel is in, or `null` for DMs and groups. */
|
|
34
|
+
serverId;
|
|
35
|
+
_status = "connecting";
|
|
36
|
+
/**
|
|
37
|
+
* @param channelId The voice channel's ID.
|
|
38
|
+
* @param serverId The ID of the server the channel is in, or `null` for DMs and groups.
|
|
39
|
+
*/
|
|
40
|
+
constructor(channelId, serverId) {
|
|
41
|
+
super();
|
|
42
|
+
this.channelId = channelId;
|
|
43
|
+
this.serverId = serverId;
|
|
44
|
+
}
|
|
45
|
+
/** Where the connection is in its lifecycle. */
|
|
46
|
+
get status() {
|
|
47
|
+
return this._status;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Carries over state from the connection this one replaces when the server moves the user,
|
|
51
|
+
* e.g. the audio player or microphone. Does nothing by default.
|
|
52
|
+
* @param _previous The connection being replaced.
|
|
53
|
+
* @internal
|
|
54
|
+
*/
|
|
55
|
+
async _takeOver(_previous) {
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Emits a base connection event. Subclasses call this instead of `emit()`, whose types can't
|
|
59
|
+
* be checked against the generic `Events`.
|
|
60
|
+
* @param event The event name.
|
|
61
|
+
* @param args The event's arguments.
|
|
62
|
+
*/
|
|
63
|
+
emitBase(event, ...args) {
|
|
64
|
+
import_events.EventEmitter.prototype.emit.call(this, event, ...args);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Emits `error` if anyone listens, so a failure inside the connection can't crash the process.
|
|
68
|
+
* @param error The error.
|
|
69
|
+
*/
|
|
70
|
+
/** @internal */
|
|
71
|
+
_reportError(error) {
|
|
72
|
+
this.reportError(error);
|
|
73
|
+
}
|
|
74
|
+
reportError(error) {
|
|
75
|
+
if (this.listenerCount("error") === 0) return;
|
|
76
|
+
this.emitBase("error", error instanceof Error ? error : new Error(String(error)));
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// src/VoiceManager.ts
|
|
81
|
+
var BaseVoiceManager = class {
|
|
82
|
+
/** The client the calls are joined with. */
|
|
83
|
+
client;
|
|
84
|
+
connections = /* @__PURE__ */ new Map();
|
|
85
|
+
pending = /* @__PURE__ */ new Map();
|
|
86
|
+
createConnection;
|
|
87
|
+
nodes = null;
|
|
88
|
+
/**
|
|
89
|
+
* @param client The client to join calls with.
|
|
90
|
+
* @param createConnection Creates the platform's connection for a channel.
|
|
91
|
+
*/
|
|
92
|
+
constructor(client, createConnection) {
|
|
93
|
+
this.client = client;
|
|
94
|
+
this.createConnection = createConnection;
|
|
95
|
+
client.on("logout", () => void this.leaveAll());
|
|
96
|
+
client.on("voiceMoveRequest", (move) => void this.handleMove(move));
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Fetches the instance's voice servers. Cached after the first call.
|
|
100
|
+
* @returns The nodes, empty if the instance has voice turned off.
|
|
101
|
+
*/
|
|
102
|
+
async fetchNodes() {
|
|
103
|
+
this.nodes ??= this.client.rest.get("/").then(
|
|
104
|
+
(config) => (config.features.livekit?.nodes ?? []).map((node) => ({
|
|
105
|
+
name: node.name,
|
|
106
|
+
url: node.public_url,
|
|
107
|
+
latitude: node.lat,
|
|
108
|
+
longitude: node.lon
|
|
109
|
+
})),
|
|
110
|
+
(error) => {
|
|
111
|
+
this.nodes = null;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
);
|
|
115
|
+
return this.nodes;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Joins a voice channel's call. Joining a channel the client is already in returns the existing
|
|
119
|
+
* connection, and joining while a join is in progress waits for it.
|
|
120
|
+
* @param channel The voice channel, DM or group, or its ID.
|
|
121
|
+
* @param options Whether to disconnect other devices, who to ring, and which voice node to use.
|
|
122
|
+
* Ignored when the client is already in the call.
|
|
123
|
+
* @returns The connection, once it's ready.
|
|
124
|
+
* @throws {StoatAPIError} If the API refuses, e.g. `MissingPermission` without the Connect permission.
|
|
125
|
+
* @example
|
|
126
|
+
* const connection = await voice.join(channel);
|
|
127
|
+
* connection.on("disconnect", () => console.log("Left the call"));
|
|
128
|
+
*/
|
|
129
|
+
async join(channel, options = {}) {
|
|
130
|
+
const channelId = this.resolveId(channel);
|
|
131
|
+
const existing = this.connections.get(channelId);
|
|
132
|
+
if (existing?.status === "ready") return existing;
|
|
133
|
+
const inFlight = this.pending.get(channelId);
|
|
134
|
+
if (inFlight) return inFlight;
|
|
135
|
+
const attempt = this.connect(channelId, options).finally(() => this.pending.delete(channelId));
|
|
136
|
+
this.pending.set(channelId, attempt);
|
|
137
|
+
return attempt;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Gets the connection to a channel's call.
|
|
141
|
+
* @param channel The channel or its ID.
|
|
142
|
+
* @returns The connection, or `undefined` if the client isn't in that call.
|
|
143
|
+
*/
|
|
144
|
+
get(channel) {
|
|
145
|
+
return this.connections.get(this.resolveId(channel));
|
|
146
|
+
}
|
|
147
|
+
/** Every call the client is in, by channel ID. */
|
|
148
|
+
get cache() {
|
|
149
|
+
return this.connections;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Leaves a channel's call. Does nothing if the client isn't in it.
|
|
153
|
+
* @param channel The channel or its ID.
|
|
154
|
+
*/
|
|
155
|
+
async leave(channel) {
|
|
156
|
+
await this.connections.get(this.resolveId(channel))?.disconnect();
|
|
157
|
+
}
|
|
158
|
+
/** Leaves every call. */
|
|
159
|
+
async leaveAll() {
|
|
160
|
+
await Promise.all([...this.connections.values()].map((connection) => connection.disconnect()));
|
|
161
|
+
}
|
|
162
|
+
async connect(channelId, options) {
|
|
163
|
+
const body = {};
|
|
164
|
+
if (options.forceDisconnect !== void 0) body.force_disconnect = options.forceDisconnect;
|
|
165
|
+
if (options.recipients !== void 0) {
|
|
166
|
+
body.recipients = options.recipients.map((user) => this.client.users.resolveId(user));
|
|
167
|
+
}
|
|
168
|
+
if (options.node !== void 0) body.node = options.node;
|
|
169
|
+
const { token, url } = await this.client.rest.post(`/channels/${channelId}/join_call`, body);
|
|
170
|
+
const cached = this.client.channels.cache.get(channelId);
|
|
171
|
+
const connection = this.createConnection(channelId, cached?.serverId ?? null);
|
|
172
|
+
try {
|
|
173
|
+
await connection.connect(url, token);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
await connection.disconnect().catch(() => {
|
|
176
|
+
});
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
const previous = this.connections.get(channelId);
|
|
180
|
+
if (previous && previous !== connection) await previous.disconnect().catch(() => {
|
|
181
|
+
});
|
|
182
|
+
this.track(channelId, connection);
|
|
183
|
+
return connection;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Caches a connection until it disconnects.
|
|
187
|
+
* @param channelId The call's channel ID.
|
|
188
|
+
* @param connection The connection.
|
|
189
|
+
*/
|
|
190
|
+
track(channelId, connection) {
|
|
191
|
+
this.connections.set(channelId, connection);
|
|
192
|
+
connection.once("disconnect", () => {
|
|
193
|
+
if (this.connections.get(channelId) === connection) this.connections.delete(channelId);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Follows the server moving the user to another call: connects there, carries the state over,
|
|
198
|
+
* then leaves the old call. Errors are emitted on the old connection.
|
|
199
|
+
* @param move The move request from the gateway.
|
|
200
|
+
*/
|
|
201
|
+
async handleMove(move) {
|
|
202
|
+
const previous = this.connections.get(move.fromChannelId);
|
|
203
|
+
if (!previous) return;
|
|
204
|
+
try {
|
|
205
|
+
const node = (await this.fetchNodes()).find((candidate) => candidate.name === move.node);
|
|
206
|
+
if (!node) throw new Error(`VOICE_NODE_UNKNOWN: The server moved the call to unknown voice node "${move.node}".`);
|
|
207
|
+
const cached = this.client.channels.cache.get(move.toChannelId);
|
|
208
|
+
const connection = this.createConnection(move.toChannelId, cached?.serverId ?? null);
|
|
209
|
+
try {
|
|
210
|
+
await connection.connect(node.url, move.token);
|
|
211
|
+
await connection._takeOver(previous);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
await connection.disconnect().catch(() => {
|
|
214
|
+
});
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
this.track(move.toChannelId, connection);
|
|
218
|
+
previous.emit("move", connection);
|
|
219
|
+
await previous.disconnect();
|
|
220
|
+
} catch (error) {
|
|
221
|
+
previous._reportError(error);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
resolveId(channel) {
|
|
225
|
+
return typeof channel === "string" ? channel : channel.id;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
229
|
+
0 && (module.exports = {
|
|
230
|
+
BaseVoiceConnection,
|
|
231
|
+
BaseVoiceManager
|
|
232
|
+
});
|
|
233
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/VoiceConnection.ts","../src/VoiceManager.ts"],"sourcesContent":["export { BaseVoiceConnection } from \"./VoiceConnection\";\nexport type { VoiceConnectionEvents, VoiceConnectionStatus } from \"./VoiceConnection\";\nexport { BaseVoiceManager } from \"./VoiceManager\";\nexport type { VoiceChannelResolvable, VoiceConnectionFactory, VoiceJoinOptions, VoiceNode } from \"./VoiceManager\";\n","import { EventEmitter } from \"events\";\n\n/** Where a voice connection is in its lifecycle. */\nexport type VoiceConnectionStatus = \"connecting\" | \"ready\" | \"disconnecting\" | \"disconnected\";\n\n/** Events every voice connection emits. Platform packages add their own. */\nexport interface VoiceConnectionEvents {\n /** Connected to the call. */\n ready: [];\n /** Left the call, or the connection was lost. */\n disconnect: [];\n /** Something went wrong while connected, e.g. sending audio failed. */\n error: [error: Error];\n /**\n * The server moved the user to another call, e.g. a moderator dragged them. This connection\n * disconnects right after; use the new one from now on. It already plays the same audio\n * (Node.js) or keeps the microphone and deafen state (browser).\n */\n move: [connection: BaseVoiceConnection];\n}\n\n/**\n * A connection to one voice channel. `@stoatx/voice-node` and `@stoatx/voice-browser` provide the\n * implementations; get one from their `VoiceManager.join()`.\n */\nexport abstract class BaseVoiceConnection<\n Events extends VoiceConnectionEvents & Record<keyof Events, any[]> = VoiceConnectionEvents,\n> extends EventEmitter<Events> {\n /** The voice channel's ID. */\n public readonly channelId: string;\n /** The ID of the server the channel is in, or `null` for DMs and groups. */\n public readonly serverId: string | null;\n\n protected _status: VoiceConnectionStatus = \"connecting\";\n\n /**\n * @param channelId The voice channel's ID.\n * @param serverId The ID of the server the channel is in, or `null` for DMs and groups.\n */\n constructor(channelId: string, serverId: string | null) {\n super();\n this.channelId = channelId;\n this.serverId = serverId;\n }\n\n /** Where the connection is in its lifecycle. */\n public get status(): VoiceConnectionStatus {\n return this._status;\n }\n\n /**\n * Connects to the call's LiveKit room. Called by `VoiceManager.join()`.\n * @param url The LiveKit server URL.\n * @param token The token from `join_call`.\n * @internal\n */\n public abstract connect(url: string, token: string): Promise<void>;\n\n /** Leaves the call. */\n public abstract disconnect(): Promise<void>;\n\n /**\n * Carries over state from the connection this one replaces when the server moves the user,\n * e.g. the audio player or microphone. Does nothing by default.\n * @param _previous The connection being replaced.\n * @internal\n */\n public async _takeOver(_previous: this): Promise<void> {}\n\n /**\n * Emits a base connection event. Subclasses call this instead of `emit()`, whose types can't\n * be checked against the generic `Events`.\n * @param event The event name.\n * @param args The event's arguments.\n */\n protected emitBase<E extends keyof VoiceConnectionEvents>(event: E, ...args: VoiceConnectionEvents[E]): void {\n EventEmitter.prototype.emit.call(this, event, ...args);\n }\n\n /**\n * Emits `error` if anyone listens, so a failure inside the connection can't crash the process.\n * @param error The error.\n */\n /** @internal */\n public _reportError(error: unknown): void {\n this.reportError(error);\n }\n\n protected reportError(error: unknown): void {\n if (this.listenerCount(\"error\") === 0) return;\n this.emitBase(\"error\", error instanceof Error ? error : new Error(String(error)));\n }\n}\n","import type { BaseChannel, Client, UserResolvable, VoiceMoveRequest } from \"@stoatx/client\";\nimport type { BaseVoiceConnection } from \"./VoiceConnection\";\n\n/** A voice channel, DM or group, or its ID. */\nexport type VoiceChannelResolvable = BaseChannel | string;\n\n/** Options for {@link BaseVoiceManager.join}. */\nexport interface VoiceJoinOptions {\n /**\n * Disconnect the user's other voice connections first, e.g. a call they're in on another device.\n */\n forceDisconnect?: boolean;\n /**\n * Who to notify when starting a call in a DM or group. Only used when nobody is in the call yet.\n */\n recipients?: UserResolvable[];\n /** The voice node to use, by name from {@link BaseVoiceManager.fetchNodes}. Defaults to the server's choice. */\n node?: string;\n}\n\n/** A voice server of the instance, from {@link BaseVoiceManager.fetchNodes}. */\nexport interface VoiceNode {\n /** The node's name, for {@link VoiceJoinOptions.node}. */\n name: string;\n /** The LiveKit URL clients connect to. */\n url: string;\n /** Where the node is, to pick the nearest one. */\n latitude: number;\n longitude: number;\n}\n\n/**\n * Creates a platform's connection for a channel.\n * @param channelId The voice channel's ID.\n * @param serverId The ID of the server the channel is in, or `null` for DMs and groups.\n */\nexport type VoiceConnectionFactory<C extends BaseVoiceConnection> = (channelId: string, serverId: string | null) => C;\n\n/**\n * Joins and tracks voice calls, one connection per channel. Use the `VoiceManager` from\n * `@stoatx/voice-node` or `@stoatx/voice-browser`, which extend this with their connection type.\n */\nexport class BaseVoiceManager<C extends BaseVoiceConnection = BaseVoiceConnection> {\n /** The client the calls are joined with. */\n public readonly client: Client;\n\n private readonly connections = new Map<string, C>();\n private readonly pending = new Map<string, Promise<C>>();\n private readonly createConnection: VoiceConnectionFactory<C>;\n private nodes: Promise<VoiceNode[]> | null = null;\n\n /**\n * @param client The client to join calls with.\n * @param createConnection Creates the platform's connection for a channel.\n */\n constructor(client: Client, createConnection: VoiceConnectionFactory<C>) {\n this.client = client;\n this.createConnection = createConnection;\n // A logged-out client can't stay in calls: its token is gone.\n client.on(\"logout\", () => void this.leaveAll());\n client.on(\"voiceMoveRequest\", (move) => void this.handleMove(move));\n }\n\n /**\n * Fetches the instance's voice servers. Cached after the first call.\n * @returns The nodes, empty if the instance has voice turned off.\n */\n public async fetchNodes(): Promise<VoiceNode[]> {\n this.nodes ??= this.client.rest.get(\"/\").then(\n (config) =>\n (config.features.livekit?.nodes ?? []).map((node) => ({\n name: node.name,\n url: node.public_url,\n latitude: node.lat,\n longitude: node.lon,\n })),\n (error: unknown) => {\n this.nodes = null;\n throw error;\n },\n );\n return this.nodes;\n }\n\n /**\n * Joins a voice channel's call. Joining a channel the client is already in returns the existing\n * connection, and joining while a join is in progress waits for it.\n * @param channel The voice channel, DM or group, or its ID.\n * @param options Whether to disconnect other devices, who to ring, and which voice node to use.\n * Ignored when the client is already in the call.\n * @returns The connection, once it's ready.\n * @throws {StoatAPIError} If the API refuses, e.g. `MissingPermission` without the Connect permission.\n * @example\n * const connection = await voice.join(channel);\n * connection.on(\"disconnect\", () => console.log(\"Left the call\"));\n */\n public async join(channel: VoiceChannelResolvable, options: VoiceJoinOptions = {}): Promise<C> {\n const channelId = this.resolveId(channel);\n\n const existing = this.connections.get(channelId);\n if (existing?.status === \"ready\") return existing;\n\n const inFlight = this.pending.get(channelId);\n if (inFlight) return inFlight;\n\n const attempt = this.connect(channelId, options).finally(() => this.pending.delete(channelId));\n this.pending.set(channelId, attempt);\n return attempt;\n }\n\n /**\n * Gets the connection to a channel's call.\n * @param channel The channel or its ID.\n * @returns The connection, or `undefined` if the client isn't in that call.\n */\n public get(channel: VoiceChannelResolvable): C | undefined {\n return this.connections.get(this.resolveId(channel));\n }\n\n /** Every call the client is in, by channel ID. */\n public get cache(): ReadonlyMap<string, C> {\n return this.connections;\n }\n\n /**\n * Leaves a channel's call. Does nothing if the client isn't in it.\n * @param channel The channel or its ID.\n */\n public async leave(channel: VoiceChannelResolvable): Promise<void> {\n await this.connections.get(this.resolveId(channel))?.disconnect();\n }\n\n /** Leaves every call. */\n public async leaveAll(): Promise<void> {\n await Promise.all([...this.connections.values()].map((connection) => connection.disconnect()));\n }\n\n private async connect(channelId: string, options: VoiceJoinOptions): Promise<C> {\n const body: { force_disconnect?: boolean; recipients?: string[]; node?: string } = {};\n if (options.forceDisconnect !== undefined) body.force_disconnect = options.forceDisconnect;\n if (options.recipients !== undefined) {\n body.recipients = options.recipients.map((user) => this.client.users.resolveId(user));\n }\n if (options.node !== undefined) body.node = options.node;\n\n const { token, url } = await this.client.rest.post(`/channels/${channelId}/join_call`, body);\n\n const cached = this.client.channels.cache.get(channelId) as { serverId?: string } | undefined;\n const connection = this.createConnection(channelId, cached?.serverId ?? null);\n\n try {\n await connection.connect(url, token);\n } catch (error) {\n // Release the room so a failed join doesn't leak it.\n await connection.disconnect().catch(() => {});\n throw error;\n }\n\n const previous = this.connections.get(channelId);\n if (previous && previous !== connection) await previous.disconnect().catch(() => {});\n\n this.track(channelId, connection);\n return connection;\n }\n\n /**\n * Caches a connection until it disconnects.\n * @param channelId The call's channel ID.\n * @param connection The connection.\n */\n private track(channelId: string, connection: C): void {\n this.connections.set(channelId, connection);\n (connection as BaseVoiceConnection).once(\"disconnect\", () => {\n // Only remove the entry if it still belongs to this connection.\n if (this.connections.get(channelId) === connection) this.connections.delete(channelId);\n });\n }\n\n /**\n * Follows the server moving the user to another call: connects there, carries the state over,\n * then leaves the old call. Errors are emitted on the old connection.\n * @param move The move request from the gateway.\n */\n private async handleMove(move: VoiceMoveRequest): Promise<void> {\n const previous = this.connections.get(move.fromChannelId);\n if (!previous) return;\n\n try {\n const node = (await this.fetchNodes()).find((candidate) => candidate.name === move.node);\n if (!node) throw new Error(`VOICE_NODE_UNKNOWN: The server moved the call to unknown voice node \"${move.node}\".`);\n\n const cached = this.client.channels.cache.get(move.toChannelId) as { serverId?: string } | undefined;\n const connection = this.createConnection(move.toChannelId, cached?.serverId ?? null);\n try {\n await connection.connect(node.url, move.token);\n await connection._takeOver(previous);\n } catch (error) {\n await connection.disconnect().catch(() => {});\n throw error;\n }\n\n this.track(move.toChannelId, connection);\n (previous as BaseVoiceConnection).emit(\"move\", connection);\n await previous.disconnect();\n } catch (error) {\n previous._reportError(error);\n }\n }\n\n private resolveId(channel: VoiceChannelResolvable): string {\n return typeof channel === \"string\" ? channel : channel.id;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA6B;AAyBtB,IAAe,sBAAf,cAEG,2BAAqB;AAAA;AAAA,EAEb;AAAA;AAAA,EAEA;AAAA,EAEN,UAAiC;AAAA;AAAA;AAAA;AAAA;AAAA,EAM3C,YAAY,WAAmB,UAAyB;AACtD,UAAM;AACN,SAAK,YAAY;AACjB,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA,EAGA,IAAW,SAAgC;AACzC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBA,MAAa,UAAU,WAAgC;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ9C,SAAgD,UAAa,MAAsC;AAC3G,+BAAa,UAAU,KAAK,KAAK,MAAM,OAAO,GAAG,IAAI;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,aAAa,OAAsB;AACxC,SAAK,YAAY,KAAK;AAAA,EACxB;AAAA,EAEU,YAAY,OAAsB;AAC1C,QAAI,KAAK,cAAc,OAAO,MAAM,EAAG;AACvC,SAAK,SAAS,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,EAClF;AACF;;;AClDO,IAAM,mBAAN,MAA4E;AAAA;AAAA,EAEjE;AAAA,EAEC,cAAc,oBAAI,IAAe;AAAA,EACjC,UAAU,oBAAI,IAAwB;AAAA,EACtC;AAAA,EACT,QAAqC;AAAA;AAAA;AAAA;AAAA;AAAA,EAM7C,YAAY,QAAgB,kBAA6C;AACvE,SAAK,SAAS;AACd,SAAK,mB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AAI,KAAK,YAAY,IAAI,SAAS,MAAM,WAAY,MAAK,YAAY,OAAO,SAAS;AAAA,IACvF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,WAAW,MAAuC;AAC9D,UAAM,WAAW,KAAK,YAAY,IAAI,KAAK,aAAa;AACxD,QAAI,CAAC,SAAU;AAEf,QAAI;AACF,YAAM,QAAQ,MAAM,KAAK,WAAW,GAAG,KAAK,CAAC,cAAc,UAAU,SAAS,KAAK,IAAI;AACvF,UAAI,CAAC,KAAM,OAAM,IAAI,MAAM,wEAAwE,KAAK,IAAI,IAAI;AAEhH,YAAM,SAAS,KAAK,OAAO,SAAS,MAAM,IAAI,KAAK,WAAW;AAC9D,YAAM,aAAa,KAAK,iBAAiB,KAAK,aAAa,QAAQ,YAAY,IAAI;AACnF,UAAI;AACF,cAAM,WAAW,QAAQ,KAAK,KAAK,KAAK,KAAK;AAC7C,cAAM,WAAW,UAAU,QAAQ;AAAA,MACrC,SAAS,OAAO;AACd,cAAM,WAAW,WAAW,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AAC5C,cAAM;AAAA,MACR;AAEA,WAAK,MAAM,KAAK,aAAa,UAAU;AACvC,MAAC,SAAiC,KAAK,QAAQ,UAAU;AACzD,YAAM,SAAS,WAAW;AAAA,IAC5B,SAAS,OAAO;AACd,eAAS,aAAa,KAAK;AAAA,IAC7B;AAAA,EACF;AAAA,EAEQ,UAAU,SAAyC;AACzD,WAAO,OAAO,YAAY,WAAW,UAAU,QAAQ;AAAA,EACzD;AACF;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
import { Client, BaseChannel, UserResolvable } from '@stoatx/client';
|
|
3
|
+
|
|
4
|
+
/** Where a voice connection is in its lifecycle. */
|
|
5
|
+
type VoiceConnectionStatus = "connecting" | "ready" | "disconnecting" | "disconnected";
|
|
6
|
+
/** Events every voice connection emits. Platform packages add their own. */
|
|
7
|
+
interface VoiceConnectionEvents {
|
|
8
|
+
/** Connected to the call. */
|
|
9
|
+
ready: [];
|
|
10
|
+
/** Left the call, or the connection was lost. */
|
|
11
|
+
disconnect: [];
|
|
12
|
+
/** Something went wrong while connected, e.g. sending audio failed. */
|
|
13
|
+
error: [error: Error];
|
|
14
|
+
/**
|
|
15
|
+
* The server moved the user to another call, e.g. a moderator dragged them. This connection
|
|
16
|
+
* disconnects right after; use the new one from now on. It already plays the same audio
|
|
17
|
+
* (Node.js) or keeps the microphone and deafen state (browser).
|
|
18
|
+
*/
|
|
19
|
+
move: [connection: BaseVoiceConnection];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A connection to one voice channel. `@stoatx/voice-node` and `@stoatx/voice-browser` provide the
|
|
23
|
+
* implementations; get one from their `VoiceManager.join()`.
|
|
24
|
+
*/
|
|
25
|
+
declare abstract class BaseVoiceConnection<Events extends VoiceConnectionEvents & Record<keyof Events, any[]> = VoiceConnectionEvents> extends EventEmitter<Events> {
|
|
26
|
+
/** The voice channel's ID. */
|
|
27
|
+
readonly channelId: string;
|
|
28
|
+
/** The ID of the server the channel is in, or `null` for DMs and groups. */
|
|
29
|
+
readonly serverId: string | null;
|
|
30
|
+
protected _status: VoiceConnectionStatus;
|
|
31
|
+
/**
|
|
32
|
+
* @param channelId The voice channel's ID.
|
|
33
|
+
* @param serverId The ID of the server the channel is in, or `null` for DMs and groups.
|
|
34
|
+
*/
|
|
35
|
+
constructor(channelId: string, serverId: string | null);
|
|
36
|
+
/** Where the connection is in its lifecycle. */
|
|
37
|
+
get status(): VoiceConnectionStatus;
|
|
38
|
+
/**
|
|
39
|
+
* Connects to the call's LiveKit room. Called by `VoiceManager.join()`.
|
|
40
|
+
* @param url The LiveKit server URL.
|
|
41
|
+
* @param token The token from `join_call`.
|
|
42
|
+
* @internal
|
|
43
|
+
*/
|
|
44
|
+
abstract connect(url: string, token: string): Promise<void>;
|
|
45
|
+
/** Leaves the call. */
|
|
46
|
+
abstract disconnect(): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Carries over state from the connection this one replaces when the server moves the user,
|
|
49
|
+
* e.g. the audio player or microphone. Does nothing by default.
|
|
50
|
+
* @param _previous The connection being replaced.
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
_takeOver(_previous: this): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Emits a base connection event. Subclasses call this instead of `emit()`, whose types can't
|
|
56
|
+
* be checked against the generic `Events`.
|
|
57
|
+
* @param event The event name.
|
|
58
|
+
* @param args The event's arguments.
|
|
59
|
+
*/
|
|
60
|
+
protected emitBase<E extends keyof VoiceConnectionEvents>(event: E, ...args: VoiceConnectionEvents[E]): void;
|
|
61
|
+
/**
|
|
62
|
+
* Emits `error` if anyone listens, so a failure inside the connection can't crash the process.
|
|
63
|
+
* @param error The error.
|
|
64
|
+
*/
|
|
65
|
+
/** @internal */
|
|
66
|
+
_reportError(error: unknown): void;
|
|
67
|
+
protected reportError(error: unknown): void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A voice channel, DM or group, or its ID. */
|
|
71
|
+
type VoiceChannelResolvable = BaseChannel | string;
|
|
72
|
+
/** Options for {@link BaseVoiceManager.join}. */
|
|
73
|
+
interface VoiceJoinOptions {
|
|
74
|
+
/**
|
|
75
|
+
* Disconnect the user's other voice connections first, e.g. a call they're in on another device.
|
|
76
|
+
*/
|
|
77
|
+
forceDisconnect?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Who to notify when starting a call in a DM or group. Only used when nobody is in the call yet.
|
|
80
|
+
*/
|
|
81
|
+
recipients?: UserResolvable[];
|
|
82
|
+
/** The voice node to use, by name from {@link BaseVoiceManager.fetchNodes}. Defaults to the server's choice. */
|
|
83
|
+
node?: string;
|
|
84
|
+
}
|
|
85
|
+
/** A voice server of the instance, from {@link BaseVoiceManager.fetchNodes}. */
|
|
86
|
+
interface VoiceNode {
|
|
87
|
+
/** The node's name, for {@link VoiceJoinOptions.node}. */
|
|
88
|
+
name: string;
|
|
89
|
+
/** The LiveKit URL clients connect to. */
|
|
90
|
+
url: string;
|
|
91
|
+
/** Where the node is, to pick the nearest one. */
|
|
92
|
+
latitude: number;
|
|
93
|
+
longitude: number;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Creates a platform's connection for a channel.
|
|
97
|
+
* @param channelId The voice channel's ID.
|
|
98
|
+
* @param serverId The ID of the server the channel is in, or `null` for DMs and groups.
|
|
99
|
+
*/
|
|
100
|
+
type VoiceConnectionFactory<C extends BaseVoiceConnection> = (channelId: string, serverId: string | null) => C;
|
|
101
|
+
/**
|
|
102
|
+
* Joins and tracks voice calls, one connection per channel. Use the `VoiceManager` from
|
|
103
|
+
* `@stoatx/voice-node` or `@stoatx/voice-browser`, which extend this with their connection type.
|
|
104
|
+
*/
|
|
105
|
+
declare class BaseVoiceManager<C extends BaseVoiceConnection = BaseVoiceConnection> {
|
|
106
|
+
/** The client the calls are joined with. */
|
|
107
|
+
readonly client: Client;
|
|
108
|
+
private readonly connections;
|
|
109
|
+
private readonly pending;
|
|
110
|
+
private readonly createConnection;
|
|
111
|
+
private nodes;
|
|
112
|
+
/**
|
|
113
|
+
* @param client The client to join calls with.
|
|
114
|
+
* @param createConnection Creates the platform's connection for a channel.
|
|
115
|
+
*/
|
|
116
|
+
constructor(client: Client, createConnection: VoiceConnectionFactory<C>);
|
|
117
|
+
/**
|
|
118
|
+
* Fetches the instance's voice servers. Cached after the first call.
|
|
119
|
+
* @returns The nodes, empty if the instance has voice turned off.
|
|
120
|
+
*/
|
|
121
|
+
fetchNodes(): Promise<VoiceNode[]>;
|
|
122
|
+
/**
|
|
123
|
+
* Joins a voice channel's call. Joining a channel the client is already in returns the existing
|
|
124
|
+
* connection, and joining while a join is in progress waits for it.
|
|
125
|
+
* @param channel The voice channel, DM or group, or its ID.
|
|
126
|
+
* @param options Whether to disconnect other devices, who to ring, and which voice node to use.
|
|
127
|
+
* Ignored when the client is already in the call.
|
|
128
|
+
* @returns The connection, once it's ready.
|
|
129
|
+
* @throws {StoatAPIError} If the API refuses, e.g. `MissingPermission` without the Connect permission.
|
|
130
|
+
* @example
|
|
131
|
+
* const connection = await voice.join(channel);
|
|
132
|
+
* connection.on("disconnect", () => console.log("Left the call"));
|
|
133
|
+
*/
|
|
134
|
+
join(channel: VoiceChannelResolvable, options?: VoiceJoinOptions): Promise<C>;
|
|
135
|
+
/**
|
|
136
|
+
* Gets the connection to a channel's call.
|
|
137
|
+
* @param channel The channel or its ID.
|
|
138
|
+
* @returns The connection, or `undefined` if the client isn't in that call.
|
|
139
|
+
*/
|
|
140
|
+
get(channel: VoiceChannelResolvable): C | undefined;
|
|
141
|
+
/** Every call the client is in, by channel ID. */
|
|
142
|
+
get cache(): ReadonlyMap<string, C>;
|
|
143
|
+
/**
|
|
144
|
+
* Leaves a channel's call. Does nothing if the client isn't in it.
|
|
145
|
+
* @param channel The channel or its ID.
|
|
146
|
+
*/
|
|
147
|
+
leave(channel: VoiceChannelResolvable): Promise<void>;
|
|
148
|
+
/** Leaves every call. */
|
|
149
|
+
leaveAll(): Promise<void>;
|
|
150
|
+
private connect;
|
|
151
|
+
/**
|
|
152
|
+
* Caches a connection until it disconnects.
|
|
153
|
+
* @param channelId The call's channel ID.
|
|
154
|
+
* @param connection The connection.
|
|
155
|
+
*/
|
|
156
|
+
private track;
|
|
157
|
+
/**
|
|
158
|
+
* Follows the server moving the user to another call: connects there, carries the state over,
|
|
159
|
+
* then leaves the old call. Errors are emitted on the old connection.
|
|
160
|
+
* @param move The move request from the gateway.
|
|
161
|
+
*/
|
|
162
|
+
private handleMove;
|
|
163
|
+
private resolveId;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export { BaseVoiceConnection, BaseVoiceManager, type VoiceChannelResolvable, type VoiceConnectionEvents, type VoiceConnectionFactory, type VoiceConnectionStatus, type VoiceJoinOptions, type VoiceNode };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
import { Client, BaseChannel, UserResolvable } from '@stoatx/client';
|
|
3
|
+
|
|
4
|
+
/** Where a voice connection is in its lifecycle. */
|
|
5
|
+
type VoiceConnectionStatus = "connecting" | "ready" | "disconnecting" | "disconnected";
|
|
6
|
+
/** Events every voice connection emits. Platform packages add their own. */
|
|
7
|
+
interface VoiceConnectionEvents {
|
|
8
|
+
/** Connected to the call. */
|
|
9
|
+
ready: [];
|
|
10
|
+
/** Left the call, or the connection was lost. */
|
|
11
|
+
disconnect: [];
|
|
12
|
+
/** Something went wrong while connected, e.g. sending audio failed. */
|
|
13
|
+
error: [error: Error];
|
|
14
|
+
/**
|
|
15
|
+
* The server moved the user to another call, e.g. a moderator dragged them. This connection
|
|
16
|
+
* disconnects right after; use the new one from now on. It already plays the same audio
|
|
17
|
+
* (Node.js) or keeps the microphone and deafen state (browser).
|
|
18
|
+
*/
|
|
19
|
+
move: [connection: BaseVoiceConnection];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A connection to one voice channel. `@stoatx/voice-node` and `@stoatx/voice-browser` provide the
|
|
23
|
+
* implementations; get one from their `VoiceManager.join()`.
|
|
24
|
+
*/
|
|
25
|
+
declare abstract class BaseVoiceConnection<Events extends VoiceConnectionEvents & Record<keyof Events, any[]> = VoiceConnectionEvents> extends EventEmitter<Events> {
|
|
26
|
+
/** The voice channel's ID. */
|
|
27
|
+
readonly channelId: string;
|
|
28
|
+
/** The ID of the server the channel is in, or `null` for DMs and groups. */
|
|
29
|
+
readonly serverId: string | null;
|
|
30
|
+
protected _status: VoiceConnectionStatus;
|
|
31
|
+
/**
|
|
32
|
+
* @param channelId The voice channel's ID.
|
|
33
|
+
* @param serverId The ID of the server the channel is in, or `null` for DMs and groups.
|
|
34
|
+
*/
|
|
35
|
+
constructor(channelId: string, serverId: string | null);
|
|
36
|
+
/** Where the connection is in its lifecycle. */
|
|
37
|
+
get status(): VoiceConnectionStatus;
|
|
38
|
+
/**
|
|
39
|
+
* Connects to the call's LiveKit room. Called by `VoiceManager.join()`.
|
|
40
|
+
* @param url The LiveKit server URL.
|
|
41
|
+
* @param token The token from `join_call`.
|
|
42
|
+
* @internal
|
|
43
|
+
*/
|
|
44
|
+
abstract connect(url: string, token: string): Promise<void>;
|
|
45
|
+
/** Leaves the call. */
|
|
46
|
+
abstract disconnect(): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Carries over state from the connection this one replaces when the server moves the user,
|
|
49
|
+
* e.g. the audio player or microphone. Does nothing by default.
|
|
50
|
+
* @param _previous The connection being replaced.
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
_takeOver(_previous: this): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Emits a base connection event. Subclasses call this instead of `emit()`, whose types can't
|
|
56
|
+
* be checked against the generic `Events`.
|
|
57
|
+
* @param event The event name.
|
|
58
|
+
* @param args The event's arguments.
|
|
59
|
+
*/
|
|
60
|
+
protected emitBase<E extends keyof VoiceConnectionEvents>(event: E, ...args: VoiceConnectionEvents[E]): void;
|
|
61
|
+
/**
|
|
62
|
+
* Emits `error` if anyone listens, so a failure inside the connection can't crash the process.
|
|
63
|
+
* @param error The error.
|
|
64
|
+
*/
|
|
65
|
+
/** @internal */
|
|
66
|
+
_reportError(error: unknown): void;
|
|
67
|
+
protected reportError(error: unknown): void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A voice channel, DM or group, or its ID. */
|
|
71
|
+
type VoiceChannelResolvable = BaseChannel | string;
|
|
72
|
+
/** Options for {@link BaseVoiceManager.join}. */
|
|
73
|
+
interface VoiceJoinOptions {
|
|
74
|
+
/**
|
|
75
|
+
* Disconnect the user's other voice connections first, e.g. a call they're in on another device.
|
|
76
|
+
*/
|
|
77
|
+
forceDisconnect?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Who to notify when starting a call in a DM or group. Only used when nobody is in the call yet.
|
|
80
|
+
*/
|
|
81
|
+
recipients?: UserResolvable[];
|
|
82
|
+
/** The voice node to use, by name from {@link BaseVoiceManager.fetchNodes}. Defaults to the server's choice. */
|
|
83
|
+
node?: string;
|
|
84
|
+
}
|
|
85
|
+
/** A voice server of the instance, from {@link BaseVoiceManager.fetchNodes}. */
|
|
86
|
+
interface VoiceNode {
|
|
87
|
+
/** The node's name, for {@link VoiceJoinOptions.node}. */
|
|
88
|
+
name: string;
|
|
89
|
+
/** The LiveKit URL clients connect to. */
|
|
90
|
+
url: string;
|
|
91
|
+
/** Where the node is, to pick the nearest one. */
|
|
92
|
+
latitude: number;
|
|
93
|
+
longitude: number;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Creates a platform's connection for a channel.
|
|
97
|
+
* @param channelId The voice channel's ID.
|
|
98
|
+
* @param serverId The ID of the server the channel is in, or `null` for DMs and groups.
|
|
99
|
+
*/
|
|
100
|
+
type VoiceConnectionFactory<C extends BaseVoiceConnection> = (channelId: string, serverId: string | null) => C;
|
|
101
|
+
/**
|
|
102
|
+
* Joins and tracks voice calls, one connection per channel. Use the `VoiceManager` from
|
|
103
|
+
* `@stoatx/voice-node` or `@stoatx/voice-browser`, which extend this with their connection type.
|
|
104
|
+
*/
|
|
105
|
+
declare class BaseVoiceManager<C extends BaseVoiceConnection = BaseVoiceConnection> {
|
|
106
|
+
/** The client the calls are joined with. */
|
|
107
|
+
readonly client: Client;
|
|
108
|
+
private readonly connections;
|
|
109
|
+
private readonly pending;
|
|
110
|
+
private readonly createConnection;
|
|
111
|
+
private nodes;
|
|
112
|
+
/**
|
|
113
|
+
* @param client The client to join calls with.
|
|
114
|
+
* @param createConnection Creates the platform's connection for a channel.
|
|
115
|
+
*/
|
|
116
|
+
constructor(client: Client, createConnection: VoiceConnectionFactory<C>);
|
|
117
|
+
/**
|
|
118
|
+
* Fetches the instance's voice servers. Cached after the first call.
|
|
119
|
+
* @returns The nodes, empty if the instance has voice turned off.
|
|
120
|
+
*/
|
|
121
|
+
fetchNodes(): Promise<VoiceNode[]>;
|
|
122
|
+
/**
|
|
123
|
+
* Joins a voice channel's call. Joining a channel the client is already in returns the existing
|
|
124
|
+
* connection, and joining while a join is in progress waits for it.
|
|
125
|
+
* @param channel The voice channel, DM or group, or its ID.
|
|
126
|
+
* @param options Whether to disconnect other devices, who to ring, and which voice node to use.
|
|
127
|
+
* Ignored when the client is already in the call.
|
|
128
|
+
* @returns The connection, once it's ready.
|
|
129
|
+
* @throws {StoatAPIError} If the API refuses, e.g. `MissingPermission` without the Connect permission.
|
|
130
|
+
* @example
|
|
131
|
+
* const connection = await voice.join(channel);
|
|
132
|
+
* connection.on("disconnect", () => console.log("Left the call"));
|
|
133
|
+
*/
|
|
134
|
+
join(channel: VoiceChannelResolvable, options?: VoiceJoinOptions): Promise<C>;
|
|
135
|
+
/**
|
|
136
|
+
* Gets the connection to a channel's call.
|
|
137
|
+
* @param channel The channel or its ID.
|
|
138
|
+
* @returns The connection, or `undefined` if the client isn't in that call.
|
|
139
|
+
*/
|
|
140
|
+
get(channel: VoiceChannelResolvable): C | undefined;
|
|
141
|
+
/** Every call the client is in, by channel ID. */
|
|
142
|
+
get cache(): ReadonlyMap<string, C>;
|
|
143
|
+
/**
|
|
144
|
+
* Leaves a channel's call. Does nothing if the client isn't in it.
|
|
145
|
+
* @param channel The channel or its ID.
|
|
146
|
+
*/
|
|
147
|
+
leave(channel: VoiceChannelResolvable): Promise<void>;
|
|
148
|
+
/** Leaves every call. */
|
|
149
|
+
leaveAll(): Promise<void>;
|
|
150
|
+
private connect;
|
|
151
|
+
/**
|
|
152
|
+
* Caches a connection until it disconnects.
|
|
153
|
+
* @param channelId The call's channel ID.
|
|
154
|
+
* @param connection The connection.
|
|
155
|
+
*/
|
|
156
|
+
private track;
|
|
157
|
+
/**
|
|
158
|
+
* Follows the server moving the user to another call: connects there, carries the state over,
|
|
159
|
+
* then leaves the old call. Errors are emitted on the old connection.
|
|
160
|
+
* @param move The move request from the gateway.
|
|
161
|
+
*/
|
|
162
|
+
private handleMove;
|
|
163
|
+
private resolveId;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export { BaseVoiceConnection, BaseVoiceManager, type VoiceChannelResolvable, type VoiceConnectionEvents, type VoiceConnectionFactory, type VoiceConnectionStatus, type VoiceJoinOptions, type VoiceNode };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// src/VoiceConnection.ts
|
|
2
|
+
import { EventEmitter } from "events";
|
|
3
|
+
var BaseVoiceConnection = class extends EventEmitter {
|
|
4
|
+
/** The voice channel's ID. */
|
|
5
|
+
channelId;
|
|
6
|
+
/** The ID of the server the channel is in, or `null` for DMs and groups. */
|
|
7
|
+
serverId;
|
|
8
|
+
_status = "connecting";
|
|
9
|
+
/**
|
|
10
|
+
* @param channelId The voice channel's ID.
|
|
11
|
+
* @param serverId The ID of the server the channel is in, or `null` for DMs and groups.
|
|
12
|
+
*/
|
|
13
|
+
constructor(channelId, serverId) {
|
|
14
|
+
super();
|
|
15
|
+
this.channelId = channelId;
|
|
16
|
+
this.serverId = serverId;
|
|
17
|
+
}
|
|
18
|
+
/** Where the connection is in its lifecycle. */
|
|
19
|
+
get status() {
|
|
20
|
+
return this._status;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Carries over state from the connection this one replaces when the server moves the user,
|
|
24
|
+
* e.g. the audio player or microphone. Does nothing by default.
|
|
25
|
+
* @param _previous The connection being replaced.
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
async _takeOver(_previous) {
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Emits a base connection event. Subclasses call this instead of `emit()`, whose types can't
|
|
32
|
+
* be checked against the generic `Events`.
|
|
33
|
+
* @param event The event name.
|
|
34
|
+
* @param args The event's arguments.
|
|
35
|
+
*/
|
|
36
|
+
emitBase(event, ...args) {
|
|
37
|
+
EventEmitter.prototype.emit.call(this, event, ...args);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Emits `error` if anyone listens, so a failure inside the connection can't crash the process.
|
|
41
|
+
* @param error The error.
|
|
42
|
+
*/
|
|
43
|
+
/** @internal */
|
|
44
|
+
_reportError(error) {
|
|
45
|
+
this.reportError(error);
|
|
46
|
+
}
|
|
47
|
+
reportError(error) {
|
|
48
|
+
if (this.listenerCount("error") === 0) return;
|
|
49
|
+
this.emitBase("error", error instanceof Error ? error : new Error(String(error)));
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// src/VoiceManager.ts
|
|
54
|
+
var BaseVoiceManager = class {
|
|
55
|
+
/** The client the calls are joined with. */
|
|
56
|
+
client;
|
|
57
|
+
connections = /* @__PURE__ */ new Map();
|
|
58
|
+
pending = /* @__PURE__ */ new Map();
|
|
59
|
+
createConnection;
|
|
60
|
+
nodes = null;
|
|
61
|
+
/**
|
|
62
|
+
* @param client The client to join calls with.
|
|
63
|
+
* @param createConnection Creates the platform's connection for a channel.
|
|
64
|
+
*/
|
|
65
|
+
constructor(client, createConnection) {
|
|
66
|
+
this.client = client;
|
|
67
|
+
this.createConnection = createConnection;
|
|
68
|
+
client.on("logout", () => void this.leaveAll());
|
|
69
|
+
client.on("voiceMoveRequest", (move) => void this.handleMove(move));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Fetches the instance's voice servers. Cached after the first call.
|
|
73
|
+
* @returns The nodes, empty if the instance has voice turned off.
|
|
74
|
+
*/
|
|
75
|
+
async fetchNodes() {
|
|
76
|
+
this.nodes ??= this.client.rest.get("/").then(
|
|
77
|
+
(config) => (config.features.livekit?.nodes ?? []).map((node) => ({
|
|
78
|
+
name: node.name,
|
|
79
|
+
url: node.public_url,
|
|
80
|
+
latitude: node.lat,
|
|
81
|
+
longitude: node.lon
|
|
82
|
+
})),
|
|
83
|
+
(error) => {
|
|
84
|
+
this.nodes = null;
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
);
|
|
88
|
+
return this.nodes;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Joins a voice channel's call. Joining a channel the client is already in returns the existing
|
|
92
|
+
* connection, and joining while a join is in progress waits for it.
|
|
93
|
+
* @param channel The voice channel, DM or group, or its ID.
|
|
94
|
+
* @param options Whether to disconnect other devices, who to ring, and which voice node to use.
|
|
95
|
+
* Ignored when the client is already in the call.
|
|
96
|
+
* @returns The connection, once it's ready.
|
|
97
|
+
* @throws {StoatAPIError} If the API refuses, e.g. `MissingPermission` without the Connect permission.
|
|
98
|
+
* @example
|
|
99
|
+
* const connection = await voice.join(channel);
|
|
100
|
+
* connection.on("disconnect", () => console.log("Left the call"));
|
|
101
|
+
*/
|
|
102
|
+
async join(channel, options = {}) {
|
|
103
|
+
const channelId = this.resolveId(channel);
|
|
104
|
+
const existing = this.connections.get(channelId);
|
|
105
|
+
if (existing?.status === "ready") return existing;
|
|
106
|
+
const inFlight = this.pending.get(channelId);
|
|
107
|
+
if (inFlight) return inFlight;
|
|
108
|
+
const attempt = this.connect(channelId, options).finally(() => this.pending.delete(channelId));
|
|
109
|
+
this.pending.set(channelId, attempt);
|
|
110
|
+
return attempt;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Gets the connection to a channel's call.
|
|
114
|
+
* @param channel The channel or its ID.
|
|
115
|
+
* @returns The connection, or `undefined` if the client isn't in that call.
|
|
116
|
+
*/
|
|
117
|
+
get(channel) {
|
|
118
|
+
return this.connections.get(this.resolveId(channel));
|
|
119
|
+
}
|
|
120
|
+
/** Every call the client is in, by channel ID. */
|
|
121
|
+
get cache() {
|
|
122
|
+
return this.connections;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Leaves a channel's call. Does nothing if the client isn't in it.
|
|
126
|
+
* @param channel The channel or its ID.
|
|
127
|
+
*/
|
|
128
|
+
async leave(channel) {
|
|
129
|
+
await this.connections.get(this.resolveId(channel))?.disconnect();
|
|
130
|
+
}
|
|
131
|
+
/** Leaves every call. */
|
|
132
|
+
async leaveAll() {
|
|
133
|
+
await Promise.all([...this.connections.values()].map((connection) => connection.disconnect()));
|
|
134
|
+
}
|
|
135
|
+
async connect(channelId, options) {
|
|
136
|
+
const body = {};
|
|
137
|
+
if (options.forceDisconnect !== void 0) body.force_disconnect = options.forceDisconnect;
|
|
138
|
+
if (options.recipients !== void 0) {
|
|
139
|
+
body.recipients = options.recipients.map((user) => this.client.users.resolveId(user));
|
|
140
|
+
}
|
|
141
|
+
if (options.node !== void 0) body.node = options.node;
|
|
142
|
+
const { token, url } = await this.client.rest.post(`/channels/${channelId}/join_call`, body);
|
|
143
|
+
const cached = this.client.channels.cache.get(channelId);
|
|
144
|
+
const connection = this.createConnection(channelId, cached?.serverId ?? null);
|
|
145
|
+
try {
|
|
146
|
+
await connection.connect(url, token);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
await connection.disconnect().catch(() => {
|
|
149
|
+
});
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
const previous = this.connections.get(channelId);
|
|
153
|
+
if (previous && previous !== connection) await previous.disconnect().catch(() => {
|
|
154
|
+
});
|
|
155
|
+
this.track(channelId, connection);
|
|
156
|
+
return connection;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Caches a connection until it disconnects.
|
|
160
|
+
* @param channelId The call's channel ID.
|
|
161
|
+
* @param connection The connection.
|
|
162
|
+
*/
|
|
163
|
+
track(channelId, connection) {
|
|
164
|
+
this.connections.set(channelId, connection);
|
|
165
|
+
connection.once("disconnect", () => {
|
|
166
|
+
if (this.connections.get(channelId) === connection) this.connections.delete(channelId);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Follows the server moving the user to another call: connects there, carries the state over,
|
|
171
|
+
* then leaves the old call. Errors are emitted on the old connection.
|
|
172
|
+
* @param move The move request from the gateway.
|
|
173
|
+
*/
|
|
174
|
+
async handleMove(move) {
|
|
175
|
+
const previous = this.connections.get(move.fromChannelId);
|
|
176
|
+
if (!previous) return;
|
|
177
|
+
try {
|
|
178
|
+
const node = (await this.fetchNodes()).find((candidate) => candidate.name === move.node);
|
|
179
|
+
if (!node) throw new Error(`VOICE_NODE_UNKNOWN: The server moved the call to unknown voice node "${move.node}".`);
|
|
180
|
+
const cached = this.client.channels.cache.get(move.toChannelId);
|
|
181
|
+
const connection = this.createConnection(move.toChannelId, cached?.serverId ?? null);
|
|
182
|
+
try {
|
|
183
|
+
await connection.connect(node.url, move.token);
|
|
184
|
+
await connection._takeOver(previous);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
await connection.disconnect().catch(() => {
|
|
187
|
+
});
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
this.track(move.toChannelId, connection);
|
|
191
|
+
previous.emit("move", connection);
|
|
192
|
+
await previous.disconnect();
|
|
193
|
+
} catch (error) {
|
|
194
|
+
previous._reportError(error);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
resolveId(channel) {
|
|
198
|
+
return typeof channel === "string" ? channel : channel.id;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
export {
|
|
202
|
+
BaseVoiceConnection,
|
|
203
|
+
BaseVoiceManager
|
|
204
|
+
};
|
|
205
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/VoiceConnection.ts","../src/VoiceManager.ts"],"sourcesContent":["import { EventEmitter } from \"events\";\n\n/** Where a voice connection is in its lifecycle. */\nexport type VoiceConnectionStatus = \"connecting\" | \"ready\" | \"disconnecting\" | \"disconnected\";\n\n/** Events every voice connection emits. Platform packages add their own. */\nexport interface VoiceConnectionEvents {\n /** Connected to the call. */\n ready: [];\n /** Left the call, or the connection was lost. */\n disconnect: [];\n /** Something went wrong while connected, e.g. sending audio failed. */\n error: [error: Error];\n /**\n * The server moved the user to another call, e.g. a moderator dragged them. This connection\n * disconnects right after; use the new one from now on. It already plays the same audio\n * (Node.js) or keeps the microphone and deafen state (browser).\n */\n move: [connection: BaseVoiceConnection];\n}\n\n/**\n * A connection to one voice channel. `@stoatx/voice-node` and `@stoatx/voice-browser` provide the\n * implementations; get one from their `VoiceManager.join()`.\n */\nexport abstract class BaseVoiceConnection<\n Events extends VoiceConnectionEvents & Record<keyof Events, any[]> = VoiceConnectionEvents,\n> extends EventEmitter<Events> {\n /** The voice channel's ID. */\n public readonly channelId: string;\n /** The ID of the server the channel is in, or `null` for DMs and groups. */\n public readonly serverId: string | null;\n\n protected _status: VoiceConnectionStatus = \"connecting\";\n\n /**\n * @param channelId The voice channel's ID.\n * @param serverId The ID of the server the channel is in, or `null` for DMs and groups.\n */\n constructor(channelId: string, serverId: string | null) {\n super();\n this.channelId = channelId;\n this.serverId = serverId;\n }\n\n /** Where the connection is in its lifecycle. */\n public get status(): VoiceConnectionStatus {\n return this._status;\n }\n\n /**\n * Connects to the call's LiveKit room. Called by `VoiceManager.join()`.\n * @param url The LiveKit server URL.\n * @param token The token from `join_call`.\n * @internal\n */\n public abstract connect(url: string, token: string): Promise<void>;\n\n /** Leaves the call. */\n public abstract disconnect(): Promise<void>;\n\n /**\n * Carries over state from the connection this one replaces when the server moves the user,\n * e.g. the audio player or microphone. Does nothing by default.\n * @param _previous The connection being replaced.\n * @internal\n */\n public async _takeOver(_previous: this): Promise<void> {}\n\n /**\n * Emits a base connection event. Subclasses call this instead of `emit()`, whose types can't\n * be checked against the generic `Events`.\n * @param event The event name.\n * @param args The event's arguments.\n */\n protected emitBase<E extends keyof VoiceConnectionEvents>(event: E, ...args: VoiceConnectionEvents[E]): void {\n EventEmitter.prototype.emit.call(this, event, ...args);\n }\n\n /**\n * Emits `error` if anyone listens, so a failure inside the connection can't crash the process.\n * @param error The error.\n */\n /** @internal */\n public _reportError(error: unknown): void {\n this.reportError(error);\n }\n\n protected reportError(error: unknown): void {\n if (this.listenerCount(\"error\") === 0) return;\n this.emitBase(\"error\", error instanceof Error ? error : new Error(String(error)));\n }\n}\n","import type { BaseChannel, Client, UserResolvable, VoiceMoveRequest } from \"@stoatx/client\";\nimport type { BaseVoiceConnection } from \"./VoiceConnection\";\n\n/** A voice channel, DM or group, or its ID. */\nexport type VoiceChannelResolvable = BaseChannel | string;\n\n/** Options for {@link BaseVoiceManager.join}. */\nexport interface VoiceJoinOptions {\n /**\n * Disconnect the user's other voice connections first, e.g. a call they're in on another device.\n */\n forceDisconnect?: boolean;\n /**\n * Who to notify when starting a call in a DM or group. Only used when nobody is in the call yet.\n */\n recipients?: UserResolvable[];\n /** The voice node to use, by name from {@link BaseVoiceManager.fetchNodes}. Defaults to the server's choice. */\n node?: string;\n}\n\n/** A voice server of the instance, from {@link BaseVoiceManager.fetchNodes}. */\nexport interface VoiceNode {\n /** The node's name, for {@link VoiceJoinOptions.node}. */\n name: string;\n /** The LiveKit URL clients connect to. */\n url: string;\n /** Where the node is, to pick the nearest one. */\n latitude: number;\n longitude: number;\n}\n\n/**\n * Creates a platform's connection for a channel.\n * @param channelId The voice channel's ID.\n * @param serverId The ID of the server the channel is in, or `null` for DMs and groups.\n */\nexport type VoiceConnectionFactory<C extends BaseVoiceConnection> = (channelId: string, serverId: string | null) => C;\n\n/**\n * Joins and tracks voice calls, one connection per channel. Use the `VoiceManager` from\n * `@stoatx/voice-node` or `@stoatx/voice-browser`, which extend this with their connection type.\n */\nexport class BaseVoiceManager<C extends BaseVoiceConnection = BaseVoiceConnection> {\n /** The client the calls are joined with. */\n public readonly client: Client;\n\n private readonly connections = new Map<string, C>();\n private readonly pending = new Map<string, Promise<C>>();\n private readonly createConnection: VoiceConnectionFactory<C>;\n private nodes: Promise<VoiceNode[]> | null = null;\n\n /**\n * @param client The client to join calls with.\n * @param createConnection Creates the platform's connection for a channel.\n */\n constructor(client: Client, createConnection: VoiceConnectionFactory<C>) {\n this.client = client;\n this.createConnection = createConnection;\n // A logged-out client can't stay in calls: its token is gone.\n client.on(\"logout\", () => void this.leaveAll());\n client.on(\"voiceMoveRequest\", (move) => void this.handleMove(move));\n }\n\n /**\n * Fetches the instance's voice servers. Cached after the first call.\n * @returns The nodes, empty if the instance has voice turned off.\n */\n public async fetchNodes(): Promise<VoiceNode[]> {\n this.nodes ??= this.client.rest.get(\"/\").then(\n (config) =>\n (config.features.livekit?.nodes ?? []).map((node) => ({\n name: node.name,\n url: node.public_url,\n latitude: node.lat,\n longitude: node.lon,\n })),\n (error: unknown) => {\n this.nodes = null;\n throw error;\n },\n );\n return this.nodes;\n }\n\n /**\n * Joins a voice channel's call. Joining a channel the client is already in returns the existing\n * connection, and joining while a join is in progress waits for it.\n * @param channel The voice channel, DM or group, or its ID.\n * @param options Whether to disconnect other devices, who to ring, and which voice node to use.\n * Ignored when the client is already in the call.\n * @returns The connection, once it's ready.\n * @throws {StoatAPIError} If the API refuses, e.g. `MissingPermission` without the Connect permission.\n * @example\n * const connection = await voice.join(channel);\n * connection.on(\"disconnect\", () => console.log(\"Left the call\"));\n */\n public async join(channel: VoiceChannelResolvable, options: VoiceJoinOptions = {}): Promise<C> {\n const channelId = this.resolveId(channel);\n\n const existing = this.connections.get(channelId);\n if (existing?.status === \"ready\") return existing;\n\n const inFlight = this.pending.get(channelId);\n if (inFlight) return inFlight;\n\n const attempt = this.connect(channelId, options).finally(() => this.pending.delete(channelId));\n this.pending.set(channelId, attempt);\n return attempt;\n }\n\n /**\n * Gets the connection to a channel's call.\n * @param channel The channel or its ID.\n * @returns The connection, or `undefined` if the client isn't in that call.\n */\n public get(channel: VoiceChannelResolvable): C | undefined {\n return this.connections.get(this.resolveId(channel));\n }\n\n /** Every call the client is in, by channel ID. */\n public get cache(): ReadonlyMap<string, C> {\n return this.connections;\n }\n\n /**\n * Leaves a channel's call. Does nothing if the client isn't in it.\n * @param channel The channel or its ID.\n */\n public async leave(channel: VoiceChannelResolvable): Promise<void> {\n await this.connections.get(this.resolveId(channel))?.disconnect();\n }\n\n /** Leaves every call. */\n public async leaveAll(): Promise<void> {\n await Promise.all([...this.connections.values()].map((connection) => connection.disconnect()));\n }\n\n private async connect(channelId: string, options: VoiceJoinOptions): Promise<C> {\n const body: { force_disconnect?: boolean; recipients?: string[]; node?: string } = {};\n if (options.forceDisconnect !== undefined) body.force_disconnect = options.forceDisconnect;\n if (options.recipients !== undefined) {\n body.recipients = options.recipients.map((user) => this.client.users.resolveId(user));\n }\n if (options.node !== undefined) body.node = options.node;\n\n const { token, url } = await this.client.rest.post(`/channels/${channelId}/join_call`, body);\n\n const cached = this.client.channels.cache.get(channelId) as { serverId?: string } | undefined;\n const connection = this.createConnection(channelId, cached?.serverId ?? null);\n\n try {\n await connection.connect(url, token);\n } catch (error) {\n // Release the room so a failed join doesn't leak it.\n await connection.disconnect().catch(() => {});\n throw error;\n }\n\n const previous = this.connections.get(channelId);\n if (previous && previous !== connection) await previous.disconnect().catch(() => {});\n\n this.track(channelId, connection);\n return connection;\n }\n\n /**\n * Caches a connection until it disconnects.\n * @param channelId The call's channel ID.\n * @param connection The connection.\n */\n private track(channelId: string, connection: C): void {\n this.connections.set(channelId, connection);\n (connection as BaseVoiceConnection).once(\"disconnect\", () => {\n // Only remove the entry if it still belongs to this connection.\n if (this.connections.get(channelId) === connection) this.connections.delete(channelId);\n });\n }\n\n /**\n * Follows the server moving the user to another call: connects there, carries the state over,\n * then leaves the old call. Errors are emitted on the old connection.\n * @param move The move request from the gateway.\n */\n private async handleMove(move: VoiceMoveRequest): Promise<void> {\n const previous = this.connections.get(move.fromChannelId);\n if (!previous) return;\n\n try {\n const node = (await this.fetchNodes()).find((candidate) => candidate.name === move.node);\n if (!node) throw new Error(`VOICE_NODE_UNKNOWN: The server moved the call to unknown voice node \"${move.node}\".`);\n\n const cached = this.client.channels.cache.get(move.toChannelId) as { serverId?: string } | undefined;\n const connection = this.createConnection(move.toChannelId, cached?.serverId ?? null);\n try {\n await connection.connect(node.url, move.token);\n await connection._takeOver(previous);\n } catch (error) {\n await connection.disconnect().catch(() => {});\n throw error;\n }\n\n this.track(move.toChannelId, connection);\n (previous as BaseVoiceConnection).emit(\"move\", connection);\n await previous.disconnect();\n } catch (error) {\n previous._reportError(error);\n }\n }\n\n private resolveId(channel: VoiceChannelResolvable): string {\n return typeof channel === \"string\" ? channel : channel.id;\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAyBtB,IAAe,sBAAf,cAEG,aAAqB;AAAA;AAAA,EAEb;AAAA;AAAA,EAEA;AAAA,EAEN,UAAiC;AAAA;AAAA;AAAA;AAAA;AAAA,EAM3C,YAAY,WAAmB,UAAyB;AACtD,UAAM;AACN,SAAK,YAAY;AACjB,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA,EAGA,IAAW,SAAgC;AACzC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBA,MAAa,UAAU,WAAgC;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ9C,SAAgD,UAAa,MAAsC;AAC3G,iBAAa,UAAU,KAAK,KAAK,MAAM,OAAO,GAAG,IAAI;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,aAAa,OAAsB;AACxC,SAAK,YAAY,KAAK;AAAA,EACxB;AAAA,EAEU,YAAY,OAAsB;AAC1C,QAAI,KAAK,cAAc,OAAO,MAAM,EAAG;AACvC,SAAK,SAAS,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,EAClF;AACF;;;AClDO,IAAM,mBAAN,MAA4E;AAAA;AAAA,EAEjE;AAAA,EAEC,cAAc,oBAAI,IAAe;AAAA,EACjC,UAAU,oBAAI,IAAwB;AAAA,EACtC;AAAA,EACT,QAAqC;AAAA;AAAA;AAAA;AAAA;AAAA,EAM7C,YAAY,QAAgB,kBAA6C;AACvE,SAAK,SAAS;AACd,SAAK,mBAAmB;AAExB,WAAO,GAAG,UAAU,MAAM,KAAK,KAAK,SAAS,CAAC;AAC9C,W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A,IACvF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,WAAW,MAAuC;AAC9D,UAAM,WAAW,KAAK,YAAY,IAAI,KAAK,aAAa;AACxD,QAAI,CAAC,SAAU;AAEf,QAAI;AACF,YAAM,QAAQ,MAAM,KAAK,WAAW,GAAG,KAAK,CAAC,cAAc,UAAU,SAAS,KAAK,IAAI;AACvF,UAAI,CAAC,KAAM,OAAM,IAAI,MAAM,wEAAwE,KAAK,IAAI,IAAI;AAEhH,YAAM,SAAS,KAAK,OAAO,SAAS,MAAM,IAAI,KAAK,WAAW;AAC9D,YAAM,aAAa,KAAK,iBAAiB,KAAK,aAAa,QAAQ,YAAY,IAAI;AACnF,UAAI;AACF,cAAM,WAAW,QAAQ,KAAK,KAAK,KAAK,KAAK;AAC7C,cAAM,WAAW,UAAU,QAAQ;AAAA,MACrC,SAAS,OAAO;AACd,cAAM,WAAW,WAAW,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AAC5C,cAAM;AAAA,MACR;AAEA,WAAK,MAAM,KAAK,aAAa,UAAU;AACvC,MAAC,SAAiC,KAAK,QAAQ,UAAU;AACzD,YAAM,SAAS,WAAW;AAAA,IAC5B,SAAS,OAAO;AACd,eAAS,aAAa,KAAK;AAAA,IAC7B;AAAA,EACF;AAAA,EAEQ,UAAU,SAAyC;AACzD,WAAO,OAAO,YAAY,WAAW,UAAU,QAAQ;AAAA,EACzD;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stoatx/voice",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Shared voice connection and manager for @stoatx/voice-node and @stoatx/voice-browser.",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/stoatx-ts/stoatx.git"
|
|
9
|
+
},
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/stoatx-ts/stoatx/issues"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/stoatx-ts/stoatx#readme",
|
|
14
|
+
"main": "./dist/index.cjs",
|
|
15
|
+
"module": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"import": "./dist/index.js",
|
|
21
|
+
"require": "./dist/index.cjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"events": "^3.3.0"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@stoatx/client": "^1.0.0"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"ulid": "^3.0.2",
|
|
39
|
+
"@stoatx/client": "1.0.0"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsup",
|
|
43
|
+
"dev": "tsup --watch",
|
|
44
|
+
"lint": "eslint src/**/*.ts"
|
|
45
|
+
}
|
|
6
46
|
}
|