libhyperproxy/src/proxy.ts

95 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-01-12 17:39:23 +00:00
import Protomux from "protomux";
2023-04-16 02:17:30 +00:00
import { DataSocketOptions, PeerOptions } from "./peer.js";
import EventEmitter from "events";
2023-01-12 17:39:23 +00:00
export interface ProxyOptions extends DataSocketOptions {
swarm: any;
protocol: string;
listen?: boolean;
autostart?: boolean;
}
export default abstract class Proxy extends EventEmitter {
2023-04-15 23:34:24 +00:00
protected _listen: any;
protected _autostart: boolean;
2023-01-12 17:39:23 +00:00
constructor({
swarm,
protocol,
onopen,
onreceive,
onsend,
onclose,
onchannel,
2023-01-12 17:39:23 +00:00
listen = false,
autostart = false,
2023-02-26 03:21:09 +00:00
emulateWebsocket = false,
2023-01-12 17:39:23 +00:00
}: ProxyOptions) {
super();
2023-01-12 17:39:23 +00:00
this._swarm = swarm;
this._protocol = protocol;
this._listen = listen;
this._autostart = autostart;
2023-02-26 03:21:09 +00:00
this._socketOptions = {
onopen,
onreceive,
onsend,
onclose,
onchannel,
2023-02-26 03:21:09 +00:00
emulateWebsocket,
};
2023-01-12 17:39:23 +00:00
this.init();
}
2023-04-15 23:45:16 +00:00
protected _socketOptions: DataSocketOptions;
2023-04-15 23:44:01 +00:00
get socketOptions(): DataSocketOptions {
return this._socketOptions;
}
2023-01-12 17:39:23 +00:00
private _swarm: any;
get swarm(): any {
return this._swarm;
}
private _protocol: string;
get protocol(): string {
return this._protocol;
}
2023-04-16 02:17:30 +00:00
protected abstract handlePeer({
2023-01-12 17:39:23 +00:00
peer,
muxer,
...options
2023-04-16 02:17:30 +00:00
}: DataSocketOptions & PeerOptions);
2023-01-12 17:39:23 +00:00
protected _init() {
// Implement in subclasses
}
private async init() {
if (this._listen) {
this._swarm.on("connection", this._handleConnection.bind(this));
}
await this._init();
}
private _handleConnection(peer: any) {
const muxer = Protomux.from(peer);
const handlePeer = this.handlePeer.bind(this, {
peer,
muxer,
...this._socketOptions,
});
if (this._autostart) {
handlePeer();
return;
}
muxer.pair(this._protocol, handlePeer);
}
}