wumbly 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1052 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/client.ts
31
+ var client_exports = {};
32
+ __export(client_exports, {
33
+ Client: () => Client
34
+ });
35
+ module.exports = __toCommonJS(client_exports);
36
+
37
+ // src/platform/client.ts
38
+ var import_node_events2 = require("events");
39
+
40
+ // src/platform/gateway.ts
41
+ var import_node_events = require("events");
42
+ var ws = __toESM(require("ws"), 1);
43
+ var Gateway = class extends import_node_events.EventEmitter {
44
+ ws = null;
45
+ heartbeatTimer = null;
46
+ seq = null;
47
+ sessionId = null;
48
+ token;
49
+ url;
50
+ intents;
51
+ constructor(options) {
52
+ super();
53
+ this.token = options.token;
54
+ this.url = options.url ?? "wss://gateway.fluxer.app/?v=1&encoding=json";
55
+ this.intents = options.intents ?? 513;
56
+ }
57
+ connect() {
58
+ return new Promise((resolve3, reject) => {
59
+ const socket = new ws.WebSocket(this.url);
60
+ this.ws = socket;
61
+ socket.on("open", () => resolve3());
62
+ socket.on("error", (err) => {
63
+ this.emit("error", err);
64
+ reject(err);
65
+ });
66
+ socket.on("close", (code, reason) => {
67
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
68
+ this.emit("close", code, String(reason));
69
+ });
70
+ socket.on("message", (raw) => {
71
+ let payload;
72
+ try {
73
+ payload = JSON.parse(String(raw));
74
+ } catch {
75
+ return;
76
+ }
77
+ this.handlePayload(payload);
78
+ });
79
+ });
80
+ }
81
+ handlePayload(payload) {
82
+ const { op, d, s, t } = payload;
83
+ if (typeof s === "number") this.seq = s;
84
+ if (op === 10) {
85
+ const interval = d?.heartbeat_interval ?? 41250;
86
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
87
+ this.heartbeatTimer = setInterval(() => this.send({ op: 1, d: this.seq }), interval);
88
+ this.identify();
89
+ return;
90
+ }
91
+ if (op === 11) return;
92
+ if (op === 0) {
93
+ if (t === "READY") this.sessionId = d?.session_id ?? null;
94
+ this.emit("dispatch", t, d);
95
+ return;
96
+ }
97
+ if (op === 7 || op === 9) {
98
+ try {
99
+ this.ws?.close();
100
+ } catch {
101
+ }
102
+ return;
103
+ }
104
+ this.emit("packet", payload);
105
+ }
106
+ identify() {
107
+ this.send({
108
+ op: 2,
109
+ d: {
110
+ token: this.token,
111
+ intents: this.intents,
112
+ properties: { os: process.platform, browser: "wumbly", device: "wumbly" }
113
+ }
114
+ });
115
+ }
116
+ send(payload) {
117
+ if (this.ws?.readyState === ws.WebSocket.OPEN) {
118
+ this.ws.send(JSON.stringify(payload));
119
+ }
120
+ }
121
+ close() {
122
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
123
+ try {
124
+ this.ws?.close();
125
+ } catch {
126
+ }
127
+ this.ws = null;
128
+ }
129
+ };
130
+
131
+ // src/platform/rest.ts
132
+ var RestClient = class {
133
+ token = null;
134
+ baseUrl;
135
+ constructor(options = {}) {
136
+ this.token = options.token ?? null;
137
+ this.baseUrl = options.baseUrl ?? "https://api.fluxer.app/v1";
138
+ }
139
+ setToken(token) {
140
+ this.token = token;
141
+ }
142
+ async request(method, path, body) {
143
+ const url = path.startsWith("http") ? path : `${this.baseUrl}${path.startsWith("/") ? "" : "/"}${path}`;
144
+ const headers = {};
145
+ if (this.token) headers.Authorization = `Bot ${this.token}`;
146
+ let payload;
147
+ if (body !== void 0) {
148
+ headers["Content-Type"] = "application/json";
149
+ payload = JSON.stringify(body);
150
+ }
151
+ const res = await fetch(url, { method, headers, body: payload });
152
+ if (res.status === 204) return void 0;
153
+ const text = await res.text();
154
+ const data = text ? JSON.parse(text) : void 0;
155
+ if (!res.ok) {
156
+ const err = new Error(data?.message ?? `HTTP ${res.status}`);
157
+ err.status = res.status;
158
+ err.data = data;
159
+ throw err;
160
+ }
161
+ return data;
162
+ }
163
+ get(path) {
164
+ return this.request("GET", path);
165
+ }
166
+ post(path, body) {
167
+ return this.request("POST", path, body);
168
+ }
169
+ patch(path, body) {
170
+ return this.request("PATCH", path, body);
171
+ }
172
+ put(path, body) {
173
+ return this.request("PUT", path, body);
174
+ }
175
+ delete(path, body) {
176
+ return this.request("DELETE", path, body);
177
+ }
178
+ };
179
+
180
+ // src/platform/events.ts
181
+ var Events = {
182
+ Ready: "ready",
183
+ MessageCreate: "messageCreate",
184
+ MessageUpdate: "messageUpdate",
185
+ MessageDelete: "messageDelete",
186
+ GuildCreate: "guildCreate",
187
+ VoiceStateUpdate: "voiceStateUpdate",
188
+ VoiceServerUpdate: "voiceServerUpdate",
189
+ VoiceStateAck: "voiceStateAck",
190
+ VoiceStatesSync: "voiceStatesSync"
191
+ };
192
+
193
+ // src/platform/client.ts
194
+ function makeLogger() {
195
+ const wrap = (level) => (msg, data) => {
196
+ const line = data === void 0 ? msg : `${msg} ${JSON.stringify(data)}`;
197
+ console[level === "error" ? "error" : "log"](line);
198
+ };
199
+ return { info: wrap("info"), warn: wrap("warn"), error: wrap("error"), debug: wrap("debug") };
200
+ }
201
+ function makeMessage(client, raw) {
202
+ const author = raw.author ?? { id: raw.author_id };
203
+ const channelId = raw.channel_id;
204
+ const guildId = raw.guild_id ?? null;
205
+ const message = {
206
+ ...raw,
207
+ id: raw.id,
208
+ content: raw.content ?? "",
209
+ author,
210
+ guildId,
211
+ channelId,
212
+ channel: client.channels.get(channelId) ?? {
213
+ id: channelId,
214
+ guildId,
215
+ guild: guildId ? client.guilds.get(guildId) ?? null : null,
216
+ send: (options) => client.sendMessage(channelId, options),
217
+ isVoice: () => false
218
+ },
219
+ guild: guildId ? client.guilds.get(guildId) ?? null : null,
220
+ member: raw.member ? { ...raw.member, user: author } : null,
221
+ reply: async (options) => {
222
+ const payload = typeof options === "string" ? { content: options } : { ...options };
223
+ payload.message_reference = { message_id: raw.id, channel_id: channelId, ...guildId ? { guild_id: guildId } : {} };
224
+ return client.sendMessage(channelId, payload);
225
+ }
226
+ };
227
+ return message;
228
+ }
229
+ var PlatformClient = class extends import_node_events2.EventEmitter {
230
+ rest = new RestClient();
231
+ logger = makeLogger();
232
+ guilds = /* @__PURE__ */ new Map();
233
+ channels = /* @__PURE__ */ new Map();
234
+ users = /* @__PURE__ */ new Map();
235
+ user = null;
236
+ ws = null;
237
+ options;
238
+ readyResolve = null;
239
+ constructor(options = {}) {
240
+ super();
241
+ this.options = options;
242
+ if (options.apiBase) this.rest.baseUrl = options.apiBase;
243
+ }
244
+ async login(token, _options) {
245
+ this.rest.setToken(token);
246
+ this.ws = new Gateway({ token, url: this.options.gatewayUrl, intents: this.options.intents });
247
+ this.ws.on("dispatch", (t, d) => this.handleDispatch(t, d));
248
+ this.ws.on("error", (e) => this.emit("error", e));
249
+ await this.ws.connect();
250
+ await new Promise((resolve3) => {
251
+ this.readyResolve = resolve3;
252
+ });
253
+ }
254
+ async destroy() {
255
+ try {
256
+ this.ws?.close();
257
+ } catch {
258
+ }
259
+ this.ws = null;
260
+ }
261
+ sendToGateway(_shardId, payload) {
262
+ this.logger.debug?.("[gateway send]", payload);
263
+ console.log("[gateway send]", JSON.stringify(payload));
264
+ this.ws?.send(payload);
265
+ }
266
+ handleDispatch(t, d) {
267
+ this.emit("raw", { t, d });
268
+ if (t.includes("VOICE")) console.log("[voice dispatch]", t, JSON.stringify(d));
269
+ switch (t) {
270
+ case "READY": {
271
+ this.user = d?.user ?? null;
272
+ if (this.user) this.users.set(this.user.id, this.user);
273
+ for (const g of d?.guilds ?? []) this.guilds.set(g.id, { ...g, shardId: 0 });
274
+ this.emit(Events.Ready);
275
+ this.readyResolve?.();
276
+ this.readyResolve = null;
277
+ return;
278
+ }
279
+ case "MESSAGE_CREATE": {
280
+ const msg = makeMessage(this, d);
281
+ this.emit(Events.MessageCreate, msg);
282
+ return;
283
+ }
284
+ case "MESSAGE_UPDATE": {
285
+ const msg = makeMessage(this, d);
286
+ this.emit(Events.MessageUpdate, msg, msg);
287
+ return;
288
+ }
289
+ case "MESSAGE_DELETE": {
290
+ this.emit(Events.MessageDelete, d);
291
+ return;
292
+ }
293
+ case "GUILD_CREATE": {
294
+ const guild = { ...d, shardId: 0 };
295
+ this.guilds.set(guild.id, guild);
296
+ for (const ch of d?.channels ?? []) this.channels.set(ch.id, { ...ch, guildId: guild.id, guild, isVoice: () => [2, 13].includes(ch.type) });
297
+ this.emit(Events.GuildCreate, guild);
298
+ this.emit(Events.VoiceStatesSync, { guildId: guild.id, voiceStates: d?.voice_states ?? [] });
299
+ return;
300
+ }
301
+ case "CHANNEL_CREATE":
302
+ case "CHANNEL_UPDATE": {
303
+ const ch = { ...d, guild: d.guild_id ? this.guilds.get(d.guild_id) ?? null : null, isVoice: () => [2, 13].includes(d.type) };
304
+ this.channels.set(ch.id, ch);
305
+ return;
306
+ }
307
+ case "VOICE_STATE_UPDATE":
308
+ this.emit(Events.VoiceStateUpdate, d);
309
+ return;
310
+ case "VOICE_SERVER_UPDATE":
311
+ this.emit(Events.VoiceServerUpdate, d);
312
+ return;
313
+ case "VOICE_STATE_ACK":
314
+ this.emit(Events.VoiceStateAck, d);
315
+ return;
316
+ default:
317
+ this.emit(t.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase()), d);
318
+ }
319
+ }
320
+ async sendMessage(channelId, options) {
321
+ const payload = typeof options === "string" ? { content: options } : options;
322
+ const raw = await this.rest.post(`/channels/${channelId}/messages`, payload);
323
+ return makeMessage(this, raw);
324
+ }
325
+ };
326
+
327
+ // src/commands/types.ts
328
+ var COMMAND_BRAND = /* @__PURE__ */ Symbol.for("wumbly.command");
329
+
330
+ // src/commands/command.ts
331
+ function normalizeCooldown(cooldown) {
332
+ if (cooldown === void 0) return null;
333
+ const value = typeof cooldown === "number" ? { limit: 1, window: cooldown, scope: "user" } : { ...cooldown };
334
+ if (!Number.isFinite(value.limit) || value.limit <= 0) {
335
+ throw new TypeError("cooldown.limit must be a positive number");
336
+ }
337
+ if (!Number.isFinite(value.window) || value.window <= 0) {
338
+ throw new TypeError("cooldown.window must be a positive number");
339
+ }
340
+ return Object.freeze({
341
+ limit: Math.floor(value.limit),
342
+ window: Math.floor(value.window),
343
+ scope: value.scope ?? "user"
344
+ });
345
+ }
346
+ var Command = class {
347
+ [COMMAND_BRAND] = true;
348
+ name;
349
+ description;
350
+ aliases;
351
+ category;
352
+ guildOnly;
353
+ ownerOnly;
354
+ cooldown;
355
+ middlewares;
356
+ run;
357
+ constructor(options) {
358
+ const name = options.name.trim();
359
+ if (!name) throw new TypeError("Command name is required");
360
+ if (/\s/.test(name)) throw new TypeError("Command names cannot contain whitespace");
361
+ this.name = name;
362
+ this.description = options.description ?? "";
363
+ this.aliases = Object.freeze([...new Set(options.aliases ?? [])]);
364
+ this.category = options.category ?? null;
365
+ this.guildOnly = options.guildOnly ?? false;
366
+ this.ownerOnly = options.ownerOnly ?? false;
367
+ this.cooldown = normalizeCooldown(options.cooldown);
368
+ this.middlewares = Object.freeze([...options.middlewares ?? []]);
369
+ this.run = options.run;
370
+ Object.freeze(this);
371
+ }
372
+ };
373
+ function isCommand(value) {
374
+ return typeof value === "object" && value !== null && value[COMMAND_BRAND] === true;
375
+ }
376
+ function createCommandContext(client, message, command, args, input) {
377
+ const frozenArgs = Object.freeze([...args]);
378
+ return {
379
+ client,
380
+ message,
381
+ command,
382
+ author: message.author,
383
+ args: frozenArgs,
384
+ input,
385
+ get rest() {
386
+ return frozenArgs.join(" ");
387
+ },
388
+ get channel() {
389
+ return message.channel ?? null;
390
+ },
391
+ get guild() {
392
+ return message.guild ?? null;
393
+ },
394
+ get member() {
395
+ return message.member ?? null;
396
+ },
397
+ reply(options) {
398
+ return message.reply(options);
399
+ },
400
+ send(options) {
401
+ const channel = message.channel;
402
+ if (!channel?.send) {
403
+ return Promise.reject(new Error("The message has no text-based channel"));
404
+ }
405
+ return channel.send(options);
406
+ }
407
+ };
408
+ }
409
+
410
+ // src/commands/cooldown.ts
411
+ function scopeKey(ctx, scope) {
412
+ switch (scope) {
413
+ case "user":
414
+ return ctx.author.id;
415
+ case "guild":
416
+ return ctx.message.guildId ?? "dm";
417
+ case "channel":
418
+ return ctx.message.channelId ?? "unknown";
419
+ case "global":
420
+ return "*";
421
+ }
422
+ }
423
+ var CooldownStore = class {
424
+ buckets = /* @__PURE__ */ new Map();
425
+ /** Register a use, or report how long the caller has to wait. */
426
+ consume(command, ctx) {
427
+ const cooldown = command.cooldown;
428
+ if (!cooldown) return { ok: true };
429
+ const key = `${command.name}:${cooldown.scope ?? "user"}:${scopeKey(
430
+ ctx,
431
+ cooldown.scope ?? "user"
432
+ )}`;
433
+ const now = Date.now();
434
+ const windowStart = now - cooldown.window;
435
+ const hits = (this.buckets.get(key) ?? []).filter((time) => time > windowStart);
436
+ if (hits.length >= cooldown.limit) {
437
+ const oldest = hits[0] ?? now;
438
+ this.buckets.set(key, hits);
439
+ return {
440
+ ok: false,
441
+ retryAfter: Math.max(0, oldest + cooldown.window - now)
442
+ };
443
+ }
444
+ hits.push(now);
445
+ this.buckets.set(key, hits);
446
+ return { ok: true };
447
+ }
448
+ clear() {
449
+ this.buckets.clear();
450
+ }
451
+ };
452
+
453
+ // src/commands/store.ts
454
+ function assertFree(key, command, names, aliases) {
455
+ const existing = names.get(key) ?? aliases.get(key);
456
+ if (existing && existing !== command) {
457
+ throw new Error(`Command key "${key}" is already used by "${existing.name}"`);
458
+ }
459
+ }
460
+ var CommandStore = class {
461
+ byName = /* @__PURE__ */ new Map();
462
+ byAlias = /* @__PURE__ */ new Map();
463
+ /** Register one command. Throws if its name or an alias is already taken. */
464
+ add(command) {
465
+ this.addMany([command]);
466
+ }
467
+ /** Register several commands, validating every key before committing. */
468
+ addMany(commands) {
469
+ const names = new Map(this.byName);
470
+ const aliases = new Map(this.byAlias);
471
+ for (const command of commands) {
472
+ const nameKey = command.name.toLowerCase();
473
+ assertFree(nameKey, command, names, aliases);
474
+ names.set(nameKey, command);
475
+ const localAliases = /* @__PURE__ */ new Set();
476
+ for (const alias of command.aliases) {
477
+ const aliasKey = alias.toLowerCase();
478
+ if (!aliasKey || aliasKey === nameKey || localAliases.has(aliasKey)) continue;
479
+ assertFree(aliasKey, command, names, aliases);
480
+ localAliases.add(aliasKey);
481
+ aliases.set(aliasKey, command);
482
+ }
483
+ }
484
+ this.byName = names;
485
+ this.byAlias = aliases;
486
+ }
487
+ /** Find a command by name or alias. */
488
+ get(name) {
489
+ const key = name.toLowerCase();
490
+ return this.byName.get(key) ?? this.byAlias.get(key) ?? null;
491
+ }
492
+ has(name) {
493
+ return this.get(name) !== null;
494
+ }
495
+ /** All registered commands, in insertion order. */
496
+ list() {
497
+ return [...this.byName.values()];
498
+ }
499
+ get size() {
500
+ return this.byName.size;
501
+ }
502
+ clear() {
503
+ this.byName.clear();
504
+ this.byAlias.clear();
505
+ }
506
+ };
507
+
508
+ // src/events/event.ts
509
+ var EVENT_BRAND = /* @__PURE__ */ Symbol.for("wumbly.event");
510
+ var Event = class {
511
+ [EVENT_BRAND] = true;
512
+ event;
513
+ once;
514
+ run;
515
+ constructor(input) {
516
+ if (!input.event) throw new TypeError("Event name is required");
517
+ this.event = input.event;
518
+ this.once = input.once ?? false;
519
+ this.run = input.run;
520
+ Object.freeze(this);
521
+ }
522
+ };
523
+ function isEvent(value) {
524
+ return typeof value === "object" && value !== null && value[EVENT_BRAND] === true;
525
+ }
526
+
527
+ // src/events/event-store.ts
528
+ var EventStore = class {
529
+ items = /* @__PURE__ */ new Set();
530
+ handlers = /* @__PURE__ */ new Map();
531
+ add(event) {
532
+ this.items.add(event);
533
+ }
534
+ addMany(events) {
535
+ for (const event of events) this.add(event);
536
+ }
537
+ list() {
538
+ return [...this.items];
539
+ }
540
+ get size() {
541
+ return this.items.size;
542
+ }
543
+ /** Attach a event if it has not been attached yet. */
544
+ attachOne(client, event) {
545
+ if (this.handlers.has(event)) return;
546
+ const handler = (...args) => {
547
+ try {
548
+ Promise.resolve(
549
+ event.run(client, ...args)
550
+ ).catch((error) => {
551
+ void client.handleEventError(error, event, args);
552
+ });
553
+ } catch (error) {
554
+ void client.handleEventError(error, event, args);
555
+ }
556
+ };
557
+ if (event.once) {
558
+ client.once(event.event, handler);
559
+ } else {
560
+ client.on(event.event, handler);
561
+ }
562
+ this.handlers.set(event, handler);
563
+ }
564
+ /** Attach every known event. */
565
+ attach(client) {
566
+ for (const event of this.items) this.attachOne(client, event);
567
+ }
568
+ /** Remove every attached handler from the client. */
569
+ detach(client) {
570
+ for (const [event, handler] of this.handlers) {
571
+ client.off(event.event, handler);
572
+ }
573
+ this.handlers.clear();
574
+ }
575
+ clear() {
576
+ this.items.clear();
577
+ this.handlers.clear();
578
+ }
579
+ };
580
+
581
+ // src/loaders/load.ts
582
+ var import_node_url = require("url");
583
+
584
+ // src/loaders/files.ts
585
+ var import_promises = require("fs/promises");
586
+ var import_node_path = require("path");
587
+
588
+ // src/runtime/environment.ts
589
+ var runtime = globalThis;
590
+ var isBun = typeof runtime.Bun !== "undefined";
591
+ var defaultExtensions = Object.freeze(
592
+ isBun ? [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"] : [".js", ".mjs", ".cjs"]
593
+ );
594
+
595
+ // src/loaders/files.ts
596
+ function isDeclarationFile(name) {
597
+ return /\.d\.[cm]?ts$/.test(name);
598
+ }
599
+ async function collectFiles(directory, options = {}) {
600
+ const root = (0, import_node_path.resolve)(directory);
601
+ const extensions = new Set(options.extensions ?? defaultExtensions);
602
+ const ignored = new Set(options.ignore ?? []);
603
+ const files = [];
604
+ async function walk(current) {
605
+ const entries = await (0, import_promises.readdir)(current, { withFileTypes: true });
606
+ for (const entry of entries) {
607
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
608
+ if (ignored.has(entry.name)) continue;
609
+ const fullPath = (0, import_node_path.resolve)(current, entry.name);
610
+ if (entry.isDirectory()) {
611
+ await walk(fullPath);
612
+ continue;
613
+ }
614
+ if (!entry.isFile() || entry.isSymbolicLink()) continue;
615
+ if (isDeclarationFile(entry.name)) continue;
616
+ if (extensions.has((0, import_node_path.extname)(entry.name))) files.push(fullPath);
617
+ }
618
+ }
619
+ await walk(root);
620
+ return files.sort();
621
+ }
622
+
623
+ // src/loaders/load.ts
624
+ var ModuleLoadError = class extends Error {
625
+ file;
626
+ constructor(file, cause) {
627
+ super(`Could not load module: ${file}`, { cause });
628
+ this.name = "ModuleLoadError";
629
+ this.file = file;
630
+ }
631
+ };
632
+ var importCounter = 0;
633
+ function flatten(value, output, seen) {
634
+ if (Array.isArray(value)) {
635
+ for (const item of value) flatten(item, output, seen);
636
+ return;
637
+ }
638
+ if (value === null || value === void 0 || seen.has(value)) return;
639
+ seen.add(value);
640
+ output.push(value);
641
+ }
642
+ function extractExports(module2) {
643
+ const values = [];
644
+ const seen = /* @__PURE__ */ new Set();
645
+ for (const value of Object.values(module2)) {
646
+ flatten(value, values, seen);
647
+ }
648
+ const commands = [];
649
+ const events = [];
650
+ for (const value of values) {
651
+ if (isCommand(value)) commands.push(value);
652
+ else if (isEvent(value)) events.push(value);
653
+ }
654
+ return { commands, events };
655
+ }
656
+ async function importFile(file, options) {
657
+ const url = (0, import_node_url.pathToFileURL)(file);
658
+ if (options.cacheBust !== false) {
659
+ url.searchParams.set("wumbly", `${Date.now()}-${++importCounter}`);
660
+ }
661
+ let module2;
662
+ try {
663
+ module2 = await import(url.href);
664
+ } catch (error) {
665
+ throw new ModuleLoadError(file, error);
666
+ }
667
+ return extractExports(module2);
668
+ }
669
+ async function loadDirectory(directory, options = {}) {
670
+ const files = await collectFiles(directory, options);
671
+ const commands = [];
672
+ const events = [];
673
+ for (const file of files) {
674
+ const loaded = await importFile(file, options);
675
+ commands.push(...loaded.commands);
676
+ events.push(...loaded.events);
677
+ }
678
+ return { commands, events, files };
679
+ }
680
+
681
+ // src/util/tokenize.ts
682
+ function tokenize(input) {
683
+ const tokens = [];
684
+ let current = "";
685
+ let quote = null;
686
+ let escaped = false;
687
+ for (const char of input) {
688
+ if (escaped) {
689
+ current += char;
690
+ escaped = false;
691
+ continue;
692
+ }
693
+ if (char === "\\") {
694
+ escaped = true;
695
+ continue;
696
+ }
697
+ if (quote) {
698
+ if (char === quote) quote = null;
699
+ else current += char;
700
+ continue;
701
+ }
702
+ if (char === '"' || char === "'") {
703
+ quote = char;
704
+ continue;
705
+ }
706
+ if (/\s/.test(char)) {
707
+ if (current) {
708
+ tokens.push(current);
709
+ current = "";
710
+ }
711
+ continue;
712
+ }
713
+ current += char;
714
+ }
715
+ if (escaped) current += "\\";
716
+ if (current) tokens.push(current);
717
+ return tokens;
718
+ }
719
+ function formatDuration(ms) {
720
+ const totalSeconds = Math.max(0, Math.ceil(ms / 1e3));
721
+ if (totalSeconds < 60) return `${totalSeconds}s`;
722
+ const minutes = Math.floor(totalSeconds / 60);
723
+ const seconds = totalSeconds % 60;
724
+ if (minutes < 60) return seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;
725
+ const hours = Math.floor(minutes / 60);
726
+ const rest = minutes % 60;
727
+ return rest ? `${hours}h ${rest}m` : `${hours}h`;
728
+ }
729
+
730
+ // src/client.ts
731
+ var import_node_path2 = require("path");
732
+
733
+ // src/voice/manager.ts
734
+ var VoiceUnavailableError = class extends Error {
735
+ constructor() {
736
+ super(
737
+ "Voice is not enabled. Pass a provider to `new Client({ voice })` or call `client.voice.use(provider)`."
738
+ );
739
+ this.name = "VoiceUnavailableError";
740
+ }
741
+ };
742
+ var VoiceManager = class {
743
+ constructor(client, provider = null) {
744
+ this.client = client;
745
+ this.provider = provider;
746
+ }
747
+ client;
748
+ provider;
749
+ sessions = /* @__PURE__ */ new Map();
750
+ voiceStates = /* @__PURE__ */ new Map();
751
+ attached = false;
752
+ /** Start tracking gateway voice states for `getVoiceChannelId`. */
753
+ attach() {
754
+ if (this.attached) return this;
755
+ this.attached = true;
756
+ this.client.on(Events.VoiceStateUpdate, ((data) => {
757
+ const guildId = data.guild_id;
758
+ const userId = data.user_id;
759
+ if (!guildId || !userId) return;
760
+ let guild = this.voiceStates.get(guildId);
761
+ if (!guild) {
762
+ guild = /* @__PURE__ */ new Map();
763
+ this.voiceStates.set(guildId, guild);
764
+ }
765
+ guild.set(userId, data.channel_id ?? null);
766
+ }));
767
+ this.client.on(Events.VoiceStatesSync, ((data) => {
768
+ const guild = /* @__PURE__ */ new Map();
769
+ for (const state of data.voiceStates ?? []) {
770
+ if (state.user_id) guild.set(state.user_id, state.channel_id ?? null);
771
+ }
772
+ this.voiceStates.set(data.guildId, guild);
773
+ }));
774
+ return this;
775
+ }
776
+ getVoiceChannelId(guildId, userId) {
777
+ return this.voiceStates.get(guildId)?.get(userId) ?? null;
778
+ }
779
+ get available() {
780
+ return this.provider !== null;
781
+ }
782
+ use(provider) {
783
+ this.provider = provider;
784
+ return this;
785
+ }
786
+ get(channelId) {
787
+ return this.sessions.get(channelId) ?? null;
788
+ }
789
+ async join(channel) {
790
+ const existing = this.sessions.get(channel.id);
791
+ if (existing) return existing;
792
+ if (!this.provider) throw new VoiceUnavailableError();
793
+ const session = await this.provider.join(this.client, channel);
794
+ this.sessions.set(channel.id, session);
795
+ return session;
796
+ }
797
+ async leave(channelOrId) {
798
+ const channelId = typeof channelOrId === "string" ? channelOrId : channelOrId.id;
799
+ const session = this.sessions.get(channelId);
800
+ if (!session) return false;
801
+ this.sessions.delete(channelId);
802
+ await session.leave();
803
+ return true;
804
+ }
805
+ async leaveAll() {
806
+ const sessions = [...this.sessions.values()];
807
+ this.sessions.clear();
808
+ await Promise.allSettled(sessions.map((s) => s.leave()));
809
+ }
810
+ };
811
+
812
+ // src/client.ts
813
+ var DEFAULT_MESSAGES = {
814
+ guildOnly: "This command can only be used in a server.",
815
+ ownerOnly: "This command is restricted to the bot owner.",
816
+ cooldown: (retryAfterMs) => `Wait ${formatDuration(retryAfterMs)} before using this command again.`,
817
+ error: "Something went wrong while running this command."
818
+ };
819
+ function resolveOptions(options) {
820
+ const dirs = /* @__PURE__ */ new Set();
821
+ if (options.commandsDir) dirs.add(options.commandsDir);
822
+ if (options.eventsDir) dirs.add(options.eventsDir);
823
+ if (options.listenersDir) dirs.add(options.listenersDir);
824
+ for (const dir of options.loadDirs ?? []) dirs.add(dir);
825
+ return {
826
+ prefix: options.prefix ?? "!",
827
+ owners: Object.freeze([...options.owners ?? []]),
828
+ allowBots: options.allowBots ?? false,
829
+ allowDMs: options.allowDMs ?? true,
830
+ middlewares: Object.freeze([...options.middlewares ?? []]),
831
+ loadDirs: Object.freeze([...dirs]),
832
+ ...options.extensions ? { extensions: Object.freeze([...options.extensions]) } : {},
833
+ ignore: Object.freeze([...options.ignore ?? []]),
834
+ cacheBust: options.cacheBust ?? true,
835
+ messages: { ...DEFAULT_MESSAGES, ...options.messages },
836
+ ...options.onCommandError ? { onCommandError: options.onCommandError } : {},
837
+ ...options.onEventError ?? options.onListenerError ? { onEventError: options.onEventError ?? options.onListenerError } : {}
838
+ };
839
+ }
840
+ async function resolvePrefix(option, message) {
841
+ if (typeof option === "string") return option || null;
842
+ if (typeof option !== "function") {
843
+ const matches = option.filter(
844
+ (prefix) => prefix.length > 0 && message.content.startsWith(prefix)
845
+ );
846
+ return matches.sort((a, b) => b.length - a.length)[0] ?? null;
847
+ }
848
+ const resolved = await option(message);
849
+ return resolved || null;
850
+ }
851
+ var Client = class extends PlatformClient {
852
+ commands = new CommandStore();
853
+ eventStore = new EventStore();
854
+ /** @deprecated Use `eventStore`. */
855
+ get listenerStore() {
856
+ return this.eventStore;
857
+ }
858
+ cooldowns = new CooldownStore();
859
+ config;
860
+ voice;
861
+ loadedDirs = /* @__PURE__ */ new Set();
862
+ started = false;
863
+ onMessage = (message) => {
864
+ void this.handleMessage(message).catch((error) => {
865
+ this.logger.error("Message handling failed", { error: String(error) });
866
+ });
867
+ };
868
+ constructor(options = {}) {
869
+ super(options.client ?? {});
870
+ this.config = resolveOptions(options);
871
+ this.voice = new VoiceManager(this, options.voice ?? null).attach();
872
+ this.on(Events.MessageCreate, this.onMessage);
873
+ }
874
+ /** Register commands and/or events. */
875
+ register(...items) {
876
+ const commands = [];
877
+ const events = [];
878
+ for (const item of items) {
879
+ if (isEvent(item)) events.push(item);
880
+ else if (isCommand(item)) commands.push(item);
881
+ else throw new TypeError("register() expects a command or an event");
882
+ }
883
+ this.registerCommand(...commands);
884
+ this.registerEvent(...events);
885
+ return this;
886
+ }
887
+ registerCommand(...commands) {
888
+ this.commands.addMany(commands);
889
+ return this;
890
+ }
891
+ registerEvent(...events) {
892
+ this.eventStore.addMany(events);
893
+ for (const event of events) this.eventStore.attachOne(this, event);
894
+ return this;
895
+ }
896
+ /** @deprecated Use `registerEvent`. */
897
+ registerListener(...events) {
898
+ return this.registerEvent(...events);
899
+ }
900
+ /** Load commands and events from the configured directories. */
901
+ async load() {
902
+ const result = { commands: [], events: [], files: [] };
903
+ for (const directory of this.config.loadDirs) {
904
+ const absolute = (0, import_node_path2.resolve)(directory);
905
+ if (this.loadedDirs.has(absolute)) continue;
906
+ const loaded = await loadDirectory(absolute, {
907
+ ...this.config.extensions ? { extensions: this.config.extensions } : {},
908
+ ignore: this.config.ignore,
909
+ cacheBust: this.config.cacheBust
910
+ });
911
+ this.commands.addMany(loaded.commands);
912
+ this.registerEvent(...loaded.events);
913
+ this.loadedDirs.add(absolute);
914
+ result.commands.push(...loaded.commands);
915
+ result.events.push(...loaded.events);
916
+ result.files.push(...loaded.files);
917
+ }
918
+ return result;
919
+ }
920
+ /** Drop loaded commands/events and scan the configured directories again. */
921
+ async reload() {
922
+ this.eventStore.detach(this);
923
+ this.eventStore.clear();
924
+ this.commands.clear();
925
+ this.cooldowns.clear();
926
+ this.loadedDirs.clear();
927
+ return this.load();
928
+ }
929
+ /**
930
+ * Load modules, attach events and log in.
931
+ *
932
+ * @param token Token to use. Defaults to `FLUXER_BOT_TOKEN`.
933
+ */
934
+ async start(token, options) {
935
+ await this.load();
936
+ this.eventStore.attach(this);
937
+ const resolvedToken = (token ?? process.env.FLUXER_BOT_TOKEN)?.trim();
938
+ if (!resolvedToken) {
939
+ throw new Error(
940
+ "A Fluxer bot token is required. Pass it to start() or set FLUXER_BOT_TOKEN."
941
+ );
942
+ }
943
+ await this.login(resolvedToken, options);
944
+ this.started = true;
945
+ return this;
946
+ }
947
+ /** Detach events, leave voice, and disconnect from Fluxer. */
948
+ async stop() {
949
+ this.eventStore.detach(this);
950
+ this.cooldowns.clear();
951
+ this.started = false;
952
+ await this.voice.leaveAll();
953
+ await this.destroy();
954
+ }
955
+ /** Whether `start()` has been called on this instance. */
956
+ get isStarted() {
957
+ return this.started;
958
+ }
959
+ /** Whether a user ID is in `owners`. */
960
+ isOwner(userId) {
961
+ return this.config.owners.includes(userId);
962
+ }
963
+ /** Called by the event store when an event throws. */
964
+ async handleEventError(error, event, args) {
965
+ if (this.config.onEventError) {
966
+ await this.config.onEventError(error, event.event, args);
967
+ return;
968
+ }
969
+ this.logger.error("Event failed", {
970
+ event: event.event,
971
+ error: String(error)
972
+ });
973
+ }
974
+ /** @deprecated Use `handleEventError`. */
975
+ async handleListenerError(error, event, args) {
976
+ return this.handleEventError(error, event, args);
977
+ }
978
+ async handleMessage(message) {
979
+ if (message.author.bot && !this.config.allowBots) return;
980
+ if (!message.guildId && !this.config.allowDMs) return;
981
+ const prefix = await resolvePrefix(this.config.prefix, message).catch((error) => {
982
+ this.logger.error("Prefix resolver failed", { error: String(error) });
983
+ return null;
984
+ });
985
+ if (!prefix || !message.content.startsWith(prefix)) return;
986
+ const input = message.content.slice(prefix.length).trimStart();
987
+ if (!input) return;
988
+ const [name, ...args] = tokenize(input);
989
+ if (!name) return;
990
+ const command = this.commands.get(name);
991
+ if (!command) return;
992
+ if (command.guildOnly && !message.guildId) {
993
+ await this.replySafely(message, this.config.messages.guildOnly);
994
+ return;
995
+ }
996
+ if (command.ownerOnly && !this.isOwner(message.author.id)) {
997
+ await this.replySafely(message, this.config.messages.ownerOnly);
998
+ return;
999
+ }
1000
+ const ctx = createCommandContext(this, message, command, args, input);
1001
+ await this.runMiddlewares(ctx);
1002
+ }
1003
+ async runMiddlewares(ctx) {
1004
+ const stack = [...this.config.middlewares, ...ctx.command.middlewares];
1005
+ let position = -1;
1006
+ const dispatch = async (index) => {
1007
+ if (index <= position) {
1008
+ throw new Error("next() called more than once in a middleware");
1009
+ }
1010
+ position = index;
1011
+ const middleware = stack[index];
1012
+ if (middleware) {
1013
+ await middleware.run(ctx, () => dispatch(index + 1));
1014
+ return;
1015
+ }
1016
+ const cooldown = this.cooldowns.consume(ctx.command, ctx);
1017
+ if (!cooldown.ok) {
1018
+ await this.replySafely(
1019
+ ctx.message,
1020
+ this.config.messages.cooldown(cooldown.retryAfter)
1021
+ );
1022
+ return;
1023
+ }
1024
+ await ctx.command.run(ctx);
1025
+ };
1026
+ try {
1027
+ await dispatch(0);
1028
+ } catch (error) {
1029
+ await this.handleCommandError(error, ctx);
1030
+ }
1031
+ }
1032
+ async handleCommandError(error, ctx) {
1033
+ if (this.config.onCommandError) {
1034
+ await this.config.onCommandError(error, ctx);
1035
+ return;
1036
+ }
1037
+ this.logger.error("Command failed", { command: ctx.command.name, userId: ctx.author.id, error: String(error) });
1038
+ await this.replySafely(ctx.message, this.config.messages.error);
1039
+ }
1040
+ async replySafely(message, content) {
1041
+ try {
1042
+ await message.reply(content);
1043
+ } catch (error) {
1044
+ this.logger.warn("Could not send reply", { error: String(error) });
1045
+ }
1046
+ }
1047
+ };
1048
+ // Annotate the CommonJS export names for ESM import in node:
1049
+ 0 && (module.exports = {
1050
+ Client
1051
+ });
1052
+ //# sourceMappingURL=client.cjs.map