@seamos/connect
v0.1.2
Published
WebSocket and HTTP connectivity utilities for SeamOS
Readme
@seamos/connect
WebSocket and HTTP connectivity utilities for SeamOS. Provides automatic port resolution from CCU, a managed WebSocket client with auto-reconnect, and a fetch wrapper — all using just endpoint paths.
Installation
npm install @seamos/connectQuick Start
import {
initPorts,
createWebSocketClient,
seamosFetch,
} from '@seamos/connect';
// 1. Initialize port mapping (call once at app startup)
await initPorts();
// 2. WebSocket — just pass the path
const client = createWebSocketClient('/ws', {
autoReconnect: true,
events: {
open: () => console.log('Connected'),
message: (e) => console.log('Message:', e.data),
close: () => console.log('Disconnected'),
},
});
// 3. HTTP fetch — just pass the path
const response = await seamosFetch('/api/data');
const data = await response.json();API
initPorts()
Fetches the assigned port from the CCU (get_assigned_ports endpoint) and stores it globally.
Must be called once before using any other port-dependent function.
Returns: Promise<void>
getAssignedPort()
Returns the assigned port number.
Returns: number
Throws if initPorts() has not been called.
getAssignedPorts()
Returns the raw port mapping object from the CCU.
Returns: Record<string, number>
Throws if initPorts() has not been called.
createWebSocketClient(path, options?)
Creates a WebSocket client connected to the given path.
Parameters:
path(string): Endpoint path (e.g.,'/ws')options(optional):protocols: WebSocket sub-protocolsevents: Event handlers object withopen,message,close,errorhandlersautoReconnect: Enable auto-reconnect (default:false)reconnectInterval: Reconnect delay in ms (default:3000)
Returns: { socket, close() }
seamosFetch(path, init?)
Fetch wrapper that automatically uses the resolved host and port.
Parameters:
path(string): API endpoint path (e.g.,'/api/data')init(optional): StandardRequestInitoptions (method, headers, body, etc.)
Returns: Promise<Response>
sendJson(socket, payload)
Sends a JSON-serialized payload through a WebSocket.
Throws if the socket is null or not in OPEN state.
closeWebSocketSafe(socket, code?, reason?)
Safely closes a WebSocket connection. No-op if null or already closed.
isProperJson(payload)
Checks whether the given payload is valid JSON (non-null object).
Returns: boolean
License
MIT
