Skip to content

Commit

Permalink
chore: add h3 example
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jan 29, 2024
1 parent 2f3e983 commit 894792a
Show file tree
Hide file tree
Showing 14 changed files with 440 additions and 150 deletions.
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ignore-workspace-root-check=true
34 changes: 34 additions & 0 deletions examples/h3/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createApp, createRouter, eventHandler } from "h3";
import { defineWebSocketHooks } from "crossws";

const router = createRouter();
export const app = createApp().use(router);

router.get(
"/",
eventHandler(() =>
import("./index.html").then((r) => r.html({ name: "h3" })),
),
);

// Listhen automatically sets up ws integration!
export const websocket = defineWebSocketHooks({
open(peer) {
console.log("[ws] open", peer);
},

message(peer, message) {
console.log("[ws] message", peer, message);
if (message.text().includes("ping")) {
peer.send("pong");
}
},

close(peer, event) {
console.log("[ws] close", peer, event);
},

error(peer, error) {
console.log("[ws] error", peer, error);
},
});
59 changes: 59 additions & 0 deletions examples/h3/index.html.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
export const html = ({ name }) => /* html */ `<!doctype html>
<head>
<title>CrossWS Test Page</title>
</head>
<body>
<h1>CrossWS Test Page (${name || "?"})</h1>
<button onclick="sendPing()">Send Ping</button>
<button onclick="connect()">Reconnect</button>
<button onclick="clearLogs()">Clear</button>
<pre id="logs"></pre>
<script type="module">
const url = "ws://" + location.host + "/_ws";
const logsEl = document.querySelector("#logs");
let lastTime = performance.now();
const log = (...args) => {
const now = performance.now();
const time = Math.round((now - lastTime) * 1000) / 1000;
lastTime = now;
console.log("[ws]", ...args);
logsEl.innerText += "\\n (" + String(time).padStart(4, ' ') + "ms) " + args.join(" ");
};
let ws
globalThis.connect = async () => {
if (ws) {
log("Closing...");
ws.close();
}
log("Connecting to", url, "...");
ws = new WebSocket(url);
ws.addEventListener("message", (event) => {
log("Message from server:", event.data);
});
log("Waiting for connection...");
await new Promise((resolve) => ws.addEventListener("open", resolve));
}
globalThis.clearLogs = () => {
logsEl.innerText = ''
}
globalThis.sendPing = () => {
log("Sending ping...");
ws.send("ping");
}
await connect();
sendPing()
</script>
</body>
`;
14 changes: 14 additions & 0 deletions examples/h3/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "crossws-examples-h3",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "listhen --ws ./app.ts",
"dev": "listhen --ws -w ./app.ts"
},
"dependencies": {
"crossws": "latest",
"h3": "latest",
"listhen": "latest"
}
}
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
],
"scripts": {
"build": "unbuild",
"play:node": "jiti playground/node.ts",
"play:ws": "jiti playground/node-ws.ts",
"play:uws": "jiti playground/node-uws.ts",
"play:bun": "bun playground/bun.ts",
"play:deno": "deno run -A playground/deno.ts",
Expand All @@ -83,13 +83,18 @@
"consola": "^3.2.3",
"eslint": "^8.56.0",
"eslint-config-unjs": "^0.2.1",
"h3": "^1.10.1",
"jiti": "^1.21.0",
"listhen": "^1.6.0",
"prettier": "^3.2.4",
"typescript": "^5.3.3",
"uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.33.0",
"unbuild": "^2.0.0",
"wrangler": "^3.25.0",
"ws": "^8.16.0"
},
"resolutions": {
"crossws": "workspace:*"
},
"packageManager": "pnpm@8.15.0"
}
7 changes: 2 additions & 5 deletions playground/_common.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import type { WebSocketHooks, WebSocketAdapter } from "../src";

export const getIndexHTMLURL = () =>
new URL("public/index.html", import.meta.url);

export const importIndexHTML = () =>
import("./public/index.html" as string).then((r) => r.default);
export const getIndexHTML = (params) =>
import("../examples/h3/index.html.ts").then((r) => r.html(params));

export function createDemo<T extends WebSocketAdapter>(
adapter: T,
Expand Down
6 changes: 3 additions & 3 deletions playground/bun.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
// You can run this demo using `bun --bun ./bun.ts` or `npm run play:bun` in repo

import bunAdapter from "../src/adapters/bun";
import { createDemo, getIndexHTMLURL } from "./_common";
import { createDemo, getIndexHTML } from "./_common";

const adapter = createDemo(bunAdapter);

Bun.serve({
port: 3001,
websocket: adapter.websocket,
fetch(req, server) {
async fetch(req, server) {
if (server.upgrade(req)) {
return;
}
return new Response(Bun.file(getIndexHTMLURL()), {
return new Response(await getIndexHTML({ name: "bun" }), {
headers: { "Content-Type": "text/html" },
});
},
Expand Down
7 changes: 2 additions & 5 deletions playground/cloudflare.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
// You can run this demo using `npm run play:cf` in repo

import type { Request, ExecutionContext } from "@cloudflare/workers-types";

import cloudflareAdapter from "../src/adapters/cloudflare";

import { createDemo, importIndexHTML } from "./_common.ts";
import { createDemo, getIndexHTML } from "./_common.ts";

const { handleUpgrade } = createDemo(cloudflareAdapter);

Expand All @@ -18,7 +15,7 @@ export default {
return handleUpgrade(request, env, context);
}

return new Response(await importIndexHTML(), {
return new Response(await getIndexHTML({ name: "cloudflare" }), {
headers: { "content-type": "text/html" },
});
},
Expand Down
6 changes: 3 additions & 3 deletions playground/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import denoAdapter from "../dist/adapters/deno.mjs";
// @ts-ignore
import type * as _Deno from "../types/lib.deno.d.ts";

import { createDemo, getIndexHTMLURL } from "./_common.ts";
import { createDemo, getIndexHTML } from "./_common.ts";

const adapter = createDemo(denoAdapter);

Deno.serve({ port: 3001 }, (req) => {
Deno.serve({ port: 3001 }, async (req) => {
if (req.headers.get("upgrade") === "websocket") {
return adapter.handleUpgrade(req);
}

return new Response(Deno.readFileSync(getIndexHTMLURL()), {
return new Response(await getIndexHTML({ name: "deno" }), {
headers: { "Content-Type": "text/html" },
});
});
10 changes: 3 additions & 7 deletions playground/node-uws.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
// You can run this demo using `npm run play:node-uws` in repo

import { readFileSync } from "node:fs";

import { App } from "uWebSockets.js";

import nodeAdapter from "../src/adapters/node-uws.ts";
import { createDemo, getIndexHTMLURL } from "./_common";
import { createDemo, getIndexHTML } from "./_common";

const adapter = createDemo(nodeAdapter);

const app = App().ws("/*", adapter.websocket);

app.get("/*", (res, req) => {
app.get("/*", async (res, req) => {
res.writeStatus("200 OK");
res.writeHeader("Content-Type", "text/html");
const indexHTML = readFileSync(getIndexHTMLURL(), "utf8");
res.end(indexHTML);
res.end(await getIndexHTML({ name: "node-uws" }));
});

app.listen(3001, () => {
Expand Down
9 changes: 3 additions & 6 deletions playground/node.ts → playground/node-ws.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
// You can run this demo using `npm run play:node` in repo

import { createServer } from "node:http";
import { readFileSync } from "node:fs";

import nodeAdapter from "../src/adapters/node";
import { createDemo, getIndexHTMLURL } from "./_common";
import { createDemo, getIndexHTML } from "./_common";

const adapter = createDemo(nodeAdapter);

const server = createServer((req, res) => {
const server = createServer(async (req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
const indexHTML = readFileSync(getIndexHTMLURL(), "utf8");
res.end(indexHTML);
res.end(await getIndexHTML({ name: "node-ws" }));
});

server.on("upgrade", adapter.handleUpgrade);
Expand Down
28 changes: 0 additions & 28 deletions playground/public/index.html

This file was deleted.

Loading

0 comments on commit 894792a

Please sign in to comment.