kernel-swarm-client/src/index.ts

117 lines
3.1 KiB
TypeScript
Raw Normal View History

import {EventEmitter} from "events";
import {DataFn, ErrTuple} from "libskynet";
import {Buffer} from "buffer";
2022-07-20 01:38:29 +00:00
const DHT_MODULE = "AQD1IgE4lTZkq1fqdoYGojKRNrSk0YQ_wrHbRtIiHDrnow";
let callModule: any,
connectModule: any;
2022-07-20 01:38:29 +00:00
async function loadLibs() {
if (callModule && connectModule) {
return;
}
if (typeof window !== "undefined" && window?.document) {
const pkg = (await import("libkernel"));
callModule = pkg.callModule;
connectModule = pkg.connectModule;
} else {
const pkg = (await import("libkmodule"));
callModule = pkg.callModule;
connectModule = pkg.connectModule;
}
2022-07-20 01:38:29 +00:00
}
export class DHT {
public async connect(pubkey: string): Promise<Socket> {
await loadLibs();
const [resp, err] = await callModule(DHT_MODULE, "connect", {pubkey});
if (err) {
throw new Error(err);
}
return new Socket(resp.id);
2022-07-20 01:38:29 +00:00
}
async ready(): Promise<ErrTuple> {
await loadLibs();
return callModule(DHT_MODULE, "ready");
}
public async addRelay(pubkey: string): Promise<void> {
await loadLibs();
const [, err] = await callModule(DHT_MODULE, "addRelay", {pubkey});
if (err) {
throw new Error(err);
}
}
2022-07-20 02:58:40 +00:00
public async removeRelay(pubkey: string): Promise<void> {
await loadLibs();
const [, err] = await callModule(DHT_MODULE, "removeRelay", {pubkey});
if (err) {
throw new Error(err);
}
}
public async clearRelays(): Promise<void> {
await loadLibs();
await callModule(DHT_MODULE, "clearRelays");
2022-07-20 01:38:29 +00:00
}
}
export class Socket extends EventEmitter {
private id: number;
private eventUpdates: { [event: string]: DataFn[] } = {};
constructor(id: number) {
super();
this.id = id;
2022-07-20 01:38:29 +00:00
}
on(eventName: string, listener: (...args: any[]) => void): this {
const [update, promise] = connectModule(
DHT_MODULE,
"listenSocketEvent",
{id: this.id, event: eventName},
(data: any) => {
this.emit(eventName, data);
}
);
this.trackEvent(eventName, update);
promise.then(() => {
this.off(eventName, listener);
});
return super.on(eventName, listener);
}
2022-07-20 01:38:29 +00:00
off(type: string, listener: any): this {
const updates = [...this.eventUpdates[type]];
this.eventUpdates[type] = [];
for (const func of updates) {
func({action: "off"});
}
return super.off(type, listener);
}
write(message: string | Buffer): void {
callModule(DHT_MODULE, "write", {id: this.id, message});
}
2022-07-20 02:58:40 +00:00
end(): void {
callModule(DHT_MODULE, "close", {id: this.id});
2022-07-20 01:38:29 +00:00
}
2022-07-20 02:58:40 +00:00
private ensureEvent(event: string): void {
if (!(event in this.eventUpdates)) {
this.eventUpdates[event] = [];
}
}
private trackEvent(event: string, update: DataFn): void {
this.ensureEvent(event as string);
this.eventUpdates[event].push(update);
}
2022-07-20 01:38:29 +00:00
}