| 1 | export class Client { |
| 2 | constructor(state) { |
| 3 | this.state = state; |
| 4 | } |
| 5 | |
| 6 | async fetch(request) { |
| 7 | const url = new URL(request.url); |
| 8 | if (url.pathname === "/connect") { |
| 9 | const input = request.method === "POST" ? await request.json() : {}; |
| 10 | const target = input.url ?? url.searchParams.get("url"); |
| 11 | if (!target) return new Response("url required", { status: 400 }); |
| 12 | const protocol = input.protocol ?? url.searchParams.get("protocol"); |
| 13 | const socket = new WebSocket(target, protocol ? [protocol] : []); |
| 14 | const message = input.message ?? url.searchParams.get("message"); |
| 15 | socket.addEventListener("open", () => { |
| 16 | if (Array.isArray(input.binary)) socket.send(new Uint8Array(input.binary)); |
| 17 | else if (message) socket.send(message); |
| 18 | }); |
| 19 | socket.addEventListener("message", async (event) => { |
| 20 | const binary = event.data instanceof ArrayBuffer; |
| 21 | await this.state.storage.put( |
| 22 | "message", |
| 23 | binary ? Array.from(new Uint8Array(event.data)) : event.data, |
| 24 | ); |
| 25 | await this.state.storage.put("binary", binary); |
| 26 | socket.close(1000, "done"); |
| 27 | }); |
| 28 | socket.addEventListener("error", async () => { |
| 29 | await this.state.storage.put("error", true); |
| 30 | }); |
| 31 | return new Response(JSON.stringify({ connecting: true }), { status: 202 }); |
| 32 | } |
| 33 | return new Response(JSON.stringify({ |
| 34 | message: await this.state.storage.get("message"), |
| 35 | binary: await this.state.storage.get("binary") ?? false, |
| 36 | error: await this.state.storage.get("error") ?? false, |
| 37 | })); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export default { |
| 42 | async fetch(request, env) { |
| 43 | return env.CLIENT.get(env.CLIENT.idFromName("client")).fetch(request); |
| 44 | }, |
| 45 | }; |