import Pipe from 'bare-pipe'
import FramedStream from 'framed-stream'
import b4a from 'b4a'
let rpcId = 0
const pipe = new Pipe('/tmp/keet-daemon.sock')
const framed = new FramedStream(pipe)
const pending = new Map()
framed.on('data', buf => {
const msg = JSON.parse(b4a.toString(buf))
const cb = pending.get(msg.id)
if (cb) { pending.delete(msg.id); cb(msg) }
})
function call (method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++rpcId
const timeout = setTimeout(() => { pending.delete(id); reject(new Error('timeout')) }, 10000)
pending.set(id, msg => {
clearTimeout(timeout)
if (msg.ok !== undefined && msg.data !== undefined) msg.result = msg.data
if (msg.error) reject(new Error(msg.error.message || String(msg.error)))
else resolve(msg.result)
})
framed.write(b4a.from(JSON.stringify({ jsonrpc: '2.0', id, method, params })))
})
}
console.log('MetadataBase key:', await call('meta.key'))
console.log('Meta invite:', await call('meta.invite'))
pipe.destroy()
setTimeout(() => Bare.exit(0), 500)