This repository has been archived by the owner on Jan 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (61 loc) · 1.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var drive = require('hyperdrive/lib/messages.js')
var tree = require('append-tree/messages.js')
var ram = require('random-access-memory')
var hypercore = require('hypercore')
var discoverySwarm = require('discovery-swarm')
var defaults = require('dat-swarm-defaults')
var duplexify = require('duplexify')
var pump = require('pump')
var through = require('through2')
module.exports = function (key) {
var duplex = duplexify.obj()
var feed = hypercore(function (filename) {
return ram()
}, key)
var swarmOpts = {
hash: false,
stream: function (opts) {
opts.live = true
return feed.replicate(opts)
}
}
var sw = discoverySwarm(defaults(swarmOpts))
sw.listen()
feed.on('ready', function () {
sw.join(feed.discoveryKey)
feed.update(function () {
var first = true
var isHyperdrive = false
var stream = feed.createReadStream()
var decode = through.obj(function (obj, enc, next) {
if (first) {
first = false
try {
var idx = drive.Index.decode(obj)
} catch (e) {
return next(null, obj)
}
if (idx.type === 'hyperdrive') {
isHyperdrive = true
return next(null, idx)
} else {
return next(null, obj)
}
}
if (isHyperdrive) {
var node = tree.Node.decode(obj)
node.value = drive.Stat.decode(node.value)
return next(null, node)
}
return next(null, obj)
})
pump(stream, decode)
duplex.setReadable(decode)
})
})
duplex.close = function () {
sw.close()
feed.close()
}
return duplex
}