@wordbombio/sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +374 -0
- package/LICENSE +21 -0
- package/README.md +173 -2
- package/dist/cli.js +4062 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +3166 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1043 -0
- package/dist/index.d.ts +1043 -0
- package/dist/index.js +3113 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,3113 @@
|
|
|
1
|
+
// src/bot.ts
|
|
2
|
+
import { Client } from "@colyseus/sdk";
|
|
3
|
+
|
|
4
|
+
// src/emitter.ts
|
|
5
|
+
function report(event, e) {
|
|
6
|
+
console.error(`[wordbomb] "${String(event)}" listener failed:`, e);
|
|
7
|
+
}
|
|
8
|
+
var Emitter = class {
|
|
9
|
+
listeners = /* @__PURE__ */ new Map();
|
|
10
|
+
on(event, fn) {
|
|
11
|
+
let set = this.listeners.get(event);
|
|
12
|
+
if (!set) {
|
|
13
|
+
set = /* @__PURE__ */ new Set();
|
|
14
|
+
this.listeners.set(event, set);
|
|
15
|
+
}
|
|
16
|
+
set.add(fn);
|
|
17
|
+
return () => this.off(event, fn);
|
|
18
|
+
}
|
|
19
|
+
once(event, fn) {
|
|
20
|
+
const off = this.on(event, (payload) => {
|
|
21
|
+
off();
|
|
22
|
+
return fn(payload);
|
|
23
|
+
});
|
|
24
|
+
return off;
|
|
25
|
+
}
|
|
26
|
+
off(event, fn) {
|
|
27
|
+
this.listeners.get(event)?.delete(fn);
|
|
28
|
+
}
|
|
29
|
+
emit(event, payload) {
|
|
30
|
+
const set = this.listeners.get(event);
|
|
31
|
+
if (!set) return;
|
|
32
|
+
for (const fn of [...set]) {
|
|
33
|
+
try {
|
|
34
|
+
const result = fn(payload);
|
|
35
|
+
if (result instanceof Promise) result.catch((e) => report(event, e));
|
|
36
|
+
} catch (e) {
|
|
37
|
+
report(event, e);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// src/errors.ts
|
|
44
|
+
var WordBombError = class extends Error {
|
|
45
|
+
constructor(code, message, status, retryAfterMs) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.code = code;
|
|
48
|
+
this.status = status;
|
|
49
|
+
this.retryAfterMs = retryAfterMs;
|
|
50
|
+
}
|
|
51
|
+
code;
|
|
52
|
+
status;
|
|
53
|
+
retryAfterMs;
|
|
54
|
+
name = "WordBombError";
|
|
55
|
+
};
|
|
56
|
+
function invalid(path, rule) {
|
|
57
|
+
return new WordBombError("INVALID", `${path} ${rule}`);
|
|
58
|
+
}
|
|
59
|
+
var CLOSE = {
|
|
60
|
+
NORMAL: 4e3,
|
|
61
|
+
BANNED: 4201,
|
|
62
|
+
PLAYING: 4202,
|
|
63
|
+
KICKED: 4203,
|
|
64
|
+
JOIN_TOO_FAST: 4205,
|
|
65
|
+
BOTS_NOT_ALLOWED: 4207,
|
|
66
|
+
BOT_ROOM_LIMIT: 4208,
|
|
67
|
+
APP_NO_ROOMS: 4209,
|
|
68
|
+
ROOM_NOT_FOUND: 4212,
|
|
69
|
+
AUTH_FAILED: 4215
|
|
70
|
+
};
|
|
71
|
+
var REALTIME_CLOSE = {
|
|
72
|
+
REPLACED: 4001,
|
|
73
|
+
REPLACED_ELSEWHERE: 4009,
|
|
74
|
+
BANNED: 4201,
|
|
75
|
+
TOKEN_EXPIRED: 4401
|
|
76
|
+
};
|
|
77
|
+
function readError(e) {
|
|
78
|
+
if (e && typeof e === "object") {
|
|
79
|
+
const code = "code" in e && typeof e.code === "number" ? e.code : 0;
|
|
80
|
+
const message = "message" in e && typeof e.message === "string" ? e.message : String(e);
|
|
81
|
+
return { code, message };
|
|
82
|
+
}
|
|
83
|
+
return { code: 0, message: String(e) };
|
|
84
|
+
}
|
|
85
|
+
function joinError(e) {
|
|
86
|
+
if (e instanceof WordBombError) return e;
|
|
87
|
+
const { code, message } = readError(e);
|
|
88
|
+
switch (code) {
|
|
89
|
+
case CLOSE.BANNED:
|
|
90
|
+
return new WordBombError("BANNED", message || "banned from this room", code);
|
|
91
|
+
case CLOSE.KICKED:
|
|
92
|
+
return new WordBombError("KICKED", message || "kicked from this room", code);
|
|
93
|
+
case CLOSE.JOIN_TOO_FAST:
|
|
94
|
+
return new WordBombError("JOIN_TOO_FAST", message || "joined too many rooms too fast", code);
|
|
95
|
+
case CLOSE.BOTS_NOT_ALLOWED:
|
|
96
|
+
return new WordBombError("BOTS_NOT_ALLOWED", message || "this room does not allow bot accounts", code);
|
|
97
|
+
case CLOSE.PLAYING:
|
|
98
|
+
return new WordBombError("ALREADY_IN_ROOM", message || "this bot is already in that room", code);
|
|
99
|
+
case CLOSE.BOT_ROOM_LIMIT:
|
|
100
|
+
return new WordBombError("BOT_ROOM_LIMIT", message || "this bot is in as many rooms as it may be at once", code);
|
|
101
|
+
case CLOSE.APP_NO_ROOMS:
|
|
102
|
+
return new WordBombError("APP_NO_ROOMS", message || "applications never join rooms, they get them from bot.apps", code);
|
|
103
|
+
case CLOSE.ROOM_NOT_FOUND:
|
|
104
|
+
return new WordBombError("ROOM_NOT_FOUND", message || "room not found", code);
|
|
105
|
+
case CLOSE.AUTH_FAILED:
|
|
106
|
+
return new WordBombError("AUTH_FAILED", message || "room rejected the bot token", code);
|
|
107
|
+
default:
|
|
108
|
+
return new WordBombError("JOIN_FAILED", message || "could not join the room", code || void 0);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/util.ts
|
|
113
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
114
|
+
function str(value, fallback = "") {
|
|
115
|
+
return typeof value === "string" ? value : fallback;
|
|
116
|
+
}
|
|
117
|
+
function num(value, fallback = 0) {
|
|
118
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
119
|
+
return Number.isFinite(n) ? n : fallback;
|
|
120
|
+
}
|
|
121
|
+
function record(value) {
|
|
122
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
123
|
+
}
|
|
124
|
+
function list(value) {
|
|
125
|
+
return Array.isArray(value) ? value : [];
|
|
126
|
+
}
|
|
127
|
+
async function readBody(res) {
|
|
128
|
+
const text = await res.text();
|
|
129
|
+
if (!text) return { data: null, text };
|
|
130
|
+
try {
|
|
131
|
+
return { data: JSON.parse(text), text };
|
|
132
|
+
} catch {
|
|
133
|
+
return { data: text, text };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function errorText(data) {
|
|
137
|
+
const body = record(data);
|
|
138
|
+
for (const key of ["error", "e", "message"]) {
|
|
139
|
+
const value = body[key];
|
|
140
|
+
if (typeof value === "string" && value) return value;
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
function httpError(what, res, data, text) {
|
|
145
|
+
const html = text.trimStart().startsWith("<");
|
|
146
|
+
const reason = errorText(data) ?? (html ? /<pre>([^<]*)<\/pre>/i.exec(text)?.[1] ?? res.statusText : text.slice(0, 200) || res.statusText);
|
|
147
|
+
const message = `${what} ${res.status}: ${reason}`;
|
|
148
|
+
if (res.status === 429) {
|
|
149
|
+
const seconds = Number(res.headers.get("retry-after"));
|
|
150
|
+
return new WordBombError("RATE_LIMITED", message, 429, Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : void 0);
|
|
151
|
+
}
|
|
152
|
+
if (res.status === 401) return new WordBombError("AUTH_FAILED", message, 401);
|
|
153
|
+
if (res.status === 403) return new WordBombError("FORBIDDEN", message, 403);
|
|
154
|
+
if (res.status === 404) return new WordBombError("NOT_FOUND", message, 404);
|
|
155
|
+
return new WordBombError("HTTP", message, res.status);
|
|
156
|
+
}
|
|
157
|
+
function chatIdWith(myId, userId) {
|
|
158
|
+
return [myId, userId].sort().join("_");
|
|
159
|
+
}
|
|
160
|
+
function isUserId(ref) {
|
|
161
|
+
return /^\d{10,}$/.test(ref) || ref.length > 16;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/feed.ts
|
|
165
|
+
var MISS_REASONS = {
|
|
166
|
+
0: "wrong",
|
|
167
|
+
2: "used",
|
|
168
|
+
3: "tooShort",
|
|
169
|
+
4: "noPrompt",
|
|
170
|
+
5: "notAWord",
|
|
171
|
+
6: "selfSolve",
|
|
172
|
+
7: "wrongStart",
|
|
173
|
+
8: "notInCategory",
|
|
174
|
+
9: "bannedLetter",
|
|
175
|
+
10: "wrongLength",
|
|
176
|
+
11: "wrongEnd"
|
|
177
|
+
};
|
|
178
|
+
var GAME_MESSAGES = ["correct", "wrong", "hurt", "eliminated", "start", "stop", "winner"];
|
|
179
|
+
function upperFor(word, locale) {
|
|
180
|
+
try {
|
|
181
|
+
return word.toLocaleUpperCase(locale);
|
|
182
|
+
} catch {
|
|
183
|
+
return word.toUpperCase();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function pickPlayer(all, ref) {
|
|
187
|
+
const want = ref.trim().toLowerCase();
|
|
188
|
+
if (!want) return null;
|
|
189
|
+
return all.find((p) => p.sessionId.toLowerCase() === want || p.id.toLowerCase() === want || p.name.toLowerCase() === want) ?? all.find((p) => p.name.toLowerCase().startsWith(want)) ?? null;
|
|
190
|
+
}
|
|
191
|
+
var REASON_NAMES = new Map(Object.values(MISS_REASONS).map((r) => [r, r]));
|
|
192
|
+
function missReason(result) {
|
|
193
|
+
const code = typeof result === "number" ? result : typeof result === "string" && result !== "" ? Number(result) : -1;
|
|
194
|
+
if (Number.isFinite(code)) return MISS_REASONS[code] ?? "wrong";
|
|
195
|
+
return typeof result === "string" && REASON_NAMES.get(result) || "wrong";
|
|
196
|
+
}
|
|
197
|
+
function dispatch(event, host, sink) {
|
|
198
|
+
const me = host.me();
|
|
199
|
+
const isMine = (sessionId) => !!me && str(sessionId) === me;
|
|
200
|
+
switch (event.t) {
|
|
201
|
+
case "start":
|
|
202
|
+
host.used.clear();
|
|
203
|
+
sink.start({ mode: host.mode(), playing: host.playing(), meIn: host.meIn() });
|
|
204
|
+
return;
|
|
205
|
+
case "stop":
|
|
206
|
+
host.used.clear();
|
|
207
|
+
sink.stop();
|
|
208
|
+
return;
|
|
209
|
+
case "solve": {
|
|
210
|
+
const word = host.upper(event.word);
|
|
211
|
+
if (word) host.used.add(word);
|
|
212
|
+
sink.solve({ player: host.lookup(event.s), word, mine: isMine(event.s) });
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
case "miss": {
|
|
216
|
+
const reason = missReason(event.result);
|
|
217
|
+
if (reason === "used" && event.word) host.used.add(host.upper(event.word));
|
|
218
|
+
sink.miss({ player: host.lookup(event.s), word: event.word, reason, mine: isMine(event.s) });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
case "hurt":
|
|
222
|
+
sink.hurt({ player: host.lookup(event.s), hearts: event.hearts, prompt: event.prompt ?? host.prompt(), mine: isMine(event.s) });
|
|
223
|
+
return;
|
|
224
|
+
case "eliminated":
|
|
225
|
+
sink.eliminated({ player: host.lookup(event.s), mine: isMine(event.s) });
|
|
226
|
+
return;
|
|
227
|
+
case "end": {
|
|
228
|
+
let myPlace = null;
|
|
229
|
+
for (const row of event.rows) if (me && row.sessionId === me) myPlace = row.place;
|
|
230
|
+
const podium = event.rows.filter((row) => row.place > 0).sort((a, b) => a.place - b.place);
|
|
231
|
+
sink.end({ podium, myPlace });
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function podiumRows(payload) {
|
|
237
|
+
return list(payload.stats).map((entry) => {
|
|
238
|
+
const row = record(entry);
|
|
239
|
+
const player = record(row.player);
|
|
240
|
+
return { place: num(row.place), name: str(player.name), sessionId: str(player.session_id) };
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
function feed(type, payload, host, sink) {
|
|
244
|
+
const m = record(payload);
|
|
245
|
+
switch (type) {
|
|
246
|
+
case "correct":
|
|
247
|
+
dispatch({ t: "solve", s: m.id, word: str(m.word) }, host, sink);
|
|
248
|
+
return;
|
|
249
|
+
case "wrong":
|
|
250
|
+
dispatch({ t: "miss", s: m.id, result: num(m.result, -1), word: str(m.word) }, host, sink);
|
|
251
|
+
return;
|
|
252
|
+
case "hurt":
|
|
253
|
+
dispatch({ t: "hurt", s: m.id, hearts: num(m.heart), prompt: typeof m.prompt === "string" ? m.prompt : null }, host, sink);
|
|
254
|
+
return;
|
|
255
|
+
case "eliminated":
|
|
256
|
+
dispatch({ t: "eliminated", s: m.id }, host, sink);
|
|
257
|
+
return;
|
|
258
|
+
case "start":
|
|
259
|
+
dispatch({ t: "start" }, host, sink);
|
|
260
|
+
return;
|
|
261
|
+
case "stop":
|
|
262
|
+
dispatch({ t: "stop" }, host, sink);
|
|
263
|
+
return;
|
|
264
|
+
case "winner":
|
|
265
|
+
dispatch({ t: "end", rows: podiumRows(m) }, host, sink);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// src/app.ts
|
|
271
|
+
var APP_ROOM_EVENT_SET = {
|
|
272
|
+
"room.ready": true,
|
|
273
|
+
"room.state": true,
|
|
274
|
+
"room.close": true,
|
|
275
|
+
"room.player.joined": true,
|
|
276
|
+
"room.player.left": true,
|
|
277
|
+
"game.start": true,
|
|
278
|
+
"game.solve": true,
|
|
279
|
+
"game.miss": true,
|
|
280
|
+
"game.hurt": true,
|
|
281
|
+
"game.eliminated": true,
|
|
282
|
+
"game.end": true,
|
|
283
|
+
"game.stop": true,
|
|
284
|
+
command: true,
|
|
285
|
+
button: true
|
|
286
|
+
};
|
|
287
|
+
var APP_ROOM_EVENTS = Object.keys(APP_ROOM_EVENT_SET);
|
|
288
|
+
function fields(line, count) {
|
|
289
|
+
const out = [];
|
|
290
|
+
let from = 2;
|
|
291
|
+
for (let i = 1; i < count; i++) {
|
|
292
|
+
const at = line.indexOf(":", from);
|
|
293
|
+
if (at < 0) break;
|
|
294
|
+
out.push(line.slice(from, at));
|
|
295
|
+
from = at + 1;
|
|
296
|
+
}
|
|
297
|
+
out.push(from <= line.length ? line.slice(from) : "");
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
var AppRoom = class extends Emitter {
|
|
301
|
+
constructor(id, ctx) {
|
|
302
|
+
super();
|
|
303
|
+
this.id = id;
|
|
304
|
+
this.feedHost = {
|
|
305
|
+
used: this.used,
|
|
306
|
+
me: () => "",
|
|
307
|
+
mode: () => this.modeId,
|
|
308
|
+
prompt: () => this.letters,
|
|
309
|
+
playing: () => {
|
|
310
|
+
let playing = 0;
|
|
311
|
+
for (const seat of this.seats.values()) if (seat.hearts > 0) playing++;
|
|
312
|
+
return playing;
|
|
313
|
+
},
|
|
314
|
+
meIn: () => false,
|
|
315
|
+
lookup: (sid) => this.lookup(str(sid)),
|
|
316
|
+
upper: (word) => upperFor(word, this.lang)
|
|
317
|
+
};
|
|
318
|
+
this.sink = {
|
|
319
|
+
start: (e) => this.emit("game.start", { room: this, ...e }),
|
|
320
|
+
stop: () => {
|
|
321
|
+
this.running = false;
|
|
322
|
+
this.turnSession = "";
|
|
323
|
+
this.emit("game.stop", { room: this });
|
|
324
|
+
},
|
|
325
|
+
solve: (e) => this.emit("game.solve", { room: this, ...e }),
|
|
326
|
+
miss: (e) => this.emit("game.miss", { room: this, ...e }),
|
|
327
|
+
hurt: (e) => this.emit("game.hurt", { room: this, ...e }),
|
|
328
|
+
eliminated: (e) => this.emit("game.eliminated", { room: this, ...e }),
|
|
329
|
+
end: (e) => this.emit("game.end", { room: this, ...e })
|
|
330
|
+
};
|
|
331
|
+
this.channel = ctx.channel(this, {
|
|
332
|
+
command: (interaction) => this.emit("command", interaction),
|
|
333
|
+
button: (interaction) => this.emit("button", interaction)
|
|
334
|
+
});
|
|
335
|
+
this.channel.sync(id);
|
|
336
|
+
ctx.bind(this, { apply: (lines) => this.apply(lines), close: () => this.close() });
|
|
337
|
+
}
|
|
338
|
+
id;
|
|
339
|
+
used = /* @__PURE__ */ new Set();
|
|
340
|
+
seats = /* @__PURE__ */ new Map();
|
|
341
|
+
gone = /* @__PURE__ */ new Map();
|
|
342
|
+
channel;
|
|
343
|
+
feedHost;
|
|
344
|
+
sink;
|
|
345
|
+
modeId = 0;
|
|
346
|
+
lang = "en-US";
|
|
347
|
+
running = false;
|
|
348
|
+
turnSession = "";
|
|
349
|
+
letters = "";
|
|
350
|
+
ready = false;
|
|
351
|
+
open = true;
|
|
352
|
+
get isOpen() {
|
|
353
|
+
return this.open;
|
|
354
|
+
}
|
|
355
|
+
get mode() {
|
|
356
|
+
return this.modeId;
|
|
357
|
+
}
|
|
358
|
+
get locale() {
|
|
359
|
+
return this.lang;
|
|
360
|
+
}
|
|
361
|
+
get started() {
|
|
362
|
+
return this.running;
|
|
363
|
+
}
|
|
364
|
+
get prompt() {
|
|
365
|
+
return this.letters;
|
|
366
|
+
}
|
|
367
|
+
get players() {
|
|
368
|
+
return [...this.seats.values()].map((seat) => this.toPlayer(seat));
|
|
369
|
+
}
|
|
370
|
+
get currentPlayer() {
|
|
371
|
+
return this.running && this.turnSession ? this.lookup(this.turnSession) : null;
|
|
372
|
+
}
|
|
373
|
+
player(ref) {
|
|
374
|
+
const hit = pickPlayer(this.players, ref);
|
|
375
|
+
if (!hit) throw new WordBombError("NOT_FOUND", `nobody called "${ref}" in app room ${this.id}`);
|
|
376
|
+
return hit;
|
|
377
|
+
}
|
|
378
|
+
async post(message) {
|
|
379
|
+
if (!this.open) throw new WordBombError("NOT_IN_ROOM", `app room ${this.id} is closed`);
|
|
380
|
+
return this.channel.post(message);
|
|
381
|
+
}
|
|
382
|
+
toPlayer(seat) {
|
|
383
|
+
return {
|
|
384
|
+
sessionId: seat.sid,
|
|
385
|
+
id: seat.id,
|
|
386
|
+
name: seat.name,
|
|
387
|
+
avatar: "",
|
|
388
|
+
hearts: seat.hearts,
|
|
389
|
+
eliminated: seat.eliminated,
|
|
390
|
+
spectating: seat.spectating,
|
|
391
|
+
isHost: false,
|
|
392
|
+
isMe: false,
|
|
393
|
+
isTurn: this.running && this.turnSession === seat.sid,
|
|
394
|
+
isGuest: seat.id.length < 10,
|
|
395
|
+
isBot: seat.bot,
|
|
396
|
+
language: this.lang
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
lookup(sid) {
|
|
400
|
+
const seat = this.seats.get(sid);
|
|
401
|
+
return seat ? this.toPlayer(seat) : this.gone.get(sid) ?? null;
|
|
402
|
+
}
|
|
403
|
+
feed(event) {
|
|
404
|
+
dispatch(event, this.feedHost, this.sink);
|
|
405
|
+
}
|
|
406
|
+
close() {
|
|
407
|
+
if (!this.open) return;
|
|
408
|
+
this.open = false;
|
|
409
|
+
this.channel.close();
|
|
410
|
+
this.emit("room.close", { room: this });
|
|
411
|
+
}
|
|
412
|
+
apply(lines) {
|
|
413
|
+
if (!this.open) return;
|
|
414
|
+
let snapshot = false;
|
|
415
|
+
let head = false;
|
|
416
|
+
let changed = false;
|
|
417
|
+
for (const line of lines) {
|
|
418
|
+
const tag = line[0];
|
|
419
|
+
if (!tag || line.length > 1 && line[1] !== ":") continue;
|
|
420
|
+
if (tag !== "j") snapshot = false;
|
|
421
|
+
switch (tag) {
|
|
422
|
+
case "S": {
|
|
423
|
+
const [mode = "", locale = "", started = ""] = fields(line, 3);
|
|
424
|
+
this.modeId = num(mode);
|
|
425
|
+
this.lang = locale || this.lang;
|
|
426
|
+
this.running = started === "1";
|
|
427
|
+
this.seats.clear();
|
|
428
|
+
this.gone.clear();
|
|
429
|
+
this.turnSession = "";
|
|
430
|
+
snapshot = true;
|
|
431
|
+
head = true;
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
case "j": {
|
|
435
|
+
const [sid = "", id = "", bot = "", spec = "", life = "", name = ""] = fields(line, 6);
|
|
436
|
+
if (!sid) break;
|
|
437
|
+
const known = this.seats.get(sid);
|
|
438
|
+
const fresh = !known;
|
|
439
|
+
const spectating = spec === "1";
|
|
440
|
+
const hearts = num(life);
|
|
441
|
+
const out = !spectating && (hearts <= 0 || !!known?.eliminated && !snapshot);
|
|
442
|
+
const seat = { sid, id, name: name || "Guest", bot: bot === "1", spectating, hearts, eliminated: this.running && out };
|
|
443
|
+
this.seats.set(sid, seat);
|
|
444
|
+
this.gone.delete(sid);
|
|
445
|
+
if (fresh && !snapshot) this.emit("room.player.joined", { room: this, player: this.toPlayer(seat) });
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
case "l": {
|
|
449
|
+
const [sid = ""] = fields(line, 1);
|
|
450
|
+
const seat = this.seats.get(sid);
|
|
451
|
+
if (!seat) break;
|
|
452
|
+
const player = this.toPlayer(seat);
|
|
453
|
+
this.seats.delete(sid);
|
|
454
|
+
this.gone.set(sid, player);
|
|
455
|
+
if (this.gone.size > 64) {
|
|
456
|
+
const oldest = this.gone.keys().next().value;
|
|
457
|
+
if (oldest !== void 0) this.gone.delete(oldest);
|
|
458
|
+
}
|
|
459
|
+
this.emit("room.player.left", { room: this, player });
|
|
460
|
+
break;
|
|
461
|
+
}
|
|
462
|
+
case "g":
|
|
463
|
+
this.running = true;
|
|
464
|
+
for (const seat of this.seats.values()) seat.eliminated = false;
|
|
465
|
+
this.feed({ t: "start" });
|
|
466
|
+
break;
|
|
467
|
+
case "G": {
|
|
468
|
+
const [winners = ""] = fields(line, 1);
|
|
469
|
+
const rows = [];
|
|
470
|
+
for (const sid of winners.split(",")) {
|
|
471
|
+
if (sid) rows.push({ place: 1, name: this.lookup(sid)?.name ?? "", sessionId: sid });
|
|
472
|
+
}
|
|
473
|
+
this.feed({ t: "end", rows });
|
|
474
|
+
this.feed({ t: "stop" });
|
|
475
|
+
break;
|
|
476
|
+
}
|
|
477
|
+
case "t": {
|
|
478
|
+
const [sid = "", prompt = ""] = fields(line, 2);
|
|
479
|
+
this.running = true;
|
|
480
|
+
this.turnSession = sid;
|
|
481
|
+
this.letters = prompt;
|
|
482
|
+
break;
|
|
483
|
+
}
|
|
484
|
+
case "c": {
|
|
485
|
+
const [sid = "", word = ""] = fields(line, 2);
|
|
486
|
+
this.feed({ t: "solve", s: sid, word });
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
case "x": {
|
|
490
|
+
const [sid = "", result = "", word = ""] = fields(line, 3);
|
|
491
|
+
this.feed({ t: "miss", s: sid, result, word });
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
case "h": {
|
|
495
|
+
const [sid = "", value = ""] = fields(line, 2);
|
|
496
|
+
const hearts = num(value);
|
|
497
|
+
const seat = this.seats.get(sid);
|
|
498
|
+
if (seat) seat.hearts = hearts;
|
|
499
|
+
this.feed({ t: "hurt", s: sid, hearts, prompt: null });
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
case "e": {
|
|
503
|
+
const [sid = ""] = fields(line, 1);
|
|
504
|
+
const seat = this.seats.get(sid);
|
|
505
|
+
if (seat) {
|
|
506
|
+
seat.eliminated = true;
|
|
507
|
+
seat.hearts = 0;
|
|
508
|
+
}
|
|
509
|
+
this.feed({ t: "eliminated", s: sid });
|
|
510
|
+
break;
|
|
511
|
+
}
|
|
512
|
+
default:
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
changed = true;
|
|
516
|
+
}
|
|
517
|
+
if (!this.ready && (head || this.seats.size)) {
|
|
518
|
+
this.ready = true;
|
|
519
|
+
this.emit("room.ready", { room: this });
|
|
520
|
+
}
|
|
521
|
+
if (changed && this.ready) this.emit("room.state", { room: this });
|
|
522
|
+
}
|
|
523
|
+
};
|
|
524
|
+
var REANNOUNCE_WAIT = 1e4;
|
|
525
|
+
var Apps = class extends Emitter {
|
|
526
|
+
constructor(interactions, realtime) {
|
|
527
|
+
super();
|
|
528
|
+
this.interactions = interactions;
|
|
529
|
+
realtime?.on("event", ({ e, d }) => {
|
|
530
|
+
if (e === "app:ev") this.onEvents(d);
|
|
531
|
+
else if (e === "app:room") this.onRoom(d);
|
|
532
|
+
});
|
|
533
|
+
realtime?.on("up", () => this.recheck());
|
|
534
|
+
realtime?.on("closed", () => this.closeAll());
|
|
535
|
+
}
|
|
536
|
+
interactions;
|
|
537
|
+
open = /* @__PURE__ */ new Map();
|
|
538
|
+
unconfirmed = /* @__PURE__ */ new Set();
|
|
539
|
+
recheckTimer = null;
|
|
540
|
+
get all() {
|
|
541
|
+
return [...this.open.values()].map((entry) => entry.room);
|
|
542
|
+
}
|
|
543
|
+
get(id) {
|
|
544
|
+
return this.open.get(id)?.room ?? null;
|
|
545
|
+
}
|
|
546
|
+
recheck() {
|
|
547
|
+
this.stopRecheck();
|
|
548
|
+
for (const key of this.open.keys()) this.unconfirmed.add(key);
|
|
549
|
+
if (!this.unconfirmed.size) return;
|
|
550
|
+
this.recheckTimer = setTimeout(() => {
|
|
551
|
+
this.recheckTimer = null;
|
|
552
|
+
for (const key of [...this.unconfirmed]) this.open.get(key)?.controls.close();
|
|
553
|
+
this.unconfirmed.clear();
|
|
554
|
+
}, REANNOUNCE_WAIT);
|
|
555
|
+
}
|
|
556
|
+
stopRecheck() {
|
|
557
|
+
if (this.recheckTimer) clearTimeout(this.recheckTimer);
|
|
558
|
+
this.recheckTimer = null;
|
|
559
|
+
this.unconfirmed.clear();
|
|
560
|
+
}
|
|
561
|
+
closeAll() {
|
|
562
|
+
this.stopRecheck();
|
|
563
|
+
for (const { controls } of [...this.open.values()]) controls.close();
|
|
564
|
+
}
|
|
565
|
+
onRoom(d) {
|
|
566
|
+
const frame = record(d);
|
|
567
|
+
const key = str(frame.k);
|
|
568
|
+
if (!key) return;
|
|
569
|
+
this.unconfirmed.delete(key);
|
|
570
|
+
if (frame.open === false || frame.open === 0) this.open.get(key)?.controls.close();
|
|
571
|
+
else this.ensure(key);
|
|
572
|
+
}
|
|
573
|
+
onEvents(d) {
|
|
574
|
+
let key;
|
|
575
|
+
let lines;
|
|
576
|
+
if (typeof d === "string") {
|
|
577
|
+
const cut = d.indexOf("\n");
|
|
578
|
+
key = cut < 0 ? d : d.slice(0, cut);
|
|
579
|
+
lines = cut < 0 ? [] : d.slice(cut + 1).split("\n");
|
|
580
|
+
} else {
|
|
581
|
+
const frame = record(d);
|
|
582
|
+
key = str(frame.k);
|
|
583
|
+
const ev = frame.ev;
|
|
584
|
+
lines = typeof ev === "string" ? ev.split("\n") : list(ev).map((line) => str(line));
|
|
585
|
+
}
|
|
586
|
+
if (!key || !lines.length) return;
|
|
587
|
+
this.unconfirmed.delete(key);
|
|
588
|
+
this.ensure(key).apply(lines);
|
|
589
|
+
}
|
|
590
|
+
ensure(key) {
|
|
591
|
+
const existing = this.open.get(key);
|
|
592
|
+
if (existing) return existing.controls;
|
|
593
|
+
const holder = {};
|
|
594
|
+
const room = new AppRoom(key, {
|
|
595
|
+
channel: (r, sink) => this.interactions.attach(r, sink, false),
|
|
596
|
+
bind: (_, controls) => {
|
|
597
|
+
holder.controls = controls;
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
const bound = holder.controls;
|
|
601
|
+
if (!bound) throw new WordBombError("INVALID", "app room failed to bind");
|
|
602
|
+
this.open.set(key, { room, controls: bound });
|
|
603
|
+
const relay = this.emit.bind(this);
|
|
604
|
+
for (const name of APP_ROOM_EVENTS) room.on(name, (payload) => relay(name, payload));
|
|
605
|
+
room.once("room.close", () => {
|
|
606
|
+
if (this.open.get(key)?.room === room) this.open.delete(key);
|
|
607
|
+
});
|
|
608
|
+
this.emit("room.open", { room });
|
|
609
|
+
return bound;
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
// src/commands.ts
|
|
614
|
+
var NAME = /^[a-z0-9_-]{1,32}$/;
|
|
615
|
+
var MAX_COMMANDS = 25;
|
|
616
|
+
var MAX_OPTIONS = 10;
|
|
617
|
+
var MAX_CHOICES = 25;
|
|
618
|
+
var MAX_CHOICE = 50;
|
|
619
|
+
var MAX_DESCRIPTION = 100;
|
|
620
|
+
var OPTION_TYPES = ["string", "number", "player", "message", "choice"];
|
|
621
|
+
var LINK = /https?:\/\/[^\s]+|[a-z0-9][-a-z0-9]*\.(com|gg|io|net|org|fun|xyz|dev|app|me|tv|cc|co|us|uk|ru|de|fr|pro|link|click|info|biz|ws|top|site|online|live|store|space|tech|world)\b/i;
|
|
622
|
+
var HIDDEN = new RegExp("[\\u{0}-\\u{1F}\\u{7F}-\\u{9F}\\u{A0}\\u{200B}\\u{200C}\\u{FEFF}\\u{202A}-\\u{202E}\\u{2066}-\\u{2069}]|(?<!\\p{Extended_Pictographic}[\\u{FE0F}\\p{Emoji_Modifier}]?)\\u{200D}|\\u{200D}(?!\\p{Extended_Pictographic})", "u");
|
|
623
|
+
var BUILT_IN = /* @__PURE__ */ new Set([
|
|
624
|
+
"admin",
|
|
625
|
+
"bm",
|
|
626
|
+
"bookmark",
|
|
627
|
+
"cards",
|
|
628
|
+
"clear",
|
|
629
|
+
"discord",
|
|
630
|
+
"draw",
|
|
631
|
+
"emergency",
|
|
632
|
+
"end",
|
|
633
|
+
"i",
|
|
634
|
+
"invite",
|
|
635
|
+
"kraken",
|
|
636
|
+
"lootbox",
|
|
637
|
+
"love",
|
|
638
|
+
"missing",
|
|
639
|
+
"monster",
|
|
640
|
+
"play",
|
|
641
|
+
"s",
|
|
642
|
+
"settings",
|
|
643
|
+
"solve",
|
|
644
|
+
"suggest",
|
|
645
|
+
"surrender",
|
|
646
|
+
"syl",
|
|
647
|
+
"title",
|
|
648
|
+
"vote",
|
|
649
|
+
"whisper"
|
|
650
|
+
]);
|
|
651
|
+
function nameOf(value, path) {
|
|
652
|
+
const raw = typeof value === "string" ? value.trim() : "";
|
|
653
|
+
const name = raw.startsWith("/") ? raw.slice(1) : raw;
|
|
654
|
+
if (!NAME.test(name)) throw invalid(path, `"${raw}" must be 1 to 32 lowercase letters, digits, _ or -`);
|
|
655
|
+
return name;
|
|
656
|
+
}
|
|
657
|
+
function textOf(value, path, max) {
|
|
658
|
+
if (typeof value !== "string" || !value.trim()) throw invalid(path, "is required");
|
|
659
|
+
if (value.length > max) throw invalid(path, `is ${value.length} characters, the limit is ${max}`);
|
|
660
|
+
if (LINK.test(value)) throw invalid(path, "can't contain links");
|
|
661
|
+
if (HIDDEN.test(value)) throw invalid(path, "can't contain control, bidi or invisible characters (tabs, line breaks, no-break or zero-width spaces)");
|
|
662
|
+
return value;
|
|
663
|
+
}
|
|
664
|
+
function choicesOf(value, path, last) {
|
|
665
|
+
if (!Array.isArray(value) || !value.length) throw invalid(path, "needs at least one choice");
|
|
666
|
+
if (value.length > MAX_CHOICES) throw invalid(path, `has ${value.length} choices, the limit is ${MAX_CHOICES}`);
|
|
667
|
+
return value.map((choice, index) => {
|
|
668
|
+
const text = textOf(choice, `${path}[${index}]`, MAX_CHOICE);
|
|
669
|
+
if (!last && /\s/.test(text)) throw invalid(`${path}[${index}]`, "can only contain spaces when it is the last option");
|
|
670
|
+
return text;
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
function optionsOf(value, path) {
|
|
674
|
+
if (value === void 0 || value === null) return [];
|
|
675
|
+
if (!Array.isArray(value)) throw invalid(path, "must be an array");
|
|
676
|
+
if (value.length > MAX_OPTIONS) throw invalid(path, `has ${value.length} options, the limit is ${MAX_OPTIONS}`);
|
|
677
|
+
const names = /* @__PURE__ */ new Set();
|
|
678
|
+
return value.map((entry, index) => {
|
|
679
|
+
const at = `${path}[${index}]`;
|
|
680
|
+
const o = record(entry);
|
|
681
|
+
const name = nameOf(o.name, `${at}.name`);
|
|
682
|
+
if (names.has(name)) throw invalid(`${at}.name`, `"${name}" is used twice`);
|
|
683
|
+
names.add(name);
|
|
684
|
+
const type = OPTION_TYPES.find((t) => t === o.type);
|
|
685
|
+
if (!type) throw invalid(`${at}.type`, `must be one of ${OPTION_TYPES.join(", ")}`);
|
|
686
|
+
if (type === "message" && index !== value.length - 1) throw invalid(at, "a message option must be the last option");
|
|
687
|
+
const def = { name, description: textOf(o.description, `${at}.description`, MAX_DESCRIPTION), type };
|
|
688
|
+
if (o.required === true) def.required = true;
|
|
689
|
+
else if (o.required !== void 0 && o.required !== false) throw invalid(`${at}.required`, "must be true or false");
|
|
690
|
+
if (type === "choice") def.choices = choicesOf(o.choices, `${at}.choices`, index === value.length - 1);
|
|
691
|
+
else if (o.choices !== void 0) throw invalid(`${at}.choices`, "only goes with type choice");
|
|
692
|
+
return def;
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
function normalizeCommands(input) {
|
|
696
|
+
if (!Array.isArray(input)) throw invalid("commands", "must be an array");
|
|
697
|
+
if (input.length > MAX_COMMANDS) throw invalid("commands", `has ${input.length} commands, the limit is ${MAX_COMMANDS}`);
|
|
698
|
+
const names = /* @__PURE__ */ new Set();
|
|
699
|
+
return input.map((entry, index) => {
|
|
700
|
+
const at = `commands[${index}]`;
|
|
701
|
+
const c = record(entry);
|
|
702
|
+
const name = nameOf(c.name, `${at}.name`);
|
|
703
|
+
if (BUILT_IN.has(name)) throw invalid(`${at}.name`, `/${name} is a built-in command`);
|
|
704
|
+
if (names.has(name)) throw invalid(`${at}.name`, `/${name} is defined twice`);
|
|
705
|
+
names.add(name);
|
|
706
|
+
const def = { name, description: textOf(c.description, `${at}.description`, MAX_DESCRIPTION) };
|
|
707
|
+
const options = optionsOf(c.options, `${at}.options`);
|
|
708
|
+
if (options.length) def.options = options;
|
|
709
|
+
return def;
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
function canonical(value) {
|
|
713
|
+
return JSON.stringify(
|
|
714
|
+
list(value).map((entry) => {
|
|
715
|
+
const c = record(entry);
|
|
716
|
+
return [
|
|
717
|
+
str(c.name),
|
|
718
|
+
str(c.description),
|
|
719
|
+
list(c.options).map((option) => {
|
|
720
|
+
const o = record(option);
|
|
721
|
+
return [str(o.name), str(o.description), str(o.type), o.required === true, list(o.choices).map((choice) => str(choice))];
|
|
722
|
+
})
|
|
723
|
+
];
|
|
724
|
+
})
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
var Commands = class {
|
|
728
|
+
constructor(http, session) {
|
|
729
|
+
this.http = http;
|
|
730
|
+
this.session = session;
|
|
731
|
+
}
|
|
732
|
+
http;
|
|
733
|
+
session;
|
|
734
|
+
current = [];
|
|
735
|
+
byName = /* @__PURE__ */ new Map();
|
|
736
|
+
v = 0;
|
|
737
|
+
queue = Promise.resolve();
|
|
738
|
+
get all() {
|
|
739
|
+
return this.current;
|
|
740
|
+
}
|
|
741
|
+
get version() {
|
|
742
|
+
return this.v;
|
|
743
|
+
}
|
|
744
|
+
get(name) {
|
|
745
|
+
return this.byName.get(name.startsWith("/") ? name.slice(1) : name) ?? null;
|
|
746
|
+
}
|
|
747
|
+
set(defs) {
|
|
748
|
+
let clean;
|
|
749
|
+
try {
|
|
750
|
+
clean = normalizeCommands(defs);
|
|
751
|
+
} catch (e) {
|
|
752
|
+
return Promise.reject(e);
|
|
753
|
+
}
|
|
754
|
+
const run = this.queue.then(
|
|
755
|
+
() => this.sync(clean),
|
|
756
|
+
() => this.sync(clean)
|
|
757
|
+
);
|
|
758
|
+
this.queue = run.catch(() => {
|
|
759
|
+
});
|
|
760
|
+
return run;
|
|
761
|
+
}
|
|
762
|
+
async sync(clean) {
|
|
763
|
+
const remote = await this.remote();
|
|
764
|
+
if (canonical(remote.cmds) !== canonical(clean)) {
|
|
765
|
+
try {
|
|
766
|
+
remote.v = num(record(await this.http.put("player", "/bots/me/commands", { cmds: clean })).v, remote.v);
|
|
767
|
+
} catch (e) {
|
|
768
|
+
if (e instanceof WordBombError && e.status === 400) throw new WordBombError("INVALID", e.message, 400);
|
|
769
|
+
throw e;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
this.current = clean;
|
|
773
|
+
this.byName.clear();
|
|
774
|
+
for (const def of clean) this.byName.set(def.name, def);
|
|
775
|
+
this.v = remote.v;
|
|
776
|
+
return this.v;
|
|
777
|
+
}
|
|
778
|
+
async remote() {
|
|
779
|
+
try {
|
|
780
|
+
const r = record(await this.http.get("player", `/bots/${this.session.me.id}/commands`));
|
|
781
|
+
return { v: num(r.v), cmds: r.cmds ?? [] };
|
|
782
|
+
} catch (e) {
|
|
783
|
+
if (e instanceof WordBombError && e.code === "NOT_FOUND") return { v: 0, cmds: [] };
|
|
784
|
+
throw e;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
|
|
789
|
+
// src/cosmetics.ts
|
|
790
|
+
var KINDS = {
|
|
791
|
+
bomb: { owned: "bombs", equipped: "bomb", message: "equip-bomb" },
|
|
792
|
+
heart: { owned: "hearts", equipped: "heart", message: "equip-heart" },
|
|
793
|
+
ghost: { owned: "ghosts", equipped: "ghost", message: "equip-ghost", none: -1 },
|
|
794
|
+
streak: { owned: "streaks", equipped: "streak", message: "equip-streak" },
|
|
795
|
+
letter: { owned: "letters", equipped: "letter", message: "equip-letter" },
|
|
796
|
+
explosion: { owned: "explosions", equipped: "explosion", message: "equip-explosion" },
|
|
797
|
+
combo: { owned: "comboSkins", equipped: "comboSkin", message: "equip-combo" }
|
|
798
|
+
};
|
|
799
|
+
var COSMETIC_KINDS = Object.keys(KINDS);
|
|
800
|
+
var Cosmetics = class {
|
|
801
|
+
constructor(session, rooms, lobby) {
|
|
802
|
+
this.session = session;
|
|
803
|
+
this.rooms = rooms;
|
|
804
|
+
this.lobby = lobby;
|
|
805
|
+
}
|
|
806
|
+
session;
|
|
807
|
+
rooms;
|
|
808
|
+
lobby;
|
|
809
|
+
owned(kind) {
|
|
810
|
+
const raw = this.session.me.data[KINDS[kind].owned];
|
|
811
|
+
if (typeof raw === "string") return raw.split(",").filter(Boolean).map(Number);
|
|
812
|
+
return Array.isArray(raw) ? raw.map((v) => num(v)) : [];
|
|
813
|
+
}
|
|
814
|
+
equipped(kind) {
|
|
815
|
+
const spec = KINDS[kind];
|
|
816
|
+
return num(this.session.me.data[spec.equipped], spec.none ?? 0);
|
|
817
|
+
}
|
|
818
|
+
async equip(kind, id) {
|
|
819
|
+
const spec = KINDS[kind];
|
|
820
|
+
const off = spec.none !== void 0 && id === spec.none;
|
|
821
|
+
if (!off && id !== 0 && !this.owned(kind).includes(id)) await this.session.refresh();
|
|
822
|
+
if (!off && id !== 0 && !this.owned(kind).includes(id)) throw new WordBombError("FORBIDDEN", `this bot does not own ${kind} ${id}`);
|
|
823
|
+
const rooms = this.rooms.all.filter((room) => room.isOpen);
|
|
824
|
+
for (const room of rooms) room.raw.send(spec.message, { id });
|
|
825
|
+
if (!rooms.length) await this.lobby.send(spec.message, { id });
|
|
826
|
+
this.session.me.data[spec.equipped] = id;
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
|
|
830
|
+
// src/http.ts
|
|
831
|
+
var Http = class {
|
|
832
|
+
constructor(session) {
|
|
833
|
+
this.session = session;
|
|
834
|
+
}
|
|
835
|
+
session;
|
|
836
|
+
async request(service, route, init = {}) {
|
|
837
|
+
let res = await this.send(service, route, init);
|
|
838
|
+
if (res.status === 401) {
|
|
839
|
+
await this.session.refresh();
|
|
840
|
+
res = await this.send(service, route, init);
|
|
841
|
+
}
|
|
842
|
+
const { data, text } = await readBody(res);
|
|
843
|
+
if (!res.ok) throw httpError(route, res, data, text);
|
|
844
|
+
return data;
|
|
845
|
+
}
|
|
846
|
+
get(service, route) {
|
|
847
|
+
return this.request(service, route);
|
|
848
|
+
}
|
|
849
|
+
post(service, route, body = {}) {
|
|
850
|
+
return this.request(service, route, { method: "POST", body });
|
|
851
|
+
}
|
|
852
|
+
put(service, route, body = {}) {
|
|
853
|
+
return this.request(service, route, { method: "PUT", body });
|
|
854
|
+
}
|
|
855
|
+
delete(service, route, body) {
|
|
856
|
+
return this.request(service, route, { method: "DELETE", body });
|
|
857
|
+
}
|
|
858
|
+
async send(service, route, init) {
|
|
859
|
+
const headers = { Authorization: `Bearer ${this.session.token}` };
|
|
860
|
+
if (init.body !== void 0) headers["Content-Type"] = "application/json";
|
|
861
|
+
const url = `${this.session.target[service]}${route}`;
|
|
862
|
+
try {
|
|
863
|
+
return await fetch(url, {
|
|
864
|
+
method: init.method ?? (init.body !== void 0 ? "POST" : "GET"),
|
|
865
|
+
headers,
|
|
866
|
+
body: init.body !== void 0 ? JSON.stringify(init.body) : void 0
|
|
867
|
+
});
|
|
868
|
+
} catch (e) {
|
|
869
|
+
throw new WordBombError("HTTP", `could not reach ${url}: ${e instanceof Error ? e.message : String(e)}`);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
|
|
874
|
+
// src/embeds.ts
|
|
875
|
+
var CDN_HOST = "wcdn.wordbomb.io";
|
|
876
|
+
var TEXT_MAX = 2e3;
|
|
877
|
+
var TOTAL_MAX = 6e3;
|
|
878
|
+
var TITLE_MAX = 256;
|
|
879
|
+
var DESCRIPTION_MAX = 2048;
|
|
880
|
+
var AUTHOR_MAX = 64;
|
|
881
|
+
var FIELDS_MAX = 10;
|
|
882
|
+
var FIELD_NAME_MAX = 64;
|
|
883
|
+
var FIELD_VALUE_MAX = 512;
|
|
884
|
+
var FOOTER_MAX = 128;
|
|
885
|
+
var ROWS_MAX = 2;
|
|
886
|
+
var BUTTONS_MAX = 5;
|
|
887
|
+
var LABEL_MAX = 40;
|
|
888
|
+
var CUSTOM_ID_MAX = 64;
|
|
889
|
+
var STYLES = [1, 2, 3, 4];
|
|
890
|
+
var absent = (value) => value === void 0 || value === null;
|
|
891
|
+
function optionalText(value, path, max) {
|
|
892
|
+
if (absent(value)) return void 0;
|
|
893
|
+
if (typeof value !== "string") throw invalid(path, "must be a string");
|
|
894
|
+
if (value.length > max) throw invalid(path, `is ${value.length} characters, the limit is ${max}`);
|
|
895
|
+
return value.trim() ? value : void 0;
|
|
896
|
+
}
|
|
897
|
+
function requiredText(value, path, max) {
|
|
898
|
+
const text = optionalText(value, path, max);
|
|
899
|
+
if (!text) throw invalid(path, "is required");
|
|
900
|
+
return text;
|
|
901
|
+
}
|
|
902
|
+
function parseHttps(value) {
|
|
903
|
+
try {
|
|
904
|
+
const url = new URL(value);
|
|
905
|
+
return url.protocol === "https:" ? url : null;
|
|
906
|
+
} catch {
|
|
907
|
+
return null;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
function httpsUrl(value, path) {
|
|
911
|
+
const text = optionalText(value, path, Infinity);
|
|
912
|
+
if (!text) return void 0;
|
|
913
|
+
if (!parseHttps(text)) throw invalid(path, "must be an https URL");
|
|
914
|
+
return text;
|
|
915
|
+
}
|
|
916
|
+
function urlObject(value, path) {
|
|
917
|
+
if (absent(value)) return void 0;
|
|
918
|
+
const url = httpsUrl(record(value).url, `${path}.url`);
|
|
919
|
+
if (!url) throw invalid(`${path}.url`, "is required");
|
|
920
|
+
return { url };
|
|
921
|
+
}
|
|
922
|
+
function array(value, path, max) {
|
|
923
|
+
if (absent(value)) return void 0;
|
|
924
|
+
if (!Array.isArray(value)) throw invalid(path, "must be an array");
|
|
925
|
+
if (value.length > max) throw invalid(path, `has ${value.length} entries, the limit is ${max}`);
|
|
926
|
+
return value;
|
|
927
|
+
}
|
|
928
|
+
function buttonStyle(value, path) {
|
|
929
|
+
if (absent(value)) return 1;
|
|
930
|
+
const style = STYLES.find((s) => s === value);
|
|
931
|
+
if (style === void 0) throw invalid(path, "must be 1 (primary), 2 (secondary), 3 (success) or 4 (danger)");
|
|
932
|
+
return style;
|
|
933
|
+
}
|
|
934
|
+
function button(value, path, ids) {
|
|
935
|
+
const b = record(value);
|
|
936
|
+
if (!absent(b.url)) throw invalid(path, "can't be a link button");
|
|
937
|
+
if (!absent(b.type) && b.type !== 2) throw invalid(`${path}.type`, "must be 2");
|
|
938
|
+
const id = requiredText(b.custom_id, `${path}.custom_id`, CUSTOM_ID_MAX);
|
|
939
|
+
if (ids.has(id)) throw invalid(`${path}.custom_id`, `"${id}" is used twice in this message`);
|
|
940
|
+
ids.add(id);
|
|
941
|
+
const out = { type: 2, style: buttonStyle(b.style, `${path}.style`), label: requiredText(b.label, `${path}.label`, LABEL_MAX), custom_id: id };
|
|
942
|
+
if (b.disabled === true) out.disabled = true;
|
|
943
|
+
return out;
|
|
944
|
+
}
|
|
945
|
+
function embedFrom(value) {
|
|
946
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid("embed", "must be an object");
|
|
947
|
+
const e = record(value);
|
|
948
|
+
const out = {};
|
|
949
|
+
const title = optionalText(e.title, "embed.title", TITLE_MAX);
|
|
950
|
+
if (title) out.title = title;
|
|
951
|
+
const url = httpsUrl(e.url, "embed.url");
|
|
952
|
+
if (url) out.url = url;
|
|
953
|
+
const description = optionalText(e.description, "embed.description", DESCRIPTION_MAX);
|
|
954
|
+
if (description) out.description = description;
|
|
955
|
+
if (!absent(e.author)) out.author = { name: requiredText(record(e.author).name, "embed.author.name", AUTHOR_MAX) };
|
|
956
|
+
const fields2 = array(e.fields, "embed.fields", FIELDS_MAX);
|
|
957
|
+
if (fields2?.length) {
|
|
958
|
+
out.fields = fields2.map((entry, index) => {
|
|
959
|
+
const f = record(entry);
|
|
960
|
+
const path = `embed.fields[${index}]`;
|
|
961
|
+
const field = { name: requiredText(f.name, `${path}.name`, FIELD_NAME_MAX), value: requiredText(f.value, `${path}.value`, FIELD_VALUE_MAX) };
|
|
962
|
+
if (f.inline === true) field.inline = true;
|
|
963
|
+
return field;
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
const thumbnail = urlObject(e.thumbnail, "embed.thumbnail");
|
|
967
|
+
if (thumbnail) out.thumbnail = thumbnail;
|
|
968
|
+
const image = urlObject(e.image, "embed.image");
|
|
969
|
+
if (image) out.image = image;
|
|
970
|
+
if (!absent(e.footer)) out.footer = { text: requiredText(record(e.footer).text, "embed.footer.text", FOOTER_MAX) };
|
|
971
|
+
const rows = array(e.components, "embed.components", ROWS_MAX);
|
|
972
|
+
if (rows?.length) {
|
|
973
|
+
const ids = /* @__PURE__ */ new Set();
|
|
974
|
+
out.components = rows.map((entry, index) => {
|
|
975
|
+
const row = record(entry);
|
|
976
|
+
const path = `embed.components[${index}]`;
|
|
977
|
+
if (!absent(row.type) && row.type !== 1) throw invalid(`${path}.type`, "must be 1");
|
|
978
|
+
const buttons = array(row.components, `${path}.components`, BUTTONS_MAX);
|
|
979
|
+
if (!buttons?.length) throw invalid(`${path}.components`, "needs at least one button");
|
|
980
|
+
return { type: 1, components: buttons.map((b, i) => button(b, `${path}.components[${i}]`, ids)) };
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
return out;
|
|
984
|
+
}
|
|
985
|
+
function checkImage(image, path, ownAvatar) {
|
|
986
|
+
if (!image || image.url === ownAvatar) return;
|
|
987
|
+
if (parseHttps(image.url)?.hostname !== CDN_HOST) throw invalid(path, `must be on ${CDN_HOST} or be your own avatar URL`);
|
|
988
|
+
}
|
|
989
|
+
function embedText(embed) {
|
|
990
|
+
let total = (embed.title?.length ?? 0) + (embed.description?.length ?? 0) + (embed.author?.name.length ?? 0) + (embed.footer?.text.length ?? 0);
|
|
991
|
+
for (const f of embed.fields ?? []) total += f.name.length + f.value.length;
|
|
992
|
+
return total;
|
|
993
|
+
}
|
|
994
|
+
function wireMessage(message, ownAvatar) {
|
|
995
|
+
const m = record(message);
|
|
996
|
+
const text = optionalText(m.text, "text", TEXT_MAX);
|
|
997
|
+
const embed = absent(m.embed) ? void 0 : embedFrom(m.embed);
|
|
998
|
+
const out = {};
|
|
999
|
+
if (text) out.t = text;
|
|
1000
|
+
if (embed) {
|
|
1001
|
+
checkImage(embed.thumbnail, "embed.thumbnail.url", ownAvatar);
|
|
1002
|
+
checkImage(embed.image, "embed.image.url", ownAvatar);
|
|
1003
|
+
if (Object.keys(embed).length) out.e = embed;
|
|
1004
|
+
}
|
|
1005
|
+
const visible = !!embed && !!(embed.title || embed.description || embed.author || embed.fields || embed.thumbnail || embed.image || embed.footer);
|
|
1006
|
+
if (!text && !visible) throw invalid("message", "needs text or an embed with a title, description, author, fields, thumbnail, image or footer");
|
|
1007
|
+
const total = (text?.length ?? 0) + (embed ? embedText(embed) : 0);
|
|
1008
|
+
if (total > TOTAL_MAX) throw invalid("message", `has ${total} characters of text, the limit is ${TOTAL_MAX}`);
|
|
1009
|
+
return out;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// src/media.ts
|
|
1013
|
+
import { readFile } from "fs/promises";
|
|
1014
|
+
import { extname } from "path";
|
|
1015
|
+
var MAX_BYTES = 2 * 1024 * 1024;
|
|
1016
|
+
var SITE = "https://wordbomb.io";
|
|
1017
|
+
var ROUTES = {
|
|
1018
|
+
avatar: { start: "/profile/avatar/upload-url", confirm: "/profile/avatar/confirm" },
|
|
1019
|
+
banner: { start: "/profile/pbg/upload-url", confirm: "/profile/pbg/confirm" },
|
|
1020
|
+
background: { start: "/profile/background/upload-url", confirm: "/profile/background/confirm" }
|
|
1021
|
+
};
|
|
1022
|
+
var EXTENSIONS = {
|
|
1023
|
+
".png": "image/png",
|
|
1024
|
+
".jpg": "image/jpeg",
|
|
1025
|
+
".jpeg": "image/jpeg",
|
|
1026
|
+
".webp": "image/webp"
|
|
1027
|
+
};
|
|
1028
|
+
function sniff(bytes) {
|
|
1029
|
+
if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) return "image/png";
|
|
1030
|
+
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
1031
|
+
const riff = String.fromCharCode(...bytes.subarray(0, 4));
|
|
1032
|
+
const webp = String.fromCharCode(...bytes.subarray(8, 12));
|
|
1033
|
+
if (riff === "RIFF" && webp === "WEBP") return "image/webp";
|
|
1034
|
+
return null;
|
|
1035
|
+
}
|
|
1036
|
+
async function load(input) {
|
|
1037
|
+
let bytes;
|
|
1038
|
+
let type = null;
|
|
1039
|
+
if (typeof input === "string") {
|
|
1040
|
+
type = EXTENSIONS[extname(input).toLowerCase()] ?? null;
|
|
1041
|
+
if (!type) throw new WordBombError("INVALID", "images must be .png, .jpg or .webp");
|
|
1042
|
+
try {
|
|
1043
|
+
bytes = new Uint8Array(await readFile(input));
|
|
1044
|
+
} catch (e) {
|
|
1045
|
+
throw new WordBombError("INVALID", `could not read ${input}: ${e instanceof Error ? e.message : String(e)}`);
|
|
1046
|
+
}
|
|
1047
|
+
} else {
|
|
1048
|
+
bytes = new Uint8Array(input instanceof Uint8Array ? input : new Uint8Array(input));
|
|
1049
|
+
}
|
|
1050
|
+
type = sniff(bytes) ?? type;
|
|
1051
|
+
if (!type) throw new WordBombError("INVALID", "images must be png, jpeg or webp");
|
|
1052
|
+
if (bytes.byteLength > MAX_BYTES) throw new WordBombError("INVALID", "images must be under 2 MB");
|
|
1053
|
+
return { bytes, type };
|
|
1054
|
+
}
|
|
1055
|
+
var ImageSlot = class {
|
|
1056
|
+
constructor(http, kind) {
|
|
1057
|
+
this.http = http;
|
|
1058
|
+
this.kind = kind;
|
|
1059
|
+
}
|
|
1060
|
+
http;
|
|
1061
|
+
kind;
|
|
1062
|
+
async upload(input) {
|
|
1063
|
+
const { bytes, type } = await load(input);
|
|
1064
|
+
const route = ROUTES[this.kind];
|
|
1065
|
+
const signed = record(await this.http.post("player", route.start, { contentType: type }));
|
|
1066
|
+
const url = str(signed.url);
|
|
1067
|
+
const publicUrl = str(signed.publicUrl);
|
|
1068
|
+
if (!url || !publicUrl) throw new WordBombError("HTTP", `${this.kind} upload got no signed url`);
|
|
1069
|
+
const put = await fetch(url, { method: "PUT", headers: { "Content-Type": type }, body: bytes }).catch((e) => {
|
|
1070
|
+
throw new WordBombError("HTTP", `${this.kind} upload failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
1071
|
+
});
|
|
1072
|
+
if (!put.ok) throw new WordBombError("HTTP", `${this.kind} upload failed with ${put.status}`, put.status);
|
|
1073
|
+
await this.http.post("player", route.confirm, { url: publicUrl });
|
|
1074
|
+
return publicUrl;
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
function avatarUrl(userId, avatar) {
|
|
1078
|
+
if (!userId || !avatar) return null;
|
|
1079
|
+
if (avatar.includes("wcdn.wordbomb.io/") || avatar.includes("cdn.wordbomb.io/")) return avatar;
|
|
1080
|
+
if (/^\d+$/.test(avatar)) return `${SITE}/avatars/${avatar}.png?v=1`;
|
|
1081
|
+
if (avatar.includes("google")) return avatar.replace(/=s\d+-c/, "=s256-c");
|
|
1082
|
+
if (/^https?:\/\//.test(avatar)) return avatar;
|
|
1083
|
+
return `https://cdn.discordapp.com/avatars/${userId}/${avatar}.png?size=256`;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// src/interactions.ts
|
|
1087
|
+
var REPLY_WINDOW = 14e3;
|
|
1088
|
+
var POST_LIMIT = 6;
|
|
1089
|
+
var POST_WINDOW = 6e4;
|
|
1090
|
+
function exactPlayer(all, ref) {
|
|
1091
|
+
const want = ref.trim().toLowerCase();
|
|
1092
|
+
if (!want) return null;
|
|
1093
|
+
return all.find((p) => p.id === ref || p.sessionId === ref) ?? all.find((p) => p.name.toLowerCase() === want) ?? null;
|
|
1094
|
+
}
|
|
1095
|
+
function coerce(type, choices, value, players) {
|
|
1096
|
+
switch (type) {
|
|
1097
|
+
case "number": {
|
|
1098
|
+
const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value.trim()) : NaN;
|
|
1099
|
+
return Number.isFinite(n) ? n : null;
|
|
1100
|
+
}
|
|
1101
|
+
case "player":
|
|
1102
|
+
return typeof value === "string" ? exactPlayer(players, value) : null;
|
|
1103
|
+
case "choice": {
|
|
1104
|
+
if (typeof value !== "string") return null;
|
|
1105
|
+
const want = value.trim().toLowerCase();
|
|
1106
|
+
return choices?.find((c) => c.toLowerCase() === want) ?? null;
|
|
1107
|
+
}
|
|
1108
|
+
default:
|
|
1109
|
+
return typeof value === "string" ? value : typeof value === "number" ? String(value) : null;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
function readOptions(raw, def, players) {
|
|
1113
|
+
const out = {};
|
|
1114
|
+
if (!def) {
|
|
1115
|
+
for (const [name, value] of Object.entries(record(raw))) {
|
|
1116
|
+
if (typeof value === "string" || typeof value === "number" && Number.isFinite(value)) out[name] = value;
|
|
1117
|
+
}
|
|
1118
|
+
return out;
|
|
1119
|
+
}
|
|
1120
|
+
const defs = def.options ?? [];
|
|
1121
|
+
const positional = Array.isArray(raw) ? list(raw) : null;
|
|
1122
|
+
const named = record(raw);
|
|
1123
|
+
defs.forEach((option, index) => {
|
|
1124
|
+
const value = positional ? positional[index] : named[option.name];
|
|
1125
|
+
if (value === void 0 || value === null || value === "") return;
|
|
1126
|
+
const parsed = coerce(option.type, option.choices, value, players);
|
|
1127
|
+
if (parsed !== null) out[option.name] = parsed;
|
|
1128
|
+
});
|
|
1129
|
+
return out;
|
|
1130
|
+
}
|
|
1131
|
+
var Interactions = class {
|
|
1132
|
+
constructor(realtime, session, commands) {
|
|
1133
|
+
this.realtime = realtime;
|
|
1134
|
+
this.session = session;
|
|
1135
|
+
this.commands = commands;
|
|
1136
|
+
}
|
|
1137
|
+
realtime;
|
|
1138
|
+
session;
|
|
1139
|
+
commands;
|
|
1140
|
+
links = /* @__PURE__ */ new Map();
|
|
1141
|
+
attach(room, sink, subscribe) {
|
|
1142
|
+
let key = "";
|
|
1143
|
+
const posts = [];
|
|
1144
|
+
const link = { subscribe, receive: (e, frame) => this.deliver(room, sink, e, frame) };
|
|
1145
|
+
const drop = () => {
|
|
1146
|
+
if (!key) return;
|
|
1147
|
+
if (this.links.get(key) === link) {
|
|
1148
|
+
this.links.delete(key);
|
|
1149
|
+
if (subscribe) this.realtime?.send("bot:unsub", { k: key });
|
|
1150
|
+
}
|
|
1151
|
+
key = "";
|
|
1152
|
+
};
|
|
1153
|
+
return {
|
|
1154
|
+
sync: (next) => {
|
|
1155
|
+
if (next === key) return;
|
|
1156
|
+
drop();
|
|
1157
|
+
key = next;
|
|
1158
|
+
if (!key) return;
|
|
1159
|
+
this.links.set(key, link);
|
|
1160
|
+
if (subscribe) this.realtime?.send("bot:sub", { k: key });
|
|
1161
|
+
},
|
|
1162
|
+
post: async (message) => {
|
|
1163
|
+
const wire = wireMessage(message, this.ownAvatar());
|
|
1164
|
+
if (!key) throw new WordBombError("NOT_IN_ROOM", `room ${room.id} has no bot channel yet, wait for room.ready`);
|
|
1165
|
+
const now = Date.now();
|
|
1166
|
+
while (posts.length) {
|
|
1167
|
+
const first = posts[0];
|
|
1168
|
+
if (first === void 0 || now - first < POST_WINDOW) break;
|
|
1169
|
+
posts.shift();
|
|
1170
|
+
}
|
|
1171
|
+
const oldest = posts[0];
|
|
1172
|
+
if (posts.length >= POST_LIMIT && oldest !== void 0) {
|
|
1173
|
+
const wait = oldest + POST_WINDOW - now;
|
|
1174
|
+
throw new WordBombError("RATE_LIMITED", `at most ${POST_LIMIT} posts a minute per room, next one in ${Math.ceil(wait / 1e3)}s`, void 0, wait);
|
|
1175
|
+
}
|
|
1176
|
+
posts.push(now);
|
|
1177
|
+
return this.say({ k: key, ...wire });
|
|
1178
|
+
},
|
|
1179
|
+
close: drop
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
resubscribe() {
|
|
1183
|
+
for (const [key, link] of this.links) {
|
|
1184
|
+
if (link.subscribe) this.realtime?.send("bot:sub", { k: key });
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
receive(e, d) {
|
|
1188
|
+
const frame = record(d);
|
|
1189
|
+
this.links.get(str(frame.k))?.receive(e, frame);
|
|
1190
|
+
}
|
|
1191
|
+
deliver(room, sink, e, frame) {
|
|
1192
|
+
const id = str(frame.i);
|
|
1193
|
+
const key = str(frame.k);
|
|
1194
|
+
const userId = str(frame.u);
|
|
1195
|
+
if (!id || !userId || userId === this.session.me.id || !room.isOpen) return;
|
|
1196
|
+
const players = room.players;
|
|
1197
|
+
const user = players.find((p) => p.id === userId);
|
|
1198
|
+
if (!user) return;
|
|
1199
|
+
if (e === "bot:cmd") {
|
|
1200
|
+
const name = str(frame.n);
|
|
1201
|
+
const def = this.commands.get(name);
|
|
1202
|
+
if (!name || !def && this.commands.all.length) return;
|
|
1203
|
+
const options = readOptions(frame.o, def, players);
|
|
1204
|
+
const answer = this.answerer(key, id);
|
|
1205
|
+
sink.command({
|
|
1206
|
+
id,
|
|
1207
|
+
room,
|
|
1208
|
+
name,
|
|
1209
|
+
user,
|
|
1210
|
+
options,
|
|
1211
|
+
string: (n) => {
|
|
1212
|
+
const v = options[n];
|
|
1213
|
+
return typeof v === "string" ? v : null;
|
|
1214
|
+
},
|
|
1215
|
+
number: (n) => {
|
|
1216
|
+
const v = options[n];
|
|
1217
|
+
return typeof v === "number" ? v : null;
|
|
1218
|
+
},
|
|
1219
|
+
player: (n) => {
|
|
1220
|
+
const v = options[n];
|
|
1221
|
+
return v && typeof v === "object" ? v : null;
|
|
1222
|
+
},
|
|
1223
|
+
reply: (message) => answer(message, message.ephemeral === true ? { eph: true } : {})
|
|
1224
|
+
});
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
if (e === "bot:btn") {
|
|
1228
|
+
const messageId = str(frame.m);
|
|
1229
|
+
const customId = str(frame.c);
|
|
1230
|
+
if (!messageId || !customId) return;
|
|
1231
|
+
const answer = this.answerer(key, id);
|
|
1232
|
+
sink.button({
|
|
1233
|
+
id,
|
|
1234
|
+
room,
|
|
1235
|
+
messageId,
|
|
1236
|
+
customId,
|
|
1237
|
+
user,
|
|
1238
|
+
reply: (message) => answer(message, message.ephemeral === true ? { eph: true } : {}),
|
|
1239
|
+
update: (message) => answer(message, { up: messageId })
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
answerer(key, id) {
|
|
1244
|
+
const deadline = Date.now() + REPLY_WINDOW;
|
|
1245
|
+
let answered = false;
|
|
1246
|
+
let sending = false;
|
|
1247
|
+
return async (message, extra) => {
|
|
1248
|
+
if (answered || sending) throw new WordBombError("INVALID", "this interaction already has its answer, each one gets exactly one reply or update");
|
|
1249
|
+
if (Date.now() > deadline) throw new WordBombError("TIMEOUT", "interactions must be answered within 14 seconds");
|
|
1250
|
+
const wire = wireMessage(message, this.ownAvatar());
|
|
1251
|
+
sending = true;
|
|
1252
|
+
try {
|
|
1253
|
+
const messageId = await this.say({ k: key, i: id, ...wire, ...extra });
|
|
1254
|
+
answered = true;
|
|
1255
|
+
return messageId;
|
|
1256
|
+
} finally {
|
|
1257
|
+
sending = false;
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
ownAvatar() {
|
|
1262
|
+
return avatarUrl(this.session.me.id, str(this.session.me.data.avatar));
|
|
1263
|
+
}
|
|
1264
|
+
async say(frame) {
|
|
1265
|
+
const rt = this.realtime;
|
|
1266
|
+
if (!rt) throw new WordBombError("REALTIME_DOWN", "posts and replies need the realtime connection (connect with realtime: true)");
|
|
1267
|
+
const r = record(await rt.request("bot:say", frame));
|
|
1268
|
+
const m = str(r.m);
|
|
1269
|
+
if (m) return m;
|
|
1270
|
+
const reason = str(r.reason) || str(r.error);
|
|
1271
|
+
if (reason === "limited") throw new WordBombError("RATE_LIMITED", "the server rate limited this message");
|
|
1272
|
+
throw new WordBombError("FORBIDDEN", `the server refused this message${reason ? `: ${reason}` : ""}`);
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
|
|
1276
|
+
// src/notifications.ts
|
|
1277
|
+
function kindOf(type, key, data) {
|
|
1278
|
+
if (key === "notification.profile_comment") return "profile_comment";
|
|
1279
|
+
if (key === "notification.comment_reply") return "comment_reply";
|
|
1280
|
+
if (type === "achievement") return "achievement";
|
|
1281
|
+
if (data.buyerName) return "gift";
|
|
1282
|
+
return "other";
|
|
1283
|
+
}
|
|
1284
|
+
function toNotification(entry) {
|
|
1285
|
+
const n = record(entry);
|
|
1286
|
+
const data = record(n.data);
|
|
1287
|
+
const type = str(n.type);
|
|
1288
|
+
const key = str(data.key);
|
|
1289
|
+
const fromName = str(data.authorName) || str(data.buyerName);
|
|
1290
|
+
const fromId = str(data.authorId);
|
|
1291
|
+
let text = str(n.message);
|
|
1292
|
+
if (key && (!text || text === key)) text = key.replace(/^notification\./, "").replace(/_/g, " ");
|
|
1293
|
+
text = text.replace("{name}", fromName || "someone");
|
|
1294
|
+
const kind = kindOf(type, key, data);
|
|
1295
|
+
if (kind === "achievement" && (data.name || data.id)) text = `achievement unlocked: ${str(data.name) || str(data.id)}`;
|
|
1296
|
+
return {
|
|
1297
|
+
at: num(n.ts),
|
|
1298
|
+
kind,
|
|
1299
|
+
type,
|
|
1300
|
+
key,
|
|
1301
|
+
text,
|
|
1302
|
+
from: fromId ? { id: fromId, name: fromName } : null,
|
|
1303
|
+
data
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
var Notifications = class {
|
|
1307
|
+
constructor(http) {
|
|
1308
|
+
this.http = http;
|
|
1309
|
+
}
|
|
1310
|
+
http;
|
|
1311
|
+
lastSeen = 0;
|
|
1312
|
+
running = false;
|
|
1313
|
+
again = false;
|
|
1314
|
+
async list() {
|
|
1315
|
+
const r = record(await this.http.get("player", "/notifications"));
|
|
1316
|
+
const all = list(r.n).map(toNotification).sort((a, b) => b.at - a.at);
|
|
1317
|
+
for (const n of all) this.lastSeen = Math.max(this.lastSeen, n.at);
|
|
1318
|
+
return all;
|
|
1319
|
+
}
|
|
1320
|
+
async prime() {
|
|
1321
|
+
await this.list();
|
|
1322
|
+
if (!this.lastSeen) this.lastSeen = Date.now();
|
|
1323
|
+
}
|
|
1324
|
+
async poll(deliver) {
|
|
1325
|
+
if (this.running) {
|
|
1326
|
+
this.again = true;
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
this.running = true;
|
|
1330
|
+
try {
|
|
1331
|
+
do {
|
|
1332
|
+
this.again = false;
|
|
1333
|
+
const since = this.lastSeen;
|
|
1334
|
+
const all = await this.list();
|
|
1335
|
+
const fresh = all.filter((n) => n.at > since).sort((a, b) => a.at - b.at);
|
|
1336
|
+
if (fresh.length) deliver(fresh);
|
|
1337
|
+
} while (this.again);
|
|
1338
|
+
} finally {
|
|
1339
|
+
this.running = false;
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
|
|
1344
|
+
// src/realtime.ts
|
|
1345
|
+
var MIN_BACKOFF = 5e3;
|
|
1346
|
+
var MAX_BACKOFF = 12e4;
|
|
1347
|
+
var FAST_RETRY = 1e3;
|
|
1348
|
+
var REQUEST_TIMEOUT = 8e3;
|
|
1349
|
+
var Realtime = class extends Emitter {
|
|
1350
|
+
constructor(session, clientId) {
|
|
1351
|
+
super();
|
|
1352
|
+
this.session = session;
|
|
1353
|
+
this.clientId = clientId;
|
|
1354
|
+
}
|
|
1355
|
+
session;
|
|
1356
|
+
clientId;
|
|
1357
|
+
ws = null;
|
|
1358
|
+
seq = 0;
|
|
1359
|
+
waiting = /* @__PURE__ */ new Map();
|
|
1360
|
+
backoff = MIN_BACKOFF;
|
|
1361
|
+
fastRetryUsed = false;
|
|
1362
|
+
retry = null;
|
|
1363
|
+
closed = false;
|
|
1364
|
+
get isOpen() {
|
|
1365
|
+
return this.ws?.readyState === WebSocket.OPEN;
|
|
1366
|
+
}
|
|
1367
|
+
connect() {
|
|
1368
|
+
if (this.closed) return;
|
|
1369
|
+
const url = `${this.session.target.ws2}/?token=${encodeURIComponent(this.session.token)}&cid=${encodeURIComponent(this.clientId)}`;
|
|
1370
|
+
const ws = new WebSocket(url);
|
|
1371
|
+
this.ws = ws;
|
|
1372
|
+
ws.onopen = () => {
|
|
1373
|
+
this.backoff = MIN_BACKOFF;
|
|
1374
|
+
this.fastRetryUsed = false;
|
|
1375
|
+
this.emit("up", void 0);
|
|
1376
|
+
};
|
|
1377
|
+
ws.onmessage = (ev) => this.receive(ev.data);
|
|
1378
|
+
ws.onerror = () => {
|
|
1379
|
+
};
|
|
1380
|
+
ws.onclose = (ev) => {
|
|
1381
|
+
if (this.ws !== ws) return;
|
|
1382
|
+
this.ws = null;
|
|
1383
|
+
this.failAll(new WordBombError("REALTIME_DOWN", "the realtime connection closed before answering"));
|
|
1384
|
+
if (this.closed) return;
|
|
1385
|
+
if (ev.code === REALTIME_CLOSE.BANNED) {
|
|
1386
|
+
this.emit("banned", void 0);
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
if (ev.code === REALTIME_CLOSE.REPLACED || ev.code === REALTIME_CLOSE.REPLACED_ELSEWHERE) {
|
|
1390
|
+
this.emit("replaced", void 0);
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
const expired = ev.code === REALTIME_CLOSE.TOKEN_EXPIRED;
|
|
1394
|
+
let delay = this.backoff;
|
|
1395
|
+
this.backoff = Math.min(this.backoff * 2, MAX_BACKOFF);
|
|
1396
|
+
if (expired && !this.fastRetryUsed) {
|
|
1397
|
+
this.fastRetryUsed = true;
|
|
1398
|
+
delay = FAST_RETRY;
|
|
1399
|
+
}
|
|
1400
|
+
this.emit("down", { code: ev.code, retryInMs: delay });
|
|
1401
|
+
this.retry = setTimeout(async () => {
|
|
1402
|
+
this.retry = null;
|
|
1403
|
+
if (expired) await this.session.refresh().catch(() => {
|
|
1404
|
+
});
|
|
1405
|
+
this.connect();
|
|
1406
|
+
}, delay);
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
send(e, d) {
|
|
1410
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return false;
|
|
1411
|
+
this.ws.send(JSON.stringify({ e, d }));
|
|
1412
|
+
return true;
|
|
1413
|
+
}
|
|
1414
|
+
async request(e, d) {
|
|
1415
|
+
await this.opened();
|
|
1416
|
+
return new Promise((resolve, reject) => {
|
|
1417
|
+
const ws = this.ws;
|
|
1418
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
1419
|
+
reject(new WordBombError("REALTIME_DOWN", "the realtime connection is down, try again in a moment"));
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
const i = ++this.seq;
|
|
1423
|
+
const timer = setTimeout(() => {
|
|
1424
|
+
if (this.waiting.delete(i)) reject(new WordBombError("TIMEOUT", `${e} got no answer`));
|
|
1425
|
+
}, REQUEST_TIMEOUT);
|
|
1426
|
+
this.waiting.set(i, {
|
|
1427
|
+
resolve: (reply) => {
|
|
1428
|
+
clearTimeout(timer);
|
|
1429
|
+
if (reply === null || reply === void 0) reject(new WordBombError("RATE_LIMITED", `${e} was rejected (rate limit or not allowed)`));
|
|
1430
|
+
else resolve(reply);
|
|
1431
|
+
},
|
|
1432
|
+
reject: (err) => {
|
|
1433
|
+
clearTimeout(timer);
|
|
1434
|
+
reject(err);
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
ws.send(JSON.stringify({ e, d, i }));
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
opened() {
|
|
1441
|
+
if (this.closed || this.isOpen) return Promise.resolve();
|
|
1442
|
+
return new Promise((resolve) => {
|
|
1443
|
+
const done = () => {
|
|
1444
|
+
clearTimeout(timer);
|
|
1445
|
+
offUp();
|
|
1446
|
+
offClosed();
|
|
1447
|
+
resolve();
|
|
1448
|
+
};
|
|
1449
|
+
const timer = setTimeout(done, REQUEST_TIMEOUT);
|
|
1450
|
+
const offUp = this.once("up", done);
|
|
1451
|
+
const offClosed = this.once("closed", done);
|
|
1452
|
+
});
|
|
1453
|
+
}
|
|
1454
|
+
close() {
|
|
1455
|
+
if (this.closed) return;
|
|
1456
|
+
this.closed = true;
|
|
1457
|
+
if (this.retry) clearTimeout(this.retry);
|
|
1458
|
+
this.retry = null;
|
|
1459
|
+
const ws = this.ws;
|
|
1460
|
+
this.ws = null;
|
|
1461
|
+
this.failAll(new WordBombError("REALTIME_DOWN", "the bot closed"));
|
|
1462
|
+
ws?.close();
|
|
1463
|
+
this.emit("closed", void 0);
|
|
1464
|
+
}
|
|
1465
|
+
failAll(err) {
|
|
1466
|
+
for (const w of this.waiting.values()) w.reject(err);
|
|
1467
|
+
this.waiting.clear();
|
|
1468
|
+
}
|
|
1469
|
+
receive(raw) {
|
|
1470
|
+
let frame;
|
|
1471
|
+
try {
|
|
1472
|
+
frame = record(JSON.parse(String(raw)));
|
|
1473
|
+
} catch {
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
if (typeof frame.r === "number") {
|
|
1477
|
+
const id = num(frame.r);
|
|
1478
|
+
const waiter = this.waiting.get(id);
|
|
1479
|
+
this.waiting.delete(id);
|
|
1480
|
+
waiter?.resolve(frame.d);
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
const e = typeof frame.e === "string" ? frame.e : "";
|
|
1484
|
+
if (!e) return;
|
|
1485
|
+
if (e === "ping") {
|
|
1486
|
+
this.send("pong", {});
|
|
1487
|
+
return;
|
|
1488
|
+
}
|
|
1489
|
+
this.emit("event", { e, d: frame.d });
|
|
1490
|
+
}
|
|
1491
|
+
};
|
|
1492
|
+
|
|
1493
|
+
// src/words.ts
|
|
1494
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
1495
|
+
var WordList = class _WordList {
|
|
1496
|
+
constructor(words = [], locale = "en-US") {
|
|
1497
|
+
this.locale = locale;
|
|
1498
|
+
for (const w of words) this.add(w);
|
|
1499
|
+
}
|
|
1500
|
+
locale;
|
|
1501
|
+
words = /* @__PURE__ */ new Set();
|
|
1502
|
+
static async fromFile(path, locale = "en-US") {
|
|
1503
|
+
const text = await readFile2(path, "utf8");
|
|
1504
|
+
return new _WordList(text.split(/\r?\n/), locale);
|
|
1505
|
+
}
|
|
1506
|
+
static fromSpec(spec, defaultLocale = "en-US") {
|
|
1507
|
+
const parts = spec.split(",").map((part) => part.trim()).filter(Boolean);
|
|
1508
|
+
return Promise.all(
|
|
1509
|
+
parts.map((part) => {
|
|
1510
|
+
const eq = part.indexOf("=");
|
|
1511
|
+
return eq > 0 ? _WordList.fromFile(part.slice(eq + 1).trim(), part.slice(0, eq).trim()) : _WordList.fromFile(part, defaultLocale);
|
|
1512
|
+
})
|
|
1513
|
+
);
|
|
1514
|
+
}
|
|
1515
|
+
get size() {
|
|
1516
|
+
return this.words.size;
|
|
1517
|
+
}
|
|
1518
|
+
normalize(word) {
|
|
1519
|
+
return word.trim().toLocaleUpperCase(this.locale);
|
|
1520
|
+
}
|
|
1521
|
+
add(word) {
|
|
1522
|
+
const w = this.normalize(word);
|
|
1523
|
+
if (w.length < 2 || this.words.has(w)) return false;
|
|
1524
|
+
this.words.add(w);
|
|
1525
|
+
return true;
|
|
1526
|
+
}
|
|
1527
|
+
remove(word) {
|
|
1528
|
+
return this.words.delete(this.normalize(word));
|
|
1529
|
+
}
|
|
1530
|
+
has(word) {
|
|
1531
|
+
return this.words.has(this.normalize(word));
|
|
1532
|
+
}
|
|
1533
|
+
candidates(prompt, opts = {}) {
|
|
1534
|
+
const p = this.normalize(prompt);
|
|
1535
|
+
const min = opts.minLength ?? 3;
|
|
1536
|
+
const out = [];
|
|
1537
|
+
for (const w of this.words) {
|
|
1538
|
+
if (w.length < min || opts.used?.has(w)) continue;
|
|
1539
|
+
if (opts.match === "startsWith" ? w.startsWith(p) : w.includes(p)) out.push(w);
|
|
1540
|
+
}
|
|
1541
|
+
return out;
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
|
|
1545
|
+
// src/autoplay.ts
|
|
1546
|
+
var PLAYABLE_MODES = /* @__PURE__ */ new Set([0, 1]);
|
|
1547
|
+
var rand = (min, max) => min + Math.random() * (max - min);
|
|
1548
|
+
var localeKey = (locale) => locale.toLowerCase();
|
|
1549
|
+
var isList = (value) => value instanceof WordList;
|
|
1550
|
+
function pick(words) {
|
|
1551
|
+
let total = 0;
|
|
1552
|
+
const weights = words.map((w) => {
|
|
1553
|
+
const weight = 1 / Math.pow(w.length, 1.6);
|
|
1554
|
+
total += weight;
|
|
1555
|
+
return weight;
|
|
1556
|
+
});
|
|
1557
|
+
let r = Math.random() * total;
|
|
1558
|
+
for (let i = 0; i < words.length; i++) {
|
|
1559
|
+
r -= weights[i] ?? 0;
|
|
1560
|
+
if (r <= 0) return words[i];
|
|
1561
|
+
}
|
|
1562
|
+
return words[words.length - 1];
|
|
1563
|
+
}
|
|
1564
|
+
function toLists(words, locale) {
|
|
1565
|
+
if (words instanceof WordList) return [words];
|
|
1566
|
+
const items = [...words];
|
|
1567
|
+
const lists = items.filter(isList);
|
|
1568
|
+
if (lists.length && lists.length === items.length) return lists;
|
|
1569
|
+
return [new WordList(items.filter((w) => typeof w === "string"), locale)];
|
|
1570
|
+
}
|
|
1571
|
+
var Autoplayer = class {
|
|
1572
|
+
constructor(room, opts) {
|
|
1573
|
+
this.room = room;
|
|
1574
|
+
this.opts = opts;
|
|
1575
|
+
for (const list2 of toLists(opts.words, room.myLocale)) this.lists.set(localeKey(list2.locale), list2);
|
|
1576
|
+
this.cpm = opts.cpm ?? 300;
|
|
1577
|
+
this.offs = [
|
|
1578
|
+
room.on("game.turn", (turn) => {
|
|
1579
|
+
this.play(turn).catch((e) => console.error("[wordbomb] autoplay turn failed:", e));
|
|
1580
|
+
}),
|
|
1581
|
+
room.on("game.solve", ({ word, mine, player }) => {
|
|
1582
|
+
if (!mine && this.opts.learn && player) this.listFor(player.language)?.add(word);
|
|
1583
|
+
}),
|
|
1584
|
+
room.on("room.settings", () => this.syncLanguage()),
|
|
1585
|
+
room.on("room.language", ({ player }) => {
|
|
1586
|
+
if (player.isMe) this.syncLanguage();
|
|
1587
|
+
}),
|
|
1588
|
+
room.on("game.stop", () => this.syncLanguage()),
|
|
1589
|
+
room.on("room.closed", () => this.stop())
|
|
1590
|
+
];
|
|
1591
|
+
void room.settled().then(() => this.syncLanguage());
|
|
1592
|
+
}
|
|
1593
|
+
room;
|
|
1594
|
+
opts;
|
|
1595
|
+
lists = /* @__PURE__ */ new Map();
|
|
1596
|
+
cpm;
|
|
1597
|
+
offs;
|
|
1598
|
+
running = true;
|
|
1599
|
+
syncing = false;
|
|
1600
|
+
get isRunning() {
|
|
1601
|
+
return this.running;
|
|
1602
|
+
}
|
|
1603
|
+
get languages() {
|
|
1604
|
+
return [...this.lists.values()].map((list2) => list2.locale);
|
|
1605
|
+
}
|
|
1606
|
+
get canPlay() {
|
|
1607
|
+
return this.lists.has(localeKey(this.room.myLocale));
|
|
1608
|
+
}
|
|
1609
|
+
listFor(locale) {
|
|
1610
|
+
return this.lists.get(localeKey(locale));
|
|
1611
|
+
}
|
|
1612
|
+
stop() {
|
|
1613
|
+
if (!this.running) return;
|
|
1614
|
+
this.running = false;
|
|
1615
|
+
for (const off of this.offs) off();
|
|
1616
|
+
}
|
|
1617
|
+
syncLanguage() {
|
|
1618
|
+
const room = this.room;
|
|
1619
|
+
if (this.syncing || !this.running || this.opts.pickLanguage === false || !room.isOpen || !room.multiLanguage || room.started) return;
|
|
1620
|
+
if (this.canPlay) return;
|
|
1621
|
+
const want = this.listFor(room.locale)?.locale ?? this.languages[0];
|
|
1622
|
+
if (!want) return;
|
|
1623
|
+
this.syncing = true;
|
|
1624
|
+
room.setLanguage(want).catch(() => false).finally(() => {
|
|
1625
|
+
this.syncing = false;
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
async play(turn) {
|
|
1629
|
+
if (!this.running || turn.masked || !turn.prompt || !PLAYABLE_MODES.has(turn.mode)) return;
|
|
1630
|
+
const list2 = this.listFor(turn.locale);
|
|
1631
|
+
if (!list2) return;
|
|
1632
|
+
const [min, max] = this.opts.thinkMs ?? [400, 1200];
|
|
1633
|
+
await sleep(Math.min(rand(min, max), turn.timeLeftMs() * 0.4));
|
|
1634
|
+
const tried = /* @__PURE__ */ new Set();
|
|
1635
|
+
for (let attempt = 0; attempt < (this.opts.attempts ?? 3); attempt++) {
|
|
1636
|
+
if (!this.running || !turn.active()) return;
|
|
1637
|
+
const options = list2.candidates(turn.prompt, { match: turn.match, used: turn.used }).filter((w) => !tried.has(w));
|
|
1638
|
+
const word = pick(options);
|
|
1639
|
+
if (!word) return;
|
|
1640
|
+
tried.add(word);
|
|
1641
|
+
if (word.length * 6e4 / this.cpm > turn.timeLeftMs()) return;
|
|
1642
|
+
const outcome = await turn.play(word, { cpm: this.cpm });
|
|
1643
|
+
if (outcome.ok) return;
|
|
1644
|
+
if (outcome.reason === "notAWord" && this.opts.forgetInvalid !== false) list2.remove(word);
|
|
1645
|
+
if (outcome.reason === "timeout" || outcome.reason === "turnOver" || outcome.reason === "busy" || outcome.reason === "left") return;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
};
|
|
1649
|
+
|
|
1650
|
+
// src/room.ts
|
|
1651
|
+
var CHAIN_MODE = 1;
|
|
1652
|
+
var STARTS_WITH_CHAIN_STYLES = /* @__PURE__ */ new Set([2, 3]);
|
|
1653
|
+
var SUBMIT_TIMEOUT = 2500;
|
|
1654
|
+
var SETTINGS_GAP = 300;
|
|
1655
|
+
var LANGUAGE_TIMEOUT = 3e3;
|
|
1656
|
+
var BOT_ROLE = -1;
|
|
1657
|
+
var ROOM_EVENT_SET = {
|
|
1658
|
+
"room.ready": true,
|
|
1659
|
+
"room.state": true,
|
|
1660
|
+
"room.closed": true,
|
|
1661
|
+
"room.player.joined": true,
|
|
1662
|
+
"room.player.left": true,
|
|
1663
|
+
"room.host": true,
|
|
1664
|
+
"room.language": true,
|
|
1665
|
+
"room.settings": true,
|
|
1666
|
+
"room.server": true,
|
|
1667
|
+
"room.system": true,
|
|
1668
|
+
"room.popup": true,
|
|
1669
|
+
"room.afk": true,
|
|
1670
|
+
"chat.message": true,
|
|
1671
|
+
"love.received": true,
|
|
1672
|
+
"game.start": true,
|
|
1673
|
+
"game.turn": true,
|
|
1674
|
+
"game.solve": true,
|
|
1675
|
+
"game.miss": true,
|
|
1676
|
+
"game.hurt": true,
|
|
1677
|
+
"game.eliminated": true,
|
|
1678
|
+
"game.end": true,
|
|
1679
|
+
"game.stop": true,
|
|
1680
|
+
command: true,
|
|
1681
|
+
button: true
|
|
1682
|
+
};
|
|
1683
|
+
var ROOM_EVENTS = Object.keys(ROOM_EVENT_SET);
|
|
1684
|
+
var SETTING_KEYS = { hearts: "heart", maxPlayers: "maxPlayer", multiLanguage: "multi_lang", botAccounts: "ba" };
|
|
1685
|
+
var GameRoom = class extends Emitter {
|
|
1686
|
+
constructor(raw, ctx) {
|
|
1687
|
+
super();
|
|
1688
|
+
this.raw = raw;
|
|
1689
|
+
this.ctx = ctx;
|
|
1690
|
+
this.feedHost = {
|
|
1691
|
+
used: this.used,
|
|
1692
|
+
me: () => this.sessionId,
|
|
1693
|
+
mode: () => this.mode,
|
|
1694
|
+
prompt: () => this.prompt,
|
|
1695
|
+
playing: () => {
|
|
1696
|
+
let playing = 0;
|
|
1697
|
+
this.state?.players?.forEach((p) => {
|
|
1698
|
+
if (num(p.heart) > 0) playing++;
|
|
1699
|
+
});
|
|
1700
|
+
return playing;
|
|
1701
|
+
},
|
|
1702
|
+
meIn: () => (this.me?.hearts ?? 0) > 0,
|
|
1703
|
+
lookup: (sid) => this.lookup(sid),
|
|
1704
|
+
upper: (word) => this.upper(word)
|
|
1705
|
+
};
|
|
1706
|
+
this.channel = ctx.channel(this, {
|
|
1707
|
+
command: (interaction) => this.emit("command", interaction),
|
|
1708
|
+
button: (interaction) => this.emit("button", interaction)
|
|
1709
|
+
});
|
|
1710
|
+
this.bind();
|
|
1711
|
+
}
|
|
1712
|
+
raw;
|
|
1713
|
+
ctx;
|
|
1714
|
+
used = /* @__PURE__ */ new Set();
|
|
1715
|
+
channel;
|
|
1716
|
+
feedHost;
|
|
1717
|
+
botKey = "";
|
|
1718
|
+
known = /* @__PURE__ */ new Map();
|
|
1719
|
+
hostSession = "";
|
|
1720
|
+
configKey = "";
|
|
1721
|
+
turnKey = "";
|
|
1722
|
+
turnSerial = 0;
|
|
1723
|
+
pending = null;
|
|
1724
|
+
ready = false;
|
|
1725
|
+
open = true;
|
|
1726
|
+
closing = false;
|
|
1727
|
+
leaving = false;
|
|
1728
|
+
restartPending = false;
|
|
1729
|
+
get id() {
|
|
1730
|
+
return this.raw.roomId;
|
|
1731
|
+
}
|
|
1732
|
+
get sessionId() {
|
|
1733
|
+
return this.raw.sessionId;
|
|
1734
|
+
}
|
|
1735
|
+
get isOpen() {
|
|
1736
|
+
return this.open;
|
|
1737
|
+
}
|
|
1738
|
+
get title() {
|
|
1739
|
+
return str(this.state?.title);
|
|
1740
|
+
}
|
|
1741
|
+
get mode() {
|
|
1742
|
+
return num(this.state?.mode);
|
|
1743
|
+
}
|
|
1744
|
+
get locale() {
|
|
1745
|
+
return str(this.state?.locale, "en-US");
|
|
1746
|
+
}
|
|
1747
|
+
get multiLanguage() {
|
|
1748
|
+
return this.state?.mlang === true;
|
|
1749
|
+
}
|
|
1750
|
+
get myLocale() {
|
|
1751
|
+
return this.me?.language ?? this.locale;
|
|
1752
|
+
}
|
|
1753
|
+
get config() {
|
|
1754
|
+
const s = this.state;
|
|
1755
|
+
return {
|
|
1756
|
+
mode: num(s?.mode),
|
|
1757
|
+
language: this.locale,
|
|
1758
|
+
multiLanguage: s?.mlang === true,
|
|
1759
|
+
locked: s?.locked === true,
|
|
1760
|
+
hearts: num(s?.heart, 2),
|
|
1761
|
+
maxPlayers: num(s?.maxp, 16),
|
|
1762
|
+
guests: s?.guests !== false,
|
|
1763
|
+
botAccounts: s?.ba === true,
|
|
1764
|
+
scenario: num(s?.sc),
|
|
1765
|
+
teamMode: s?.teamMode === true,
|
|
1766
|
+
chainStyle: num(s?.mode) === CHAIN_MODE ? num(s?.cs) : 0,
|
|
1767
|
+
title: str(s?.title)
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
get locked() {
|
|
1771
|
+
return this.state?.locked === true;
|
|
1772
|
+
}
|
|
1773
|
+
get started() {
|
|
1774
|
+
return this.state?.started === true;
|
|
1775
|
+
}
|
|
1776
|
+
get prompt() {
|
|
1777
|
+
return str(this.state?.letter);
|
|
1778
|
+
}
|
|
1779
|
+
get players() {
|
|
1780
|
+
const out = [];
|
|
1781
|
+
this.state?.players?.forEach((p, sid) => out.push(this.toPlayer(p, sid)));
|
|
1782
|
+
return out;
|
|
1783
|
+
}
|
|
1784
|
+
get me() {
|
|
1785
|
+
return this.lookup(this.sessionId);
|
|
1786
|
+
}
|
|
1787
|
+
get host() {
|
|
1788
|
+
const host = this.state?.host;
|
|
1789
|
+
return host ? this.lookup(host) : null;
|
|
1790
|
+
}
|
|
1791
|
+
get isHost() {
|
|
1792
|
+
return !!this.sessionId && this.state?.host === this.sessionId;
|
|
1793
|
+
}
|
|
1794
|
+
get currentPlayer() {
|
|
1795
|
+
const sid = this.state?.currentPlayerSessionId;
|
|
1796
|
+
return this.started && sid ? this.lookup(sid) : null;
|
|
1797
|
+
}
|
|
1798
|
+
player(ref) {
|
|
1799
|
+
const hit = pickPlayer(this.players, ref);
|
|
1800
|
+
if (!hit) throw new WordBombError("NOT_FOUND", `nobody called "${ref}" in room ${this.id}`);
|
|
1801
|
+
return hit;
|
|
1802
|
+
}
|
|
1803
|
+
async post(message) {
|
|
1804
|
+
this.assertOpen();
|
|
1805
|
+
return this.channel.post(message);
|
|
1806
|
+
}
|
|
1807
|
+
settled(timeoutMs = 3e3) {
|
|
1808
|
+
if (this.ready || !this.open) return Promise.resolve();
|
|
1809
|
+
return new Promise((resolve) => {
|
|
1810
|
+
const timer = setTimeout(done, timeoutMs);
|
|
1811
|
+
const offReady = this.once("room.ready", done);
|
|
1812
|
+
const offClosed = this.once("room.closed", done);
|
|
1813
|
+
function done() {
|
|
1814
|
+
clearTimeout(timer);
|
|
1815
|
+
offReady();
|
|
1816
|
+
offClosed();
|
|
1817
|
+
resolve();
|
|
1818
|
+
}
|
|
1819
|
+
});
|
|
1820
|
+
}
|
|
1821
|
+
say(text) {
|
|
1822
|
+
this.send("chat", { message: text.slice(0, 255) });
|
|
1823
|
+
}
|
|
1824
|
+
whisper(ref, text) {
|
|
1825
|
+
const p = this.resolve(ref);
|
|
1826
|
+
this.send("command", { command: "whisper", args: { to: p.sessionId, message: text.slice(0, 255) } });
|
|
1827
|
+
}
|
|
1828
|
+
love(ref) {
|
|
1829
|
+
this.send("love", { id: this.resolve(ref).id });
|
|
1830
|
+
}
|
|
1831
|
+
toggleSpectate() {
|
|
1832
|
+
this.send("spectate", {});
|
|
1833
|
+
}
|
|
1834
|
+
start() {
|
|
1835
|
+
this.send("start", {});
|
|
1836
|
+
}
|
|
1837
|
+
end() {
|
|
1838
|
+
this.send("end", {});
|
|
1839
|
+
}
|
|
1840
|
+
kick(ref) {
|
|
1841
|
+
this.send("kick", { id: this.resolve(ref).id, ban: false });
|
|
1842
|
+
}
|
|
1843
|
+
ban(ref) {
|
|
1844
|
+
this.send("kick", { id: this.resolve(ref).id, ban: true });
|
|
1845
|
+
}
|
|
1846
|
+
giveHost(ref) {
|
|
1847
|
+
this.send("host", { id: this.resolve(ref).id });
|
|
1848
|
+
}
|
|
1849
|
+
setTitle(title) {
|
|
1850
|
+
this.send("command", { command: "title", args: { title } });
|
|
1851
|
+
}
|
|
1852
|
+
async settings(patch) {
|
|
1853
|
+
const { mode, language, locked, ...rest } = patch;
|
|
1854
|
+
if (locked !== void 0) {
|
|
1855
|
+
this.send("settings", { locked });
|
|
1856
|
+
await sleep(SETTINGS_GAP);
|
|
1857
|
+
}
|
|
1858
|
+
const head = {};
|
|
1859
|
+
if (mode !== void 0) head.mode = mode;
|
|
1860
|
+
if (language !== void 0) head.language = language;
|
|
1861
|
+
if (Object.keys(head).length) {
|
|
1862
|
+
this.send("settings", head);
|
|
1863
|
+
await sleep(SETTINGS_GAP);
|
|
1864
|
+
}
|
|
1865
|
+
for (const [name, value] of Object.entries(rest)) {
|
|
1866
|
+
if (value === void 0) continue;
|
|
1867
|
+
this.send("settings", { key: SETTING_KEYS[name] ?? name, value });
|
|
1868
|
+
await sleep(SETTINGS_GAP);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
setLanguage(locale) {
|
|
1872
|
+
this.assertOpen();
|
|
1873
|
+
if (!this.multiLanguage) {
|
|
1874
|
+
return Promise.reject(new WordBombError("INVALID", "players only pick their own language in multi-language rooms; the host sets the room language with settings({ language })"));
|
|
1875
|
+
}
|
|
1876
|
+
if (this.myLocale === locale) return Promise.resolve(true);
|
|
1877
|
+
return new Promise((resolve) => {
|
|
1878
|
+
const timer = setTimeout(() => finish(false), LANGUAGE_TIMEOUT);
|
|
1879
|
+
const offLanguage = this.on("room.language", ({ player }) => {
|
|
1880
|
+
if (player.isMe) finish(player.language === locale);
|
|
1881
|
+
});
|
|
1882
|
+
const offPopup = this.on("room.popup", ({ text }) => {
|
|
1883
|
+
if (text === "invalid_language") finish(false);
|
|
1884
|
+
});
|
|
1885
|
+
const offClosed = this.on("room.closed", () => finish(false));
|
|
1886
|
+
this.raw.send("lang-set", locale);
|
|
1887
|
+
function finish(ok) {
|
|
1888
|
+
clearTimeout(timer);
|
|
1889
|
+
offLanguage();
|
|
1890
|
+
offPopup();
|
|
1891
|
+
offClosed();
|
|
1892
|
+
resolve(ok);
|
|
1893
|
+
}
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
clearInput() {
|
|
1897
|
+
this.send("word", { t: "r", w: "" });
|
|
1898
|
+
}
|
|
1899
|
+
type(text, opts = {}) {
|
|
1900
|
+
return this.typeFor(this.turnSerial, text, opts);
|
|
1901
|
+
}
|
|
1902
|
+
submit(word) {
|
|
1903
|
+
return this.submitFor(this.turnSerial, word);
|
|
1904
|
+
}
|
|
1905
|
+
play(word, opts = {}) {
|
|
1906
|
+
return this.playFor(this.turnSerial, word, opts);
|
|
1907
|
+
}
|
|
1908
|
+
autoplay(opts) {
|
|
1909
|
+
return new Autoplayer(this, opts);
|
|
1910
|
+
}
|
|
1911
|
+
async leave() {
|
|
1912
|
+
if (!this.open) return;
|
|
1913
|
+
this.leaving = true;
|
|
1914
|
+
await this.raw.leave().catch(() => {
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1917
|
+
async typeFor(serial, text, opts) {
|
|
1918
|
+
const delay = 6e4 / Math.min(Math.max(opts.cpm ?? 300, 60), 3e3);
|
|
1919
|
+
if (!this.open || serial !== this.turnSerial) return false;
|
|
1920
|
+
this.clearInput();
|
|
1921
|
+
for (const ch of text) {
|
|
1922
|
+
if (!this.open || serial !== this.turnSerial) return false;
|
|
1923
|
+
this.send("word", { t: "a", a: ch });
|
|
1924
|
+
await sleep(delay);
|
|
1925
|
+
}
|
|
1926
|
+
return this.open && serial === this.turnSerial;
|
|
1927
|
+
}
|
|
1928
|
+
submitFor(serial, word) {
|
|
1929
|
+
this.assertOpen();
|
|
1930
|
+
if (serial !== this.turnSerial) return Promise.resolve({ ok: false, word, reason: "turnOver" });
|
|
1931
|
+
if (this.pending) return Promise.resolve({ ok: false, word, reason: "busy" });
|
|
1932
|
+
return new Promise((resolve) => {
|
|
1933
|
+
const timer = setTimeout(() => this.settle({ ok: false, word, reason: "timeout" }), SUBMIT_TIMEOUT);
|
|
1934
|
+
this.pending = { word, key: this.upper(word), resolve, timer };
|
|
1935
|
+
this.raw.send("submit", { word });
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
async playFor(serial, word, opts) {
|
|
1939
|
+
if (!await this.typeFor(serial, word, opts)) return { ok: false, word, reason: this.open ? "turnOver" : "left" };
|
|
1940
|
+
return this.submitFor(serial, word);
|
|
1941
|
+
}
|
|
1942
|
+
get state() {
|
|
1943
|
+
return this.raw.state;
|
|
1944
|
+
}
|
|
1945
|
+
send(type, payload) {
|
|
1946
|
+
this.assertOpen();
|
|
1947
|
+
this.raw.send(type, payload);
|
|
1948
|
+
}
|
|
1949
|
+
assertOpen() {
|
|
1950
|
+
if (!this.open) throw new WordBombError("NOT_IN_ROOM", `room ${this.id} is closed`);
|
|
1951
|
+
}
|
|
1952
|
+
resolve(ref) {
|
|
1953
|
+
return typeof ref === "string" ? this.player(ref) : ref;
|
|
1954
|
+
}
|
|
1955
|
+
upper(word) {
|
|
1956
|
+
return upperFor(word, this.myLocale);
|
|
1957
|
+
}
|
|
1958
|
+
toPlayer(p, sid) {
|
|
1959
|
+
const s = this.state;
|
|
1960
|
+
const id = str(p.auth_id);
|
|
1961
|
+
const hearts = num(p.heart);
|
|
1962
|
+
return {
|
|
1963
|
+
sessionId: sid,
|
|
1964
|
+
id,
|
|
1965
|
+
name: str(p.username, "Guest"),
|
|
1966
|
+
avatar: str(p.avatar),
|
|
1967
|
+
hearts,
|
|
1968
|
+
eliminated: p.eliminated === true,
|
|
1969
|
+
spectating: p.spectating === true,
|
|
1970
|
+
isHost: s?.host === sid,
|
|
1971
|
+
isMe: sid === this.sessionId,
|
|
1972
|
+
isTurn: s?.started === true && s.currentPlayerSessionId === sid,
|
|
1973
|
+
isGuest: id.length < 10,
|
|
1974
|
+
isBot: p.bot === true || p.type === BOT_ROLE,
|
|
1975
|
+
language: s?.mlang === true ? str(p.lang, this.locale) : this.locale
|
|
1976
|
+
};
|
|
1977
|
+
}
|
|
1978
|
+
lookup(sid) {
|
|
1979
|
+
const key = str(sid);
|
|
1980
|
+
if (!key) return null;
|
|
1981
|
+
const p = this.state?.players?.get(key);
|
|
1982
|
+
return p ? this.toPlayer(p, key) : this.known.get(key) ?? null;
|
|
1983
|
+
}
|
|
1984
|
+
snapshot() {
|
|
1985
|
+
const out = /* @__PURE__ */ new Map();
|
|
1986
|
+
this.state?.players?.forEach((p, sid) => out.set(sid, this.toPlayer(p, sid)));
|
|
1987
|
+
return out;
|
|
1988
|
+
}
|
|
1989
|
+
bind() {
|
|
1990
|
+
const r = this.raw;
|
|
1991
|
+
r.onStateChange(() => this.onState());
|
|
1992
|
+
r.onMessage("chat", (m) => this.onChat(m));
|
|
1993
|
+
const sink = this.sink();
|
|
1994
|
+
for (const type of GAME_MESSAGES) r.onMessage(type, (m) => feed(type, m, this.feedHost, sink));
|
|
1995
|
+
r.onMessage("server-message", (m) => {
|
|
1996
|
+
const text = str(m.msg);
|
|
1997
|
+
if (!text || text.startsWith("/")) return;
|
|
1998
|
+
if (text === "sn_room_empty_closing" || /No active players remain/i.test(text)) this.closing = true;
|
|
1999
|
+
const args = Array.isArray(m.args) ? m.args.filter((arg) => typeof arg === "string" || typeof arg === "number") : [];
|
|
2000
|
+
this.emit("room.server", { room: this, text, args });
|
|
2001
|
+
});
|
|
2002
|
+
r.onMessage("popup", (m) => this.emit("room.popup", { room: this, title: str(m.title), text: str(m.message) }));
|
|
2003
|
+
r.onMessage("love", (m) => this.emit("love.received", { room: this, from: this.lookup(m.from) }));
|
|
2004
|
+
r.onMessage("afk-warning", (m) => {
|
|
2005
|
+
if (m.active === false) return;
|
|
2006
|
+
const extended = this.ctx.keepAlive && m.canExtend === true;
|
|
2007
|
+
if (extended) r.send("afk-keepalive", {});
|
|
2008
|
+
this.emit("room.afk", { room: this, seconds: num(m.seconds), extended });
|
|
2009
|
+
});
|
|
2010
|
+
r.onMessage("reconnect-data", (m) => {
|
|
2011
|
+
const multiLanguage = m.mlang === true;
|
|
2012
|
+
this.restartPending = true;
|
|
2013
|
+
this.ctx.restarting({
|
|
2014
|
+
roomId: str(m.roomId, this.id),
|
|
2015
|
+
locale: multiLanguage ? this.myLocale : str(m.locale, this.locale),
|
|
2016
|
+
mode: num(m.mode, this.mode),
|
|
2017
|
+
multiLanguage,
|
|
2018
|
+
locked: m.locked === true,
|
|
2019
|
+
guests: m.guests !== false,
|
|
2020
|
+
botAccounts: m.ba === true,
|
|
2021
|
+
chainStyle: num(m.cs),
|
|
2022
|
+
scenario: num(m.sc)
|
|
2023
|
+
});
|
|
2024
|
+
});
|
|
2025
|
+
r.onMessage("*", () => {
|
|
2026
|
+
});
|
|
2027
|
+
r.onLeave((code) => this.onLeave(code));
|
|
2028
|
+
}
|
|
2029
|
+
sink() {
|
|
2030
|
+
return {
|
|
2031
|
+
start: (e) => this.emit("game.start", { room: this, ...e }),
|
|
2032
|
+
stop: () => {
|
|
2033
|
+
this.endTurn();
|
|
2034
|
+
this.emit("game.stop", { room: this });
|
|
2035
|
+
},
|
|
2036
|
+
solve: (e) => {
|
|
2037
|
+
if (e.mine) this.settle({ ok: true, word: this.pending?.word ?? e.word }, e.word);
|
|
2038
|
+
this.emit("game.solve", { room: this, ...e });
|
|
2039
|
+
},
|
|
2040
|
+
miss: (e) => {
|
|
2041
|
+
if (e.mine) this.settle({ ok: false, word: this.pending?.word ?? e.word, reason: e.reason }, e.word);
|
|
2042
|
+
this.emit("game.miss", { room: this, ...e });
|
|
2043
|
+
},
|
|
2044
|
+
hurt: (e) => this.emit("game.hurt", { room: this, ...e }),
|
|
2045
|
+
eliminated: (e) => {
|
|
2046
|
+
if (e.mine) this.endTurn();
|
|
2047
|
+
this.emit("game.eliminated", { room: this, ...e });
|
|
2048
|
+
},
|
|
2049
|
+
end: (e) => this.emit("game.end", { room: this, ...e })
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
onState() {
|
|
2053
|
+
const s = this.state;
|
|
2054
|
+
if (!s?.players) return;
|
|
2055
|
+
if (!this.ready && !s.players.get(this.sessionId)) return;
|
|
2056
|
+
const key = str(s.bk);
|
|
2057
|
+
if (key !== this.botKey) {
|
|
2058
|
+
this.botKey = key;
|
|
2059
|
+
this.channel.sync(key);
|
|
2060
|
+
}
|
|
2061
|
+
if (!this.ready) {
|
|
2062
|
+
this.ready = true;
|
|
2063
|
+
this.known = this.snapshot();
|
|
2064
|
+
this.hostSession = str(s.host);
|
|
2065
|
+
this.configKey = JSON.stringify(this.config);
|
|
2066
|
+
this.emit("room.ready", { room: this });
|
|
2067
|
+
} else {
|
|
2068
|
+
this.diff();
|
|
2069
|
+
}
|
|
2070
|
+
this.emit("room.state", { room: this });
|
|
2071
|
+
this.checkTurn();
|
|
2072
|
+
}
|
|
2073
|
+
diff() {
|
|
2074
|
+
const next = this.snapshot();
|
|
2075
|
+
const before = this.known;
|
|
2076
|
+
this.known = next;
|
|
2077
|
+
const config = JSON.stringify(this.config);
|
|
2078
|
+
if (config !== this.configKey) {
|
|
2079
|
+
this.configKey = config;
|
|
2080
|
+
this.emit("room.settings", { room: this });
|
|
2081
|
+
}
|
|
2082
|
+
for (const [sid, player] of next) {
|
|
2083
|
+
const was = before.get(sid);
|
|
2084
|
+
if (!was) {
|
|
2085
|
+
if (!player.isMe) this.emit("room.player.joined", { room: this, player });
|
|
2086
|
+
} else if (was.language !== player.language) {
|
|
2087
|
+
this.emit("room.language", { room: this, player });
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
for (const [sid, player] of before) {
|
|
2091
|
+
if (!next.has(sid) && !player.isMe) this.emit("room.player.left", { room: this, player });
|
|
2092
|
+
}
|
|
2093
|
+
const host = str(this.state?.host);
|
|
2094
|
+
if (host && host !== this.hostSession) {
|
|
2095
|
+
this.hostSession = host;
|
|
2096
|
+
const player = next.get(host);
|
|
2097
|
+
if (player) this.emit("room.host", { room: this, player });
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
checkTurn() {
|
|
2101
|
+
const s = this.state;
|
|
2102
|
+
if (!s?.started || s.currentPlayerSessionId !== this.sessionId) {
|
|
2103
|
+
if (this.turnKey) this.endTurn();
|
|
2104
|
+
return;
|
|
2105
|
+
}
|
|
2106
|
+
const key = `${num(s.turn)}:${str(s.letter)}`;
|
|
2107
|
+
if (key === this.turnKey) return;
|
|
2108
|
+
this.turnKey = key;
|
|
2109
|
+
const serial = ++this.turnSerial;
|
|
2110
|
+
const prompt = str(s.letter);
|
|
2111
|
+
const mode = num(s.mode);
|
|
2112
|
+
const match = mode === CHAIN_MODE && STARTS_WITH_CHAIN_STYLES.has(num(s.cs)) ? "startsWith" : "contains";
|
|
2113
|
+
const deadline = Date.now() + Math.max(0, num(s.time)) * 1e3;
|
|
2114
|
+
const upperPrompt = this.upper(prompt);
|
|
2115
|
+
const turn = {
|
|
2116
|
+
room: this,
|
|
2117
|
+
prompt,
|
|
2118
|
+
locale: this.myLocale,
|
|
2119
|
+
masked: prompt.startsWith("#"),
|
|
2120
|
+
mode,
|
|
2121
|
+
match,
|
|
2122
|
+
deadline,
|
|
2123
|
+
used: this.used,
|
|
2124
|
+
timeLeftMs: () => Math.max(0, deadline - Date.now()),
|
|
2125
|
+
active: () => this.open && serial === this.turnSerial,
|
|
2126
|
+
matches: (word) => {
|
|
2127
|
+
const w = this.upper(word);
|
|
2128
|
+
return !this.used.has(w) && (match === "startsWith" ? w.startsWith(upperPrompt) : w.includes(upperPrompt));
|
|
2129
|
+
},
|
|
2130
|
+
submit: (word) => this.submitFor(serial, word),
|
|
2131
|
+
play: (word, opts) => this.playFor(serial, word, opts ?? {})
|
|
2132
|
+
};
|
|
2133
|
+
this.emit("game.turn", turn);
|
|
2134
|
+
}
|
|
2135
|
+
endTurn() {
|
|
2136
|
+
this.turnKey = "";
|
|
2137
|
+
this.turnSerial++;
|
|
2138
|
+
}
|
|
2139
|
+
settle(outcome, serverWord) {
|
|
2140
|
+
const p = this.pending;
|
|
2141
|
+
if (!p) return;
|
|
2142
|
+
if (serverWord !== void 0 && this.upper(serverWord) !== p.key) return;
|
|
2143
|
+
this.pending = null;
|
|
2144
|
+
clearTimeout(p.timer);
|
|
2145
|
+
p.resolve(outcome);
|
|
2146
|
+
}
|
|
2147
|
+
onChat(m) {
|
|
2148
|
+
const text = m.message;
|
|
2149
|
+
if (typeof text !== "string") return;
|
|
2150
|
+
if (m.type === "system") {
|
|
2151
|
+
this.emit("room.system", { room: this, text });
|
|
2152
|
+
return;
|
|
2153
|
+
}
|
|
2154
|
+
if (m.type) return;
|
|
2155
|
+
const from = this.lookup(m.id);
|
|
2156
|
+
if (from?.isMe) return;
|
|
2157
|
+
const name = this.ctx.myName().toLowerCase();
|
|
2158
|
+
const whisper = m.priv === true;
|
|
2159
|
+
this.emit("chat.message", {
|
|
2160
|
+
room: this,
|
|
2161
|
+
from,
|
|
2162
|
+
text,
|
|
2163
|
+
whisper,
|
|
2164
|
+
team: m.team === true,
|
|
2165
|
+
mentionsMe: whisper || !!name && text.toLowerCase().includes(name),
|
|
2166
|
+
reply: (reply) => this.say(reply),
|
|
2167
|
+
whisperBack: (reply) => {
|
|
2168
|
+
if (from) this.whisper(from, reply);
|
|
2169
|
+
}
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
onLeave(code) {
|
|
2173
|
+
this.open = false;
|
|
2174
|
+
this.botKey = "";
|
|
2175
|
+
this.channel.close();
|
|
2176
|
+
this.endTurn();
|
|
2177
|
+
this.settle({ ok: false, word: this.pending?.word ?? "", reason: "left" });
|
|
2178
|
+
let reason = "disconnected";
|
|
2179
|
+
if (this.leaving) reason = "left";
|
|
2180
|
+
else if (code === CLOSE.KICKED) reason = this.closing ? "closed" : "kicked";
|
|
2181
|
+
else if (code === CLOSE.BANNED) reason = "banned";
|
|
2182
|
+
else if (code === CLOSE.JOIN_TOO_FAST) reason = "joinTooFast";
|
|
2183
|
+
else if (code === CLOSE.BOTS_NOT_ALLOWED) reason = "botsNotAllowed";
|
|
2184
|
+
else if (this.restartPending) reason = "restart";
|
|
2185
|
+
else if (code === CLOSE.NORMAL || code === 1e3) reason = "closed";
|
|
2186
|
+
this.emit("room.closed", { room: this, reason, code });
|
|
2187
|
+
}
|
|
2188
|
+
};
|
|
2189
|
+
|
|
2190
|
+
// src/rooms.ts
|
|
2191
|
+
import { Unpackr } from "msgpackr";
|
|
2192
|
+
var LOBBY_TIMEOUT = 5e3;
|
|
2193
|
+
var PROFILE_SEND_WAIT = 1500;
|
|
2194
|
+
var REJOIN_DELAY = 2e3;
|
|
2195
|
+
var RESTART_FIRST_DELAY = 3e3;
|
|
2196
|
+
var RESTART_MAX_DELAY = 3e4;
|
|
2197
|
+
var RESTART_ATTEMPTS = 10;
|
|
2198
|
+
var RESTART_FATAL = /* @__PURE__ */ new Set(["BANNED", "KICKED", "BOTS_NOT_ALLOWED", "AUTH_FAILED", "APP_NO_ROOMS", "BOT_ROOM_LIMIT"]);
|
|
2199
|
+
var ROOM_CODE = /^[A-Z]{4}$/;
|
|
2200
|
+
function normalizeId(roomId) {
|
|
2201
|
+
const id = roomId.trim();
|
|
2202
|
+
return id.length === 4 ? id.toUpperCase() : id;
|
|
2203
|
+
}
|
|
2204
|
+
var appNoRooms = () => new WordBombError("APP_NO_ROOMS", "applications never join rooms, they get them from bot.apps");
|
|
2205
|
+
var notRoomCode = (roomId) => new WordBombError("INVALID", `${JSON.stringify(String(roomId).slice(0, 32))} is not a room code, codes are 4 letters like ABCD`);
|
|
2206
|
+
var unpackr = new Unpackr({ useRecords: true, structuredClone: false });
|
|
2207
|
+
var Lobby = class {
|
|
2208
|
+
constructor(client, locale) {
|
|
2209
|
+
this.client = client;
|
|
2210
|
+
this.locale = locale;
|
|
2211
|
+
}
|
|
2212
|
+
client;
|
|
2213
|
+
locale;
|
|
2214
|
+
async rooms() {
|
|
2215
|
+
return this.with(async (lobby) => {
|
|
2216
|
+
const snapshot = await new Promise((resolve, reject) => {
|
|
2217
|
+
const timer = setTimeout(() => reject(new WordBombError("TIMEOUT", "the lobby sent no room list")), LOBBY_TIMEOUT);
|
|
2218
|
+
lobby.onMessage("rooms", (m) => {
|
|
2219
|
+
clearTimeout(timer);
|
|
2220
|
+
resolve(m);
|
|
2221
|
+
});
|
|
2222
|
+
});
|
|
2223
|
+
const packed = record(snapshot).b;
|
|
2224
|
+
const rows = packed instanceof Uint8Array ? unpackr.unpack(packed) : Array.isArray(packed) ? unpackr.unpack(Uint8Array.from(packed)) : [];
|
|
2225
|
+
const out = [];
|
|
2226
|
+
for (const entry of list(rows)) {
|
|
2227
|
+
const row = record(entry);
|
|
2228
|
+
const md = record(row.metadata);
|
|
2229
|
+
if (md.ranked || md.tournament || md.player1) continue;
|
|
2230
|
+
out.push({
|
|
2231
|
+
id: str(row.roomId),
|
|
2232
|
+
name: str(md.name),
|
|
2233
|
+
players: num(row.clients),
|
|
2234
|
+
mode: num(md.mode),
|
|
2235
|
+
eventRoom: !!md.eventType,
|
|
2236
|
+
multiLanguage: md.mlang === true,
|
|
2237
|
+
language: str(md.language),
|
|
2238
|
+
started: md.started === true,
|
|
2239
|
+
guestsAllowed: md.g !== false
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
return out;
|
|
2243
|
+
});
|
|
2244
|
+
}
|
|
2245
|
+
async send(type, payload) {
|
|
2246
|
+
await this.with(async (lobby) => {
|
|
2247
|
+
await sleep(800);
|
|
2248
|
+
lobby.send(type, payload);
|
|
2249
|
+
await sleep(PROFILE_SEND_WAIT);
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
async with(fn) {
|
|
2253
|
+
const lobby = await this.client.joinOrCreate("lobby", { locale: this.locale }).catch((e) => {
|
|
2254
|
+
throw joinError(e);
|
|
2255
|
+
});
|
|
2256
|
+
lobby.onMessage("*", () => {
|
|
2257
|
+
});
|
|
2258
|
+
try {
|
|
2259
|
+
return await fn(lobby);
|
|
2260
|
+
} finally {
|
|
2261
|
+
lobby.leave().catch(() => {
|
|
2262
|
+
});
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
};
|
|
2266
|
+
var Rooms = class {
|
|
2267
|
+
constructor(client, ctx) {
|
|
2268
|
+
this.client = client;
|
|
2269
|
+
this.ctx = ctx;
|
|
2270
|
+
}
|
|
2271
|
+
client;
|
|
2272
|
+
ctx;
|
|
2273
|
+
open = /* @__PURE__ */ new Map();
|
|
2274
|
+
rejoins = /* @__PURE__ */ new Set();
|
|
2275
|
+
queue = Promise.resolve();
|
|
2276
|
+
get all() {
|
|
2277
|
+
return [...this.open.values()];
|
|
2278
|
+
}
|
|
2279
|
+
get(roomId) {
|
|
2280
|
+
return this.open.get(normalizeId(roomId)) ?? null;
|
|
2281
|
+
}
|
|
2282
|
+
join(roomId, opts = {}) {
|
|
2283
|
+
if (this.ctx.isApp()) return Promise.reject(appNoRooms());
|
|
2284
|
+
const id = typeof roomId === "string" ? normalizeId(roomId) : "";
|
|
2285
|
+
if (!ROOM_CODE.test(id)) return Promise.reject(notRoomCode(roomId));
|
|
2286
|
+
return this.serial(async () => this.open.get(id) ?? this.adopt(await this.connectById(id, opts), opts));
|
|
2287
|
+
}
|
|
2288
|
+
create(opts = {}) {
|
|
2289
|
+
if (this.ctx.isApp()) return Promise.reject(appNoRooms());
|
|
2290
|
+
return this.serial(async () => {
|
|
2291
|
+
const room = await this.adopt(await this.connectNew(opts), {});
|
|
2292
|
+
if (opts.multiLanguage && opts.language) await room.settings({ language: opts.language });
|
|
2293
|
+
return room;
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
async leave(roomId) {
|
|
2297
|
+
await this.get(roomId)?.leave();
|
|
2298
|
+
}
|
|
2299
|
+
async leaveAll() {
|
|
2300
|
+
for (const timer of this.rejoins) clearTimeout(timer);
|
|
2301
|
+
this.rejoins.clear();
|
|
2302
|
+
await Promise.all(this.all.map((room) => room.leave()));
|
|
2303
|
+
}
|
|
2304
|
+
serial(fn) {
|
|
2305
|
+
const run = this.queue.then(fn, fn);
|
|
2306
|
+
this.queue = run.catch(() => {
|
|
2307
|
+
});
|
|
2308
|
+
return run;
|
|
2309
|
+
}
|
|
2310
|
+
connectById(id, opts) {
|
|
2311
|
+
return this.client.joinById(id, { locale: opts.language ?? this.ctx.locale, spectate: !!opts.spectate }).catch((e) => {
|
|
2312
|
+
throw joinError(e);
|
|
2313
|
+
});
|
|
2314
|
+
}
|
|
2315
|
+
connectNew(opts) {
|
|
2316
|
+
const config = { ...opts.config };
|
|
2317
|
+
if (opts.hearts !== void 0) config.heart = opts.hearts;
|
|
2318
|
+
if (opts.timer !== void 0) config.timer = opts.timer;
|
|
2319
|
+
if (opts.maxPlayers !== void 0) config.maxPlayer = opts.maxPlayers;
|
|
2320
|
+
return this.client.create("my_room", {
|
|
2321
|
+
locale: opts.multiLanguage ? "mlang" : opts.language ?? this.ctx.locale,
|
|
2322
|
+
open: !opts.private,
|
|
2323
|
+
mode: opts.mode ?? 0,
|
|
2324
|
+
config
|
|
2325
|
+
}).catch((e) => {
|
|
2326
|
+
throw joinError(e);
|
|
2327
|
+
});
|
|
2328
|
+
}
|
|
2329
|
+
later(ms, fn) {
|
|
2330
|
+
const timer = setTimeout(() => {
|
|
2331
|
+
this.rejoins.delete(timer);
|
|
2332
|
+
fn();
|
|
2333
|
+
}, ms);
|
|
2334
|
+
this.rejoins.add(timer);
|
|
2335
|
+
}
|
|
2336
|
+
recover(info, opts, attempt) {
|
|
2337
|
+
this.later(Math.min(RESTART_FIRST_DELAY * 2 ** attempt, RESTART_MAX_DELAY), () => {
|
|
2338
|
+
if (this.open.has(info.roomId)) return;
|
|
2339
|
+
this.serial(async () => this.open.get(info.roomId) ?? this.adopt(await this.reconnect(info, opts), opts)).catch((e) => {
|
|
2340
|
+
const code = e instanceof WordBombError ? e.code : null;
|
|
2341
|
+
if (attempt + 1 >= RESTART_ATTEMPTS || code && RESTART_FATAL.has(code)) this.ctx.failed(e);
|
|
2342
|
+
else this.recover(info, opts, attempt + 1);
|
|
2343
|
+
});
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
async reconnect(info, opts) {
|
|
2347
|
+
try {
|
|
2348
|
+
return await this.connectById(info.roomId, { ...opts, language: info.locale });
|
|
2349
|
+
} catch (e) {
|
|
2350
|
+
if (!(e instanceof WordBombError) || e.code !== "ROOM_NOT_FOUND" && e.code !== "JOIN_FAILED") throw e;
|
|
2351
|
+
}
|
|
2352
|
+
const config = { multiLang: info.multiLanguage, chain: info.chainStyle };
|
|
2353
|
+
if (info.scenario) config.scenario = info.scenario;
|
|
2354
|
+
const created = await this.client.create("my_room", {
|
|
2355
|
+
reconnectRoomId: info.roomId,
|
|
2356
|
+
locale: info.locale,
|
|
2357
|
+
mode: info.mode,
|
|
2358
|
+
open: !info.locked,
|
|
2359
|
+
guests: info.guests,
|
|
2360
|
+
ba: info.botAccounts,
|
|
2361
|
+
config
|
|
2362
|
+
}).catch((e) => {
|
|
2363
|
+
throw joinError(e);
|
|
2364
|
+
});
|
|
2365
|
+
if (created.roomId === info.roomId) return created;
|
|
2366
|
+
created.leave().catch(() => {
|
|
2367
|
+
});
|
|
2368
|
+
throw new WordBombError("JOIN_FAILED", `room ${info.roomId} is coming back under another id, trying again`);
|
|
2369
|
+
}
|
|
2370
|
+
async adopt(raw, rejoinWith) {
|
|
2371
|
+
let restart = null;
|
|
2372
|
+
const room = new GameRoom(raw, {
|
|
2373
|
+
...this.ctx,
|
|
2374
|
+
restarting: (info) => {
|
|
2375
|
+
restart = info;
|
|
2376
|
+
}
|
|
2377
|
+
});
|
|
2378
|
+
this.open.set(room.id, room);
|
|
2379
|
+
room.once("room.closed", ({ reason }) => {
|
|
2380
|
+
if (this.open.get(room.id) === room) this.open.delete(room.id);
|
|
2381
|
+
if (!this.ctx.rejoin) return;
|
|
2382
|
+
if (reason === "restart" && restart) this.recover(restart, rejoinWith, 0);
|
|
2383
|
+
else if (reason === "disconnected") {
|
|
2384
|
+
this.later(REJOIN_DELAY, () => {
|
|
2385
|
+
this.join(room.id, rejoinWith).catch((e) => this.ctx.failed(e));
|
|
2386
|
+
});
|
|
2387
|
+
}
|
|
2388
|
+
});
|
|
2389
|
+
this.ctx.adopted(room);
|
|
2390
|
+
await room.settled();
|
|
2391
|
+
if (!room.isOpen) throw new WordBombError("JOIN_FAILED", `room ${room.id} closed right after joining`);
|
|
2392
|
+
return room;
|
|
2393
|
+
}
|
|
2394
|
+
};
|
|
2395
|
+
|
|
2396
|
+
// src/session.ts
|
|
2397
|
+
var KEY_PATTERN = /^wbb_(\d{17,20})_[A-Za-z0-9_-]{20,}$/;
|
|
2398
|
+
var REFRESH_MS = 100 * 60 * 1e3;
|
|
2399
|
+
var RETRY_MS = 30 * 1e3;
|
|
2400
|
+
function claims(token) {
|
|
2401
|
+
const part = token.split(".")[1];
|
|
2402
|
+
if (!part) return {};
|
|
2403
|
+
try {
|
|
2404
|
+
return record(JSON.parse(Buffer.from(part, "base64url").toString("utf8")));
|
|
2405
|
+
} catch {
|
|
2406
|
+
return {};
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
var Session = class {
|
|
2410
|
+
constructor(target, key, onError, onBanned) {
|
|
2411
|
+
this.target = target;
|
|
2412
|
+
this.onError = onError;
|
|
2413
|
+
this.onBanned = onBanned;
|
|
2414
|
+
const trimmed = key.trim();
|
|
2415
|
+
const match = KEY_PATTERN.exec(trimmed);
|
|
2416
|
+
if (!match?.[1]) throw new WordBombError("INVALID", "a bot key looks like wbb_<bot id>_<secret>. Create one at https://wordbomb.io/bots");
|
|
2417
|
+
this.key = trimmed;
|
|
2418
|
+
this.me = { id: match[1], name: "", data: {} };
|
|
2419
|
+
}
|
|
2420
|
+
target;
|
|
2421
|
+
onError;
|
|
2422
|
+
onBanned;
|
|
2423
|
+
token = "";
|
|
2424
|
+
kind = "bot";
|
|
2425
|
+
me;
|
|
2426
|
+
key;
|
|
2427
|
+
listeners = /* @__PURE__ */ new Set();
|
|
2428
|
+
inflight = null;
|
|
2429
|
+
timer = null;
|
|
2430
|
+
closed = false;
|
|
2431
|
+
onToken(fn) {
|
|
2432
|
+
this.listeners.add(fn);
|
|
2433
|
+
}
|
|
2434
|
+
refresh() {
|
|
2435
|
+
if (!this.inflight) {
|
|
2436
|
+
this.inflight = this.exchange().finally(() => {
|
|
2437
|
+
this.inflight = null;
|
|
2438
|
+
});
|
|
2439
|
+
}
|
|
2440
|
+
return this.inflight;
|
|
2441
|
+
}
|
|
2442
|
+
close() {
|
|
2443
|
+
this.closed = true;
|
|
2444
|
+
if (this.timer) clearTimeout(this.timer);
|
|
2445
|
+
this.timer = null;
|
|
2446
|
+
}
|
|
2447
|
+
async exchange() {
|
|
2448
|
+
let res;
|
|
2449
|
+
try {
|
|
2450
|
+
res = await fetch(`${this.target.game}/auth/bot`, {
|
|
2451
|
+
method: "POST",
|
|
2452
|
+
headers: { "Content-Type": "application/json" },
|
|
2453
|
+
body: JSON.stringify({ key: this.key })
|
|
2454
|
+
});
|
|
2455
|
+
} catch (e) {
|
|
2456
|
+
throw new WordBombError("HTTP", `could not reach ${this.target.game}: ${e instanceof Error ? e.message : String(e)}`);
|
|
2457
|
+
}
|
|
2458
|
+
const { data, text } = await readBody(res);
|
|
2459
|
+
const body = record(data);
|
|
2460
|
+
if (body.banned === true) throw new WordBombError("BANNED", str(body.banReason, "this bot is banned"), res.status);
|
|
2461
|
+
if (res.status === 503) {
|
|
2462
|
+
const seconds = Number(res.headers.get("retry-after"));
|
|
2463
|
+
throw new WordBombError("BOTS_DISABLED", `bot login 503: ${errorText(data) ?? "bots are turned off"}, try again later`, 503, Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : void 0);
|
|
2464
|
+
}
|
|
2465
|
+
if (!res.ok) throw httpError("bot login", res, data, text);
|
|
2466
|
+
const token = str(body.token);
|
|
2467
|
+
if (!token) throw new WordBombError("AUTH_FAILED", "bot login returned no token", res.status);
|
|
2468
|
+
const user = record(body.user);
|
|
2469
|
+
const userData = record(user.data);
|
|
2470
|
+
const claim = claims(token).app;
|
|
2471
|
+
this.token = token;
|
|
2472
|
+
this.kind = claim === 1 || claim === true || userData.app === true || user.app === true ? "app" : "bot";
|
|
2473
|
+
this.me.id = str(user.id, this.me.id);
|
|
2474
|
+
this.me.name = str(userData.displayName) || str(user.displayName) || str(user.username) || this.me.name;
|
|
2475
|
+
this.me.data = Object.keys(userData).length ? userData : user;
|
|
2476
|
+
for (const fn of this.listeners) fn(token);
|
|
2477
|
+
this.schedule(REFRESH_MS);
|
|
2478
|
+
}
|
|
2479
|
+
schedule(ms) {
|
|
2480
|
+
if (this.closed) return;
|
|
2481
|
+
if (this.timer) clearTimeout(this.timer);
|
|
2482
|
+
this.timer = setTimeout(() => {
|
|
2483
|
+
this.refresh().catch((e) => {
|
|
2484
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
2485
|
+
if (err instanceof WordBombError && err.code === "BANNED") {
|
|
2486
|
+
this.onBanned();
|
|
2487
|
+
return;
|
|
2488
|
+
}
|
|
2489
|
+
this.onError(err);
|
|
2490
|
+
if (err instanceof WordBombError && err.code === "AUTH_FAILED") return;
|
|
2491
|
+
this.schedule(RETRY_MS);
|
|
2492
|
+
});
|
|
2493
|
+
}, ms);
|
|
2494
|
+
}
|
|
2495
|
+
};
|
|
2496
|
+
|
|
2497
|
+
// src/social.ts
|
|
2498
|
+
var DM_MAX = 400;
|
|
2499
|
+
var COMMENT_MAX = 500;
|
|
2500
|
+
var Users = class {
|
|
2501
|
+
constructor(http) {
|
|
2502
|
+
this.http = http;
|
|
2503
|
+
}
|
|
2504
|
+
http;
|
|
2505
|
+
byName = /* @__PURE__ */ new Map();
|
|
2506
|
+
names = /* @__PURE__ */ new Map();
|
|
2507
|
+
async resolve(ref) {
|
|
2508
|
+
if (typeof ref !== "string") return ref.id;
|
|
2509
|
+
const value = ref.trim();
|
|
2510
|
+
if (!value) throw new WordBombError("INVALID", "empty user reference");
|
|
2511
|
+
if (isUserId(value)) return value;
|
|
2512
|
+
const cached = this.byName.get(value.toLowerCase());
|
|
2513
|
+
if (cached) return cached;
|
|
2514
|
+
const r = record(await this.http.get(`player`, `/profile/username/${encodeURIComponent(value)}`));
|
|
2515
|
+
const id = str(r.id);
|
|
2516
|
+
if (!id) throw new WordBombError("NOT_FOUND", `no player named ${value}`);
|
|
2517
|
+
this.byName.set(value.toLowerCase(), id);
|
|
2518
|
+
return id;
|
|
2519
|
+
}
|
|
2520
|
+
async get(ref) {
|
|
2521
|
+
const id = await this.resolve(ref);
|
|
2522
|
+
const r = record(await this.http.get("player", `/profile/${id}`));
|
|
2523
|
+
const p = record(r.p);
|
|
2524
|
+
const name = str(p.displayName) || str(p.username) || id;
|
|
2525
|
+
this.remember(id, name);
|
|
2526
|
+
return {
|
|
2527
|
+
id,
|
|
2528
|
+
name,
|
|
2529
|
+
username: str(p.username),
|
|
2530
|
+
avatar: str(p.avatar),
|
|
2531
|
+
avatarUrl: avatarUrl(id, str(p.avatar)),
|
|
2532
|
+
about: str(p.about) || str(p.aboutMe),
|
|
2533
|
+
exp: num(p.exp),
|
|
2534
|
+
wins: num(p.win),
|
|
2535
|
+
score: num(p.score),
|
|
2536
|
+
wp: num(p.wp),
|
|
2537
|
+
clan: str(record(r.clan).name) || null,
|
|
2538
|
+
isFriend: r.friend === true,
|
|
2539
|
+
raw: p
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
remember(id, name) {
|
|
2543
|
+
if (id && name) this.names.set(id, name);
|
|
2544
|
+
}
|
|
2545
|
+
nameOf(id) {
|
|
2546
|
+
return this.names.get(id) ?? "";
|
|
2547
|
+
}
|
|
2548
|
+
};
|
|
2549
|
+
var Dms = class {
|
|
2550
|
+
constructor(http, users, session) {
|
|
2551
|
+
this.http = http;
|
|
2552
|
+
this.users = users;
|
|
2553
|
+
this.session = session;
|
|
2554
|
+
}
|
|
2555
|
+
http;
|
|
2556
|
+
users;
|
|
2557
|
+
session;
|
|
2558
|
+
async send(to, text) {
|
|
2559
|
+
const id = await this.users.resolve(to);
|
|
2560
|
+
await this.sendToChat(chatIdWith(this.session.me.id, id), text);
|
|
2561
|
+
}
|
|
2562
|
+
async sendToChat(chatId, text) {
|
|
2563
|
+
const body = text.trim().slice(0, DM_MAX);
|
|
2564
|
+
if (!body) throw new WordBombError("INVALID", "message is empty");
|
|
2565
|
+
const r = record(await this.http.post("social", `/inbox/${encodeURIComponent(chatId)}/send`, { t: body }));
|
|
2566
|
+
if (r.i === "0") throw new WordBombError("LINK_DROPPED", "messages with links are dropped");
|
|
2567
|
+
}
|
|
2568
|
+
async history(withUser, limit = 20) {
|
|
2569
|
+
const id = await this.users.resolve(withUser);
|
|
2570
|
+
const l = Math.min(Math.max(Math.round(limit), 1), 100);
|
|
2571
|
+
const r = record(await this.http.get("social", `/inbox/${chatIdWith(this.session.me.id, id)}?l=${l}`));
|
|
2572
|
+
return list(r.d).map((entry) => {
|
|
2573
|
+
const m = record(entry);
|
|
2574
|
+
const kind = str(m.y, "text");
|
|
2575
|
+
return { senderId: str(m.s), mine: str(m.s) === this.session.me.id, kind, text: kind === "text" ? str(m.t) : null };
|
|
2576
|
+
}).reverse();
|
|
2577
|
+
}
|
|
2578
|
+
async inbox(limit = 20) {
|
|
2579
|
+
const l = Math.min(Math.max(Math.round(limit), 1), 50);
|
|
2580
|
+
const r = record(await this.http.get("social", `/inbox?l=${l}`));
|
|
2581
|
+
return list(r.d).map((entry) => {
|
|
2582
|
+
const c = record(entry);
|
|
2583
|
+
const other = list(c.p).map(record).find((p) => str(p.id) !== this.session.me.id);
|
|
2584
|
+
const last = c.l ? record(c.l) : null;
|
|
2585
|
+
const lastKind = last ? str(last.y, "text") : "";
|
|
2586
|
+
if (other) this.users.remember(str(other.id), str(other.displayName));
|
|
2587
|
+
return {
|
|
2588
|
+
chatId: str(c.i),
|
|
2589
|
+
group: !!c.g,
|
|
2590
|
+
with: other ? { id: str(other.id), name: str(other.displayName) } : null,
|
|
2591
|
+
unread: num(c.nc),
|
|
2592
|
+
last: last ? { senderId: str(last.s), kind: lastKind, text: lastKind === "text" ? str(last.t) : null } : null
|
|
2593
|
+
};
|
|
2594
|
+
});
|
|
2595
|
+
}
|
|
2596
|
+
fromRealtime(d) {
|
|
2597
|
+
const payload = record(d);
|
|
2598
|
+
const m = record(payload.m);
|
|
2599
|
+
const senderId = str(m.s);
|
|
2600
|
+
const kind = str(m.y, "text");
|
|
2601
|
+
if (!senderId || senderId === this.session.me.id || kind === "deleted" || kind === "system") return null;
|
|
2602
|
+
const chatId = str(payload.i);
|
|
2603
|
+
const name = str(record(payload.u).n) || this.users.nameOf(senderId) || "someone";
|
|
2604
|
+
this.users.remember(senderId, name);
|
|
2605
|
+
const group = chatId.split("_").length !== 2;
|
|
2606
|
+
return {
|
|
2607
|
+
chatId,
|
|
2608
|
+
group,
|
|
2609
|
+
from: { id: senderId, name },
|
|
2610
|
+
kind,
|
|
2611
|
+
text: kind === "text" ? str(m.t) : null,
|
|
2612
|
+
reply: (text) => group ? this.sendToChat(chatId, text) : this.send(senderId, text)
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
};
|
|
2616
|
+
var Friends = class {
|
|
2617
|
+
constructor(http, users, realtime) {
|
|
2618
|
+
this.http = http;
|
|
2619
|
+
this.users = users;
|
|
2620
|
+
this.realtime = realtime;
|
|
2621
|
+
}
|
|
2622
|
+
http;
|
|
2623
|
+
users;
|
|
2624
|
+
realtime;
|
|
2625
|
+
online = /* @__PURE__ */ new Map();
|
|
2626
|
+
async list() {
|
|
2627
|
+
const [friends, requests] = await Promise.all([this.http.get("player", "/friends"), this.http.get("player", "/friends/requests")]);
|
|
2628
|
+
const toRef = (entry) => {
|
|
2629
|
+
const f = record(entry);
|
|
2630
|
+
const ref = { id: str(f.id), name: str(f.displayName) };
|
|
2631
|
+
this.users.remember(ref.id, ref.name);
|
|
2632
|
+
return ref;
|
|
2633
|
+
};
|
|
2634
|
+
return {
|
|
2635
|
+
friends: list(record(friends).mapped).map((entry) => {
|
|
2636
|
+
const ref = toRef(entry);
|
|
2637
|
+
const presence = this.online.get(ref.id);
|
|
2638
|
+
return { ...ref, online: !!presence, status: presence?.status ?? null, room: presence?.room ?? null };
|
|
2639
|
+
}),
|
|
2640
|
+
incoming: list(record(requests).mapped).map(toRef)
|
|
2641
|
+
};
|
|
2642
|
+
}
|
|
2643
|
+
async accept(user) {
|
|
2644
|
+
await this.http.post("player", "/friends/accept", { friendId: await this.users.resolve(user) });
|
|
2645
|
+
}
|
|
2646
|
+
async decline(user) {
|
|
2647
|
+
await this.http.delete("player", "/friends/request", { friendId: await this.users.resolve(user) });
|
|
2648
|
+
}
|
|
2649
|
+
async remove(user) {
|
|
2650
|
+
await this.http.delete("player", `/friends/${encodeURIComponent(await this.users.resolve(user))}`);
|
|
2651
|
+
}
|
|
2652
|
+
async invite(user, roomId) {
|
|
2653
|
+
if (!this.realtime) throw new WordBombError("REALTIME_DOWN", "invites need the realtime connection (connect with realtime: true)");
|
|
2654
|
+
const r = record(await this.realtime.request("friend:invite", { friendId: await this.users.resolve(user), roomId }));
|
|
2655
|
+
return { delivered: r.delivered === true, reason: str(r.reason) || null };
|
|
2656
|
+
}
|
|
2657
|
+
friendRequest(user) {
|
|
2658
|
+
return { from: user, accept: () => this.accept(user), decline: () => this.decline(user) };
|
|
2659
|
+
}
|
|
2660
|
+
};
|
|
2661
|
+
function friendRoom(value) {
|
|
2662
|
+
const r = record(value);
|
|
2663
|
+
const id = str(r.id);
|
|
2664
|
+
if (!id) return null;
|
|
2665
|
+
return { id, locked: r.locked === true || r.kind === "private", started: r.started === true, players: num(r.players) };
|
|
2666
|
+
}
|
|
2667
|
+
var Comments = class {
|
|
2668
|
+
constructor(http, users, session) {
|
|
2669
|
+
this.http = http;
|
|
2670
|
+
this.users = users;
|
|
2671
|
+
this.session = session;
|
|
2672
|
+
}
|
|
2673
|
+
http;
|
|
2674
|
+
users;
|
|
2675
|
+
session;
|
|
2676
|
+
async list(profile, limit = 20) {
|
|
2677
|
+
const profileId = profile ? await this.users.resolve(profile) : this.session.me.id;
|
|
2678
|
+
const l = Math.min(Math.max(Math.round(limit), 1), 50);
|
|
2679
|
+
const r = record(await this.http.get("player", `/profile/comments/${profileId}?l=${l}`));
|
|
2680
|
+
const all = list(r.comments).map((entry) => this.toComment(record(entry), profileId));
|
|
2681
|
+
const threads = all.filter((c) => !c.parentId).map((c) => ({ ...c, replies: all.filter((x) => x.parentId === c.id) }));
|
|
2682
|
+
return { total: num(r.total, threads.length), canComment: r.canComment !== false, threads };
|
|
2683
|
+
}
|
|
2684
|
+
async post(profile, text) {
|
|
2685
|
+
return this.create({ profileId: await this.users.resolve(profile) }, text);
|
|
2686
|
+
}
|
|
2687
|
+
async reply(to, text) {
|
|
2688
|
+
const target = { profileId: to.profileId, parentId: to.parentId ?? to.id };
|
|
2689
|
+
if (to.parentId) target.replyToId = to.id;
|
|
2690
|
+
return this.create(target, text);
|
|
2691
|
+
}
|
|
2692
|
+
async create(target, text) {
|
|
2693
|
+
const body = text.trim().slice(0, COMMENT_MAX);
|
|
2694
|
+
if (!body) throw new WordBombError("INVALID", "comment is empty");
|
|
2695
|
+
const r = record(await this.http.post("player", "/profile/comment/create", { ...target, text: body }));
|
|
2696
|
+
if (r.success !== true) throw new WordBombError("FORBIDDEN", `comment not posted: ${str(r.error, "unknown reason")}`);
|
|
2697
|
+
const c = record(r.comment);
|
|
2698
|
+
return this.toComment(
|
|
2699
|
+
{ ...c, id: str(c.id), r: target.parentId ?? null, authorId: this.session.me.id, authorName: this.session.me.name, text: str(c.text, body) },
|
|
2700
|
+
str(target.profileId)
|
|
2701
|
+
);
|
|
2702
|
+
}
|
|
2703
|
+
toComment(c, profileId) {
|
|
2704
|
+
const comment = {
|
|
2705
|
+
id: str(c.id),
|
|
2706
|
+
profileId,
|
|
2707
|
+
parentId: str(c.r) || null,
|
|
2708
|
+
author: { id: str(c.authorId), name: str(c.authorName) },
|
|
2709
|
+
text: str(c.text),
|
|
2710
|
+
at: typeof c.timestamp === "number" ? c.timestamp : Date.parse(str(c.timestamp)) || 0,
|
|
2711
|
+
pinned: c.pinned === true,
|
|
2712
|
+
reply: (text) => this.reply(comment, text)
|
|
2713
|
+
};
|
|
2714
|
+
this.users.remember(comment.author.id, comment.author.name);
|
|
2715
|
+
return comment;
|
|
2716
|
+
}
|
|
2717
|
+
};
|
|
2718
|
+
var OwnProfile = class {
|
|
2719
|
+
constructor(http, users, session) {
|
|
2720
|
+
this.http = http;
|
|
2721
|
+
this.users = users;
|
|
2722
|
+
this.session = session;
|
|
2723
|
+
}
|
|
2724
|
+
http;
|
|
2725
|
+
users;
|
|
2726
|
+
session;
|
|
2727
|
+
get() {
|
|
2728
|
+
return this.users.get(this.session.me.id);
|
|
2729
|
+
}
|
|
2730
|
+
async update(fields2) {
|
|
2731
|
+
const body = {};
|
|
2732
|
+
if (fields2.displayName !== void 0) body.displayName = fields2.displayName;
|
|
2733
|
+
if (fields2.about !== void 0) body.aboutMe = fields2.about;
|
|
2734
|
+
if (!Object.keys(body).length) return;
|
|
2735
|
+
const r = record(await this.http.post("game", "/profile/update", body));
|
|
2736
|
+
if (r.cooldown) throw new WordBombError("RATE_LIMITED", `name change on cooldown (${str(r.cooldown, String(r.cooldown))})`);
|
|
2737
|
+
if (r.success !== true) throw new WordBombError("FORBIDDEN", `profile not updated: ${str(r.error, "unknown reason")}`);
|
|
2738
|
+
if (body.displayName) this.session.me.name = body.displayName;
|
|
2739
|
+
}
|
|
2740
|
+
};
|
|
2741
|
+
|
|
2742
|
+
// src/targets.ts
|
|
2743
|
+
var TARGETS = {
|
|
2744
|
+
local: {
|
|
2745
|
+
game: "http://localhost:2567",
|
|
2746
|
+
gameWs: "ws://localhost:2567",
|
|
2747
|
+
social: "http://localhost:3006",
|
|
2748
|
+
player: "http://localhost:3007",
|
|
2749
|
+
ws2: "ws://localhost:3011"
|
|
2750
|
+
},
|
|
2751
|
+
prod: {
|
|
2752
|
+
game: "https://io.wordbomb.io",
|
|
2753
|
+
gameWs: "wss://io.wordbomb.io",
|
|
2754
|
+
social: "https://social.wordbomb.io",
|
|
2755
|
+
player: "https://player.wordbomb.io",
|
|
2756
|
+
ws2: "wss://ws2.wordbomb.io"
|
|
2757
|
+
}
|
|
2758
|
+
};
|
|
2759
|
+
function resolveTarget(target) {
|
|
2760
|
+
return typeof target === "string" ? TARGETS[target] : target;
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2763
|
+
// src/bot.ts
|
|
2764
|
+
var NOTIFY_MAX = 200;
|
|
2765
|
+
var WordBomb = class _WordBomb extends Emitter {
|
|
2766
|
+
target;
|
|
2767
|
+
http;
|
|
2768
|
+
realtime;
|
|
2769
|
+
users;
|
|
2770
|
+
dm;
|
|
2771
|
+
friends;
|
|
2772
|
+
comments;
|
|
2773
|
+
profile;
|
|
2774
|
+
notifications;
|
|
2775
|
+
lobby;
|
|
2776
|
+
rooms;
|
|
2777
|
+
apps;
|
|
2778
|
+
commands;
|
|
2779
|
+
cosmetics;
|
|
2780
|
+
avatar;
|
|
2781
|
+
banner;
|
|
2782
|
+
background;
|
|
2783
|
+
session;
|
|
2784
|
+
client;
|
|
2785
|
+
interactions;
|
|
2786
|
+
closed = false;
|
|
2787
|
+
requested = /* @__PURE__ */ new Set();
|
|
2788
|
+
static async connect(opts) {
|
|
2789
|
+
const bot = new _WordBomb(opts);
|
|
2790
|
+
await bot.session.refresh();
|
|
2791
|
+
await Promise.all([
|
|
2792
|
+
bot.notifications.prime().catch((e) => bot.fail(e)),
|
|
2793
|
+
bot.kind === "app" ? Promise.resolve() : bot.friends.list().catch((e) => bot.fail(e))
|
|
2794
|
+
]);
|
|
2795
|
+
bot.start();
|
|
2796
|
+
return bot;
|
|
2797
|
+
}
|
|
2798
|
+
constructor(opts) {
|
|
2799
|
+
super();
|
|
2800
|
+
this.target = resolveTarget(opts.target);
|
|
2801
|
+
const locale = opts.locale ?? "en-US";
|
|
2802
|
+
this.session = new Session(
|
|
2803
|
+
this.target,
|
|
2804
|
+
opts.key,
|
|
2805
|
+
(e) => this.fail(e),
|
|
2806
|
+
() => this.emit("banned", void 0)
|
|
2807
|
+
);
|
|
2808
|
+
this.client = new Client(this.target.gameWs);
|
|
2809
|
+
this.session.onToken((token) => {
|
|
2810
|
+
this.client.auth.token = token;
|
|
2811
|
+
});
|
|
2812
|
+
this.http = new Http(this.session);
|
|
2813
|
+
this.realtime = opts.realtime === false ? null : new Realtime(this.session, opts.clientId ?? "bot");
|
|
2814
|
+
this.users = new Users(this.http);
|
|
2815
|
+
this.dm = new Dms(this.http, this.users, this.session);
|
|
2816
|
+
this.friends = new Friends(this.http, this.users, this.realtime);
|
|
2817
|
+
this.comments = new Comments(this.http, this.users, this.session);
|
|
2818
|
+
this.profile = new OwnProfile(this.http, this.users, this.session);
|
|
2819
|
+
this.notifications = new Notifications(this.http);
|
|
2820
|
+
this.commands = new Commands(this.http, this.session);
|
|
2821
|
+
this.interactions = new Interactions(this.realtime, this.session, this.commands);
|
|
2822
|
+
this.apps = new Apps(this.interactions, this.realtime);
|
|
2823
|
+
this.lobby = new Lobby(this.client, locale);
|
|
2824
|
+
this.rooms = new Rooms(this.client, {
|
|
2825
|
+
locale,
|
|
2826
|
+
keepAlive: opts.keepRoomsAlive !== false,
|
|
2827
|
+
rejoin: opts.rejoinRooms !== false,
|
|
2828
|
+
myName: () => this.session.me.name,
|
|
2829
|
+
isApp: () => this.session.kind === "app",
|
|
2830
|
+
channel: (room, sink) => this.interactions.attach(room, sink, true),
|
|
2831
|
+
adopted: (room) => this.adopt(room),
|
|
2832
|
+
failed: (e) => this.fail(e)
|
|
2833
|
+
});
|
|
2834
|
+
this.cosmetics = new Cosmetics(this.session, this.rooms, this.lobby);
|
|
2835
|
+
this.avatar = new ImageSlot(this.http, "avatar");
|
|
2836
|
+
this.banner = new ImageSlot(this.http, "banner");
|
|
2837
|
+
this.background = new ImageSlot(this.http, "background");
|
|
2838
|
+
}
|
|
2839
|
+
get me() {
|
|
2840
|
+
return { id: this.session.me.id, name: this.session.me.name };
|
|
2841
|
+
}
|
|
2842
|
+
get token() {
|
|
2843
|
+
return this.session.token;
|
|
2844
|
+
}
|
|
2845
|
+
get kind() {
|
|
2846
|
+
return this.session.kind;
|
|
2847
|
+
}
|
|
2848
|
+
async notify(user, text) {
|
|
2849
|
+
if (this.kind !== "app") throw new WordBombError("FORBIDDEN", "only applications send notifications");
|
|
2850
|
+
const body = text.trim();
|
|
2851
|
+
if (!body || body.length > NOTIFY_MAX) throw new WordBombError("INVALID", `notification text must be 1 to ${NOTIFY_MAX} characters`);
|
|
2852
|
+
await this.http.post("player", "/apps/notify", { to: await this.users.resolve(user), text: body });
|
|
2853
|
+
}
|
|
2854
|
+
async close() {
|
|
2855
|
+
if (this.closed) return;
|
|
2856
|
+
this.closed = true;
|
|
2857
|
+
await this.rooms.leaveAll().catch(() => {
|
|
2858
|
+
});
|
|
2859
|
+
this.realtime?.close();
|
|
2860
|
+
this.session.close();
|
|
2861
|
+
}
|
|
2862
|
+
start() {
|
|
2863
|
+
const rt = this.realtime;
|
|
2864
|
+
if (!rt) return;
|
|
2865
|
+
rt.on("event", ({ e, d }) => this.onRealtime(e, d));
|
|
2866
|
+
rt.on("up", () => {
|
|
2867
|
+
this.interactions.resubscribe();
|
|
2868
|
+
this.emit("realtime.up", void 0);
|
|
2869
|
+
});
|
|
2870
|
+
rt.on("down", (info) => this.emit("realtime.down", info));
|
|
2871
|
+
rt.on("banned", () => this.emit("banned", void 0));
|
|
2872
|
+
rt.on("replaced", () => this.fail(new WordBombError("REPLACED", "another process connected with this key, so this one stopped getting DMs, invites and commands")));
|
|
2873
|
+
rt.connect();
|
|
2874
|
+
}
|
|
2875
|
+
fail(e) {
|
|
2876
|
+
this.emit("error", e instanceof Error ? e : new WordBombError("HTTP", String(e)));
|
|
2877
|
+
}
|
|
2878
|
+
adopt(room) {
|
|
2879
|
+
const relay = this.emit.bind(this);
|
|
2880
|
+
for (const name of ROOM_EVENTS) room.on(name, (payload) => relay(name, payload));
|
|
2881
|
+
this.emit("room.joined", { room });
|
|
2882
|
+
}
|
|
2883
|
+
friendName(id) {
|
|
2884
|
+
return this.users.nameOf(id) || "a friend";
|
|
2885
|
+
}
|
|
2886
|
+
request(from) {
|
|
2887
|
+
if (this.requested.has(from.id)) return;
|
|
2888
|
+
this.requested.add(from.id);
|
|
2889
|
+
const req = this.friends.friendRequest(from);
|
|
2890
|
+
this.emit("friend.request", { ...req, decline: () => {
|
|
2891
|
+
this.requested.delete(from.id);
|
|
2892
|
+
return req.decline();
|
|
2893
|
+
} });
|
|
2894
|
+
}
|
|
2895
|
+
async pendingRequests() {
|
|
2896
|
+
if (this.kind === "app") return;
|
|
2897
|
+
const { incoming } = await this.friends.list();
|
|
2898
|
+
for (const from of incoming) this.request(from);
|
|
2899
|
+
}
|
|
2900
|
+
onRealtime(e, d) {
|
|
2901
|
+
const data = record(d);
|
|
2902
|
+
const id = str(data.id);
|
|
2903
|
+
switch (e) {
|
|
2904
|
+
case "bot:cmd":
|
|
2905
|
+
case "bot:btn":
|
|
2906
|
+
this.interactions.receive(e, d);
|
|
2907
|
+
return;
|
|
2908
|
+
case "notif":
|
|
2909
|
+
this.notifications.poll((fresh) => {
|
|
2910
|
+
for (const n of fresh) {
|
|
2911
|
+
this.emit("notification", n);
|
|
2912
|
+
if (n.kind === "profile_comment" || n.kind === "comment_reply") this.emit("profile.comment", n);
|
|
2913
|
+
if (n.kind === "achievement") this.emit("achievement", n);
|
|
2914
|
+
}
|
|
2915
|
+
}).catch((err) => this.fail(err));
|
|
2916
|
+
return;
|
|
2917
|
+
case "inbox": {
|
|
2918
|
+
const message = this.dm.fromRealtime(d);
|
|
2919
|
+
if (message) this.emit("dm.message", message);
|
|
2920
|
+
return;
|
|
2921
|
+
}
|
|
2922
|
+
case "friends:init":
|
|
2923
|
+
for (const entry of list(data.online)) {
|
|
2924
|
+
const f = record(entry);
|
|
2925
|
+
const fid = str(f.id);
|
|
2926
|
+
if (fid) this.friends.online.set(fid, { status: str(f.status, "online"), room: friendRoom(f.room) });
|
|
2927
|
+
}
|
|
2928
|
+
if (num(data.requestsCount) > 0) this.pendingRequests().catch((e2) => this.fail(e2));
|
|
2929
|
+
return;
|
|
2930
|
+
case "friend:room": {
|
|
2931
|
+
if (!id) return;
|
|
2932
|
+
const room = friendRoom(data.room);
|
|
2933
|
+
const presence = this.friends.online.get(id);
|
|
2934
|
+
if (presence) presence.room = room;
|
|
2935
|
+
this.emit("friend.room", { id, name: this.friendName(id), room });
|
|
2936
|
+
return;
|
|
2937
|
+
}
|
|
2938
|
+
case "friend:online":
|
|
2939
|
+
if (!id) return;
|
|
2940
|
+
this.friends.online.set(id, { status: str(data.status, "online"), room: this.friends.online.get(id)?.room ?? null });
|
|
2941
|
+
this.emit("friend.online", { id, name: this.friendName(id), status: str(data.status, "online") });
|
|
2942
|
+
return;
|
|
2943
|
+
case "friend:offline":
|
|
2944
|
+
if (!id) return;
|
|
2945
|
+
this.friends.online.delete(id);
|
|
2946
|
+
this.emit("friend.offline", { id, name: this.friendName(id) });
|
|
2947
|
+
return;
|
|
2948
|
+
case "friend:request": {
|
|
2949
|
+
const ref = this.userRef(data.friend);
|
|
2950
|
+
if (ref) this.request(ref);
|
|
2951
|
+
return;
|
|
2952
|
+
}
|
|
2953
|
+
case "friend:request_canceled":
|
|
2954
|
+
if (!id) return;
|
|
2955
|
+
this.requested.delete(id);
|
|
2956
|
+
this.emit("friend.request.canceled", { id });
|
|
2957
|
+
return;
|
|
2958
|
+
case "friend:added": {
|
|
2959
|
+
const ref = this.userRef(data.friend);
|
|
2960
|
+
if (!ref) return;
|
|
2961
|
+
this.requested.delete(ref.id);
|
|
2962
|
+
this.emit("friend.added", ref);
|
|
2963
|
+
return;
|
|
2964
|
+
}
|
|
2965
|
+
case "friend:removed":
|
|
2966
|
+
if (!id) return;
|
|
2967
|
+
this.friends.online.delete(id);
|
|
2968
|
+
this.emit("friend.removed", { id });
|
|
2969
|
+
return;
|
|
2970
|
+
case "friend:invite": {
|
|
2971
|
+
const fromId = str(data.fromId);
|
|
2972
|
+
if (!fromId) return;
|
|
2973
|
+
const from = { id: fromId, name: str(data.fromName) || this.friendName(fromId) };
|
|
2974
|
+
this.users.remember(from.id, from.name);
|
|
2975
|
+
const roomId = str(data.roomId) || null;
|
|
2976
|
+
this.emit("invite.received", {
|
|
2977
|
+
from,
|
|
2978
|
+
roomId,
|
|
2979
|
+
join: () => roomId ? this.rooms.join(roomId) : Promise.reject(new WordBombError("INVALID", "this invite has no room"))
|
|
2980
|
+
});
|
|
2981
|
+
return;
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
}
|
|
2985
|
+
userRef(value) {
|
|
2986
|
+
const f = record(value);
|
|
2987
|
+
const id = str(f.id);
|
|
2988
|
+
if (!id) return null;
|
|
2989
|
+
const ref = { id, name: str(f.displayName) || str(f.name) || "someone" };
|
|
2990
|
+
this.users.remember(ref.id, ref.name);
|
|
2991
|
+
return ref;
|
|
2992
|
+
}
|
|
2993
|
+
};
|
|
2994
|
+
|
|
2995
|
+
// src/types.ts
|
|
2996
|
+
var MODES = {
|
|
2997
|
+
0: "original",
|
|
2998
|
+
1: "chain",
|
|
2999
|
+
5: "typing race",
|
|
3000
|
+
7: "dungeon",
|
|
3001
|
+
9: "spelling bee",
|
|
3002
|
+
10: "scapes",
|
|
3003
|
+
15: "color guesser",
|
|
3004
|
+
16: "button",
|
|
3005
|
+
17: "draw",
|
|
3006
|
+
18: "squad",
|
|
3007
|
+
22: "trivia",
|
|
3008
|
+
23: "chess",
|
|
3009
|
+
24: "map",
|
|
3010
|
+
26: "okey"
|
|
3011
|
+
};
|
|
3012
|
+
function modeName(mode) {
|
|
3013
|
+
return MODES[mode] ?? `mode ${mode}`;
|
|
3014
|
+
}
|
|
3015
|
+
|
|
3016
|
+
// package.json
|
|
3017
|
+
var package_default = {
|
|
3018
|
+
name: "@wordbombio/sdk",
|
|
3019
|
+
version: "0.2.0",
|
|
3020
|
+
description: "Build official bots for Word Bomb with a bot key",
|
|
3021
|
+
type: "module",
|
|
3022
|
+
main: "./dist/index.cjs",
|
|
3023
|
+
module: "./dist/index.js",
|
|
3024
|
+
types: "./dist/index.d.ts",
|
|
3025
|
+
exports: {
|
|
3026
|
+
".": {
|
|
3027
|
+
import: {
|
|
3028
|
+
types: "./dist/index.d.ts",
|
|
3029
|
+
default: "./dist/index.js"
|
|
3030
|
+
},
|
|
3031
|
+
require: {
|
|
3032
|
+
types: "./dist/index.d.cts",
|
|
3033
|
+
default: "./dist/index.cjs"
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
},
|
|
3037
|
+
files: [
|
|
3038
|
+
"dist",
|
|
3039
|
+
"README.md",
|
|
3040
|
+
"AGENTS.md"
|
|
3041
|
+
],
|
|
3042
|
+
engines: {
|
|
3043
|
+
node: ">=22.9"
|
|
3044
|
+
},
|
|
3045
|
+
scripts: {
|
|
3046
|
+
prebuild: `node -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,
|
|
3047
|
+
build: "tsup",
|
|
3048
|
+
typecheck: "tsc --noEmit",
|
|
3049
|
+
example: "node --env-file-if-exists=.env --import tsx examples/autoplayer.ts",
|
|
3050
|
+
"example:chat": "node --env-file-if-exists=.env --import tsx examples/chatbot.ts",
|
|
3051
|
+
"example:tracker": "node --env-file-if-exists=.env --import tsx examples/tracker.ts",
|
|
3052
|
+
"example:hyphens": "node --env-file-if-exists=.env --import tsx examples/hyphen-champion.ts",
|
|
3053
|
+
mcp: "tsx src/cli.ts mcp",
|
|
3054
|
+
prepublishOnly: "npm run typecheck && npm run build"
|
|
3055
|
+
},
|
|
3056
|
+
keywords: [
|
|
3057
|
+
"wordbomb",
|
|
3058
|
+
"word bomb",
|
|
3059
|
+
"bot",
|
|
3060
|
+
"mcp",
|
|
3061
|
+
"sdk"
|
|
3062
|
+
],
|
|
3063
|
+
dependencies: {
|
|
3064
|
+
"@colyseus/sdk": "^0.18.2",
|
|
3065
|
+
msgpackr: "^2.0.1"
|
|
3066
|
+
},
|
|
3067
|
+
devDependencies: {
|
|
3068
|
+
"@types/node": "^22.8.4",
|
|
3069
|
+
tsup: "^8.3.5",
|
|
3070
|
+
tsx: "^4.19.2",
|
|
3071
|
+
typescript: "^5.9.0"
|
|
3072
|
+
},
|
|
3073
|
+
publishConfig: {
|
|
3074
|
+
access: "public"
|
|
3075
|
+
},
|
|
3076
|
+
bin: {
|
|
3077
|
+
wordbomb: "dist/cli.js"
|
|
3078
|
+
},
|
|
3079
|
+
license: "MIT"
|
|
3080
|
+
};
|
|
3081
|
+
|
|
3082
|
+
// src/version.ts
|
|
3083
|
+
var VERSION = package_default.version;
|
|
3084
|
+
export {
|
|
3085
|
+
APP_ROOM_EVENTS,
|
|
3086
|
+
AppRoom,
|
|
3087
|
+
Apps,
|
|
3088
|
+
Autoplayer,
|
|
3089
|
+
COSMETIC_KINDS,
|
|
3090
|
+
Commands,
|
|
3091
|
+
Comments,
|
|
3092
|
+
Cosmetics,
|
|
3093
|
+
Dms,
|
|
3094
|
+
Friends,
|
|
3095
|
+
GameRoom,
|
|
3096
|
+
ImageSlot,
|
|
3097
|
+
Lobby,
|
|
3098
|
+
MODES,
|
|
3099
|
+
Notifications,
|
|
3100
|
+
OwnProfile,
|
|
3101
|
+
ROOM_EVENTS,
|
|
3102
|
+
Rooms,
|
|
3103
|
+
TARGETS,
|
|
3104
|
+
Users,
|
|
3105
|
+
VERSION,
|
|
3106
|
+
WordBomb,
|
|
3107
|
+
WordBombError,
|
|
3108
|
+
WordList,
|
|
3109
|
+
avatarUrl,
|
|
3110
|
+
modeName,
|
|
3111
|
+
resolveTarget
|
|
3112
|
+
};
|
|
3113
|
+
//# sourceMappingURL=index.js.map
|