OverviewFilesCommitsIssuesDocsReleasesPeers

keet-cli / keet-core-4.14.4-pretty / lib / bundle / index.js

79 lines · javascript ref:
const e = require("ready-resource"),
  r = require("bundlebee"),
  t = require("hypercore"),
  s = require("b4a"),
  i = require("hypercore/messages"),
  o = require("bare-zlib"),
  { EXPERIMENTAL: n } = require("../../schema/versions"),
  { KeetContractError: u } = require("../core/contract/errors"),
  a = require("../core/contract/index.js"),
  c = require("compact-encoding"),
  h = c.array(i.wire.data),
  d = 12,
  l = 25,
  _ = "/lib/contract/index.js",
  b = "/lib/core/contract/index.js"
function y(e) {
  return new Promise((r, t) => {
    o.gunzip(e, (e, s) => {
      if (e) return t(e)
      r(s)
    })
  })
}
module.exports = class extends e {
  constructor(e, t, { hydrate: s = !1 } = {}) {
    if ((super(), (this.keet = e), (this._ownsBee = !e.opts.bundlebee), e.opts.bundlebee))
      this._bee = e.opts.bundlebee
    else {
      const s = e.opts.bundlesStore || e.rootCorestore.namespace(t)
      this._bee = new r(s, { key: e._bundlesKey, length: e._bundlesLength })
    }
    ;((this._bundles = {}), (this._routers = {}), (this._hydrate = s))
  }
  get core() {
    return this._bee.core
  }
  async _open() {
    if (!this._hydrate) return this._bee.ready()
    let e = []
    try {
      const r = require("./latest-bundle.trace.js")
      e = c.decode(h, await y(r))
    } catch (e) {
      this.keet.onerror(e, { prefix: "TRACE_LOAD_ERROR" })
    }
    for (const r of e)
      try {
        await this._bee.core.applyProof(r)
      } catch (e) {
        if (r.manifest) {
          const e = t.key(r.manifest)
          if (!s.equals(e, this._bee.core.key)) continue
        }
        this.keet.onerror(e, { prefix: "TRACE_APPLY_ERROR" })
      }
    await this._bee.ready()
  }
  _close() {
    if (this._ownsBee) return this._bee.close()
  }
  async loadBundle(e) {
    if (this._bundles[e]) return this._bundles[e]
    if (e >= n) return ((this._bundles[e] = a), a)
    const r = e < d ? d : e,
      t = r >= l ? b : _,
      s = await this._bee.findABI(r)
    if (!s) throw u.BUNDLE_NOT_AVAILABLE(r)
    const i = await this._bee.load(new URL("../..", module.url), t, s)
    return ((this._bundles[e] = i.exports), this._bundles[e])
  }
  async loadRouter(e) {
    return (
      this._routers[e] ||
        (await this.loadBundle(e), (this._routers[e] = this._bundles[e].createRouter())),
      this._routers[e]
    )
  }
}