Because modern browsers natively support both WebSocket and fetch, adapting
the EdgeWorker is incredibly straightforward. We can strip out all the Node.js
imports and export it as a clean ES6 module.
This class is ready to be dropped straight into Mesh OSeither loaded
dynamically into your virtual file system, attached to a UI component, or run
silently in the background as a Web Worker.
The Browser Client (browser-edge-worker.js)
Here is the native ES6 implementation. We switch to the browser's standard
addEventListener pattern and rely entirely on native web APIs.
export class BrowserEdgeWorker { constructor(registryWsUrl, registryRestUrl =
null) { this.wsUrl = registryWsUrl; this.restUrl = registryRestUrl ||
registryWsUrl.replace('ws://', 'http://').replace('wss://', 'https://').replace
('/stream', ''); this.routines = new Map(); this.activeSubscriptions = new
Set(); this.connect(); } connect() { this.ws = new WebSocket(this.wsUrl);
this.ws.addEventListener('open', () => { console.log(`[Edge] Connected to
Registry at ${this.wsUrl}`); if (this.activeSubscriptions.size > 0) {
this._sendSubscriptionMessage(Array.from(this.activeSubscriptions)); } });
this.ws.addEventListener('message', (event) => { try { const payload =
JSON.parse(event.data); if (payload.type === 'ROUTINE_UPDATE') {
this.hotReload(payload.routine, payload.artifact); } } catch (err) {
console.error('[Edge] Failed to process incoming WS message:', err); } });
this.ws.addEventListener('close', () => { console.warn('[Edge] Connection
lost. Reconnecting in 5s...'); setTimeout(() => this.connect(), 5000); });
this.ws.addEventListener('error', (err) => { console.error('[Edge] WebSocket
error:', err); // The close event will fire immediately after, handling the
reconnect }); } subscribe(routineName) { this.activeSubscriptions.add(routineNa
me); if (this.ws && this.ws.readyState === WebSocket.OPEN) { this._sendSubscrip
tionMessage([routineName]); } } _sendSubscriptionMessage(routinesArray) {
this.ws.send(JSON.stringify({ type: 'SUBSCRIBE', routines: routinesArray }));
} hotReload(name, artifactString) { try { // Evaluates the IIFE payload
securely in the browser context const routineModule = eval(artifactString);
this.routines.set(name, routineModule); console.log(`[Edge] Hot-reloaded
[${name}] directly into memory.`); } catch (err) { console.error(`[Edge]
Hot-reload failed for [${name}]:`, err.message); } } // Run a subscribed
routine locally in the browser async run(routineName, params) { const routine
= this.routines.get(routineName); if (!routine) throw new Error(`Routine
[${routineName}] is not loaded. Did you sub
scribe?`); return await routine.run(params); } // Utility: Trigger a remote
execution on the registry server async remoteRun(routineName, params = {}) {
const res = await fetch(`${this.restUrl}/routines/${routineName}/run`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body:
JSON.stringify(params) }); if (!res.ok) { const errBody = await
res.json().catch(() => ({})); throw new Error(errBody.error || `HTTP
${res.status}`); } return await res.json(); } }
Usage in the Browser
You can import this directly into any HTML file, canvas UI, or Web Worker
script. Notice how we route the connection to the production domain using your
standard tunnel configuration.
<script type="module"> import { BrowserEdgeWorker } from './browser-edge-worker
.js'; // Connect to the Cloudflare tunnel routing to your local registry const
edge = new BrowserEdgeWorker('wss://omega-mesh.fi/stream'); // Subscribe to
the logic we need for the UI edge.subscribe('calculate_tax'); // Bind
execution directly to a DOM event document.getElementById('calc-button').addEve
ntListener('click', async () => { const userInput = parseFloat(document.getElem
entById('amount').value); try { // Executes locally in the browser instantly!
const result = await edge.run('calculate_tax', { subtotal: userInput, region:
'FI' }); console.log("Calculated:", result); document.getElementById('output').
innerText = `,${result.final_total}`; } catch (err) { console.error(err.message
); } }); </script> Total:
Why this shines in a virtualized environment:
Network Interception Compatibility: If you are using ServiceWorkers to mock or
intercept network requests, native fetch and WebSocket calls pass right
through the standard browser routing logic naturally.
True Edge Execution: The user's browser performs the actual compute
operations, entirely offloading the work from the registry server once the
artifact is downloaded.
Zero-Refresh Updates: If you push a new version of calculate_tax via your CLI
while a user has Mesh OS open, their browser receives the WS broadcast, evals
the new artifact, and the very next time they click the button, it runs the
new code without ever refreshing the page.