@t8n/tsocket
v1.0.0
Published
The ultimate highly advanced functions-based extended WebSocket extension for TitanPL.
Readme
@t8n/tsocket — TitanPL Realtime DX Layer
The ultimate highly advanced functions-based extended WebSocket extension for TitanPL.
@t8n/tsocket doesn't just wrap Titan's native t.ws — it extends it with premium features like semantic event routing, stateful client metadata, room-based broadcasting, and middleware pipelines.
🚀 Native vs. tSocket
| Feature | Titan Native (t.ws) | @t8n/tsocket |
| :--- | :--- | :--- |
| Logic Type | Single if/else block | Multi-event routing (socket.on) |
| Events | Native only (open, message, close) | Custom Semantic Events (any name) |
| State | Stateless per request | Stateful Clients (client.get/set) |
| Broadcasting | Global only (ws.broadcast) | Room-scoped (socket.to(room).broadcast) |
| Control Flow | Manual | Middleware Pipeline (socket.use) |
🛠 Usage Example
import { createSocket } from "@t8n/tsocket";
export const chat = createSocket((socket) => {
// 1. Synchronous Middleware (Perfect for Auth)
socket.use((client, next) => {
if (!client.get("authenticated")) {
// Logic for authentication...
}
next();
});
// 2. Semantic Event Routing
socket.on("open", (client) => {
client.send("welcome", "Welcome to Titan Extended!");
});
socket.on("chat", (client, data) => {
// 3. Global & Room Broadcasting
socket.broadcast("message", {
user: client.get("username"),
text: data
});
});
socket.on("join", (client, room) => {
// 4. Integrated Room Management
client.join(room);
socket.to(room).broadcast("user_joined", client.id);
});
});💎 The "Extended" Core
1. Semantic Protocol 📦
tSocket automatically handles the heavy lifting of message parsing. It normalizes incoming JSON into semantic events, allowing you to use socket.on("custom_event") instead of checking string contents manually.
2. Stateful Client Objects 👤
Unlike standard Titan actions where state is lost between messages, tSocket provides the client.set(key, value) and client.get(key) methods. This allows you to store session-specific data (usernames, auth tokens, scores) directly on the socket instance within the worker's memory.
3. Integrated Room System 🏘️
No need to manage your own Maps for groups. tSocket's client.join("room") and client.leave("room") manage worker-local sets automatically. Target specific rooms with socket.to("room").broadcast(...).
4. Middleware Pipelines ⛓️
Implement clean, modular interceptors for your WebSocket logic. Great for:
- Authentication & RBAC
- Message Validation
- Logging & Analytics
- Data Transformation
🚀 API Surface
Socket Interface
socket.on(event, handler): Register logic for a specific semantic event.socket.broadcast(event, data): Send a formatted event to all clients in the worker.socket.emit(event, data): Alias for global broadcast.socket.to(room).broadcast(event, data): Precision broadcasting to a subset of clients.socket.use(middleware): Inject logic into the action execution pipeline.
Client Interface
client.id: The unique native socket ID.client.send(event, data): Send a targeted message to this specific client.client.join(room)/client.leave(room): Advanced membership management.client.rooms: Access list of current room memberships.client.set(key, value)/client.get(key): Worker-local session persistence.
🎯 Protocol Standard
tSocket mandates a clean, JSON-first communication protocol:
Incoming:{"event": "chat", "data": "hello world"}
Outgoing:{"event": "chat", "data": "hello world"}
Fallback logic is provided for raw strings (defaulting to the "message" event) for maximum compatibility.
🚀 Full Demo Application
You can build a complete, production-ready real-time system in minutes. Below is the full source for a room-based chat application.
1. Server Action (app/actions/chat.js)
import { createSocket } from "@t8n/tsocket";
export const chat = createSocket((socket) => {
// Handshake and Identification
socket.on("open", (client) => {
client.send("welcome", {
msg: "Welcome to the Titan Starship!",
id: client.id
});
});
// Room Management
socket.on("join", (client, room) => {
const r = room.toLowerCase();
client.join(r);
// Notify others in the room
socket.to(r).broadcast("user_joined", {
user: client.id,
room: r
});
client.send("room_joined", { room: r });
});
// Cross-Thread Room Broadcasting
socket.on("room_chat", (client, data) => {
let { room, message } = data;
room = room.toLowerCase();
// Broadcast to everyone (Client filters by room)
socket.broadcast("room_message", {
user: client.id,
room: room,
text: message
});
});
// Generic String Support
socket.on("message", (client, data) => {
socket.broadcast("room_message", {
user: client.id,
room: "general",
text: `[Raw] ${data}`
});
});
});2. Frontend Client (static/index.html)
<!DOCTYPE html>
<html>
<head>
<title>tSocket Unified Test 🚀</title>
</head>
<body style="background: #111; color: #fff; font-family: sans-serif; padding: 2rem;">
<h1>🛰️ tSocket Unified Test</h1>
<div id="status" style="color: #666;">Connecting...</div>
<div style="margin-bottom: 1rem;">
<input id="server" style="background: #222; color: #fff; border: 1px solid #444; padding: 0.5rem;" value="localhost:5100">
<button onclick="connect()">Connect</button>
<button onclick="join()">Join 'huii'</button>
</div>
<div id="messages" style="margin-top: 1rem; border: 1px solid #333; padding: 1rem; height: 300px; overflow-y: auto; background: #000; font-family: monospace;"></div>
<div style="margin-top: 1rem;">
<input id="input" style="background: #222; color: #fff; border: 1px solid #444; padding: 0.5rem; width: 300px;" placeholder="Message...">
<button onclick="send()">Send</button>
</div>
<script>
let ws;
let myId, currentRoom;
const m = document.getElementById('messages');
const s = document.getElementById('status');
function log(msg) {
const d = document.createElement('div');
d.innerText = `[${new Date().toLocaleTimeString()}] ${msg}`;
m.appendChild(d);
m.scrollTop = m.scrollHeight;
}
function connect() {
const host = document.getElementById('server').value;
ws = new WebSocket(`ws://${host}/chat`);
ws.onopen = () => { s.innerText = 'Connected'; log('SYSTEM: Link Established.'); };
ws.onmessage = (e) => {
const d = JSON.parse(e.data);
const { event, data } = d;
if (event === 'welcome') myId = data.id;
if (event === 'room_joined') { currentRoom = data.room; log(`SYSTEM: Joined ${data.room}`); }
if (event === 'room_message') {
// Critical: Filter for current room across threads
if (data.room !== currentRoom) return;
log(`${data.user === myId ? '[YOU]' : '['+data.user+']'}: ${data.text}`);
}
};
}
function join() { ws.send(JSON.stringify({ event: "join", data: "huii" })); }
function send() {
const i = document.getElementById('input');
ws.send(JSON.stringify({ event: "room_chat", data: { room: currentRoom, message: i.value } }));
i.value = '';
}
</script>
</body>
</html>📦 Installation
npm install @t8n/tsocketDesigned to be the developer's choice for building real-time TitanPL extensions with elegance and precision.
