@bunizao/edgeport 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bunizao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # edgeport
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/bunizao/edgeport/actions/workflows/ci.yml/badge.svg)](https://github.com/bunizao/edgeport/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@bunizao/edgeport?logo=npm&color=cb3837)](https://www.npmjs.com/package/@bunizao/edgeport)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+ [![Cloudflare Workers](https://img.shields.io/badge/runs%20on-Cloudflare%20Workers-f38020?logo=cloudflare&logoColor=white)](https://developers.cloudflare.com/workers/)
7
+ [![Node](https://img.shields.io/badge/node-%E2%89%A522-339933?logo=node.js&logoColor=white)](package.json)
8
+ [![Bun](https://img.shields.io/badge/bun-supported-f9f1e1?logo=bun&logoColor=black)](https://bun.sh)
9
+
10
+ [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/bunizao/edgeport)
11
+
12
+ Expose a local dev server at **your own Cloudflare hostname** over a single
13
+ outbound WebSocket. Hot reload works, and so does everything else your
14
+ browser does: streaming responses, cookies, redirects, and WebSockets such as
15
+ Vite HMR.
16
+
17
+ ```
18
+ browser ──https──▶ dev.example.com ──▶ edgeport Worker + Durable Object
19
+ ▲
20
+ │ one outbound wss:// (HTTPS_PROXY ok)
21
+ │
22
+ edgeport agent ──▶ localhost:4321 (your dev server)
23
+ ```
24
+
25
+ ## Why
26
+
27
+ Tunnel daemons such as `cloudflared` dial their own edge ports with their own
28
+ TLS, so they fail in sandboxes and cloud dev containers whose only way out is
29
+ an HTTPS proxy. edgeport only needs one ordinary `wss://` connection to a
30
+ Worker you own, so it runs anywhere that can open a web page, and the preview
31
+ URL stays the same every time.
32
+
33
+ ## Setup
34
+
35
+ 1. Deploy the Worker (once):
36
+
37
+ ```sh
38
+ git clone https://github.com/bunizao/edgeport && cd edgeport
39
+ bun install
40
+ # Optional: serve it on your own hostname: uncomment "routes" in wrangler.jsonc.
41
+ bunx wrangler deploy
42
+ openssl rand -base64 32 | bunx wrangler secret put EDGEPORT_SECRET
43
+ ```
44
+
45
+ One Worker can serve several hostnames; each gets its own Durable Object.
46
+ To keep the preview private, put a Cloudflare Access application in front
47
+ of the hostname, and add a bypass policy for the path `/_edgeport/connect`
48
+ (the agent authenticates there with the secret instead).
49
+
50
+ 2. Run the agent next to your dev server:
51
+
52
+ ```sh
53
+ export EDGEPORT_SECRET=... # the same secret
54
+ npx @bunizao/edgeport 4321 --edge https://dev.example.com
55
+ ```
56
+
57
+ Pass `--host-header localhost:4321` if your dev server only accepts its
58
+ local host name (Vite's `server.allowedHosts`, for example).
59
+
60
+ The agent reconnects on its own with backoff. While no agent is connected the
61
+ hostname shows a small page that reloads itself every few seconds.
62
+
63
+ ## What reaches your dev server
64
+
65
+ - Method, path, query, headers and body, streamed in both directions.
66
+ - `Host` is the edge hostname, or `--host-header` when given.
67
+ `X-Forwarded-Host` and `X-Forwarded-Proto` carry the public values.
68
+ - Cloudflare's request headers (`cf-connecting-ip`, `cf-ray`, ...) are kept,
69
+ so code that checks them behaves as it would behind a Cloudflare Tunnel.
70
+ - WebSocket upgrades are bridged frame by frame, with the negotiated
71
+ subprotocol.
72
+
73
+ ## Faster first loads
74
+
75
+ Dev servers such as Vite serve one module per file, and the browser finds
76
+ each level of imports only after the previous level arrives. Through any
77
+ relay that is a waterfall of round trips. edgeport helps in three ways:
78
+
79
+ - **Learned preloads.** The edge remembers which module scripts each page
80
+ pulled in, and on the next load adds `<link rel="modulepreload">` for all
81
+ of them, so the browser fetches them in parallel. Source modules are
82
+ `no-cache` in dev, so this speeds up every full reload.
83
+ - **Warm origin.** When the agent connects, the edge sends it the learned
84
+ list and the agent fetches each path once locally, so a freshly restarted
85
+ dev server has transformed everything before the first browser asks.
86
+ - **Loading hint.** A thin progress bar and a small "Loading over edgeport ·
87
+ N files" label appear if a page takes longer than half a second, and fade
88
+ out on load.
89
+
90
+ The edge sets a `__edgeport_client` cookie to group one browser's requests.
91
+ Set the Worker variable `EDGEPORT_FIRST_LOAD=off` to leave HTML untouched.
92
+
93
+ ## Limits
94
+
95
+ - Meant for development previews, not production traffic. Every request
96
+ passes through one Durable Object and one WebSocket.
97
+ - Cloudflare may compress responses on the way out, which can batch very
98
+ small streamed chunks, exactly as it does for a tunnel.
99
+ - Request bodies are capped by your Workers plan's request size limit.
100
+
101
+ ## Develop
102
+
103
+ ```sh
104
+ bun install
105
+ bun run check # type-check the Worker and the agent
106
+ bun run test # unit tests
107
+ bun run test:e2e # starts wrangler dev and a test origin, then exercises the relay
108
+ bun run build # bundle the CLI into dist/
109
+ ```
110
+
111
+ ## Protocol
112
+
113
+ Every frame on the agent socket is binary: one type byte, a 32-bit stream id,
114
+ then the payload. See [`src/protocol.ts`](src/protocol.ts).
115
+
116
+ ## License
117
+
118
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,490 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { parseArgs } from "node:util";
5
+
6
+ // src/agent.ts
7
+ import http from "node:http";
8
+ import https from "node:https";
9
+
10
+ // src/protocol.ts
11
+ var AGENT_PATH = "/_edgeport/connect";
12
+ var PING_TEXT = "edgeport:ping";
13
+ var PROTOCOL_VERSION = 1;
14
+ var Frame = {
15
+ RequestHead: 1,
16
+ RequestBody: 2,
17
+ RequestEnd: 3,
18
+ ResponseHead: 4,
19
+ ResponseBody: 5,
20
+ ResponseEnd: 6,
21
+ Abort: 7,
22
+ SocketOpen: 8,
23
+ SocketAccept: 9,
24
+ SocketText: 10,
25
+ SocketBinary: 11,
26
+ SocketClose: 12,
27
+ Warm: 13
28
+ };
29
+ var encoder = new TextEncoder;
30
+ var decoder = new TextDecoder;
31
+ function encode(type, id, payload) {
32
+ let body;
33
+ if (payload === undefined)
34
+ body = new Uint8Array(0);
35
+ else if (payload instanceof Uint8Array)
36
+ body = payload;
37
+ else if (typeof payload === "string")
38
+ body = encoder.encode(payload);
39
+ else
40
+ body = encoder.encode(JSON.stringify(payload));
41
+ const frame = new Uint8Array(5 + body.byteLength);
42
+ frame[0] = type;
43
+ new DataView(frame.buffer).setUint32(1, id >>> 0, false);
44
+ frame.set(body, 5);
45
+ return frame;
46
+ }
47
+ function decode(data) {
48
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
49
+ if (bytes.byteLength < 5)
50
+ throw new Error("edgeport: short frame");
51
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
52
+ return { type: bytes[0], id: view.getUint32(1, false), payload: bytes.subarray(5) };
53
+ }
54
+ function text(payload) {
55
+ return decoder.decode(payload);
56
+ }
57
+ function json(payload) {
58
+ return JSON.parse(decoder.decode(payload));
59
+ }
60
+ var HOP_BY_HOP = new Set([
61
+ "connection",
62
+ "keep-alive",
63
+ "proxy-authenticate",
64
+ "proxy-authorization",
65
+ "proxy-connection",
66
+ "te",
67
+ "trailer",
68
+ "transfer-encoding",
69
+ "upgrade",
70
+ "http2-settings"
71
+ ]);
72
+ function sendableCloseCode(code) {
73
+ if (code === undefined || code === 1005 || code === 1006 || code === 1015)
74
+ return 1000;
75
+ if (code === 1000 || code >= 3000 && code <= 4999 || code >= 1001 && code <= 1014 && code !== 1004)
76
+ return code;
77
+ return 1000;
78
+ }
79
+
80
+ // src/socket.ts
81
+ var isBun = typeof Bun !== "undefined";
82
+ var nodeWebSocket;
83
+ var nodeProxyDispatcher;
84
+ async function prepareSockets() {
85
+ if (isBun || nodeWebSocket)
86
+ return;
87
+ const undici = await import("undici");
88
+ nodeWebSocket = undici.WebSocket;
89
+ nodeProxyDispatcher = new undici.EnvHttpProxyAgent;
90
+ }
91
+ function proxyFor(url) {
92
+ const target = new URL(url);
93
+ const secure = target.protocol === "wss:" || target.protocol === "https:";
94
+ const proxy = secure ? process.env.HTTPS_PROXY ?? process.env.https_proxy : process.env.HTTP_PROXY ?? process.env.http_proxy;
95
+ if (!proxy)
96
+ return;
97
+ const host = target.hostname.replace(/^\[|\]$/g, "");
98
+ const noProxy = (process.env.NO_PROXY ?? process.env.no_proxy ?? "").split(",").map((entry) => entry.trim().toLowerCase()).filter(Boolean);
99
+ if (host === "localhost" || host === "127.0.0.1" || host === "::1")
100
+ return;
101
+ for (const entry of noProxy) {
102
+ if (entry === "*")
103
+ return;
104
+ const bare = entry.replace(/^\*?\./, "").replace(/:\d+$/, "");
105
+ if (host === bare || host.endsWith(`.${bare}`))
106
+ return;
107
+ }
108
+ return proxy;
109
+ }
110
+ function openSocket(url, options = {}) {
111
+ let ws;
112
+ const proxy = options.direct ? undefined : proxyFor(url);
113
+ if (isBun) {
114
+ const init = { headers: options.headers };
115
+ if (options.protocols?.length)
116
+ init.protocols = options.protocols;
117
+ if (proxy)
118
+ init.proxy = proxy;
119
+ ws = new WebSocket(url, init);
120
+ } else {
121
+ if (!nodeWebSocket)
122
+ throw new Error("call prepareSockets() before openSocket() on Node");
123
+ ws = new nodeWebSocket(url, {
124
+ headers: options.headers,
125
+ protocols: options.protocols,
126
+ dispatcher: proxy ? nodeProxyDispatcher : undefined
127
+ });
128
+ }
129
+ ws.binaryType = "arraybuffer";
130
+ const wrapper = {
131
+ get protocol() {
132
+ return ws.protocol;
133
+ },
134
+ get bufferedAmount() {
135
+ return ws.bufferedAmount;
136
+ },
137
+ send(data) {
138
+ if (ws.readyState === WebSocket.OPEN)
139
+ ws.send(data);
140
+ },
141
+ close(code, reason) {
142
+ if (ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED)
143
+ return;
144
+ try {
145
+ ws.close(code, reason);
146
+ } catch {
147
+ ws.close();
148
+ }
149
+ }
150
+ };
151
+ ws.addEventListener("open", () => wrapper.onopen?.());
152
+ ws.addEventListener("message", (event) => {
153
+ const data = event.data;
154
+ if (typeof data === "string")
155
+ wrapper.onmessage?.(data);
156
+ else if (data instanceof ArrayBuffer)
157
+ wrapper.onmessage?.(data);
158
+ else if (ArrayBuffer.isView(data))
159
+ wrapper.onmessage?.(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
160
+ });
161
+ ws.addEventListener("close", (event) => wrapper.onclose?.(event.code, event.reason));
162
+ ws.addEventListener("error", (event) => wrapper.onerror?.(event.message ?? ""));
163
+ return wrapper;
164
+ }
165
+
166
+ // src/agent.ts
167
+ var PING_INTERVAL_MS = 20000;
168
+ var HIGH_WATER = 4 * 1024 * 1024;
169
+
170
+ class Agent {
171
+ options;
172
+ socket;
173
+ stopped = false;
174
+ attempt = 0;
175
+ pingTimer;
176
+ requests = new Map;
177
+ responses = new Map;
178
+ sockets = new Map;
179
+ origin;
180
+ edge;
181
+ log;
182
+ constructor(options) {
183
+ this.options = options;
184
+ this.origin = new URL(options.origin);
185
+ this.edge = new URL(options.edge);
186
+ this.log = options.log ?? ((line) => console.log(line));
187
+ }
188
+ start() {
189
+ this.stopped = false;
190
+ this.connect();
191
+ }
192
+ stop() {
193
+ this.stopped = true;
194
+ clearInterval(this.pingTimer);
195
+ this.socket?.close(1000, "agent stopping");
196
+ this.resetStreams();
197
+ }
198
+ connect() {
199
+ const url = new URL(AGENT_PATH, this.edge);
200
+ url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
201
+ let socket;
202
+ try {
203
+ socket = openSocket(url.toString(), {
204
+ headers: { authorization: `Bearer ${this.options.secret}`, "x-edgeport-version": String(PROTOCOL_VERSION) }
205
+ });
206
+ } catch (error) {
207
+ this.log(`edgeport: ${error instanceof Error ? error.message : error}`);
208
+ this.reconnect();
209
+ return;
210
+ }
211
+ this.socket = socket;
212
+ socket.onopen = () => {
213
+ this.attempt = 0;
214
+ this.log(`edgeport: ${this.edge.origin} -> ${this.origin.origin}`);
215
+ clearInterval(this.pingTimer);
216
+ this.pingTimer = setInterval(() => socket.send(PING_TEXT), PING_INTERVAL_MS);
217
+ };
218
+ socket.onmessage = (data) => {
219
+ if (typeof data === "string")
220
+ return;
221
+ try {
222
+ this.onFrame(data);
223
+ } catch (error) {
224
+ this.log(`edgeport: bad frame: ${error instanceof Error ? error.message : error}`);
225
+ }
226
+ };
227
+ socket.onclose = (code, reason) => {
228
+ if (this.socket !== socket)
229
+ return;
230
+ clearInterval(this.pingTimer);
231
+ this.resetStreams();
232
+ if (this.stopped)
233
+ return;
234
+ this.log(`edgeport: disconnected (${code}${reason ? ` ${reason}` : ""})`);
235
+ if (code === 1008 || reason === "unauthorized") {
236
+ this.log("edgeport: the edge rejected the secret");
237
+ }
238
+ this.reconnect();
239
+ };
240
+ socket.onerror = (message) => {
241
+ if (message)
242
+ this.log(`edgeport: ${message}`);
243
+ };
244
+ }
245
+ reconnect() {
246
+ if (this.stopped)
247
+ return;
248
+ const delay = Math.min(1e4, 500 * 2 ** this.attempt++);
249
+ setTimeout(() => this.connect(), delay);
250
+ }
251
+ resetStreams() {
252
+ for (const request of this.requests.values())
253
+ request.destroy();
254
+ for (const response of this.responses.values())
255
+ response.destroy();
256
+ for (const socket of this.sockets.values())
257
+ socket.close(1001, "edgeport agent reconnecting");
258
+ this.requests.clear();
259
+ this.responses.clear();
260
+ this.sockets.clear();
261
+ }
262
+ send(frame) {
263
+ this.socket?.send(frame);
264
+ }
265
+ onFrame(data) {
266
+ const { type, id, payload } = decode(data);
267
+ switch (type) {
268
+ case Frame.RequestHead:
269
+ this.startRequest(id, json(payload));
270
+ return;
271
+ case Frame.RequestBody:
272
+ this.requests.get(id)?.write(Buffer.from(payload));
273
+ return;
274
+ case Frame.RequestEnd:
275
+ this.requests.get(id)?.end();
276
+ return;
277
+ case Frame.Abort:
278
+ this.requests.get(id)?.destroy();
279
+ this.responses.get(id)?.destroy();
280
+ this.requests.delete(id);
281
+ this.responses.delete(id);
282
+ return;
283
+ case Frame.Warm:
284
+ this.warm(json(payload));
285
+ return;
286
+ case Frame.SocketOpen:
287
+ this.openOriginSocket(id, json(payload));
288
+ return;
289
+ case Frame.SocketText:
290
+ this.sockets.get(id)?.send(text(payload));
291
+ return;
292
+ case Frame.SocketBinary:
293
+ this.sockets.get(id)?.send(payload.slice());
294
+ return;
295
+ case Frame.SocketClose: {
296
+ const { code, reason } = json(payload);
297
+ const socket = this.sockets.get(id);
298
+ this.sockets.delete(id);
299
+ socket?.close(sendableCloseCode(code), reason ?? "");
300
+ return;
301
+ }
302
+ }
303
+ }
304
+ originHeaders(headers) {
305
+ const out = {};
306
+ for (const [name, value] of headers) {
307
+ const lower = name.toLowerCase();
308
+ if (HOP_BY_HOP.has(lower) || lower === "host")
309
+ continue;
310
+ const existing = out[lower];
311
+ if (existing === undefined)
312
+ out[lower] = value;
313
+ else
314
+ out[lower] = Array.isArray(existing) ? [...existing, value] : [existing, value];
315
+ }
316
+ out.host = this.options.hostHeader ?? this.edge.host;
317
+ out["x-forwarded-host"] ??= this.edge.host;
318
+ out["x-forwarded-proto"] ??= this.edge.protocol.replace(":", "");
319
+ return out;
320
+ }
321
+ startRequest(id, head) {
322
+ const transport = this.origin.protocol === "https:" ? https : http;
323
+ const request = transport.request({
324
+ protocol: this.origin.protocol,
325
+ hostname: this.origin.hostname,
326
+ port: this.origin.port || undefined,
327
+ method: head.method,
328
+ path: head.path,
329
+ headers: this.originHeaders(head.headers),
330
+ agent: false
331
+ });
332
+ this.requests.set(id, request);
333
+ request.on("response", (response) => {
334
+ this.responses.set(id, response);
335
+ const headers = [];
336
+ const raw = response.rawHeaders;
337
+ for (let i = 0;i < raw.length; i += 2)
338
+ headers.push([raw[i], raw[i + 1]]);
339
+ this.send(encode(Frame.ResponseHead, id, { status: response.statusCode ?? 502, statusText: response.statusMessage, headers }));
340
+ response.on("data", (chunk) => {
341
+ this.send(encode(Frame.ResponseBody, id, new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)));
342
+ if ((this.socket?.bufferedAmount ?? 0) > HIGH_WATER) {
343
+ response.pause();
344
+ const wait = setInterval(() => {
345
+ if ((this.socket?.bufferedAmount ?? 0) < HIGH_WATER / 2 || !this.responses.has(id)) {
346
+ clearInterval(wait);
347
+ response.resume();
348
+ }
349
+ }, 25);
350
+ }
351
+ });
352
+ response.on("end", () => {
353
+ if (!this.responses.delete(id))
354
+ return;
355
+ this.requests.delete(id);
356
+ this.send(encode(Frame.ResponseEnd, id));
357
+ });
358
+ response.on("error", () => this.failStream(id, "origin response failed"));
359
+ });
360
+ request.on("error", (error) => this.failStream(id, `origin unreachable: ${error.message}`));
361
+ }
362
+ async warm(paths) {
363
+ const started = Date.now();
364
+ let next = 0;
365
+ let ok = 0;
366
+ const worker = async () => {
367
+ while (next < paths.length && !this.stopped) {
368
+ const path = paths[next++];
369
+ const done = await new Promise((resolve) => {
370
+ const transport = this.origin.protocol === "https:" ? https : http;
371
+ const request = transport.request({
372
+ protocol: this.origin.protocol,
373
+ hostname: this.origin.hostname,
374
+ port: this.origin.port || undefined,
375
+ path,
376
+ headers: { host: this.options.hostHeader ?? this.edge.host, accept: "*/*" },
377
+ agent: false
378
+ }, (response) => {
379
+ response.resume();
380
+ response.on("end", () => resolve((response.statusCode ?? 500) < 400));
381
+ response.on("error", () => resolve(false));
382
+ });
383
+ request.on("error", () => resolve(false));
384
+ request.setTimeout(30000, () => request.destroy());
385
+ request.end();
386
+ });
387
+ if (done)
388
+ ok++;
389
+ }
390
+ };
391
+ await Promise.all(Array.from({ length: 6 }, worker));
392
+ if (paths.length)
393
+ this.log(`edgeport: warmed ${ok}/${paths.length} paths in ${((Date.now() - started) / 1000).toFixed(1)}s`);
394
+ }
395
+ failStream(id, message) {
396
+ const pending = this.requests.has(id) || this.responses.has(id);
397
+ this.requests.delete(id);
398
+ this.responses.delete(id);
399
+ if (pending)
400
+ this.send(encode(Frame.Abort, id, message));
401
+ }
402
+ openOriginSocket(id, open) {
403
+ const url = new URL(open.path, this.origin);
404
+ url.protocol = this.origin.protocol === "https:" ? "wss:" : "ws:";
405
+ const headers = {};
406
+ for (const [name, value] of Object.entries(this.originHeaders(open.headers))) {
407
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
408
+ }
409
+ let socket;
410
+ try {
411
+ socket = openSocket(url.toString(), { headers, protocols: open.protocols, direct: true });
412
+ } catch (error) {
413
+ this.send(encode(Frame.Abort, id, error instanceof Error ? error.message : String(error)));
414
+ return;
415
+ }
416
+ let accepted = false;
417
+ socket.onopen = () => {
418
+ accepted = true;
419
+ this.sockets.set(id, socket);
420
+ this.send(encode(Frame.SocketAccept, id, { protocol: socket.protocol || undefined }));
421
+ };
422
+ socket.onmessage = (data) => {
423
+ if (!this.sockets.has(id))
424
+ return;
425
+ this.send(typeof data === "string" ? encode(Frame.SocketText, id, data) : encode(Frame.SocketBinary, id, new Uint8Array(data)));
426
+ };
427
+ socket.onclose = (code, reason) => {
428
+ if (!accepted) {
429
+ this.send(encode(Frame.Abort, id, `origin refused the WebSocket (${code})`));
430
+ return;
431
+ }
432
+ if (!this.sockets.delete(id))
433
+ return;
434
+ this.send(encode(Frame.SocketClose, id, { code, reason }));
435
+ };
436
+ }
437
+ }
438
+
439
+ // src/cli.ts
440
+ var usage = `Usage: edgeport <origin> --edge <url> [--host-header <host>]
441
+
442
+ Expose a local dev server at your own Cloudflare hostname over one outbound
443
+ WebSocket. Works behind HTTPS proxies and in cloud dev containers.
444
+
445
+ Arguments:
446
+ <origin> Local server to expose, e.g. http://127.0.0.1:4321
447
+ (a bare port such as 4321 means http://127.0.0.1:4321)
448
+
449
+ Options:
450
+ --edge <url> Public URL of your deployed edgeport Worker
451
+ (env EDGEPORT_EDGE)
452
+ --host-header <host> Host header sent to the origin (default: the edge host)
453
+ -h, --help Show this help
454
+
455
+ Environment:
456
+ EDGEPORT_SECRET Shared secret, the same value as the Worker's
457
+ EDGEPORT_SECRET (required)
458
+ HTTPS_PROXY, NO_PROXY Used for the connection to the edge
459
+ `;
460
+ var { values, positionals } = parseArgs({
461
+ allowPositionals: true,
462
+ options: {
463
+ edge: { type: "string" },
464
+ "host-header": { type: "string" },
465
+ help: { type: "boolean", short: "h" }
466
+ }
467
+ });
468
+ if (values.help) {
469
+ process.stdout.write(usage);
470
+ process.exit(0);
471
+ }
472
+ var fail = (message) => {
473
+ process.stderr.write(`edgeport: ${message}
474
+
475
+ ${usage}`);
476
+ process.exit(2);
477
+ };
478
+ var rawOrigin = positionals[0] ?? fail("missing <origin>");
479
+ var origin = /^\d+$/.test(rawOrigin) ? `http://127.0.0.1:${rawOrigin}` : rawOrigin;
480
+ var edge = values.edge ?? process.env.EDGEPORT_EDGE ?? fail("missing --edge");
481
+ var secret = process.env.EDGEPORT_SECRET ?? fail("EDGEPORT_SECRET is not set");
482
+ await prepareSockets();
483
+ var agent = new Agent({ edge, secret, origin, hostHeader: values["host-header"] });
484
+ agent.start();
485
+ for (const signal of ["SIGINT", "SIGTERM"]) {
486
+ process.on(signal, () => {
487
+ agent.stop();
488
+ process.exit(0);
489
+ });
490
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@bunizao/edgeport",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "repository": "github:bunizao/edgeport",
5
+ "publishConfig": { "access": "public" },
6
+ "description": "Expose a local dev server at your own Cloudflare hostname over a single outbound WebSocket. Hot reload included, works behind HTTPS proxies.",
7
+ "type": "module",
8
+ "license": "MIT",
9
+ "bin": {
10
+ "edgeport": "dist/cli.js"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "src",
15
+ "wrangler.jsonc"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "scripts": {
21
+ "prepack": "bun run build",
22
+ "build": "bun build src/cli.ts --target node --outfile dist/cli.js --external undici",
23
+ "check": "tsc -p tsconfig.worker.json && tsc -p tsconfig.node.json",
24
+ "test": "bun test test/protocol.test.ts",
25
+ "test:e2e": "bun test/e2e.ts",
26
+ "dev:edge": "wrangler dev --port 8787",
27
+ "deploy": "wrangler deploy"
28
+ },
29
+ "dependencies": {
30
+ "undici": "^8.14.1"
31
+ },
32
+ "devDependencies": {
33
+ "@cloudflare/workers-types": "^5.20261127.1",
34
+ "@types/bun": "^1.3.0",
35
+ "@types/node": "^24.0.0",
36
+ "typescript": "^5.9.3",
37
+ "wrangler": "^4.50.0"
38
+ }
39
+ }