-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtunnel.ts
More file actions
185 lines (160 loc) · 5.83 KB
/
tunnel.ts
File metadata and controls
185 lines (160 loc) · 5.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { spawn, ChildProcess } from "node:child_process";
import { EventEmitter } from "node:events";
import { bin } from "./constants.js";
import { Connection } from "./types.js";
import { ConnectionHandler, TryCloudflareHandler } from "./handler.js";
export type TunnelOptions = Record<string, string | number | boolean>;
export interface TunnelEvents {
// Status events
url: (url: string) => void;
connected: (connection: Connection) => void;
disconnected: (connection: Connection) => void;
// Process events
stdout: (data: string) => void;
stderr: (data: string) => void;
error: (error: Error) => void;
exit: (code: number | null, signal: NodeJS.Signals | null) => void;
}
export type OutputHandler = (output: string, tunnel: Tunnel) => void;
export class Tunnel extends EventEmitter {
private _process: ChildProcess;
private outputHandlers: OutputHandler[] = [];
constructor(options: TunnelOptions | string[] = ["tunnel", "--hello-world"]) {
super();
this.setupDefaultHandlers();
const args = Array.isArray(options) ? options : build_args(options);
this._process = this.createProcess(args);
this.setupEventHandlers();
}
public get process(): ChildProcess {
return this._process;
}
private setupDefaultHandlers() {
new ConnectionHandler(this);
new TryCloudflareHandler(this);
}
/**
* Add a custom output handler
* @param handler Function to handle cloudflared output
*/
public addHandler(handler: OutputHandler): void {
this.outputHandlers.push(handler);
}
/**
* Remove a previously added output handler
* @param handler The handler to remove
*/
public removeHandler(handler: OutputHandler): void {
const index = this.outputHandlers.indexOf(handler);
if (index !== -1) {
this.outputHandlers.splice(index, 1);
}
}
private processOutput(output: string): void {
// Run all handlers on the output
for (const handler of this.outputHandlers) {
try {
handler(output, this);
} catch (error) {
this.emit("error", error instanceof Error ? error : new Error(String(error)));
}
}
}
private setupEventHandlers() {
// cloudflared outputs to stderr, but I think its better to listen to stdout too
this.on("stdout", (output) => {
this.processOutput(output);
});
this.on("stderr", (output) => {
this.processOutput(output);
});
}
private createProcess(args: string[]): ChildProcess {
const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
child.on("error", (error) => this.emit("error", error));
child.on("exit", (code, signal) => this.emit("exit", code, signal));
if (process.env.VERBOSE) {
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
}
child.stdout?.on("data", (data) => this.emit("stdout", data.toString()));
child.stderr?.on("data", (data) => this.emit("stderr", data.toString()));
return child;
}
public stop = this._stop.bind(this);
private _stop(): boolean {
return this.process.kill("SIGINT");
}
public on<E extends keyof TunnelEvents>(event: E, listener: TunnelEvents[E]): this {
return super.on(event, listener);
}
public once<E extends keyof TunnelEvents>(event: E, listener: TunnelEvents[E]): this {
return super.once(event, listener);
}
public off<E extends keyof TunnelEvents>(event: E, listener: TunnelEvents[E]): this {
return super.off(event, listener);
}
public emit<E extends keyof TunnelEvents>(
event: E,
...args: Parameters<TunnelEvents[E]>
): boolean {
return super.emit(event, ...args);
}
/**
* Create a quick tunnel without a Cloudflare account.
* @param url The local service URL to connect to. If not provided, the hello world mode will be used.
* @param options The options to pass to cloudflared.
*/
public static quick(url?: string, options: TunnelOptions = {}): Tunnel {
const args = ["tunnel"];
if (url) {
args.push("--url", url);
} else {
args.push("--hello-world");
}
args.push(...build_options(options));
return new Tunnel(args);
}
/**
* Create a tunnel with a Cloudflare account.
* @param token The Cloudflare Tunnel token.
* @param options The options to pass to cloudflared.
*/
public static withToken(token: string, options: TunnelOptions = {}): Tunnel {
options["--token"] = token;
return new Tunnel(build_args(options));
}
}
/**
* Create a tunnel.
* @param options The options to pass to cloudflared.
* @returns A Tunnel instance
*/
export function tunnel(options: TunnelOptions = {}): Tunnel {
return new Tunnel(options);
}
/**
* Build the arguments for the cloudflared command.
* @param options The options to pass to cloudflared.
* @returns The arguments for the cloudflared command.
*/
export function build_args(options: TunnelOptions): string[] {
const args: string[] = "--hello-world" in options ? ["tunnel"] : ["tunnel", "run"];
args.push(...build_options(options));
return args;
}
export function build_options(options: TunnelOptions): string[] {
const opts: string[] = [];
for (const [key, value] of Object.entries(options)) {
if (typeof value === "string") {
opts.push(`${key}`, value);
} else if (typeof value === "number") {
opts.push(`${key}`, value.toString());
} else if (typeof value === "boolean") {
if (value === true) {
opts.push(`${key}`);
}
}
}
return opts;
}