'use strict' const test = require('brittle') const fs = require('fs') const os = require('os') const path = require('path') const b4a = require('b4a') const { GLOBAL_MESH_SEED, GLOBAL_MESH_ID, GLOBAL_MESH_NAME, globalMeshKey, globalMeshKeyPair, globalMeshKeyZ32, globalMeshTopic, isGlobalMeshKey } = require('../lib/global-mesh') const { MeshRegistry } = require('../lib/mesh-registry') test('global mesh key and topic are stable', (t) => { t.is(GLOBAL_MESH_SEED, 'flying-jib/global-mesh/v1') t.is(GLOBAL_MESH_ID, 'global-v2') t.is(GLOBAL_MESH_NAME, 'Flying Jib Global') const a = globalMeshKey() const b = globalMeshKey() t.ok(b4a.equals(a, b)) t.is(globalMeshKeyZ32(), globalMeshKeyZ32()) t.ok(isGlobalMeshKey(a)) t.ok(isGlobalMeshKey(globalMeshKeyZ32())) t.absent(isGlobalMeshKey('not-a-key')) const topic = globalMeshTopic() t.is(topic.byteLength, 32) t.ok(b4a.equals(topic, globalMeshTopic())) const kp = globalMeshKeyPair() t.ok(b4a.equals(kp.publicKey, a)) }) test('global mesh enroll + replicate to reader peer', { timeout: 60000 }, async (t) => { const dirA = fs.mkdtempSync(path.join(os.tmpdir(), 'fj-global-a-')) const dirB = fs.mkdtempSync(path.join(os.tmpdir(), 'fj-global-b-')) // No shared keyPair — unique local writers + well-known bootstrap (avoids fd-lock) const meshA = new MeshRegistry({ storageDir: dirA, bootstrap: globalMeshKey(), topic: globalMeshTopic(), meshId: GLOBAL_MESH_ID, name: GLOBAL_MESH_NAME, openMembership: true, global: true, swarm: false }) await meshA.ready() t.ok(meshA.key) t.ok(isGlobalMeshKey(meshA.key)) t.ok(meshA.global) const region = await meshA.enroll({ regionId: 'global-r1', worldKey: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', bounds: { minX: 0, maxX: 511, minZ: 0, maxZ: 511 }, name: 'Alpha' }) t.is(region.regionId, 'global-r1') t.is((await meshA.listRegions()).length, 1) const meshB = new MeshRegistry({ storageDir: dirB, bootstrap: globalMeshKey(), topic: globalMeshTopic(), meshId: GLOBAL_MESH_ID, name: GLOBAL_MESH_NAME, openMembership: true, global: true, swarm: false }) await meshB.ready() t.ok(isGlobalMeshKey(meshB.key)) const s1 = meshA.base.replicate(true) const s2 = meshB.base.replicate(false) s1.pipe(s2).pipe(s1) let seen = null const deadline = Date.now() + 20000 while (Date.now() < deadline) { await meshB.base.update().catch(() => {}) const list = await meshB.listRegions() seen = list.find((r) => r.regionId === 'global-r1') if (seen) break await new Promise((r) => setTimeout(r, 200)) } t.ok(seen, 'reader peer should see enrolled region') if (seen) t.is(seen.name, 'Alpha') s1.destroy() s2.destroy() await meshA.close() await meshB.close() })