mirror of
https://github.com/logos-messaging/negentropy.git
synced 2026-01-02 14:03:07 +00:00
Negentropy Javascript Implementation
The library is contained in a single javascript file. It shouldn't need any dependencies, in either a browser or node.js:
const Negentropy = require('Negentropy.js');
Storage
First, you need to create a storage instance. Currently only Vector is implemented:
let storage = new NegentropyStorageVector();
Next, add all the items in your collection, and seal():
for (let item of myItems) {
storage.insert(timestamp, id);
}
ne.seal();
timestampshould be a JSNumberidshould be a hex string,Uint8Array, or node.jsBuffer
Reconciliation
Create a Negentropy object:
let ne = new Negentropy(storage, 50_000);
- The second parameter (
50'000above) is theframeSizeLimit. This can be omitted (or0) to permit unlimited-sized frames.
On the client-side, create an initial message, and then transmit it to the server, receive the response, and reconcile until complete (signified by returning null for newMsg):
let msg = await ne.initiate();
while (msg.length !== null) {
let response = queryServer(msg);
let [newMsg, have, need] = await ne.reconcile(msg);
msg = newMsg;
// handle have/need
}
- The output
msgs and the IDs inhave/needare hex strings, but you can setne.wantUint8ArrayOutput = trueif you wantUint8Arrays instead.
The server-side is similar, except it doesn't create an initial message, there are no have/need arrays, and newMsg will never be null:
while (1) {
let msg = receiveMsgFromClient();
let [newMsg] = await ne.reconcile(msg);
respondToClient(newMsg);
}
- The
initiate()andreconcile()methods are async because thecrypto.subtle.digest()browser API is async. - Timestamp values greater than
Number.MAX_VALUEwill currently cause failures.