This repository has been archived by the owner on Aug 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
resolver.js
76 lines (67 loc) · 1.82 KB
/
resolver.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
66
67
68
69
70
71
72
73
74
75
76
'use strict'
const CID = require('cids')
const util = require('./util')
/**
* Resolves a path within a PB block.
*
* If the path resolves half-way to a link, then the `remainderPath` is the part
* after the link that can be used for further resolving
*
* Returns the value or a link and the partial missing path. This way the
* IPLD Resolver can fetch the link and continue to resolve.
*
* @param {Uint8Array} binaryBlob - Binary representation of a PB block
* @param {string} [path='/'] - Path that should be resolved
*/
exports.resolve = (binaryBlob, path = '/') => {
let node = util.deserialize(binaryBlob)
const parts = path.split('/').filter(Boolean)
while (parts.length) {
const key = parts.shift()
// @ts-ignore
if (node[key] === undefined) {
// There might be a matching named link
for (const link of node.Links) {
if (link.Name === key) {
return {
value: link.Hash,
remainderPath: parts.join('/')
}
}
}
// There wasn't even a matching named link
throw new Error(`Object has no property '${key}'`)
}
// @ts-ignore
node = node[key]
if (CID.isCID(node)) {
return {
value: node,
remainderPath: parts.join('/')
}
}
}
return {
value: node,
remainderPath: ''
}
}
/**
* Return all available paths of a block.
*
* @generator
* @param {Uint8Array} binaryBlob - Binary representation of a PB block
* @yields {string} - A single path
*/
exports.tree = function * (binaryBlob) {
const node = util.deserialize(binaryBlob)
// There is always a `Data` and `Links` property
yield 'Data'
yield 'Links'
for (let ii = 0; ii < node.Links.length; ii++) {
yield `Links/${ii}`
yield `Links/${ii}/Name`
yield `Links/${ii}/Tsize`
yield `Links/${ii}/Hash`
}
}