zeus-sdk
v1.1.0
Published
Official TypeScript/JavaScript client for the Zeus realtime server
Maintainers
Readme
zeus-sdk
Official TypeScript/JavaScript client for the Zeus realtime server.
npm install zeus-sdkConnect
import Zeus from 'zeus-sdk'
const zeus = new Zeus({
host: 'localhost',
port: 7878,
token: 'your-token-from-zeus.yaml',
debug: true, // log connection events
autoReconnect: true, // reconnect on disconnect (default: true)
})
await zeus.connect()Cache
// Set a value (with optional TTL in seconds)
await zeus.cache.set('key', 'value')
await zeus.cache.set('session:alice', 'token123', { ttl: 3600 })
// Get a value
const val = await zeus.cache.getString('key') // string | null
const buf = await zeus.cache.get('key') // Buffer | null
// JSON helpers
await zeus.cache.setJSON('user:1', { name: 'Alice', role: 'admin' })
const user = await zeus.cache.getJSON<User>('user:1') // User | null
// Get-or-set (cache-aside pattern)
const report = await zeus.cache.getOrSet('report:may', () => generateReport(), { ttl: 3600 })
// Delete / clear
await zeus.cache.delete('key')
await zeus.cache.clear()Channels (Pub/Sub)
// Subscribe — returns an unsubscribe function
const unsub = await zeus.channels.subscribe('prices:BTC', (payload, channel) => {
console.log('update on', channel, '→', payload.toString())
})
// Subscribe with JSON parsing
await zeus.channels.subscribeJSON<{ usd: number }>('prices:BTC', (data) => {
console.log('BTC price:', data.usd)
})
// Subscribe with history replay (get last N messages immediately)
await zeus.channels.subscribe('news', handler, true)
// Publish
await zeus.channels.publish('prices:BTC', JSON.stringify({ usd: 67420 }))
await zeus.channels.publishJSON('prices:BTC', { usd: 67420 })
// Retain: new subscribers always get this value immediately
await zeus.channels.publish('server:status', 'online', true)
// Unsubscribe
unsub()Queues
// Push a job (producer)
const msgId = await zeus.queues.push('send-email', {
to: '[email protected]',
subject: 'Welcome!',
body: 'Thanks for signing up.'
})
// Consume jobs (worker) — must call job.ack() or job.nack()
const stop = await zeus.queues.consume('send-email', async (job) => {
const data = JSON.parse(job.payload.toString()) as EmailPayload
try {
await sendEmail(data.to, data.subject, data.body)
await job.ack() // ✅ processed — Zeus deletes it
} catch (err) {
await job.nack(err.message) // ❌ failed — Zeus retries with backoff
}
})
// Stop consuming
await stop()If your worker throws without calling ack() or nack(), the SDK automatically nacks the job.
Chat
// Join a room — history is available immediately
const room = await zeus.chat.join('team-general')
console.log('Recent messages:', room.history)
// Listen for new messages
room.on('message', (msg) => {
console.log(`[${msg.sender}] ${msg.text()}`)
// msg.json<T>() for JSON payloads
})
// Send messages
await room.send('Hey team 👋')
await room.sendJSON({ type: 'order', id: 42 })
await room.sendTyped('image', imageBuffer)
// Fetch paginated history
const older = await room.getHistory({ limit: 100 })
const page2 = await room.getHistory({ afterId: older[0].id })
// Presence — who's online
const members = await room.getPresence()
const online = members.filter(m => m.online)
// Receipts — mark messages as read (requires receipt_tracking feature)
room.on('receipt', ({ msgId, state, userId }) => {
// state: 0=sent, 1=delivered, 2=read
updateTicks(msgId, state)
})
await room.markRead(msgId)
// Edit / Delete (requires persistence)
await room.edit(msgId, 'corrected text')
await room.delete(msgId)
room.on('edit', ({ msgId, newPayload }) => updateMessage(msgId, newPayload))
room.on('delete', ({ msgId }) => removeMessage(msgId))
// Polls (requires polls feature)
const pollId = await room.createPoll({
question: 'When should we meet?',
options: ['2pm', '4pm', '6pm'],
closeSecs: 86400,
})
await room.vote(pollId, 1)
const results = await room.getPollResults(pollId)
room.on('poll', (results) => updatePollUI(results))
// User metadata (requires user_metadata feature)
await room.setMeta({ display_name: 'Alice', avatar_url: '...', role: 'admin' })
const aliceMeta = await room.getMeta('alice')
room.on('presence', (entry) => updatePresenceUI(entry))
// Leave
await room.leave()Utilities
// Ping
const ms = await zeus.ping()
console.log(`Latency: ${ms}ms`)
// Check connection
zeus.connected // boolean
// Disconnect
zeus.disconnect()Connection options
| Option | Type | Default | Description |
|---|---|---|---|
| host | string | — | Zeus server host |
| port | number | — | Zeus server port |
| token | string | — | Auth token from zeus.yaml |
| autoReconnect | boolean | true | Reconnect on disconnect |
| reconnectDelay | number | 2000 | ms between reconnect attempts |
| maxReconnectAttempts | number | 0 | 0 = unlimited |
| connectTimeout | number | 10000 | Connection timeout in ms |
| debug | boolean | false | Log connection events |
Events on zeus.connection
zeus.connection.on('connect', () => ...) // authenticated and ready
zeus.connection.on('disconnect', () => ...) // connection lost
zeus.connection.on('reconnecting', (n) => ...) // attempt number N
zeus.connection.on('error', (err) => ...) // fatal error
zeus.connection.on('push', (frame) => ...) // raw server push frame