Skip to content

Commit

Permalink
Merge branch 'ws'
Browse files Browse the repository at this point in the history
  • Loading branch information
nksaraf committed Sep 24, 2023
2 parents 5bf5e03 + 94f59aa commit b7ba820
Show file tree
Hide file tree
Showing 30 changed files with 3,354 additions and 2,312 deletions.
6 changes: 6 additions & 0 deletions .changeset/eighty-dryers-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@vinxi/plugin-references": patch
"vinxi": patch
---

refactor internals to have user customizable modes
6 changes: 6 additions & 0 deletions .changeset/wicked-wasps-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@vinxi/plugin-references": patch
"vinxi": patch
---

fixes
6 changes: 2 additions & 4 deletions examples/react/spa/basic/app.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,8 @@ export default createApp({
name: "client",
mode: "spa",
handler: "./index.ts",
compile: {
target: "browser",
plugins: () => [reactRefresh()],
},
target: "browser",
plugins: () => [reactRefresh()],
},
],
});
7 changes: 7 additions & 0 deletions examples/vanilla/spa/app.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ export default createApp({
target: "browser",
plugins: () => [references.clientRouterPlugin()],
},
{
name: "ws",
base: "/party",
mode: "handler",
handler: "./app/websocket.ts",
target: "server",
},
references.serverRouter({
middleware: "./app/middleware.tsx",
}),
Expand Down
11 changes: 10 additions & 1 deletion examples/vanilla/spa/app/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,13 @@ import { sayHello } from "./actions";
import "./style.css";

console.log(await sayHello());
alert("Hello world!");
console.log("Hello world!");

const ws = new WebSocket(`ws://${window.location.host}/party`);

await new Promise((resolve) => {
ws.addEventListener("open", resolve);
});
ws.send("Hello world!");

console.log(await fetch("/party").then((res) => res.text()));
122 changes: 122 additions & 0 deletions examples/vanilla/spa/app/websocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import {
Connection,
ConnectionContext,
Context,
Party,
Server,
Stub,
} from "vinxi/runtime/party";
import {
getHeader,
isWebSocketEvent,
isWebSocketUpgradeRequest,
toWebRequest,
toWebSocketEvent,
upgradeWebSocket,
} from "vinxi/runtime/server";
import { eventHandler, lazyEventHandler } from "vinxi/runtime/server";

class InternalParty implements Party {
connections = new Map();
getConnections(tag?: string): Iterable<Connection> {
return this.connections.values();
}
getConnection(id: string): Connection {
return this.connections.get(id);
}
id: string;
constructor(id: string) {
this.id = id;
}
onConnect(connection: Connection): void | Promise<void> {
this.connections.set(connection.id, connection);
}

onClose(connection: Connection): void | Promise<void> {
this.connections.delete(connection.id);
}

storage: Storage;
name: string;
internalID: string;
env: Record<string, unknown>;
context: Context;

broadcast(msg: string, without?: string[]) {
for (const conn of this.connections.values()) {
if (without && without.includes(conn.id)) {
continue;
}
conn.send(msg);
}
}

parties: Record<string, { get(id: string): Stub }>;
}

export class PartyServer implements Server {
constructor(readonly party: Party) {}
onConnect(connection, ctx) {}

getConnectionTags(
connection: Connection,
context: ConnectionContext,
): string[] | Promise<string[]> {
return [];
}

onRequest(req: Request): Response | Promise<Response> {
return new Response("Not found", { status: 501 });
}

onMessage(message, sender: Connection): void | Promise<void> {
const text =
typeof message === "string" ? message : new TextDecoder().decode(message);
sender.send(
JSON.stringify({
type: "message",
conns: [...this.party.getConnections()].map((conn) => conn.id),
}),
);
}
}

function webSocketHandler(websocketServer) {
return lazyEventHandler(async () => {
const party = new InternalParty("1");
const server = new websocketServer(party);
await server.onStart?.();
return eventHandler((e) => {
if (isWebSocketEvent(e)) {
const wsEvent = toWebSocketEvent(e);
console.log("websocket event", wsEvent);
if (wsEvent.type === "connection") {
const id = Math.random().toString(36).slice(2);
wsEvent.connection.id = id;
party.onConnect(wsEvent.connection);
server.onConnect?.(wsEvent.connection);
} else if (wsEvent.type === "message") {
server.onMessage?.(wsEvent.message, wsEvent.connection);
} else if (wsEvent.type === "error") {
server.onError?.(wsEvent.connection, wsEvent.error);
} else if (wsEvent.type === "close") {
party.onClose(wsEvent.connection);
server.onClose?.(wsEvent.connection);
}
}

if (isWebSocketUpgradeRequest(e)) {
console.log("upgrade request");
return upgradeWebSocket(e);
// if (getHeader(e, "upgrade") === "websocket") {
// return "upgrade";
// }
// return server.onRequest?.(toWebRequest(e));
} else {
return server.onRequest?.(toWebRequest(e));
}
});
});
}

export default webSocketHandler(PartyServer);
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
"patchedDependencies": {
"vite@4.3.9": "patches/vite@4.3.9.patch",
"@tanstack/react-start@0.0.1-beta.111": "patches/@tanstack__react-start@0.0.1-beta.111.patch"
},
"overrides": {
"h3": "npm:@vinxi/h3@1.8.6",
"listhen": "npm:@vinxi/listhen"
}
},
"dependencies": {
Expand Down
2 changes: 2 additions & 0 deletions packages/vinxi-references/server-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { eventHandler, toWebRequest } from "vinxi/runtime/server";
async function loadModule(id) {
if (import.meta.env.DEV) {
return await import(
/* @vite-ignore */
import.meta.env.MANIFEST["server"].chunks[id].output.path
);
}
Expand All @@ -12,6 +13,7 @@ async function loadModule(id) {
return globalThis.$$chunks[id + ".js"];
}
return await import(
/* @vite-ignore */
import.meta.env.MANIFEST["server"].chunks[id].output.path
);
}
Expand Down
Loading

0 comments on commit b7ba820

Please sign in to comment.