@hromada/sync 0.6.0 · a watcher and folders of 100 000 files · apache-2.0
Your folders,the same everywhere.No accepted version lost.
sync keeps a folder the same on your machines with no server and no cloud, as a library you put into your own Node service. Two edits at once keep both, every machine reaches the same result whatever order changes arrive in, and every change is signed by the machine that made it.
Status: 0.6 - a watcher and folders of 100 000 files. The engine, real folders on
disk, the transport between mesh members, the modes both, send and receive,
invitations, guests with until, a watcher and large folders are done and tested; explain() and a CLI come next. npm install @hromada/sync - before 1.0 the API may change.
What it solves
Keeping a folder the same on a laptop, a home PC and a NAS sounds simple until two of them change the same file, one is restored from a backup, or one is lost. sync is built around those cases.
Two edits at once, both kept
Both laptops end with the same winner at the path and the other version as a copy with the same name on every machine.
02Order does not matter
Three machines' changes arriving in all 6 orders give one and the same folder.
03A lost laptop, revoked
What it wrote before stays everywhere; with its stolen key nothing new is accepted.
04Restored from an old backup
A machine that forgot its last edits cannot overwrite the copies others already have.
05Two real folders
Files and folders arrive, an edit on both sides keeps both, a delete goes to the trash - on disk, through a journal.
07A site's JSON-LD, on two machines
All three libraries: crawl a site from its sitemap, pack it with recpack, keep it on a laptop over hromada; day 2 only a small diff travels.
08A NAS that only receives
Invited by the laptop, it takes every change with reading rights only, keeps its own files, and a delete lands in its trash.
09Publish to two servers
The publisher only sends, the servers only receive; a hotfix made on a server steps aside instead of being lost.
10A guest for a while
Invited with until: reads until then, gets nothing new after, keeps what it already copied.
How it works, in plain words
Every change becomes a small signed record. The folder is whatever those records add up to.
name.sync-conflict-<time>-<id>.ext, the same name on every machine.Examples
Each one is a whole file from the repository's examples/ folder, run by the tests on every change. The engine runs in memory, so every "machine" is a replica in one process and "meeting" means handing over signed records. The output under each one is a real run, made when this site was built.
git clone https://github.com/Olexan-art/sync && cd sync
npm ci && npm run build
node examples/01-conflict-two-laptops.mjs01Two laptops edit the same file offline
You add milk to the shopping list at home, someone adds bread at work, both offline. Both edits should survive, and every machine should agree on which one stays at the path.

// Two laptops edit the same file offline; when they meet, both keep the same winner and the other version as a copy.
// Run it: node examples/01-conflict-two-laptops.mjs
import { createHash, randomBytes } from "node:crypto";
import { RIGHTS, Replica, replicaKey, viewDigest } from "@hromada/sync";
const meshId = new TextEncoder().encode("my-mesh"), folderId = randomBytes(16);
const home = replicaKey(), work = replicaKey();
const owner = Buffer.from(home.replicaId).toString("hex"); // the first replica owns the folder
const A = new Replica({ meshId, folderId, owner, key: home });
const B = new Replica({ meshId, folderId, owner, key: work });
const meet = (x, y) => { x.flush(); y.flush(); y.receiveRecords(x.records()); x.receiveRecords(y.records()); };
const file = (text, mtime) => { const sha256 = createHash("sha256").update(text).digest(); return { type: "file", size: text.length, mtime, sha256, chunks: [{ len: text.length, sha: sha256 }] }; };
A.grant(B.principal, RIGHTS.read | RIGHTS.write);
A.write("notes.md", file("shopping list", 1_000));
meet(A, B);
A.write("notes.md", file("shopping list + milk", 2_000)); // offline on the home laptop
B.write("notes.md", file("shopping list + bread", 3_000)); // offline at work
meet(A, B);
for (const [name, r] of [["home", A], ["work", B]]) {
const paths = [...r.view().keys()].sort();
console.log(`${name}: ${paths.join(", ")}`);
}
console.log(`same state on both: ${viewDigest(A.view()) === viewDigest(B.view())}`);
A.resolveConflicts(); // records the outcome; B would reach the same one
meet(A, B);
console.log(`conflicts left: ${A.state().conflicts.size}, versions lost: 0`);home: notes.md, notes.sync-conflict-19700101-000002-a0454c080f17fb13.md
work: notes.md, notes.sync-conflict-19700101-000002-a0454c080f17fb13.md
same state on both: true
conflicts left: 0, versions lost: 0What happens
- Each laptop's edit is a signed record. When they meet, each takes the other's records.
- Both compute the same winner (the newer edit here) and keep the other version as a copy whose name is the same on both machines.
resolveConflicts()records the outcome; a second machine resolving on its own reaches the very same one, and the two settle as one.
02Whatever order changes arrive in
Three machines change the same file. Over a real network their changes reach the others in any order, some late, some twice.

// Three machines change one file at once; whatever order their changes arrive in, everyone ends with the same folder.
// Run it: node examples/02-order-does-not-matter.mjs
import { createHash, randomBytes } from "node:crypto";
import { RIGHTS, Replica, replicaKey, viewDigest } from "@hromada/sync";
const meshId = new TextEncoder().encode("my-mesh"), folderId = randomBytes(16);
const keys = [replicaKey(), replicaKey(), replicaKey()];
const owner = Buffer.from(keys[0].replicaId).toString("hex");
const [a, b, c] = keys.map((key) => new Replica({ meshId, folderId, owner, key }));
const file = (text, mtime) => { const sha256 = createHash("sha256").update(text).digest(); return { type: "file", size: text.length, mtime, sha256, chunks: [{ len: text.length, sha: sha256 }] }; };
a.grant(b.principal, RIGHTS.write);
a.grant(c.principal, RIGHTS.write);
a.flush();
for (const r of [b, c]) r.receiveRecords(a.records());
a.write("plan.txt", file("plan from a", 100));
b.write("plan.txt", file("plan from b", 300));
c.write("plan.txt", file("plan from c", 200));
const sent = [a, b, c].map((r) => (r.flush(), r.records()));
const orders = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]];
const results = new Set();
for (const order of orders) {
const fresh = new Replica({ meshId, folderId, owner, key: replicaKey() });
for (const i of order) fresh.receiveRecords(sent[i]);
results.add(viewDigest(fresh.view()));
}
console.log(`${orders.length} arrival orders, ${results.size} resulting folder state`);
for (const r of [b, c]) a.receiveRecords(r.records());
console.log(`winner: plan.txt, copies: ${[...a.view().keys()].filter((p) => p.includes("sync-conflict")).length}`);6 arrival orders, 1 resulting folder state
winner: plan.txt, copies: 2What happens
- A fresh replica takes the three machines' records in each of the 6 possible orders.
- Every time, the folder comes out byte for byte the same: one winner, two copies.
- This is the core property: the state is a pure function of the set of records.
03A laptop is lost
The laptop had write access to the folder. Its work up to now should stay; whoever finds it should not be able to change anything.

// A laptop is lost: the owner takes its rights away. What it wrote before stays; what it writes after is refused everywhere.
// Run it: node examples/03-revoke-a-laptop.mjs
import { createHash, randomBytes } from "node:crypto";
import { RIGHTS, Replica, replicaKey } from "@hromada/sync";
const meshId = new TextEncoder().encode("my-mesh"), folderId = randomBytes(16);
const keys = [replicaKey(), replicaKey(), replicaKey()];
const owner = Buffer.from(keys[0].replicaId).toString("hex");
const [pc, laptop, nas] = keys.map((key) => new Replica({ meshId, folderId, owner, key }));
const send = (from, ...to) => { from.flush(); for (const t of to) t.receiveRecords(from.records()); };
const file = (text, mtime) => { const sha256 = createHash("sha256").update(text).digest(); return { type: "file", size: text.length, mtime, sha256, chunks: [{ len: text.length, sha: sha256 }] }; };
pc.grant(laptop.principal, RIGHTS.write);
pc.grant(nas.principal, RIGHTS.write);
send(pc, laptop, nas);
laptop.write("report.txt", file("written before it was lost", 1));
send(laptop, pc, nas);
pc.revoke(laptop.principal); // the owner's decision: a signed record, not a clock
send(pc, laptop, nas);
console.log(`laptop may write now: ${laptop.canWrite()}`);
const thief = new Replica({ meshId, folderId, owner, key: keys[1] }); // someone with the stolen key, a new run
send(pc, thief);
try { thief.write("evil.txt", file("written after", 2)); } catch (e) { console.log(`write refused: ${e.code}`); }
for (const r of [pc, nas]) console.log(`${r === pc ? "pc " : "nas"}: ${[...r.view().keys()].sort().join(", ")}`);laptop may write now: false
write refused: not_allowed
pc : report.txt
nas: report.txtWhat happens
revoke()is a signed decision of the folder's owner, not a clock: it counts the same on every machine.- Every change some honest machine had accepted before it stays everywhere, together with what it relied on.
- The stolen key, started again, gets nothing new accepted:
not_allowedhere, and refused by every other machine anyway.
04Restored from last week's backup
The laptop's disk died; it is restored from a backup made before its last edit, which the PC already has. Then it edits the same file offline.

// A machine is restored from last week's backup and edits a file before it meets anyone. The edit it no longer
// remembers, which another machine already has, is not overwritten: both versions stay.
// Run it: node examples/04-restore-from-backup.mjs
import { createHash, randomBytes } from "node:crypto";
import { RIGHTS, Replica, replicaKey } from "@hromada/sync";
const meshId = new TextEncoder().encode("my-mesh"), folderId = randomBytes(16);
const pcKey = replicaKey(), laptopKey = replicaKey();
const owner = Buffer.from(pcKey.replicaId).toString("hex");
const pc = new Replica({ meshId, folderId, owner, key: pcKey });
let laptop = new Replica({ meshId, folderId, owner, key: laptopKey });
const send = (from, to) => { from.flush(); to.receiveRecords(from.records()); to.receiveStubs(from.stubs()); };
const file = (text, mtime) => { const sha256 = createHash("sha256").update(text).digest(); return { type: "file", size: text.length, mtime, sha256, chunks: [{ len: text.length, sha: sha256 }] }; };
const text = (r, p) => (r.view().get(p) ? Buffer.from(r.view().get(p).sha256).toString("hex").slice(0, 8) : "-");
pc.grant(laptop.principal, RIGHTS.write);
send(pc, laptop);
laptop.write("thesis.md", file("chapter 1", 1));
send(laptop, pc);
laptop.flush();
const backup = { records: laptop.records(), stubs: laptop.stubs() }; // last week
laptop.write("thesis.md", file("chapter 1 + chapter 2", 2)); // reached the pc...
send(laptop, pc);
laptop = new Replica({ meshId, folderId, owner, key: laptopKey }); // ...then the disk died; restored from the backup
laptop.receiveRecords(backup.records);
laptop.receiveStubs(backup.stubs);
laptop.write("thesis.md", file("chapter 1 + a new chapter 2", 3)); // offline, before meeting anyone
send(laptop, pc);
send(pc, laptop);
pc.resolveConflicts();
send(pc, laptop);
const kept = [...pc.view().keys()].filter((p) => p.startsWith("thesis"));
console.log(`versions kept: ${kept.length} (${kept.join(", ")})`);
console.log(`pc and laptop agree: ${text(pc, "thesis.md") === text(laptop, "thesis.md")}`);versions kept: 2 (thesis.md, thesis.sync-conflict-19700101-000000-d1eae9406f8ed6ee.md)
pc and laptop agree: trueWhat happens
- The restored laptop starts a new epoch, so its new edit claims nothing about the edit it forgot.
- The two versions are seen as a conflict, not as one replacing the other: both stay.
- The fuzz found exactly this loss in an earlier design; the new-epoch rule removes it by construction.
05Two real folders on one machine
The engine is only half of it: files have to land on a disk that can fill up, crash mid-write or be edited at the worst moment.

// Two real folders kept in step on one machine: files, a folder, an edit on both sides, a delete into the trash.
// Run it: node examples/05-two-real-folders.mjs
import { mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { RIGHTS, SyncFolder } from "@hromada/sync";
const meshId = new TextEncoder().encode("my-mesh");
const laptop = mkdtempSync(join(tmpdir(), "laptop-")), pc = mkdtempSync(join(tmpdir(), "pc-"));
const folders = [];
const fetch = async (sha) => { for (const f of folders) { const b = await f.localChunk(sha); if (b) return b; } };
const a = await SyncFolder.create(laptop, { meshId, fetch });
const b = await SyncFolder.join(pc, { meshId, fetch, folderId: a.replica.folder.folderId, owner: a.replica.folder.owner });
folders.push(a, b);
a.replica.grant(b.replica.principal, RIGHTS.write);
const meet = async () => { for (const [x, y] of [[a, b], [b, a]]) { await x.persist(); await y.receive(x.replica.records(), x.replica.stubs()); } };
const round = async () => { await a.sync(); await b.sync(); await meet(); await a.sync(); await b.sync(); };
const list = (dir) => readdirSync(dir, { recursive: true }).filter((p) => !String(p).startsWith(".hromada")).map((p) => String(p).split("\\").join("/")).sort();
mkdirSync(join(laptop, "photos"));
writeFileSync(join(laptop, "notes.md"), "shopping list");
writeFileSync(join(laptop, "photos", "cat.jpg"), Buffer.alloc(300_000, 9));
await round();
console.log(`pc has: ${list(pc).join(", ")}`);
writeFileSync(join(laptop, "notes.md"), "shopping list + milk"); // both edit before they meet
writeFileSync(join(pc, "notes.md"), "shopping list + bread");
await round();
await round();
console.log(`after an edit on both: ${list(pc).filter((p) => p.startsWith("notes")).length} versions of notes.md on each side`);
rmSync(join(pc, "photos", "cat.jpg"));
await round();
console.log(`cat.jpg on the laptop: ${list(laptop).includes("photos/cat.jpg") ? "still there" : "moved to its trash"} (${a.trashed().length} in the trash)`);
console.log(`same files on both: ${JSON.stringify(list(laptop)) === JSON.stringify(list(pc))}`);
await a.close();
await b.close();
for (const d of [laptop, pc]) rmSync(d, { recursive: true, force: true });pc has: notes.md, photos, photos/cat.jpg
after an edit on both: 2 versions of notes.md on each side
cat.jpg on the laptop: moved to its trash (2 in the trash)
same files on both: trueWhat happens
SyncFolderscans a folder, cuts files into content-defined chunks (recpack's FastCDC) and records what changed.- An incoming file is built next to its target, checked by SHA-256, and renamed in place; the old one goes to
.hromada-trashfirst, through a journal that a crash cannot leave half done. - A local edit is recorded on the version the disk held, so an incoming version never silently replaces it: both stay.
07A site's JSON-LD, kept on a second machine
A shop's structured data (prices, stock, the shop itself) lives in JSON-LD on every page. You want a copy you can compare day to day, on a machine that is not the crawler - and to hear at once when a template drops a price.

// Crawl the JSON-LD of a whole site, pack it with recpack, and keep it in step on a second machine with sync over a
// hromada mesh. On day 2 only a small diff travels, and the second machine spots a page that lost its price.
// Run it: node examples/07-jsonld-site-sync.mjs (a local demo shop, no internet)
// node examples/07-jsonld-site-sync.mjs https://your.site/sitemap.xml --limit 500 (any live site)
import { createServer } from "node:http";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { applyPatch, pack, patch, unpack } from "@hromada/recpack";
import { createMesh, joinMesh } from "hromada/mesh";
import { RIGHTS, SyncFolder, linkFolder } from "@hromada/sync";
const args = process.argv.slice(2);
const limit = args.includes("--limit") ? Number(args[args.indexOf("--limit") + 1]) : 500;
const kb = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : n >= 1024 ? `${(n / 1024).toFixed(1)} KB` : `${n} B`);
const tmp = (n) => mkdtempSync(join(tmpdir(), n));
const until = async (ok) => { for (let i = 0; i < 600 && !ok(); i++) await new Promise((r) => setTimeout(r, 50)); };
// ---- a demo shop on 127.0.0.1: 500 product pages with the JSON-LD most shops have; on day 2 three pages change ----
function demoShop() {
let day = 1;
const org = { "@context": "https://schema.org", "@type": "Organization", name: "Demo Garden Shop", url: "https://shop.example", logo: "https://shop.example/logo.png", sameAs: ["https://facebook.com/demo.garden", "https://instagram.com/demo.garden"], contactPoint: { "@type": "ContactPoint", telephone: "+380-44-000-00-00", contactType: "customer service" } };
const product = (i) => {
const offer = { "@type": "Offer", url: `https://shop.example/product/${i}`, priceCurrency: "UAH", price: (99 + (i % 40) * 25).toFixed(2), availability: "https://schema.org/InStock", seller: { "@type": "Organization", name: "Demo Garden Shop" } };
if (day === 2 && i === 7) offer.price = "149.00"; // a new price
if (day === 2 && i === 310) offer.availability = "https://schema.org/OutOfStock";
if (day === 2 && i === 42) delete offer.price; // a template bug: the price is gone
return [org, { "@context": "https://schema.org", "@type": "Product", name: `Garden tool ${i}`, sku: `GT-${10000 + i}`, image: [`https://shop.example/img/${i}.jpg`], description: `Garden tool ${i}: steel, ash handle, made in Ukraine.`, brand: { "@type": "Brand", name: "Demo Tools" }, offers: offer },
{ "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: [{ "@type": "ListItem", position: 1, name: "Garden", item: "https://shop.example/garden" }, { "@type": "ListItem", position: 2, name: `Garden tool ${i}` }] }];
};
const server = createServer((req, res) => {
const base = `http://127.0.0.1:${server.address().port}`;
if (req.url === "/sitemap.xml") return res.end(`<?xml version="1.0"?><urlset>${Array.from({ length: 500 }, (_, i) => `<url><loc>${base}/product/${i + 1}</loc></url>`).join("")}</urlset>`);
const m = /^\/product\/(\d+)$/.exec(req.url);
if (!m) return res.writeHead(404).end();
res.end(`<html><head>${product(Number(m[1])).map((b) => `<script type="application/ld+json">${JSON.stringify(b)}</script>`).join("")}</head><body>...</body></html>`);
});
return new Promise((ok) => server.listen(0, "127.0.0.1", () => ok({ sitemap: `http://127.0.0.1:${server.address().port}/sitemap.xml`, nextDay: () => (day = 2), close: () => server.close() })));
}
// ---- the crawler: sitemap (or sitemap index) -> pages -> the <script type="application/ld+json"> blocks ----
const get = async (url) => {
const r = await fetch(url, { signal: AbortSignal.timeout(15_000), headers: { "user-agent": "hromada-sync-example/0.4 (+https://hromada.pages.dev/sync/)" } });
if (!r.ok) throw new Error(`${r.status} ${url}`);
return r.text();
};
async function pageUrls(sitemap, max) {
const xml = await get(sitemap);
const locs = [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replaceAll("&", "&"));
if (!/<sitemapindex/i.test(xml)) return locs.slice(0, max);
const out = [];
for (const sm of locs) if (out.length < max) out.push(...(await pageUrls(sm, max - out.length)));
return out;
}
const jsonLd = (html) => [...html.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)].flatMap((m) => { try { return [JSON.parse(m[1].trim())]; } catch { return []; } });
async function crawl(urls) {
const pages = [];
let next = 0;
await Promise.all(Array.from({ length: 4 }, async () => { // at most 4 requests at a time: polite to any site
while (next < urls.length) {
const i = next++, u = new URL(urls[i]);
pages[i] = { url: u.pathname + u.search, ld: await get(urls[i]).then(jsonLd, () => []) };
}
}));
return pages;
}
// what repeats on many pages: the bytes a shared block with an @id would save
function repeats(pages) {
const count = new Map(), walk = (o, f) => { if (o && typeof o === "object" && f(o) !== false) for (const v of Object.values(o)) walk(v, f); };
for (const p of pages) walk(p.ld, (o) => { if (o["@type"]) { const k = JSON.stringify(o); count.set(k, (count.get(k) ?? 0) + 1); } });
const seen = new Set(), types = new Map();
let bytes = 0;
for (const p of pages) walk(p.ld, (o) => {
const k = o["@type"] && JSON.stringify(o);
if (!k || count.get(k) < 2) return;
types.set(o["@type"], (types.get(o["@type"]) ?? 0) + 1);
if (seen.has(k)) bytes += Buffer.byteLength(k); else seen.add(k);
return false; // the outermost repeat only
});
return { bytes, top: [...types].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([t, n]) => `${t} x${n}`).join(", ") };
}
const prices = (ld) => { const out = []; const walk = (o) => { if (o && typeof o === "object") { if (/Offer/.test(o["@type"] ?? "") && (o.price ?? o.lowPrice) !== undefined) out.push(o.price ?? o.lowPrice); Object.values(o).forEach(walk); } }; walk(ld); return out; };
const save = (file, data) => { const p = pack(data); writeFileSync(file, Buffer.concat([Buffer.from([p.codec]), p.bytes])); return 1 + p.bytes.length; }; // codec byte + recpack block
const load = (file) => { const b = readFileSync(file); return unpack({ codec: b[0], bytes: b.subarray(1) }); };
// ---- day 1: crawl, look at the repeats, pack ----
const shop = args.some((a) => /^https?:/.test(a)) ? undefined : await demoShop();
const sitemap = args.find((a) => /^https?:/.test(a)) ?? shop.sitemap;
const urls = await pageUrls(sitemap, limit);
const day1 = await crawl(urls);
const raw = Buffer.byteLength(JSON.stringify(day1.map((p) => p.ld)));
const rep = repeats(day1);
console.log(`crawler: ${day1.length} pages, ${day1.filter((p) => p.ld.length).length} with JSON-LD, ${kb(raw)} as JSON`);
console.log(`repeats: ${kb(rep.bytes)} (${Math.round((100 * rep.bytes) / Math.max(raw, 1))}%) are blocks seen on many pages${rep.top ? ` - ${rep.top}: say them once, with an @id` : ""}`);
// the two machines: a crawler (a server, say) and a laptop, members of one mesh; the laptop may read the folder
const crawlerMesh = await createMesh({ dir: tmp("mesh-crawler-"), name: "crawler" });
const laptopMesh = await joinMesh(crawlerMesh.createInvite(), { dir: tmp("mesh-laptop-"), name: "laptop" });
await until(() => !!crawlerMesh.member("laptop"));
const meshId = new TextEncoder().encode(crawlerMesh.id), dirC = tmp("crawler-"), dirL = tmp("laptop-");
const crawler = await SyncFolder.create(dirC, { meshId });
const laptop = await SyncFolder.join(dirL, { meshId, folderId: crawler.replica.folder.folderId, owner: crawler.replica.folder.owner });
crawler.replica.grant(laptop.replica.principal, RIGHTS.read);
const links = [linkFolder(crawler, crawlerMesh), linkFolder(laptop, laptopMesh)];
const size1 = save(join(dirC, "catalog.rpk"), day1);
console.log(`recpack: catalog.rpk ${kb(size1)} (${(raw / size1).toFixed(0)}x smaller than the JSON)`);
await links[0].syncNow();
await until(() => existsSync(join(dirL, "catalog.rpk")));
const laptopDay1 = load(join(dirL, "catalog.rpk"));
console.log(`laptop: catalog.rpk arrived over the mesh, ${laptopDay1.length} pages, the same: ${JSON.stringify(laptopDay1) === JSON.stringify(day1)}`);
// ---- day 2: crawl again; only the pages that changed travel, as one small diff ----
shop?.nextDay();
const day2 = await crawl(urls);
const changes = day2.flatMap((p, i) => { const d = patch(day1[i], p, { deep: true }); return Object.keys(d).length ? [{ i, d }] : []; });
const size2 = save(join(dirC, "diff-day2.rpk"), changes);
console.log(`day 2 diff: diff-day2.rpk ${kb(size2)} (${changes.length} of ${day2.length} pages changed) - the only file that travels`);
await links[0].syncNow();
await until(() => existsSync(join(dirL, "diff-day2.rpk")));
const laptopDay2 = structuredClone(laptopDay1);
for (const { i, d } of load(join(dirL, "diff-day2.rpk"))) laptopDay2[i] = applyPatch(laptopDay2[i], d);
console.log(`laptop rebuilt day 2 exactly: ${JSON.stringify(laptopDay2) === JSON.stringify(day2)}`);
for (const { i } of changes) {
const was = prices(laptopDay1[i].ld), now = prices(laptopDay2[i].ld);
if (was.length && !now.length) console.log(`alert: ${laptopDay2[i].url} lost its price in JSON-LD (was ${was[0]})`);
else if (String(was) !== String(now)) console.log(`price: ${laptopDay2[i].url} ${was[0]} -> ${now[0]}`);
else console.log(`changed: ${laptopDay2[i].url}`);
}
for (const l of links) l.stop();
await crawler.close();
await laptop.close();
await crawlerMesh.stop();
await laptopMesh.stop();
shop?.close();
for (const d of [dirC, dirL]) rmSync(d, { recursive: true, force: true });crawler: 500 pages, 500 with JSON-LD, 502.4 KB as JSON
repeats: 248.5 KB (49%) are blocks seen on many pages - Organization x1000, Brand x500, ListItem x500: say them once, with an @id
recpack: catalog.rpk 5.9 KB (84x smaller than the JSON)
laptop: catalog.rpk arrived over the mesh, 500 pages, the same: true
day 2 diff: diff-day2.rpk 444 B (3 of 500 pages changed) - the only file that travels
laptop rebuilt day 2 exactly: true
price: /product/7 274.00 -> 149.00
alert: /product/42 lost its price in JSON-LD (was 149.00)
changed: /product/310What happens
- The crawler reads the sitemap (or a sitemap index), fetches the pages four at a time and keeps every
<script type="application/ld+json">block; it shows how much of it repeats on every page (an@idwould say it once). - recpack packs the whole catalogue into
catalog.rpk; sync carries it to the laptop over hromada's encrypted connections. - On day 2 only the pages that changed travel, as a small
diff-day2.rpk; the laptop rebuilds day 2 from it and reports a page that lost its price. - With no argument it runs a local demo shop of 500 pages (no internet);
node examples/07-jsonld-site-sync.mjs https://your.site/sitemap.xml --limit 500reads a live site - WordPress, Shopify, BigCommerce or your own. A live site repeats less than the demo shop, so its ratio is lower.
08A NAS keeps a copy, and nothing more
You want every change of your laptop's folder on the NAS - but the NAS must not push anything back, and files someone drops on it should stay there.
// A NAS that keeps a copy of the laptop's folder: invited by the laptop, it accepts, takes every change in `receive`
// mode, keeps its own files to itself, and a delete on the laptop lands in the NAS trash.
// Run it: node examples/08-nas-receive.mjs
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createMesh, joinMesh } from "hromada/mesh";
import { accept, onOffer, syncFolder } from "@hromada/sync";
const tmp = (n) => mkdtempSync(join(tmpdir(), n));
const until = async (ok) => { for (let i = 0; i < 400 && !(await ok()); i++) await new Promise((r) => setTimeout(r, 50)); };
const laptopMesh = await createMesh({ dir: tmp("mesh-laptop-"), name: "laptop" });
const nasMesh = await joinMesh(laptopMesh.createInvite(), { dir: tmp("mesh-nas-"), name: "nas" });
await until(() => !!laptopMesh.member("nas"));
// the NAS says which invitations it takes: here, any from the laptop
const nasDir = tmp("nas-");
let nas;
onOffer(nasMesh, async (offer) => {
console.log(`nas: offered "${offer.label}" by ${offer.fromName}, mode ${offer.mode}`);
if (offer.fromName === "laptop") nas = await accept(nasMesh, offer, { path: nasDir, pollMs: 200 });
});
// the laptop shares its folder with the NAS, in one line
const laptopDir = tmp("laptop-");
writeFileSync(join(laptopDir, "report.txt"), "Q3 report");
const laptop = await syncFolder(laptopMesh, { path: laptopDir, with: { nas: "receive" }, label: "Documents", pollMs: 200 });
await laptop.syncNow();
await until(() => existsSync(join(nasDir, "report.txt")));
console.log(`nas has report.txt: ${readFileSync(join(nasDir, "report.txt"), "utf8")}`);
console.log(`nas may write: ${nas.folder.replica.canWrite()}`);
writeFileSync(join(nasDir, "nas-notes.txt"), "kept on the NAS only");
await nas.syncNow();
rmSync(join(laptopDir, "report.txt"));
await laptop.syncNow();
await until(() => nas.folder.trashed().some((t) => t.path === "report.txt")); // gone from the folder, kept in the trash
console.log(`laptop sees nas-notes.txt: ${existsSync(join(laptopDir, "nas-notes.txt"))}`);
console.log(`nas trash: ${nas.folder.trashed().map((t) => t.path).join(", ")}`);
await laptop.close();
await nas.close();
await laptopMesh.stop();
await nasMesh.stop();nas: offered "Documents" by laptop, mode receive
nas has report.txt: Q3 report
nas may write: false
laptop sees nas-notes.txt: false
nas trash: report.txtWhat happens
- The laptop names who gets the folder in one line:
syncFolder(mesh, { path, with: { nas: "receive" } }). That sends the NAS an invitation (pvm-sync-offer). - The NAS decides:
onOfferhears the invitation,acceptjoins. Without that nothing is written to its disk. receivecomes with reading rights only. The NAS's own files stay on the NAS, unannounced; a file deleted on the laptop goes to the NAS's.hromada-trash, not into nothing.
09Publish a site to two servers
One machine builds the site, two servers serve it. Someone fixes a typo by hand on one server; the next release must win - without throwing the fix away.
// Publishing a site to two servers: the publisher's folder is in `send` mode (its changes go out, nothing comes back),
// the servers in `receive` (they take the published version; a hotfix made on a server stays there, and when the next
// version comes it steps aside as a local copy instead of being lost).
// Run it: node examples/09-publish-send.mjs
import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createMesh, joinMesh } from "hromada/mesh";
import { accept, onOffer, syncFolder } from "@hromada/sync";
const tmp = (n) => mkdtempSync(join(tmpdir(), n));
const until = async (ok) => { for (let i = 0; i < 400 && !(await ok()); i++) await new Promise((r) => setTimeout(r, 50)); };
const read = (d, p) => { try { return readFileSync(join(d, p), "utf8"); } catch { return undefined; } };
const pubMesh = await createMesh({ dir: tmp("mesh-pub-"), name: "publisher" });
const servers = [];
for (const name of ["web1", "web2"]) {
const mesh = await joinMesh(pubMesh.createInvite(), { dir: tmp(`mesh-${name}-`), name });
const dir = tmp(`${name}-`);
const s = { name, mesh, dir };
onOffer(mesh, async (offer) => { s.link = await accept(mesh, offer, { path: dir, pollMs: 200 }); });
servers.push(s);
}
await until(() => pubMesh.members().length === 2);
const site = tmp("site-");
writeFileSync(join(site, "index.html"), "<h1>v1</h1>");
const pub = await syncFolder(pubMesh, { path: site, mode: "send", with: { web1: "receive", web2: "receive" }, pollMs: 200 });
await pub.syncNow();
await until(() => servers.every((s) => read(s.dir, "index.html") === "<h1>v1</h1>"));
console.log(`published v1 to: ${servers.map((s) => s.name).join(", ")}`);
// a hotfix by hand on web1, then the next version from the publisher
writeFileSync(join(servers[0].dir, "index.html"), "<h1>v1 hotfix</h1>");
await servers[0].link.syncNow();
writeFileSync(join(site, "index.html"), "<h1>v2</h1>");
await pub.syncNow();
await until(() => servers.every((s) => read(s.dir, "index.html") === "<h1>v2</h1>"));
for (const s of servers) await s.link.syncNow();
console.log(`both serve v2: ${servers.every((s) => read(s.dir, "index.html") === "<h1>v2</h1>")}`);
const copy = readdirSync(servers[0].dir).find((n) => n.startsWith("index.local-"));
console.log(`web1 kept its hotfix as ${copy?.replace(/\d{8}-\d{6}/, "<time>")}: ${read(servers[0].dir, copy)}`);
console.log(`publisher still has: ${read(site, "index.html")}`);
await pub.close();
for (const s of servers) await s.link.close();
await pubMesh.stop();
for (const s of servers) await s.mesh.stop();published v1 to: web1, web2
both serve v2: true
web1 kept its hotfix as index.local-<time>.html: <h1>v1 hotfix</h1>
publisher still has: <h1>v2</h1>What happens
- The publisher's folder is in
sendmode: its changes go out, nothing of the others is written to its disk (override()makes its own the newest everywhere). - The servers are in
receivemode: they take every published version. - The hand-made hotfix met the next version, so it stepped aside as
index.local-<time>.htmlon that server, never announced;revert()would put local changes in the trash and take the network's state.
10A guest who may read for a while
You share slides with someone for the meeting, not forever.
// A guest who may read a folder for a while: invited with `until`, it gets what is there; once the time is up it is
// served nothing new (each side checks by its own clock) and keeps what it already copied.
// Run it: node examples/10-guest-until.mjs
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createMesh, joinMesh } from "hromada/mesh";
import { accept, onOffer, syncFolder } from "@hromada/sync";
const tmp = (n) => mkdtempSync(join(tmpdir(), n));
const until = async (ok) => { for (let i = 0; i < 400 && !(await ok()); i++) await new Promise((r) => setTimeout(r, 50)); };
const ownerMesh = await createMesh({ dir: tmp("mesh-owner-"), name: "owner" });
const guestMesh = await joinMesh(ownerMesh.createInvite(), { dir: tmp("mesh-guest-"), name: "guest" });
await until(() => !!ownerMesh.member("guest"));
const guestDir = tmp("guest-");
let guest;
onOffer(guestMesh, async (offer) => {
console.log(`guest: offered mode ${offer.mode}, for ${Math.round((offer.until - Date.now()) / 1000)} s`);
guest = await accept(guestMesh, offer, { path: guestDir, pollMs: 200 });
});
const dir = tmp("owner-");
writeFileSync(join(dir, "slides.pdf"), "the slides");
const end = Date.now() + 3000;
const owner = await syncFolder(ownerMesh, { path: dir, with: { guest: { mode: "receive", until: end } }, pollMs: 200 });
await owner.syncNow();
await until(() => existsSync(join(guestDir, "slides.pdf")));
console.log(`guest has slides.pdf: ${readFileSync(join(guestDir, "slides.pdf"), "utf8")}`);
await until(() => Date.now() > end + 300);
writeFileSync(join(dir, "notes.txt"), "after the meeting");
await owner.syncNow();
await guest.syncNow();
await new Promise((r) => setTimeout(r, 1000));
await guest.syncNow();
console.log(`after until - guest has notes.txt: ${existsSync(join(guestDir, "notes.txt"))}, still has slides.pdf: ${existsSync(join(guestDir, "slides.pdf"))}`);
await owner.close();
await guest.close();
await ownerMesh.stop();
await guestMesh.stop();guest: offered mode receive, for 3 s
guest has slides.pdf: the slides
after until - guest has notes.txt: false, still has slides.pdf: trueWhat happens
with: { guest: { mode: "receive", until } }invites the guest with reading rights that end atuntil.- Each side checks
untilby its own clock on every request: after it, the owner serves the guest nothing new, before any owner records a revocation. - The guest keeps what it already copied: nothing can delete files on someone else's disk.
How it is tested
The hard part of sync is not the happy path. So most of the effort went into a simulation that tries to break it.
| What | How much |
|---|---|
| Unit tests, with golden vectors from Certificate Transparency (Merkle) and RFC 8032 (ed25519) | 50 (adversarial revocation tests among them), run on Linux, macOS and Windows with Node 22 and 24 |
| Simulation fuzz: 3-5 replicas, random edits and deletes, partial out-of-order delivery, restarts, restores from old backups, VM clones, revocations | 5 000 worlds of 120-200 steps: all converge, no accepted version lost |
| Real folders: a crash injected at every step of a file replace, a full disk, files changing while read, links, reserved names, case collisions, a torn log | on NTFS, ext4 and APFS in CI |
| Disk fuzz: three real folders, random edits, deletes, syncs, exchanges and restarts | 200 worlds: the same files everywhere, every written content kept |
| Over a real hromada mesh: two replicas editing, a member with no grant, a late joiner, a forged and a replayed hello, a revoked replica | 5 tests; each security one fails when its guard is removed |
| Large folders (0.6): 100 000 files of 1-4 KB on Windows - first scan 183 s (the disk most of it), one edit reported by a watcher 0.9 s, one change received and applied 0.65 s + 0.9 s, ~4.2 KB of memory per file; the state updated in place is checked against computing it whole in every fuzz world | bench/scale.ts, bench/heap.ts; 600 engine worlds x 200 steps: 31 283 in-place updates, no difference |
Modes and invitations (0.5): receive and send on real folders, override and revert; an offer nobody accepted, a device that knows the folder id but was not invited, a guest past until, with limiting whom a replica serves | 9 tests and 3 examples; each guard of the invitations fails its test when removed |
| Ways to lose data found on the way (21 by the fuzzes, 1 by review), each fixed and written into the spec | 22 |
What comes next
.hromada-trash, ignore rules, safety stops (a missing disk, a mass delete or change), tests with a full disk and crashes mid-write.both, send, receive), invitations that write nothing without consent, guests with until, with and syncFolder(mesh, ...) in one line.sync({ paths }) and a watcher (with a fallback when the system runs out of watches), the state updated in place, applying proportional to what changed, measured at 100 000 files.explain(), status, a CLI and MCP tools for AI agents.The whole plan, with the guarantees and the stages: PLAN.md.
Words used here
- replica
- The folder on one machine.
- record
- One signed change: an edit, a delete, a conflict's outcome, a grant or a revocation.
- epoch
- One run of a replica. Every start opens a new one, chained to the last.
- conflict copy
- The version that did not win, kept beside the file under a name that is the same on every machine.
- owner
- The machine that created the folder, and those it made owners: they decide who may write.
- fuzz
- A test that runs thousands of random scenarios and checks that the promises hold in every one.
Questions people ask
Can I sync my folders with it today?
For trying, yes: version 0.6 keeps real folders in step between members of a hromada mesh with syncFolder(mesh, { path, with, watch: true }), in the modes both, send and receive, with invitations, guests and a watcher, up to 100 000 files a folder. A CLI comes in 0.7. Install it with npm install @hromada/sync; before 1.0 the API may change.
How is it different from Syncthing?
Syncthing is an application, and an excellent one. sync is meant to be a Node.js library you build into your own service, with a programmatic API, MCP tools for AI agents and explain() for every decision, over the hromada mesh.
What happens when two machines change the same file?
Both versions are kept (the hero's "no version lost" means every version the folder accepted; the trash's retention policy, stage 0.3, will remove old ones on purpose). Every machine picks the same winner by a fixed order and keeps the other version as a conflict copy with the same name everywhere. See it run.
What if a machine is restored from an old backup or cloned?
Every start of a replica opens a new epoch chained to the last, so a restored or cloned machine cannot claim changes it never saw, and nobody's version is hidden. See it run.
Is it secure?
Every record is signed by the machine that made it, in batches tied to the network and the folder; a relay cannot forge a change. Encryption in transit comes from hromada (Noise XX, AES-256-GCM); a replica proves its key, bound to its mesh device, before it is served anything.
What does it need?
Node.js 22.15 or later and one dependency, recpack (for content-defined chunks); signatures and hashes come from node:crypto.
When not to use it
- You need finished folder sync today. 0.6 moves files over the mesh, with modes, invitations and a watcher, but there is no CLI yet. Use Syncthing until 1.0.
- A backup. A synced copy follows every change, ransomware's included. Keep real backups.
- Huge folders. Measured at 100 000 files a folder (~420 MB of memory); more only after measurements.
- Phones and browsers. Node.js only.
More: README · PLAN.md · SPEC.md (the format and the rules) · SECURITY.md · CHANGELOG