Skip to content

Teleportation & Cross-Platform Communication

The Quantum Portal Analogy

Imagine you have a portal in your living room that connects to your office. You toss a document through the portal, and it instantly appears on your desk. No courier, no mail, no delay.

Teleportation in Nexus works the same way - events "travel" between:

  • Client ↔ Server (WebSocket, REST)
  • Tab A ↔ Tab B (BroadcastChannel)
  • Window ↔ iframe (postMessage)
  • Browser ↔ Node.js (WebSocket)

The Problem: Client/Server Split

Modern apps are distributed:

[Browser] --HTTP--> [Server] --WS--> [Database]

Traditional event buses only work within one context:

  • Client events stay in browser
  • Server events stay in Node.js
  • No built-in bridging

Manual bridging is painful:

typescript
// Client
socket.emit('message', { text: 'Hello' });

// Server
socket.on('message', (data) => {
  // Manually route to event bus
  serverBus.emit('chat:message', data);
});

// And back...
serverBus.on('chat:broadcast', (data) => {
  socket.emit('broadcast', data);
});

The Solution: Automatic Teleportation

Nexus provides two-way bridging:

1. Client → Server (Teleport)

typescript
// CLIENT
const bus = new Nexus({
  teleport: (event, payload) => {
    websocket.send(JSON.stringify({ event, payload }));
  }
});

// Any emit automatically goes to server!
bus.emit('chat:message', { text: 'Hello' });
// → Sent to local listeners AND WebSocket

2. Server → Client (Feed)

typescript
// CLIENT
websocket.onmessage = (msg) => {
  const { event, payload } = JSON.parse(msg.data);
  bus.feed(event, payload); // Inject into event bus
};

Key insight: feed() marks events as fromRemote: true to prevent echo loops.

How Teleportation Works

Basic Example: Real-Time Chat

Client Setup

typescript
import { Nexus } from '@caeligo/nexus-orchestrator';

const ws = new WebSocket('ws://localhost:3000');

const bus = new Nexus({
  teleport: (event, payload) => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ event, payload }));
    }
  }
});

// Ingest server messages
ws.onmessage = (msg) => {
  const { event, payload } = JSON.parse(msg.data);
  bus.feed(event, payload);
};

// Send message
document.getElementById('send')?.addEventListener('click', () => {
  const text = document.getElementById('input').value;
  bus.emit('chat:message', { text, author: currentUser });
});

// Receive messages
bus.on('chat:message', (msg) => {
  addMessageToUI(msg.author, msg.text);
});

Server Setup (Node.js + ws)

typescript
import { WebSocketServer } from 'ws';
import { Nexus } from '@caeligo/nexus-orchestrator';

const wss = new WebSocketServer({ port: 3000 });
const serverBus = new Nexus();

wss.on('connection', (socket) => {
  console.log('Client connected');
  
  // Ingest client messages
  socket.on('message', (data) => {
    const { event, payload } = JSON.parse(data.toString());
    serverBus.feed(event, payload);
  });
  
  // Send server events to this client
  const teleport = (event: string, payload: any) => {
    socket.send(JSON.stringify({ event, payload }));
  };
  
  // Broadcast handler
  serverBus.on('chat:message', (msg) => {
    // Broadcast to all clients
    wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({ 
          event: 'chat:message', 
          payload: msg 
        }));
      }
    });
  });
});

Real-World Example: Collaborative Dashboard

Client (React Component)

typescript
import { Nexus } from '@caeligo/nexus-orchestrator';
import { useEffect, useState } from 'react';

const ws = new WebSocket('ws://localhost:3000');

const bus = new Nexus({
  teleport: (event, payload) => {
    ws.send(JSON.stringify({ event, payload }));
  }
});

ws.onmessage = (msg) => {
  const { event, payload } = JSON.parse(msg.data);
  bus.feed(event, payload);
};

function Dashboard() {
  const [metrics, setMetrics] = useState({ cpu: 0, memory: 0 });
  
  useEffect(() => {
    // Request initial data
    bus.emit('metrics:request', { timestamp: Date.now() });
    
    // Listen for updates
    const sub = bus.on('metrics:update', (data) => {
      setMetrics(data);
    });
    
    return () => sub.unsubscribe();
  }, []);
  
  return (
    <div>
      <h1>CPU: {metrics.cpu}%</h1>
      <h1>Memory: {metrics.memory} MB</h1>
    </div>
  );
}

Server (Node.js)

typescript
import { Nexus } from '@caeligo/nexus-orchestrator';
import os from 'os';

const serverBus = new Nexus();

// Monitor system metrics
setInterval(() => {
  const cpus = os.cpus();
  const cpuUsage = cpus.reduce((acc, cpu) => {
    const total = Object.values(cpu.times).reduce((a, b) => a + b);
    const idle = cpu.times.idle;
    return acc + (100 - (idle / total * 100));
  }, 0) / cpus.length;
  
  const totalMem = os.totalmem();
  const freeMem = os.freemem();
  const usedMem = totalMem - freeMem;
  
  // Emit to all connected clients
  serverBus.emit('metrics:update', {
    cpu: cpuUsage.toFixed(1),
    memory: (usedMem / 1024 / 1024).toFixed(0)
  });
}, 1000);

// Handle client requests
serverBus.on('metrics:request', () => {
  // Send immediate snapshot
  serverBus.emit('metrics:update', getCurrentMetrics());
});

Cross-Tab Synchronization (BroadcastChannel)

Share events across browser tabs:

typescript
const bus = new Nexus({
  crossTabName: 'my-app-v1' // Unique channel name
});

// In Tab A
bus.emit('cart:add', { productId: 123 });

// Tab B automatically receives it
bus.on('cart:add', (product) => {
  updateCartBadge();
});

Behind the scenes:

typescript
if (this.config.crossTabName && !options.fromRemote) {
  this.channel.postMessage({ event, payload });
}

Edge Case: Preventing Echo Loops

What if server echoes events back to sender?

typescript
// CLIENT
bus.emit('chat:message', { text: 'Hello' });
// → Goes to server via teleport

// SERVER receives it, processes, and broadcasts
serverBus.feed('chat:message', data);
serverBus.emit('chat:message', data);
// → Broadcasts to ALL clients (including sender)

// CLIENT receives own message via WebSocket
ws.onmessage = (msg) => {
  bus.feed('chat:message', msg.data);
  // → Marked as fromRemote: true
  // → Won't teleport again (loop prevented!)
};

Safety mechanism:

typescript
emit(event, payload, options) {
  if (this.config.teleport && !options.fromRemote) {
    this.config.teleport(event, payload);
  }
  // ^ Only teleport if NOT from remote source
}

Edge Case: Selective Teleportation

Don't send everything to server:

typescript
const bus = new Nexus({
  teleport: (event, payload) => {
    // Only sync specific events
    if (event.startsWith('sync:')) {
      ws.send(JSON.stringify({ event, payload }));
    }
  }
});

bus.emit('sync:cart', { items: [...] });     // → Goes to server
bus.emit('ui:animation', { ... });           // → Stays local
bus.emit('analytics:track', { ... });        // → Stays local

Pattern: Request/Reply Across Network

RPC pattern works with teleportation:

typescript
// CLIENT
const user = await bus.request('user:fetch', { id: 123 });

// SERVER
bus.on('user:fetch', async (payload) => {
  const user = await database.getUser(payload.id);
  bus.reply(payload, user);
  // → Reply is teleported back to client
});

Full-stack RPC!

Pattern: Optimistic Updates

Update UI immediately, sync to server in background:

typescript
// CLIENT
function addToCart(product) {
  // Optimistic update (instant UI)
  updateCartUI(product);
  
  // Sync to server (eventual consistency)
  bus.emit('cart:add', product);
  
  // Handle server rejection
  bus.on('cart:add-failed', () => {
    revertCartUI(product);
    showError('Product unavailable');
  });
}

Pattern: Offline Queue

Queue events when disconnected:

typescript
let offlineQueue: Array<{event: string, payload: any}> = [];
let isOnline = true;

const bus = new Nexus({
  teleport: (event, payload) => {
    if (isOnline) {
      ws.send(JSON.stringify({ event, payload }));
    } else {
      offlineQueue.push({ event, payload });
    }
  }
});

ws.onclose = () => {
  isOnline = false;
  showOfflineBanner();
};

ws.onopen = () => {
  isOnline = true;
  
  // Flush queue
  while (offlineQueue.length > 0) {
    const { event, payload } = offlineQueue.shift()!;
    ws.send(JSON.stringify({ event, payload }));
  }
  
  hideOfflineBanner();
};

Testing Teleportation

typescript
import { describe, it, expect, vi } from 'vitest';
import { Nexus } from '@caeligo/nexus-orchestrator';

describe('Teleportation', () => {
  it('should call teleport callback', () => {
    const teleportSpy = vi.fn();
    const bus = new Nexus({ teleport: teleportSpy });
    
    bus.emit('test:event', { data: 123 });
    
    expect(teleportSpy).toHaveBeenCalledWith('test:event', { data: 123 });
  });
  
  it('should not teleport remote events', () => {
    const teleportSpy = vi.fn();
    const bus = new Nexus({ teleport: teleportSpy });
    
    bus.feed('test:event', { data: 456 });
    
    expect(teleportSpy).not.toHaveBeenCalled();
  });
});

Next Steps

Quick Reference

Teleport (send):

typescript
const bus = new Nexus({
  teleport: (event, payload) => {
    websocket.send(JSON.stringify({ event, payload }));
  }
});

Feed (receive):

typescript
websocket.onmessage = (msg) => {
  const { event, payload } = JSON.parse(msg.data);
  bus.feed(event, payload);
};

Cross-tab sync:

typescript
const bus = new Nexus({
  crossTabName: 'my-app'
});

Selective teleport:

typescript
teleport: (event, payload) => {
  if (shouldSync(event)) {
    ws.send(JSON.stringify({ event, payload }));
  }
}

Released under the MIT License.