This commit is contained in:
Raven Scott
2026-05-20 21:02:45 -04:00
parent 1f3f4b24a2
commit 14d0980b4f
734 changed files with 682 additions and 746 deletions
@@ -0,0 +1,56 @@
/**
* Basic usage example for hyper-p2p-reactive-state
* Run with: bare examples/basic-usage.js
*/
const process = require('bare-process')
const { HyperP2PReactiveState } = require('../index.js')
async function main () {
const topic = 'example-reactive-state-' + Date.now()
const state = new HyperP2PReactiveState({
topic,
metadata: { role: 'example', version: '0.1.0' }
})
state.on('ready', () => console.log('✅ State manager ready'))
state.on('change', (change) => {
console.log(`🔄 Change: ${change.key} = ${JSON.stringify(change.value)} (by ${change.peer})`)
})
state.on('peer-connected', (p) => console.log('👥 Peer connected:', p.peer))
await state.ready()
// Set some reactive state
await state.set('game:score', 1250)
await state.set('game:player', { name: 'Agent', xp: 3400 })
await state.set('config:theme', 'cyberpunk')
console.log('Current state:', state.toJSON())
// Query example
const gameKeys = state.query({ keyPrefix: 'game:' })
console.log('Game related:', gameKeys.length, 'entries')
// Subscribe example
const unsub = state.subscribe(['config:theme', 'game:score'], (c) => {
console.log('📡 Subscribed update:', c)
})
await state.set('config:theme', 'neon')
await state.delete('game:score')
unsub()
console.log('Peers:', state.getPeers().length)
// Simulate shutdown
setTimeout(async () => {
await state.close()
console.log('✅ Closed gracefully')
process.exit(0)
}, 2000)
}
main().catch(console.error)