UNPKG

lilybird

Version:
58 lines (57 loc) 2.05 kB
import { CachingManager } from "./cache/manager.js"; import { DebugREST, REST } from "./http/rest.js"; import { ListenerCompiler } from "./compiler.js"; import { WebSocketManager } from "#ws"; export class Client { rest; cache; ws; #dispatch; constructor(options, debug) { this.rest = options.useDebugRest === true ? new DebugREST(debug) : new REST(); this.cache = typeof options.cachingManager !== "undefined" ? options.cachingManager : new CachingManager(); this.ws = new WebSocketManager({ intents: options.intents, presence: options.presence }, undefined, debug); this.#dispatch = options.dispatch; } async login(token, dispatch = this.#dispatch) { if (typeof dispatch === "undefined") throw new Error("the client doesn't have any 'dispatch' function defined."); this.ws.init(token, dispatch); this.rest.setToken(token); await this.ws.connect(); return token; } close() { this.rest.setToken(undefined); this.ws.close(); } async ping() { const start = performance.now(); await this.rest.getGateway(); const final = performance.now() - start; return { ws: await this.ws.ping(), rest: final }; } } export async function createClient(options) { const compiler = new ListenerCompiler({ transformers: options.transformers, transformClient: options.transformClient }); compiler.addListenersFromObject(options.listeners); if (typeof options.caching !== "undefined") compiler.appendCachingHandlers(options.caching); const client = new Client({ intents: options.intents, presence: options.presence, useDebugRest: typeof options.debug !== "undefined", cachingManager: options.cachingManager }, options.debug); await client.login(options.token, compiler.getDispatchFunction(client, client.ws.resumeInfo)); return client; }