{"name":"hyperbee2","version":"2.0.1","author":{"url":"@mafintosh","name":"Mathias Buus"},"license":"Apache-2.0","_id":"hyperbee2@2.0.1","maintainers":[{"name":"mafintosh","email":"mathiasbuus@gmail.com"}],"homepage":"https://github.com/mafintosh/hyperbee2","bugs":{"url":"https://github.com/mafintosh/hyperbee2/issues"},"dist":{"shasum":"e0c68e9839a5c3d196f0e694c742109cb7aa8bf4","tarball":"http://registry-npm.ywwl.com/hyperbee2/download/hyperbee2-2.0.1.tgz","fileCount":15,"integrity":"sha512-M2akqJQb9FC+VkNb7hJd6VYAzCZiP+YPWnOGjV1iRLK+8qywC9BiMXCPuex+xRs6y/loPf5Jb/UGYobqTBHFiA==","signatures":[{"sig":"MEUCIG35ZT2rEXZmbsE5tQSj+pcmbUCw8JcCaNVo9nryRseNAiEA4QZ5wPhsrwcZH3uxnsZowIo+Pq1Jfn9rlj2kgkDvPoE=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":87686,"size":17205,"noattachment":false,"key":"/hyperbee2/-/hyperbee2-2.0.1.tgz"},"main":"index.js","gitHead":"761db780a26bd54eb81009d65cefd9a64c1636e2","scripts":{"lint":"lunte && prettier . --check","test":"node test/all.js","format":"prettier . --write","test:bare":"bare test/all.js","test:generate":"brittle -r test/all.js test/*.js"},"_npmUser":{"name":"mafintosh","email":"mathiasbuus@gmail.com"},"repository":{"url":"git+https://github.com/mafintosh/hyperbee2.git","type":"git"},"_npmVersion":"11.7.0","description":"btree","directories":{},"_nodeVersion":"22.16.0","dependencies":{"b4a":"^1.6.7","streamx":"^2.22.1","hypercore":"^11.15.0","scope-lock":"^1.2.4","hyperschema":"^1.14.0","compact-encoding":"^2.16.1","protocol-buffers-encodings":"^1.2.0"},"_hasShrinkwrap":false,"devDependencies":{"lunte":"^1.4.0","brittle":"^3.18.0","prettier":"^3.6.2","corestore":"^7.4.5","prettier-config-holepunch":"^2.0.0"},"_npmOperationalInternal":{"tmp":"tmp/hyperbee2_2.0.1_1768044648682_0.6039772808259449","host":"s3://npm-registry-packages-npm-production"},"readme":"# hyperbee2\n\n```\nnpm install hyperbee2\n```\n\nNext major version for [hyperbee](https://github.com/holepunchto/hyperbee).\nWill be merged in there and released a new major when fully done.\n\nAn append-only B-tree on top of a [Hypercore][hypercore].\n\n## Usage\n\n```js\nimport Hyperbee2 from 'hyperbee2'\nimport Corestore from 'corestore'\n\n// Create/open tree\nconst tree = new Hyperbee2(new Corestore('./mystore'))\n\n// Wait for tree to become available\nawait tree.ready()\n\n// Write some values to tree\nconst batch = tree.write()\nbatch.tryPut(Buffer.from('name'), Buffer.from('example'))\nbatch.tryPut(Buffer.from('email'), Buffer.from('example@example.com'))\nawait batch.flush()\n\n// Read values from tree\nconst name = await tree.get(Buffer.from('name'))\nconst email = await tree.get(Buffer.from('email'))\n\n// Print values\nconsole.log(name.value.toString()) // example\nconsole.log(email.value.toString()) // example@example.com\n```\n\n## License\n\nApache-2.0\n\n## API\n\n### Hyperbee\n\n#### `const db = new Hyperbee(store, [options])`\n\nMake a new Hyperbee2 instance. The `store` argument expects a\n[Corestore][corestore].\n\nOptions include:\n\n```js\n{\n  key: null,               // Buffer or String. Key of Hypercore to load via Corestore\n  maxCacheSize: 4096,      // Max number of nodes to keep in NodeCache\n  core: Hypercore(...),    // Hypercore within the Corestore to use (defaults to loading key, or using name='bee')\n  view: false,             // Is this a view of an open Hyperbee? (i.e. do not close underlying store)\n  writable: true,          // Is append / truncate allowed on the underlying Hypercore?\n  unbatch: 0,              // Number of write batches to rollback during bootstrap\n  autoUpdate: false,       // Reload root node when underlying Hypercore is appended to?\n  preload: null,           // A function called by ready() after the Hypercore is ready. Can be async.\n  wait: true,              // Wait for Hypercore to download blocks\n  mappings: false,         // Follow core mappings, both the ones given to write() and\n                           // the ones found in the tree. Off by default, set to true to opt in.\n}\n```\n\nMappings are persisted next to the core table on the next write, so readers\nthat open the tree later resolve them without being given them. They are\nopt-in: a Hyperbee only writes and reads them with `mappings: true`.\n\n#### `await db.ready()`\n\nEnsures the underlying [Hypercore][hypercore] is ready and prepares the Hyperbee\nfor use. If `autoUpdate` was set to true in the constructor's options,\nthis will start watching the [Hypercore][hypercore] for new writes.\n\nCalling `get()` will call this automatically for you.\n\n#### `await db.close()`\n\nFully close the Hyperbee. If it is not a view on another Hyperbee,\nthis will also close it's [Hypercore][hypercore].\n\n#### `db.head()`\n\nReturns an object with the following properties:\n\n```\n{\n  length,  // Number of blocks from the start of Hypercore that apply to this tree.\n  key,     // Buffer or null. The key of the underlying Hypercore.\n}\n```\n\nIf the Hyperbee is not ready, this will return null.\n\n#### `db.isGenesis()`\n\nReturns true if the tree is empty, i.e. no blocks apply to it yet and `db.head().length` is 0.\nReturns false if the Hyperbee is not ready.\n\n#### `db.cache`\n\nRead only. The NodeCache used by this Hyperbee.\n\n#### `db.core`\n\nRead only. The [Hypercore][hypercore] used by this Hyperbee.\n\n#### `db.opening`\n\nRead only. A Promise that resolves to `undefined` once the [Corestore][corestore]\nis ready.\n\n#### `db.closing`\n\nRead only. Initially null. When `db.close()` is called, this is set to\na Promise that resolves to `undefined` when the close completes.\n\n#### `db.opened`\n\nRead only. Boolean indicating whether the [Corestore][corestore] has opened.\n\n#### `db.closed`\n\nRead only. Boolean indicating whether the [Corestore][corestore] has closed.\n\n#### `db.replicate()`\n\nCalls `replicate` on underlying [Corestore][corestore].\n\n#### `await db.cores([options])`\n\nThe keys of the cores the tree reads from, mapped: the core the root lives on\nfirst, then the cores it references. Options:\n\n```js\n{\n  local: true,       // Boolean. Include the local core\n  recursive: false,  // Boolean. Also walk the core tables of every core reached\n  timeout: ...,      // Number. Timeout for the checkpoint reads\n  wait: ...          // Boolean. Wait for checkpoint blocks to download\n}\n```\n\nWith `recursive` the result covers everything the tree can reach through core\ntables, one checkpoint read per core. It is a superset of what the current\nroot references, as tables only ever grow.\n\n#### `db.checkout([options])`\n\nReturns a new Hyperbee as a view on the underlying [Hypercore][hypercore].\n\nOptions:\n\n```js\n{\n  writable: false,           // Boolean. Will the new tree be writable?\n  length: this.core.length,  // Number. Length of blocks used from the Hypercore\n  key: null,                 // Buffer or null. Key of the Hypercore\n  timeout: this.timeout,     // Number. Wait at most this many milliseconds per Hypercore read (0 means no timeout)\n  wait: this.wait,           // Boolean. Wait for Hypercore to download blocks\n}\n```\n\n#### `db.move([options])`\n\nReplaces the root of the tree with a new entry, potentially using a new\n[Hypercore][hypercore].\n\nOptions:\n\n```js\n{\n  writable: this.writable,   // Boolean. Is this tree writable after the move?\n  length: this.core.length,  // Number. Length of blocks used from the Hypercore\n  key: null,                 // Buffer or null. Key of the Hypercore\n}\n```\n\nIf `key` is mapped the core it maps to is opened instead.\n\n#### `db.snapshot([options])`\n\nReturns a new Hyperbee that is a read only view of the current tree.\n\nOptions:\n\n```js\n{\n  timeout: this.timeout,     // Number. Wait at most this many milliseconds per Hypercore read (0 means no timeout)\n  wait: this.wait,           // Boolean. Wait for Hypercore to download blocks\n}\n```\n\n#### `db.undo(n, [options])`\n\nReturns a new Hyperbee that is a writable view of the current tree,\nwith the last `n` write batches ignored.\n\nOptions:\n\n```js\n{\n  timeout: this.timeout,     // Number. Wait at most this many milliseconds per Hypercore read (0 means no timeout)\n  wait: this.wait,           // Boolean. Wait for Hypercore to download blocks\n}\n```\n\n#### `db.write([options])`\n\nReturns a [WriteBatch](#writebatch) object through which the tree can be updated.\n\nOptions:\n\n```js\n{\n  length: -1,                     // Length of blocks used from the Hypercore\n                                  // (i.e. what point in the hypercore is the write\n                                  // going to extend when flush() is called?).\n                                  // If -1, the length will be calculated on flush()\n                                  // using root.seq + 1.\n  key: null,                      // Buffer or null. Key of the Hypercore.\n  autoUpdate: true,               // Boolean .Should Hyperbee automatically reflect updates\n                                  // after each flush()?\n  mappings: null,                // [{ from, to }]. Read core `from` as core `to`, which holds the\n                                  // same blocks, and write them into this checkpoint, even with\n                                  // nothing else to write. Readers of the tree learn them from it.\n                                  // Ignored unless the Hyperbee has `mappings: true`\n  compat: false,                  // Boolean. Write blocks compatible with Hyperbee 1?\n  type: encoding.TYPE_LATEST,     // Number. Block format to use.\n  inlineValueSize: 1024,          // Values smaller than this byte length are\n                                  // written inline in the node. Larger values\n                                  // are referenced via a pointer into the block.\n  preferredBlockSize: 4096,       // Try to write blocks of approximately this size\n                                  // when flushing updates.\n}\n```\n\nErrors:\n\n- If the tree is not writable this will throw an Error\n\n#### `db.createReadStream([options])`\n\nReturns a [streamx][streamx] Readable Stream. This is async iterable.\n\nOptions:\n\n```js\n{\n  prefetch: true,        // Prefetch future blocks after yielding an entry?\n  reverse: false,        // Iterate backwards over keys?\n  limit: -1,             // Max number of entries to yield (-1 means no limit)\n  gte: undefined,        // Buffer. Key lower bound (inclusive)\n  gt: undefined,         // Buffer. Key lower bound (exclusive)\n  lte: undefined,        // Buffer. Key upper bound (inclusive)\n  lt: undefined,         // Buffer. Key upper bound (exclusive)\n  highWaterMark: 16384,  // Size of read ahead buffer calculated\n                         // as: number of entries * 1024\n}\n```\n\nIterating over the stream will yield the following properties:\n\n```js\n{\n  core,    // Hypercore: the hypercore the entry is stored in\n  offset,  // Number: the index of the entry in the block\n  seq,     // Number: the sequence number of the block in the hypercore\n  key,     // Buffer: the key of the entry\n  value,   // Buffer: the value of the entry\n}\n```\n\nExample:\n\n```js\nfor await (const data of b.createReadStream()) {\n  console.log(data.key, '-->', data.value)\n}\n```\n\n#### `db.createDiffStream(right, [options])`\n\nReturns a [streamx][streamx] Readable Stream that provides\nsynchronized iteration over two trees. This is async iterable.\n\nOptions: Same as options for `createReadStream()`.\n\nIterating over the stream will yield the same properties as\n`createReadStream()` split into left (`db` in this case) and right\n(`right` parameter).\n\n```js\n{\n  left: {core, offset, seq, key, value},   // see createReadStream()\n  right: {core, offset, seq, key, value},  // see createReadStream()\n}\n```\n\nExample:\n\n```js\nimport Hyperbee from './index.js'\nimport Corestore from 'corestore'\n\nconst b1 = new Hyperbee(new Corestore('./store1'))\nconst b2 = new Hyperbee(new Corestore('./store2'))\n\nawait b1.ready()\nawait b2.ready()\n\nconst w1 = b1.write()\nw1.tryPut(Buffer.from('A'), Buffer.from('A'))\nw1.tryPut(Buffer.from('B'), Buffer.from('B'))\nw1.tryPut(Buffer.from('C'), Buffer.from('C'))\nawait w1.flush()\n\nconst w2 = b2.write()\nw2.tryPut(Buffer.from('A'), Buffer.from('A'))\nw2.tryPut(Buffer.from('C'), Buffer.from('C'))\nw2.tryPut(Buffer.from('E'), Buffer.from('E'))\nawait w2.flush()\n\nfor await (const data of b1.createDiffStream(b2)) {\n  console.log(data.left?.key.toString(), data.right?.key.toString())\n}\n```\n\nExample output:\n\n```js\nA A\nB undefined\nC C\nundefined E\n```\n\n#### `db.createChangesStream([options])`\n\nReturns a [streamx][streamx] Readable Stream for iterating over all\nbatches previously written to the tree. This is async iterable.\n\nOptions:\n\n```js\n{\n  head: null,            // null means use this.tree.head()\n  highWaterMark: 16384,  // Size of read ahead buffer calculated\n                         // as: number of entries * 1024\n  timeout: 0,            // Wait at most this many milliseconds (0 means no timeout).\n                         // Defaults to the value of the Hyperbee's timeout option.\n  wait: true,            // Wait for Hypercore to download blocks\n                         // Defaults to the value of the Hyperbee's wait option.\n  prefetch: 128,         // Download this many blocks below the current head in\n                         // the background while iterating. 0 disables it.\n}\n```\n\nIterating over the stream will yield:\n\n```js\n{\n  head: {\n    length,  // Number: number of blocks from the start of Hypercore\n             // that apply to this version of the tree\n    key,     // Buffer or null: the key of the Hypercore for this version\n  },\n  tail: {\n    length,  // Number: number of blocks from the start of Hypercore\n             // that apply to the previous version of the tree\n    key,     // Buffer or null: the key of the Hypercore for the previous\n             // version\n  },\n  batch: [   // Blocks written in this batch\n    {tree, keys, values, cohorts, metadata, ...},\n    ...\n  ],\n}\n```\n\n#### `await db.peek([range])`\n\nAttempts to get the first entry within the given range.\n\nReturns `null` if no entry exists in the range, or an object with\nthe following properties on success:\n\n```js\n{\n  core,    // Hypercore: the hypercore the entry is stored in\n  offset,  // Number: the index of the entry in the block\n  seq,     // Number: the sequence number of the block in the hypercore\n  key,     // Buffer: the key of the entry\n  value,   // Buffer: the value of the entry\n}\n```\n\nThe `range` argument accepts the same properties as the options for\n[`createReadStream()`](#dbcreatereadstreamoptions).\n\n#### `await db.download([range])`\n\nFetches all entries in the given range. The promise resolves once\nall matching entries have been fetched.\n\nRather than iterating the entries in order, the tree nodes in the range are\nwalked with up to `parallelism` fetches in flight at a time, visiting the\nchildren of each node in random order so the requests spread over the tree.\n\n```js\n{\n  gte,          // Buffer: only download entries with keys >= this\n  gt,           // Buffer: only download entries with keys > this\n  lte,          // Buffer: only download entries with keys <= this\n  lt,           // Buffer: only download entries with keys < this\n  parallelism,  // Number: max concurrent fetches, defaults to 1024\n  timeout,      // Number: wait at most this many milliseconds (0 means no timeout)\n}\n```\n\n#### `await db.get(key, [options])`\n\nAttempt to find an entry by its key. `key` is a buffer.\n\nReturns `null` if no entry exists in the range, or an object with\nthe following properties on success:\n\n```js\n{\n  core,    // Hypercore: the hypercore the entry is stored in\n  offset,  // Number: the index of the entry in the block\n  seq,     // Number: the sequence number of the block in the hypercore\n  key,     // Buffer: the key of the entry\n  value,   // Buffer: the value of the entry\n}\n```\n\nOptions:\n\n```js\n{\n  timeout,  // Number: wait at most this many milliseconds (0 means no timeout)\n  wait,     // Boolean: wait for Hypercore to download blocks\n}\n```\n\n#### `b.on('ready', listener)`\n\nEmitted once the Hyperbee is ready for use.\n\n##### `b.on('update', listener)`\n\nEmitted in the following scenarios:\n\n- When a `WriteBatch` is flushed and its `autoUpdate` option is `true`\n  (the default).\n- When the underlying core is appended to (locally or remotely) and the\n  `Hyperbee`'s `autoUpdate` option is `true`.\n- After a `move()` call on the `Hyperbee`.\n- After a rollback completes because the `unbatch` option to the\n  `Hyperbee` constructor was greater than `0`.\n\nWarning: this event may be emitted multiple times for the same\nupdate if `autoUpdate` is set on the `Hyperbee` and on `WriteBatch`:\n\n```js\nconst b = new Hyperbee(store, { autoUpdate: true })\nb.on('update', () => console.log('New update'))\n\nconst w = b.write(/* autoUpdate is true by default */)\nw.tryPut(Buffer.from('key'), Buffer.from('value'))\nawait w.flush()\n\n// The following will be printed:\n// New udpate\n// New udpate\n```\n\n##### `b.on('close', listener)`\n\nEmitted one the `close()` method completes.\n\n### WriteBatch\n\nA WriteBatch can be constructed via Hyperbee's [write()](#dbwriteoptions)\nmethod. Using a batch, multiple updates can be queued then applied together.\n\n```js\nconst batch = b.write();\nbatch.tryPut(Buffer.from('key'), Buffer.from('value');\nawait batch.flush();\n```\n\n**Warning:** WriteBatch does not hold an exclusive lock on the database\nwhile queuing operations unless you call `lock()`. By default, the\nlock is only acquired when the operations are flushed. So be careful\nabout building concurrent batches:\n\n```js\nimport Hyperbee from './index.js'\nimport Corestore from 'corestore'\n\nconst b = new Hyperbee(new Corestore('./store'))\nawait b.ready()\n\nconst w1 = b.write()\nw1.tryPut(Buffer.from('name'), Buffer.from('Sneezy'))\n\nconst w2 = b.write()\nw2.tryPut(Buffer.from('name'), Buffer.from('Sleepy'))\nw2.tryPut(Buffer.from('email'), Buffer.from('sleepy@example.com'))\n\n// Be careful about application order vs. order the operations\n// were queued when building batches concurrently.\nawait w2.flush()\nawait w1.flush()\n\nfor await (const data of b.createReadStream(b)) {\n  console.log(data.key.toString(), '-->', data.value.toString())\n}\n\n// Output: (email and name mismatch)\n//\n// email --> sleepy@example.com\n// name --> Sneezy\n```\n\n### `await batch.lock()`\n\nAquires an exclusive write lock now instead of waiting for `flush()`\nto be called. No writes will occur until this batch is closed allowing\nyou to keep a consistent view of the database while building the batch.\n\n#### `batch.tryPut(key, value)`\n\nQueues an operation to associate `key` with `value`. Any existing entry\nfor `key` will be overwritten. Both `key` and `value` are buffers.\n\n#### `batch.tryDelete(key)`\n\nQueues an operation to remove the entry with `key`, if it exists. If it\ndoes not exist, this method does nothing (and will not throw). `key` is a\nbuffer.\n\n#### `batch.tryClear()`\n\nQueues an operation to clear all entries from the tree.\n\n#### `await batch.flush()`\n\nAquires an exclusive write lock and applies the operations queued in this\nbatch to the tree, clearing the queue.\n\n**Warning:** continuing to use the batch after flushing can cause unpredictable\nbehavior. Batches applied after the first flush will be 'unapplied' if you\nflush again later. This can lead to accidentally removing data from the tree.\n\n```js\nimport Hyperbee from './index.js'\nimport Corestore from 'corestore'\n\nconst b = new Hyperbee(new Corestore('./store'))\nawait b.ready()\n\nconst w1 = b.write()\nw1.tryPut(Buffer.from('name'), Buffer.from('Sneezy'))\n\nconst w2 = b.write()\nw2.tryPut(Buffer.from('name'), Buffer.from('Sleepy'))\nw2.tryPut(Buffer.from('email'), Buffer.from('sleepy@example.com'))\n\nawait w1.flush()\nawait w2.flush()\n\n// Warning: flushing w1 again will unapply w2!\nw1.tryPut(Buffer.from('active'), Buffer.from('false'))\nawait w1.flush()\n\nfor await (const data of b.createReadStream(b)) {\n  console.log(data.key.toString(), '-->', data.value.toString())\n}\n\n// Output: (name has reverted to 'Sneezy', email is missing)\n//\n// active --> false\n// name --> Sneezy\n```\n\n#### `batch.close()`\n\nCloses the batch without flushing operations. Subsequent attempts\nto flush the batch will result in an error.\n\n[hypercore]: https://github.com/holepunchto/hypercore\n[corestore]: https://github.com/holepunchto/corestore\n[streamx]: https://github.com/mafintosh/streamx\n","publish_time":1768044648825,"_cnpm_publish_time":1768044648825,"dist-tags":{"latest":"2.21.4"}}