forked from localtunnel/server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
96 lines (81 loc) · 2.25 KB
/
client.ts
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
import { parseArgs } from "util";
import browser from "open";
import type { Payload } from "./types";
async function main({
port,
domain,
subdomain,
open,
}: {
port?: string;
domain?: string;
subdomain?: string;
open?: boolean;
}) {
const params = new URLSearchParams({
new: "",
...(subdomain ? { subdomain } : {}),
}).toString();
const serverUrl = `ws://${domain}?${params}`;
const socket = new WebSocket(serverUrl);
const url = `http://localhost:${port}`;
socket.addEventListener("message", async (event) => {
const data = JSON.parse(event.data as string);
if (data.url) {
console.log(`\n↪ Your URL: \x1b[32m${data.url}\x1b[0m\n`);
if (open) browser(data.url);
}
const { method, headers: reqHeaders, pathname, body: reqBody } = data;
if (method) {
const now = performance.now();
const res = await fetch(`${url}${pathname || ""}`, {
method,
headers: reqHeaders,
body: reqBody,
});
const elapsed = performance.now() - now;
console.log(
`\x1b[32m${method}\x1b[0m ${pathname} in ${elapsed.toFixed(2)}ms`
);
const { status, statusText, headers } = res;
const body = await res.text();
const payload: Payload = {
method,
pathname,
status,
statusText,
headers,
body,
};
socket.send(JSON.stringify(payload));
}
});
socket.addEventListener("open", (event: any) => {
if (!event.target.readyState) throw "not ready";
});
socket.addEventListener("close", () => {
console.warn("server closed connection");
process.exit();
});
}
/**
* Eg. `bun client.ts -p 3000 -d example.so -s my-subdomain -o`
* > my-subdomain.example.so will be proxied to localhost:3000
* See README for full usage.
*/
const { values } = parseArgs({
args: process.argv,
options: {
port: { type: "string", short: "p", default: "3000" },
domain: { type: "string", short: "d", default: "localhost:1234" },
subdomain: { type: "string", short: "s" },
open: { type: "boolean", short: "o" },
version: { type: "boolean", short: "v" },
},
allowPositionals: true,
});
if (values.version) {
console.log(process.env.npm_package_version);
process.exit();
}
main(values);