Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: experimental websocket support #158

Merged
merged 5 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Elegant HTTP listener!

## Features

βœ… Dev server with HMR, static, and typescript support with <a href="https://github.com/unjs/jiti">unjs/jiti</a><br>
βœ… Dev server with HMR, static, WebSockets and typescript support with <a href="https://github.com/unjs/jiti">unjs/jiti</a><br>

βœ… Works with Node.js, express, and <a href="https://github.com/unjs/h3">unjs/h3</a> out of the box <br>

Expand All @@ -24,6 +24,8 @@ Elegant HTTP listener!

βœ… Gracefully shutdown Server with <a href="https://github.com/thedillonb/http-shutdown">http-shutdown</a><br>

βœ… Zero Config WebSockets with <a href="https://github.com/unjs/crossws">unjs/crossws</a>

βœ… Copy the URL to the clipboard<br>

βœ… HTTPS support with self-signed certificates<br>
Expand Down Expand Up @@ -57,7 +59,10 @@ import { createApp, eventHandler } from "h3";

export const app = createApp();

app.use("/", eventHandler(() => "Hello world!"));
app.use(
"/",
eventHandler(() => "Hello world!"),
);
```

or use npx to invoke `listhen` command:
Expand Down Expand Up @@ -193,6 +198,16 @@ Print QR Code for public address.

When enabled, listhen tries to listen to all network interfaces. You can also enable this option using `--host` CLI flag.

### `ws`

- Default: `false`

Enable experimental WebSocket support.

Option can be a function for Node.js `upgrade` handler (`(req, head) => void`) or an Object to use [CrossWS Hooks](https://github.com/unjs/crossws).

When using dev server CLI, you can easily use `--ws` and a named export called `webSocket` to define [CrossWS Hooks](https://github.com/unjs/crossws) with HMR support!

## License

MIT. Made with πŸ’–
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"lint": "eslint --ext .ts . && prettier -c src test",
"lint:fix": "eslint --fix --ext .ts . && prettier -w src test",
"listhen": "node ./scripts/listhen.mjs",
"play": "node ./scripts/listhen.mjs -w ./playground",
"play": "node ./scripts/listhen.mjs -w ./playground --ws",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
"test": "pnpm lint && vitest run --coverage"
},
Expand All @@ -44,6 +44,7 @@
"citty": "^0.1.5",
"clipboardy": "^4.0.0",
"consola": "^3.2.3",
"crossws": "^0.1.0",
"defu": "^6.1.4",
"get-port-please": "^3.1.2",
"h3": "^1.10.1",
Expand Down Expand Up @@ -71,4 +72,4 @@
"vitest": "^1.2.2"
},
"packageManager": "pnpm@8.15.0"
}
}
54 changes: 54 additions & 0 deletions playground/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,62 @@
import { createApp, eventHandler } from "h3";
import { defineWebSocketHooks } from "crossws";

Check warning on line 2 in playground/index.ts

View check run for this annotation

Codecov / codecov/patch

playground/index.ts#L2

Added line #L2 was not covered by tests

export const app = createApp();

app.use(
"/ws",
eventHandler(() => {
return getWebSocketTestPage();
}),
);

Check warning on line 12 in playground/index.ts

View check run for this annotation

Codecov / codecov/patch

playground/index.ts#L6-L12

Added lines #L6 - L12 were not covered by tests
app.use(
"/",
eventHandler(() => ({ hello: "world!" })),
);

function getWebSocketTestPage() {
return `
<!doctype html>
<head>
<title>WebSocket Test Page</title>
</head>
<body>
<div id="logs"></div>
<script type="module">
const url = \`ws://\${location.host}/_ws\`;
const logsEl = document.querySelector("#logs");
const log = (...args) => {
console.log("[ws]", ...args);
logsEl.innerHTML += \`<p>[\${new Date().toJSON()}] \${args.join(" ")}</p>\`;
};

log(\`Connecting to "\${url}""...\`);
const 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));

log("Sending ping...");
ws.send("ping");
</script>
</body>
`;
}

export const webSocket = defineWebSocketHooks({
open(peer) {
console.log("[ws] open", peer);
peer.send("Hello!");
},
message(peer, message) {
console.log("[ws] message", peer);
if (message.text() === "ping") {
peer.send("pong");
}
},
});

Check warning on line 62 in playground/index.ts

View check run for this annotation

Codecov / codecov/patch

playground/index.ts#L17-L62

Added lines #L17 - L62 were not covered by tests
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
await listen(devServer.nodeListener, {
...opts,
_entry: devServer._entry,
ws: opts.ws ? devServer._ws : undefined,

Check warning on line 60 in src/cli.ts

View check run for this annotation

Codecov / codecov/patch

src/cli.ts#L60

Added line #L60 was not covered by tests
});
await devServer.reload(true);
}
Expand Down Expand Up @@ -85,6 +86,10 @@
type: "boolean",
description: "Open the URL in the browser",
},
ws: {
type: "boolean",
description: "Enable Experimental WebSocket support",
},

Check warning on line 92 in src/cli.ts

View check run for this annotation

Codecov / codecov/patch

src/cli.ts#L89-L92

Added lines #L89 - L92 were not covered by tests
https: {
type: "boolean",
description: "Enable HTTPS",
Expand Down
17 changes: 17 additions & 0 deletions src/listen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,23 @@
listhenOptions.port = _addr.port;
}

// --- WebSocket ---
if (listhenOptions.ws) {
if (typeof listhenOptions.ws === "function") {
server.on("upgrade", listhenOptions.ws);
} else {
consola.warn(
"[listhen] Using experimental websocket API. Learn more: `https://crossws.unjs.io`",
);
const nodeWSAdapter = await import("crossws/adapters/node").then(
(r) => r.default || r,
);
// @ts-expect-error TODO
const { handleUpgrade } = nodeWSAdapter(listhenOptions.ws);
server.on("upgrade", handleUpgrade);
}

Check warning on line 146 in src/listen.ts

View check run for this annotation

Codecov / codecov/patch

src/listen.ts#L134-L146

Added lines #L134 - L146 were not covered by tests
}

// --- GetURL Utility ---
const getURL = (host = listhenOptions.hostname, baseURL?: string) =>
generateURL(host, listhenOptions, baseURL);
Expand Down
49 changes: 46 additions & 3 deletions src/server/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
import { dirname, join, resolve } from "pathe";
import type { ConsolaInstance } from "consola";
import { resolve as _resolve } from "mlly";
import type { WebSocketHooks } from "crossws";
import { createResolver } from "./_resolver";

export interface DevServerOptions {
cwd?: string;
staticDirs?: string[];
logger?: ConsolaInstance;
ws?: boolean | Partial<WebSocketHooks>;
}

export async function createDevServer(
Expand Down Expand Up @@ -54,6 +56,28 @@
// Create app instance
const app = createApp();

// WebSocket
let _ws: Partial<WebSocketHooks> | undefined;
const webSocketHooks = Object.create(null);
if (options.ws) {
const createDynamicHook =
(name: string) =>
async (...args: any[]) => {
if (typeof options.ws === "object") {
await (options.ws as any)[name]?.(...args);
}
return (webSocketHooks as any)[name]?.(...args);
};
_ws = new Proxy(
{},
{
get(_, prop) {
return createDynamicHook(prop as string);
},
},
);
}

Check warning on line 80 in src/server/dev.ts

View check run for this annotation

Codecov / codecov/patch

src/server/dev.ts#L59-L80

Added lines #L59 - L80 were not covered by tests
// Register static asset handlers
const staticDirs = (options.staticDirs || ["public"])
.filter(Boolean)
Expand Down Expand Up @@ -122,9 +146,27 @@
`πŸš€ Loading server entry ${resolver.formateRelative(_entry)}`,
);
}
let _handler = await resolver
.import(_entry)
.then((r) => r.handler || r.handle || r.app || r.default || r);

const _loadedEntry = await resolver.import(_entry);

let _handler =
_loadedEntry.handler ||
_loadedEntry.handle ||
_loadedEntry.app ||
_loadedEntry.default ||
_loadedEntry;

if (options.ws) {
Object.assign(
webSocketHooks,
_loadedEntry.webSocket ||
_loadedEntry.websocket ||
_handler.webSocket ||
_handler.websocket ||
{},
);
}

Check warning on line 169 in src/server/dev.ts

View check run for this annotation

Codecov / codecov/patch

src/server/dev.ts#L149-L169

Added lines #L149 - L169 were not covered by tests
if (_handler.handler) {
_handler = _handler.handler; // h3 app
}
Expand Down Expand Up @@ -153,6 +195,7 @@
resolver,
nodeListener: toNodeListener(app),
reload: (_initial?: boolean) => loadHandle(_initial),
_ws,

Check warning on line 198 in src/server/dev.ts

View check run for this annotation

Codecov / codecov/patch

src/server/dev.ts#L198

Added line #L198 was not covered by tests
_entry: resolveEntry(),
};
}
Expand Down
3 changes: 2 additions & 1 deletion src/server/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@

// Create dev server
const devServer = await createDevServer(entry, {
cwd: options.cwd,
...options,

Check warning on line 25 in src/server/watcher.ts

View check run for this annotation

Codecov / codecov/patch

src/server/watcher.ts#L25

Added line #L25 was not covered by tests
logger,
});

// Initialize listener
const listenter = await listen(devServer.nodeListener, {
...options,
_entry: devServer._entry,
ws: options.ws ? devServer._ws : undefined,

Check warning on line 33 in src/server/watcher.ts

View check run for this annotation

Codecov / codecov/patch

src/server/watcher.ts#L33

Added line #L33 was not covered by tests
});

// Load dev server handler first time
Expand Down
15 changes: 14 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { Server } from "node:http";
import type { IncomingMessage, Server } from "node:http";
import type { Server as HTTPServer } from "node:https";
import { AddressInfo } from "node:net";
import type { GetPortInput } from "get-port-please";
import type { WebSocketHooks } from "crossws";

export interface Certificate {
key: string;
Expand Down Expand Up @@ -52,6 +53,18 @@ export interface ListenOptions {
* Open a tunnel using https://github.com/unjs/untun
*/
tunnel?: boolean;
/**
* WebSocket Upgrade Handler
*
* Input can be an upgrade handler or CrossWS options
*
* @experimental CrossWS usage is subject to change
* @see https://github.com/unjs/crossws
*/
ws?:
| boolean
| Partial<WebSocketHooks>
| ((req: IncomingMessage, head: Buffer) => void);
}

export type GetURLOptions = Pick<
Expand Down