All files index.js

100% Statements 105/105
100% Branches 37/37
100% Functions 17/17
100% Lines 104/104
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 2271x 1x 1x     77x 77x   58x   19x       124x       3x 3x         49x 49x 72x 72x 41x 11x   30x       49x     1x         6x 6x 6x       19x 19x 2x   17x 17x 17x 14x 14x 14x   17x 17x 17x 17x   17x 17x                       5x 5x     5x         5x     5x 2x 2x 2x     5x 1x   5x 5x                       10x 10x 10x       15x 15x 15x 42x   42x 10x   32x   16x     32x 8x   24x 24x 24x 24x 17x   7x       15x                               25x 25x 24x 24x 9x 9x   24x 14x 14x 14x 21x 21x   14x     25x       19x   19x 19x   19x 19x 19x 19x 19x 19x 19x                         8x       8x 8x 3x 3x 3x   8x 8x         15x 3x   15x    
const CID = require('cids')
const multihashes = require('multihashes')
const assert = require('assert')
 
function isValidCID (link) {
  try {
    CID.isCID(new CID(link))
  } catch (e) {
    return false
  }
  return true
}
 
function isObject (obj) {
  return typeof obj === 'object' && obj !== null
}
 
function clearObject (myObject) {
  for (var member in myObject) {
    delete myObject[member]
  }
}
 
function findLeafLinks (node) {
  let links = []
  for (const name in node) {
    const edge = node[name]
    if (isObject(edge)) {
      if (edge['/'] !== undefined && !isValidCID(edge)) {
        links.push(edge)
      } else {
        links = findLeafLinks(edge).concat(links)
      }
    }
  }
  return links
}
 
module.exports = class Graph {
  /**
   * @param {Object} ipfsDag an instance of [ipfs.dag](https://github.com/ipfs/interface-ipfs-core/tree/master/API/dag#dag-api)
   */
  constructor (ipfsDag) {
    assert(ipfsDag, 'ipld-graph must have an instance of ipfs.dag')
    this._dag = ipfsDag
    this._loading = new Map()
  }
 
  _loadCID (node, link, dropOptions = false) {
    const loadingOp = this._loading.get(link)
    if (loadingOp) {
      return loadingOp
    } else {
      const promise = new Promise(async (resolve, reject) => {
        const cid = new CID(link)
        if (!dropOptions) {
          node.options = {}
          node.options.format = cid.codec
          node.options.hashAlg = multihashes.decode(cid.multihash).name
        }
        let value = (await this._dag.get(cid)).value
        node['/'] = value
        this._loading.delete(link)
        resolve()
      })
      this._loading.set(link, promise)
      return promise
    }
  }
 
  /**
   * sets a value on a root object given its path
   * @param {Object} node
   * @param {String} path
   * @param {*} value
   * @return {Promise}
   */
  async set (node, path, value) {
    path = formatPath(path)
    value = {
      '/': value
    }
    const last = path.pop()
    let {
      value: foundVal,
      remainderPath: remainder,
      parent
    } = await this._get(node, path)
 
    // if the found value is a litaral attach an object to the parent object
    if (!isObject(foundVal)) {
      const pos = path.length - remainder.length - 1
      const name = path.slice(pos, pos + 1)[0]
      foundVal = parent[name] = {}
    }
    // extend the path for the left over path names
    for (const name of remainder) {
      foundVal = foundVal[name] = {}
    }
    foundVal[last] = value
    return node
  }
 
  /**
   * traverses an object's path and returns the resulting value in a Promise
   * @param {Object} node
   * @param {String} path
   * @param {boolean} dropOptions - whether to add the encoding options of the
   * nodes when loading from IPFS. Defaults to true
   * @return {Promise}
   */
  async get (node, path, dropOptions) {
    path = formatPath(path)
    const {value} = await this._get(node, path, dropOptions)
    return value
  }
 
  async _get (node, path, dropOptions) {
    let parent = node
    path = path.slice(0)
    while (1) {
      const link = node['/']
      // if there is a link, traverse throught it
      if (isValidCID(link)) {
        await this._loadCID(node, link, dropOptions)
      } else {
        if (link !== undefined) {
          // link is a POJO
          node = link
        }
        // traverse through POJOs
        if (!path.length) {
          break
        }
        const name = path.shift()
        const edge = node[name]
        node = edge
        if (isObject(edge)) {
          parent = node
        } else {
          break
        }
      }
    }
    return {
      value: node,
      remainderPath: path,
      parent: parent
    }
  }
 
  /**
   * Resolves all the links in an object and does so recusivly for N `level`
   * @param {Object} node
   * @param {Integer} levels
   * @param {boolean} dropOptions - whether to add the encoding options of the
   * nodes when loading from IPFS. Defaults to true
   * @return {Promise}
   */
  async tree (node, levels = 1, dropOptions) {
    const orignal = node
    if (node) {
      const link = node['/']
      if (isValidCID(link)) {
        await this._loadCID(node, link, dropOptions)
        node = node['/']
      }
      if (levels && isObject(node)) {
        levels--
        const promises = []
        for (const name in node) {
          const edge = node[name]
          promises.push(this.tree(edge, levels, dropOptions))
        }
        await Promise.all(promises)
      }
    }
    return orignal
  }
 
  _flush (node, opts) {
    const awaiting = []
 
    const links = findLeafLinks(node)
    links.forEach(link => awaiting.push(this._flush(link, opts)))
 
    return Promise.all(awaiting).then(() => {
      const link = node['/']
      let options = Object.assign(opts, node.options)
      delete node.options
      return this._dag.put(link, options).then(cid => {
        const str = cid.toBaseEncodedString()
        node['/'] = str
      })
    })
  }
 
  /**
   * flush an object to ipfs returning the resulting CID in a promise
   * @param {Object} node
   * @param {Object} opts - encoding options for [`dag.put`](https://github.com/ipfs/interface-ipfs-core/tree/master/API/dag#dagput)
   * @param {Function} opts.onHash - a callback that happens on each merklized node. It is given two arguments `hash` and `node` which is the node that was hashed
   * @return {Promise}
   */
  async flush (node, opts = {}) {
    const defaults = {
      format: 'dag-cbor',
      hashAlg: 'sha2-256'
    }
    Object.assign(opts, defaults)
    if (!node['/']) {
      const oldRoot = Object.assign({}, node)
      clearObject(node)
      node['/'] = oldRoot
    }
    await this._flush(node, opts)
    return node
  }
}
 
function formatPath (path) {
  if (!path.split) {
    path = path.toString()
  }
  return path.split('/')
}