-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathtunnel.ts
More file actions
72 lines (61 loc) · 2.02 KB
/
Copy pathtunnel.ts
File metadata and controls
72 lines (61 loc) · 2.02 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
import { spawn } from 'child_process';
export interface DevTunnel {
tunnelUrl: string;
close(): void;
}
/**
* Create a tunnel using `cloudflared` mapped to `localhost:{port}`
*/
export function createDevTunnel(port: number, cloudflaredPath: string): Promise<DevTunnel> {
return new Promise((resolve, reject) => {
let tunnelUrl: string;
let connectionsCount = 0;
let resolved = false;
const cloudflared = spawn(cloudflaredPath, [
'tunnel',
'--no-autoupdate',
'--url',
`http://localhost:${port}`,
]);
const close = () => {
if (cloudflared.exitCode === null && !cloudflared.killed) {
cloudflared.kill('SIGTERM');
}
};
const resolveWhenReady = () => {
if (resolved || !tunnelUrl || connectionsCount < 1) {
return;
}
resolved = true;
resolve({
tunnelUrl,
close,
});
};
cloudflared.stderr.on('data', (data) => {
const output = data.toString();
// Store the tunnel URL provided by cloudflare
const tunnelUrlOutput = output.match(/https:\/\/.*\.trycloudflare\.com/);
if (tunnelUrlOutput) {
tunnelUrl = tunnelUrlOutput[0];
}
// Count the number of connections to the tunnel
// We need at least 1 connection to be able to use the tunnel
const tunnelConnectionOutput = output.match(/Registered tunnel/);
if (tunnelConnectionOutput) {
connectionsCount++;
}
resolveWhenReady();
});
cloudflared.on('close', (code) => {
if (!resolved && code !== 0) {
reject(new Error(`cloudflared exited with code ${code}`));
}
});
cloudflared.on('error', (error) => {
if (!resolved) {
reject(error);
}
});
});
}