{"bugs":{"url":"https://github.com/datproject/sdk/issues"},"dist":{"shasum":"6149d8ca10b45b356ad5f1608852c54a1184b3f6","tarball":"https://registry.npmjs.org/dat-sdk/-/dat-sdk-2.0.0-2.tgz","fileCount":14,"integrity":"sha512-ExWw9sTIl2NaCwH7k6FdOBVF+2Tx+rngTJnOtgIBIDgEF4pzFjyXDV/3UA4NJjJLpns6jRkxvvBQpVTt3wTS2w==","signatures":[{"sig":"MEUCIF4Tm+nNCmEjWS+fR8U9bcp3xs3hVFfrtC6pO2CyHIprAiEAzn7APJrdIq3Jgbi386Az/EncsG4EHp4EQjuNuGLr3fU=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":63300,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeQwN7CRA9TVsSAnZWagAAuyQP/jgD2rTBD34rqTmkXvCm\nlKTV75KGVpuYWnlNkSmp4aEl0QCmd7Qi+fOilEbJ4JCyPbr/ns1OiA/Yg/k4\nWt5HnlOKcNWfqmstITkC6vTVEYgnda18aAFvt2COw43DzjfdNgHQCu+v3UVg\nkfAHKgu7U8lcl5t8nGSz4rbKXbRiXqdwPTGAuAOaldszHuS0upWzoD/rrvAc\nwD0zDd4WgWb0fX/8OXA8Qm2249sg+F5pdrpf27f9zNOJSnQPSgt5vDdv/f4Z\nrd0FPsG8IhZSGd/74VuN30cPMDWPHuRm9S1B3gndDjDupWphRRtoXNdUh5v8\ncInXRKXiKgjnqu/WpM+ah/2Hm0LPFkxBC/ES6M5X6bU/T8vov5HaOye9onmd\nXS0gQeubilX1P+dYy2osxSFWEcKCma/xk4sH+RP+eoC31JxNWJxoCU1aGQyb\ngRPqZM9f2TYX48+GJuAnfWehMg52DNNGvQhdx68YlA9pglV12X5JP5Mu9D/+\nvh04732F7c8GkS4aA2hcJ66DvtihJ0CMUabWGszgOXceQDwj9BWEzy3Ew/rK\nemGfIX1zVywFvB18UVwcVgqFzXdmUGV98x0KiF1n4uxAUzuBtOlBVpHgHkBg\n2pMy/xr+5T0XF1ViBW0gQSLFoi2a2Yw0px/T0nH2aVPh3gEve6O/jawXVU0+\nxa5n\r\n=QqNl\r\n-----END PGP SIGNATURE-----\r\n"},"main":"index.js","name":"dat-sdk","author":{"name":"datproject"},"readme":"# sdk\nThe official Dat SDK\n\n[<img src=\"https://datproject.github.io/design/downloads/dat-logo.png\" align=\"right\" width=\"140\">][Dat Project]\n\n## Why use this?\n\nDat consists of a bunch of low level building blocks for working with data in distributed applications. Although this modularity makes it easy to mix and match pieces, it adds complexity when it comes to actually building something.\n\nThe Dat SDK combines the lower level pieces of the Dat ecosystem into high level APIs that you can use across platforms so that you can focus on your application rather than the gritty details of how it works.\n\n## Goals\n\n- High level API\n- Cross-platform with same codebase\n  - ✔ Node\n  - ✔ Web (non-beaker)\n  - ✔ Beaker (Promise API acts as polyfill for Beaker)\n  - React-Native?\n  - Electron?\n\n\n## Installing\n\n[Node.js](https://nodejs.org/) / [Browserify](http://browserify.org/) workflows:\n\n```shell\nnpm install --save dat-sdk\n```\n\n```js\nconst SDK = require('dat-sdk')\nconst SDKPromise = require('dat-sdk/promise')\nconst {DatArchive} = require('dat-sdk/auto')\n```\n\nOr Web Browsers\n\n```html\n<script src=\"https://bundle.run/dat-sdk@1\"></script>\n<script src=\"https://bundle.run/dat-sdk@1/promise.js\"></script>\n<script src=\"https://bundle.run/dat-sdk@1/auto.js\"></script>\n<script>\n  const SDK = window.datSDK\n  // Look at the examples from here\n</script>\n```\n\n## Examples (browserify)\n\nYou can bundle your code with [browserify](http://browserify.org/) using the following command:\n\n```\nbrowserify index.js > bundle.js\n```\n\nThen you can include `bundle.js` in your HTML page.\n\n## Examples (webpack.config.js)\n\nTo bundle with webpack instead of browserify, resolve the `fs` module with the `graceful-fs` module.\n\n```js\nconst path = require('path')\n\nmodule.exports = {\n  entry: './index.js',\n  target: 'web',\n  resolve: {\n    alias: {\n      fs: 'graceful-fs'\n    }\n  },\n  output: {\n    filename: 'bundle.js',\n    path: path.resolve(__dirname, 'dist')\n  }\n}\n```\n\nThen you can include `./dist/bundle.js` in your HTML page.\n\n## Examples (Promise)\n\n```js\n// Auto-detects sane defaults based on your environment\n// Uses Beaker's APIs if they are if they are available\n// DatArchive is the same as Beaker\n// https://beakerbrowser.com/docs/apis/dat\nconst {DatArchive} = require('dat-sdk/auto')\n\nconst archive = await DatArchive.load('dat://dat.foundation')\n\nconst someData = await archive.readFile('/dat.json', 'utf8')\n\nconsole.log('Dat foundation dat.json:', someData)\n\nconst myArchive = await DatArchive.create({\n  title: 'My Archive'\n})\n\nawait myArchive.writeFile('/example.txt', 'Hello World!')\n\n// Log the secret key in case you want to save it for later\nconsole.log(await myArchive.getSecretKey())\n\n// Use a saved secret key\nawait DatArchive.load(someKey, {\n  secretKey: someSecretKey\n})\n```\n\n## API/Examples (Callbacks)\n\n```js\nconst SDK = require('dat-sdk')\nconst { Hypercore, Hyperdrive, resolveName, deleteStorage, destroy } = SDK()\n\nconst archive = Hyperdrive(null, {\n  // This archive will disappear after the process exits\n  // This is here so that running the example doesn't clog up your history\n  persist: false,\n  // storage can be set to an instance of `random-access-*`\n  // const RAI = require('random-access-idb')\n  // otherwise it defaults to `random-access-web` in the browser\n  // and `random-access-file` in node\n  storage: null  //storage: RAI\n})\n\narchive.ready(() => {\n  const url = `dat://${archive.key.toString('hex')}`\n\n  // TODO: Save this for later!\n  console.log(`Here's your URL: ${url}`)\n\n  // Check out the hyperdrive docs for what you can do with it\n  // https://www.npmjs.com/package/hyperdrive#api\n  archive.writeFile('/example.txt', 'Hello World!', () => {\n    console.log('Written example file!')\n  })\n})\n\nresolveName('dat://beakerbrowser.com', (err, url) => {\n  if (err) throw err\n  const archive = Hyperdrive(url)\n\n  archive.readFile('/dat.json', 'utf8', (err, data) => {\n    if (err) throw err\n    console.log(`Beaker's dat.json is ${data}`)\n\n    archive.close((err) => {\n      if (err) throw err\n      deleteStorage(archive.key, (e) => {\n        if (e) throw e\n        console.log('Deleted beaker storage')\n      })\n    })\n  })\n})\n\nconst SOME_URL = 'dat://0a9e202b8055721bd2bc93b3c9bbc03efdbda9cfee91f01a123fdeaadeba303e/'\n\nconst someArchive = Hyperdrive(SOME_URL)\n\nreallyReady(someArchive, () => {\n  someArchive.readdir('/', console.log)\n})\n\n// This make sure you sync up with peers before trying to do anything with the archive\nfunction reallyReady (archive, cb) {\n  if (archive.metadata.peers.length) {\n    archive.metadata.update({ ifAvailable: true }, cb)\n  } else {\n    archive.metadata.once('peer-add', () => {\n      archive.metadata.update({ ifAvailable: true }, cb)\n    })\n  }\n}\n\n// Create a hypercore\n// Check out the hypercore docs for what you can do with it\n// https://github.com/mafintosh/hypercore\nconst myCore = Hypercore(null, {\n  valueEncoding: 'json',\n  persist: false,\n  // storage can be set to an instance of `random-access-*`\n  // const RAI = require('random-access-idb')\n  // otherwise it defaults to `random-access-web` in the browser\n  // and `random-access-file` in node\n  storage: null  // storage: RAI\n})\n\n// Add some data to it\nmyCore.append(JSON.stringify({\n  name: 'Alice'\n}), () => {\n  // Use extension messages for sending extra data over the p2p connection\n  const discoveryCoreKey = 'dat://bee80ff3a4ee5e727dc44197cb9d25bf8f19d50b0f3ad2984cfe5b7d14e75de7'\n  const discoveryCore = new Hypercore(discoveryCoreKey, {\n    extensions: ['discovery']\n  })\n\n  // When you find a new peer, tell them about your core\n  discoveryCore.on('peer-add', (peer) => {\n    console.log('Got a peer!')\n    peer.extension('discovery', myCore.key)\n  })\n\n  // When a peer tells you about their core, load it\n  discoveryCore.on('extension', (type, message) => {\n    console.log('Got extension message', type, message)\n    if (type !== 'discovery') return\n    discoveryCore.close()\n\n    const otherCore = new Hypercore(message, {\n      valueEncoding: 'json',\n      persist: false\n    })\n\n    // Render the peer's data from their core\n    otherCore.get(0, console.log)\n  })\n})\n\nconst hypertrie = require('hypertrie')\n\n// Pass in hypercores from the SDK into other dat data structures\n// Check out what you can do with hypertrie from there:\n// https://github.com/mafintosh/hypertrie\nconst trie = hypertrie(null, {\n  feed: new Hypercore(null, {\n    persist: false\n  })\n})\n\ntrie.put('key', 'value', () => {\n  trie.get('key', (err, node) => {\n    console.log('Got key: ', node.key)\n    console.log('Loaded value from trie: ', node.value)\n  })\n})\n\n```\n\n## API (Promise)\n\n### `const {DatArchive, destroy} = SDK({ storageOpts, swarmOpts, driveOpts, coreOpts, dnsOpts })`\n\nThis initializes the Dat SDK.\n\n\n- `storageOpts`: This lets you configure how the SDK will store data. Used by the [universal-dat-storage](https://github.com/RangerMauve/universal-dat-storage) module.\n  - `application: 'dat'`: The name of the application using the SDK if you want to have the data stored separately. Used by [env-paths](https://github.com/sindresorhus/env-paths#pathsdata) to generate the storageLocation\n  - `storageLocation: null`: A location (on disk) to store the archives in.\n- `swarmOpts`: This lets you configure [discovery-swarm](https://www.npmjs.com/package/discovery-swarm) and [discovery-swarm-web](https://www.npmjs.com/package/discovery-swarm-web)\n  - `id`: The ID to use when doing p2p traffic\n  - `maxConnections`: The maximum number of connections to keep for this swarm.\n  - `extensions: []`: The set of extension messages to use when replicating with peers\n  - `utp: true`: Whether to use utp in discovery-swarm\n  - `tcp: true`: Whether to use tcp in discovery-swarm\n  - `bootstrap: ['signal.mauve.moe']`: The WebRTC bootstrap server list used by discovery-swarm-web\n  - `discovery: 'discoveryswarm.mauve.moe'`: The proxy server used by discovery-swarm-web\n- `driveOpts`: This lets you configure the behavior of [Hyperdrive](https://github.com/mafintosh/hyperdrive) instances\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory archives\n  - `extensions`: The set of extension message types to use with this archive when replicating.\n- `coreOpts`: This lets you configure the behavior of [Hypercore](https://github.com/mafintosh/hypercore) instances\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory feeds\n  - `extensions`: The set of extension message types to use with this feed when replicating.\n  - `valueEncoding: 'json' | 'utf-8' | 'binary'`: The encoding to use for the data stored in the hypercore. Use JSON to store / retrieve objects.\n- `dnsOpts`: Configure the [dat dns](https://github.com/datprotocol/dat-dns) resolution module. You probably shouldn't mess with this.\n  - `recordName: 'dat'`: name of .well-known file\n  - `protocolRegex: /^dat:\\/\\/([0-9a-f]{64})/i`: RegExp object for custom protocol\n  - `hashRegex: /^[0-9a-f]{64}?$/i`: RegExp object for custom hash i.e.\n  - `txtRegex: /\"?datkey=([0-9a-f]{64})\"?/i`: RegExp object for DNS TXT record of custom protocol\n\n### `await destroy()`\n\nRelease all resources being used by the SDK so you can safely stop your process.\n\n### `const archive = await DatArchive.load(location, opts)`\n\nThis loads up a Dat Archive for the given URL / Key / File path.\n\n- `location`: This is either the `dat://` URL (which might have a domain), a dat key, or a file path for your archive.\n- `opts`: These are options for configuring this archive\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory archives\n  - `secretkey`: The secret key to use for this archive to get write access\n\n### `const archive = await DatArchive.create(opts)`\n\nThis creates a new Dat Archive.\n\n- `opts` These are the options for the archive's metadata and it's properties\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory archives\n  - `secretkey`: The secret key to use for this archive to get write access\n  - `title`: The title of the archive\n  - `description`: A brief description of what the archive contains\n  - `type`: An array of strings for the type of archive this is. See the [manifest](https://beakerbrowser.com/docs/apis/manifest.html#type) docs for more info.\n\n### `const archive = await DatArchive.fork(url, opts)`\n\nCreate a new archive based on the data within another archive\n\n- `url` The URL of the archive to fork off of\n- `opts` These options will be used in the new archive.\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory archives\n  - `secretkey`: The secret key to use for this archive to get write access\n  - `title`: The title of the archive\n  - `description`: A brief description of what the archive contains\n  - `type`: An array of strings for the type of archive this is. See the [manifest](https://beakerbrowser.com/docs/apis/manifest.html#type) docs for more info.\n\n### `await DatArchive.unlink(url)`\n\nDelete the storage for an archive.\n\n- `url`: The URL of the archive to delete\n\n### `const archive = await DatArchive.selectArchive()`\n\nPrompt the user to select an archive from the ones they have created locally. The implementation is super hacky, so use with caution.\n\n### `const url = await DatArchive.resolveName(url)`\n\nResolve a URL that uses dat-dns to the raw `dat://` url.\n\n- `url`: The `dat://` URL with a domain to resolve\n\n#### `const url = archive.url`\n\nGet the URL for the given archive.\n\n#### `const info = await archive.getInfo()`\n\nGet metadata about the archive\n\n- `info`: The metadata related to the archive.\n  - `key`: string (the archive public key)\n  - `url`: string (the archive URL)\n  - `isOwner`: boolean (is the user the owner of this archive?)\n  - `version`: number (the archive's current revision number)\n  - `peers`: number (the number of active connections for the archive)\n  - `mtime`: number (the walltime of the last received update; is reliable)\n  - `size`: number (bytes, the size-on-disk of the archive)\n  - `title`: string (the archive title)\n  - `description`: string (the archive description)\n  - `type`: array of strings (the archive's type identifiers)\n  - `links`: object (top-level links to other resources)\n\n#### `await archive.configure(configuration)`\n\nUpdate the metadata about the archive.\n\n- `configuration`: The metadata to update\n  - `title` String. The title of the archive.\n  - `description` String. The description of the archive.\n  - `type` Array<String>. The archive’s type identifiers. Learn more.\n  - `links` Object. Top-level links to other resources. Learn more.\n  - `web_root` String. Path of the folder from which all web requests should be served.\n  - `fallback_page` String. Path to a fallback page to serve instead of the default 404 page.\n\n#### `const stat = await archive.stat(path)`\n\n- `path`: The path to get stats about from the archive\n- `stat.isDirectory()`: Check if the path is a directory\n- `stat.isFile()`: Check if the path is a file\n- `stat.size`: number (bytes)\n- `stat.blocks`: number (number of data blocks in the metadata)\n- `stat.downloaded`: number (number of blocks downloaded, if a remote archive)\n- `stat.mtime`: Date (last modified time; not reliable)\n- `stat.ctime`: Date (creation time; not reliable)`\n\n#### `const data = await archive.readFile(path, opts)`\n\n- `path` The path to the file you wish to read\n- `opts.encoding`: The encoding to read the file with, can be one of `utf8`, `base64`, `hex`, and `binary`\n- `data`: The entire contents of the file, either as a string, or an ArrayBuffer if you used the `binary` encoding.\n\n#### `const list = await archive.readdir(path, opts)`\n\nLists the files and folders within a directory.\n\n- `path`: The path to the directory you wish to read\n- `opts`\n  - `recursive`: Set to `true` to list subdirectories, too\n  - `stat`: Get the `Stat` objects instead of names.\n- `list`: Either a list of the file/folder names or a list of the Stat object for those items.\n\n#### `await archive.writeFile(path, data, opts)`\n\nWrite a file to your archive.\n\n- `path`: The location to write your file to.\n- `data`: Either a string or ArrayBuffer for the data you wish to save\n- `opts.encoding`: The encoding to use when writing. Must be one of `utf8`, `base64`, `hex`, or `binary`. Encoding will default to `utf8` for strings, and `binary` for ArrayBuffers.\n\n#### `await archive.mkdir(path)`\n\nCreate a directory at the given path. Will fail if the parent directory doesn't exist.\n\n- `path`: The path to the directory\n\n#### `await archive.unlink(path)`\n\nDelete the file at the given path.\n\n- `path`: The path to the file\n\n#### `await rmdir(path, opts)`\n\nDeletes the directory at the given path.\n\n- `path`: The path to the directory\n- `opts.recursive`: Whether to delete subfolders / files.\n\n#### `await archive.copy(path, dstPath)`\n\nCopy a file from one location to another.\n\n- `path`: The path to the file / directory to copy from.\n- `dstPath`: The location the file/directory should be copied to\n\n#### `await archive.rename(oldPath, newPath)`\n\nRename / move a file or directory.\n\n- `oldPath`: The path of the file/directory to rename\n- `newPath`: What the file/directory should be renamed to.\n\n#### `const history = await archive.history({opts})`\n\nList the history of all the changes in this archive.\n\n- `opts`: The options for how to fetch the history of the archive\n  - `start`: Where in the history to start reading\n  - `end`: Where in the history to stop reading\n  - `reverse`: Set to `true` to iterate through the history backwards\n- `history`: An array of history items representing changes\n  - `path`: Which file / directory got modified.\n  - `version`: The version number the archive was at for this item\n  - `type`: Either `put` for additions or `del` for deletions\n\n#### `const olderArchive = archive.checkout(version)`\n\nGet a view of the archive as it was at an earlier version.\n\n- `version`: The integer representing the version you whish to look at. This correlates to the version in the history.\n\n#### `await archive.download(path)`\n\nDownload the file or folder at the given path from the network. Use `/` to download the entire archive.\n\n#### `const events = archive.watch(pattern, onInvalidated)`\n\n```js\nconst events = archive.watch(['**/*.md'])\nevents.addEventListener('changed', ({path}) => console.log(path, 'changed!'))\n\nevents.close() // Stop listening for changes\n```\n\nWatch for changes in the archive.\n\n- `pattern`: This can either be omitted to view all changes, or have an [anymatch](https://www.npmjs.com/package/anymatch) pattern to filter out just the changes you want.\n- `onInvalidated`: You can optionally pass in this function to listen for changes instead of using an event listener.\n\n#### `archive.addEventListener('network-changed', ({peers}) => void 0)`\n\nListen for changes in the number of peers connected to for the archive.\n\n- `peers`: The number of connected peers\n\n#### `archive.addEventListener('download', ({feed, block, bytes}) => void 0)`\n\nListen for download progress from the archive\n\n- `feed`: The data feed the block was part of. Either `metadata` or `content`\n- `block`: The index of the block downloaded\n- `bytes`: The size of the block in bytes\n\n#### `archive.addEventListener('upload', ({feed, block, bytes}) => void 0)`\n\nListen for upload progress from the archive.\n\n- `feed`: The data feed the block was part of. Either `metadata` or `content`\n- `block`: The index of the block uploaded\n- `bytes`: The size of the block in bytes\n\n#### `archive.addEventListener('sync', ({feed}) => void 0)`\n\nEmitted when all known data has been downloaded\n\n## API (Callbacks)\n\n### `const {Hypercore, Hyperdrive, resolveName, deleteStorage, destroy} = SDK({ storageOpts, swarmOpts, driveOpts, coreOpts, dnsOpts })`\n\nCreates an instance of the Dat SDK based on the options.\n\n- `storageOpts`: This lets you configure how the SDK will store data. Used by the [universal-dat-storage](https://github.com/RangerMauve/universal-dat-storage) module.\n  - `application: 'dat'`: The name of the application using the SDK if you want to have the data stored separately. Used by [env-paths](https://github.com/sindresorhus/env-paths#pathsdata) to generate the storageLocation\n  - `storageLocation: null`: A location (on disk) to store the archives in.\n- `swarmOpts`: This lets you configure [discovery-swarm](https://www.npmjs.com/package/discovery-swarm) and [discovery-swarm-web](https://www.npmjs.com/package/discovery-swarm-web)\n  - `id`: The ID to use when doing p2p traffic\n  - `maxConnections`: The maximum number of connections to keep for this swarm.\n  - `extensions: []`: The set of extension messages to use when replicating with peers\n  - `utp: true`: Whether to use utp in discovery-swarm\n  - `tcp: true`: Whether to use tcp in discovery-swarm\n  - `bootstrap: ['signal.mauve.moe']`: The WebRTC bootstrap server list used by discovery-swarm-web\n  - `discovery: 'discoveryswarm.mauve.moe'`: The proxy server used by discovery-swarm-web\n- `driveOpts`: This lets you configure the behavior of [Hyperdrive](https://github.com/mafintosh/hyperdrive) instances\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory archives\n  - `extensions`: The set of extension message types to use with this archive when replicating.\n- `coreOpts`: This lets you configure the behavior of [Hypercore](https://github.com/mafintosh/hypercore) instances\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory feeds\n  - `extensions`: The set of extension message types to use with this feed when replicating.\n  - `valueEncoding: 'json' | 'utf-8' | 'binary'`: The encoding to use for the data stored in the hypercore. Use JSON to store / retrieve objects.\n- `dnsOpts`: Configure the [dat dns](https://github.com/datprotocol/dat-dns) resolution module. You probably shouldn't mess with this.\n  - `recordName: 'dat'`: name of .well-known file\n  - `protocolRegex: /^dat:\\/\\/([0-9a-f]{64})/i`: RegExp object for custom protocol\n  - `hashRegex: /^[0-9a-f]{64}?$/i`: RegExp object for custom hash i.e.\n  - `txtRegex: /\"?datkey=([0-9a-f]{64})\"?/i`: RegExp object for DNS TXT record of custom protocol\n\n### `destroy(cb)`\n\nThis closes all resources used by the SDK so you can safely end your process. `cb` will be invoked once resources are closed or if there's an error.\n\n### `resolveName(url, cb(err, key))`\n\nResolve a DNS name to a Dat key.\n\n  - `url` is a Dat URL like `dat://dat.foundation`\n  - `cb` will get invoked with the result of the resolve\n  - `key` will be the Dat key that you can pass to `hyperdrive`\n  - `err` will be any errors that happen during resolution\n\n### `deleteStorage(key, cb)`\n\nDelete the storage for a given archive or hypercore key.\n\n- `key` should be the key for the hypercore or hyperdrive that should be deleted\n- `cb` will be invoked after the deletion is over.\n\n### `const archive = Hyperdrive(location, opts)`\n\nThis initializes a Hyperdrive (aka a Dat archive), the SDK will begin finding peers for it and will de-duplicate calls to initializing the same archive more than once.\n\n- `location`: This **must** be provided. It's either a path for where the archive should be stored, or a Dat URL / key. If this is null, a new key will be generated.\n- `opts`: These are the options for configuring the hyperdrive.\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory archives\n  - `extensions`: The set of extension message types to use with this archive when replicating.\n  - `secretKey`: A secret key for granting write access. This can be useful when restoring backups.\n\nThe rest of the Hyperdrive docs were taken from the [Hyperdrive README](https://github.com/mafintosh/hyperdrive/blob/v9/README.md)\n\n#### `archive.version`\n\nGet the current version of the archive (incrementing number).\n\n#### `archive.key`\n\nThe public key identifying the archive.\n\n#### `archive.discoveryKey`\n\nA key derived from the public key that can be used to discovery other peers sharing this archive.\n\n#### `archive.writable`\n\nA boolean indicating whether the archive is writable.\n\n#### `archive.on('ready')`\n\nEmitted when the archive is fully ready and all properties has been populated.\n\n#### `archive.on('update')`\n\nEmitted when the archive has got a new change.\n\n#### `archive.on('error', err)`\n\nEmitted when a critical error during load happened.\n\n#### `archive.on('close')`\n\nEmitted when the archive has been closed\n\n#### `archive.on('extension', name, message, peer)`\n\nEmitted when a peer sends you an extension message with `archive.extension()`.\nYou can respond with `peer.extension(name, message)`.\n\n#### `var oldDrive = archive.checkout(version, [opts])`\n\nCheckout a readonly copy of the archive at an old version. Options are used to configure the `oldDrive`:\n\n```js\n{\n  metadataStorageCacheSize: 65536 // how many entries to use in the metadata hypercore's LRU cache\n  contentStorageCacheSize: 65536 // how many entries to use in the content hypercore's LRU cache\n  treeCacheSize: 65536 // how many entries to use in the append-tree's LRU cache\n}\n```\n\n#### `archive.download([path], [callback])`\n\nDownload all files in path of current version.\nIf no path is specified this will download all files.\n\nYou can use this with `.checkout(version)` to download a specific version of the archive.\n\n``` js\narchive.checkout(version).download()\n```\n\n#### `var stream = archive.history([options])`\n\nGet a stream of all changes and their versions from this archive.\n\n#### `archive.extension(name, message)`\n\nSend an extension message to connected peers. [Read more in the hypercore docs](https://github.com/mafintosh/hypercore#feedextensionname-message).\n\n#### `var stream = archive.createReadStream(name, [options])`\n\nRead a file out as a stream. Similar to fs.createReadStream.\n\nOptions include:\n\n``` js\n{\n  start: optionalByteOffset, // similar to fs\n  end: optionalInclusiveByteEndOffset, // similar to fs\n  length: optionalByteLength\n}\n```\n\n#### `archive.readFile(name, [options], callback)`\n\nRead an entire file into memory. Similar to fs.readFile.\n\nOptions can either be an object or a string\n\nOptions include:\n```js\n{\n  encoding: string\n  cached: true|false // default: false\n}\n```\nor a string can be passed as options to simply set the encoding - similar to fs.\n\nIf `cached` is set to `true`, this function returns results only if they have already been downloaded.\n\n#### `var stream = archive.createDiffStream(version, [options])`\n\nDiff this archive with another version. `version` can both be a version number of a checkout instance of the archive. The `data` objects looks like this\n\n``` js\n{\n  type: 'put' | 'del',\n  name: '/some/path/name.txt',\n  value: {\n    // the stat object\n  }\n}\n```\n\n#### `var stream = archive.createWriteStream(name, [options])`\n\nWrite a file as a stream. Similar to fs.createWriteStream.\nIf `options.cached` is set to `true`, this function returns results only if they have already been downloaded.\n\n#### `archive.writeFile(name, buffer, [options], [callback])`\n\nWrite a file from a single buffer. Similar to fs.writeFile.\n\n#### `archive.unlink(name, [callback])`\n\nUnlinks (deletes) a file. Similar to fs.unlink.\n\n#### `archive.mkdir(name, [options], [callback])`\n\nExplictly create an directory. Similar to fs.mkdir\n\n#### `archive.rmdir(name, [callback])`\n\nDelete an empty directory. Similar to fs.rmdir.\n\n#### `archive.readdir(name, [options], [callback])`\n\nLists a directory. Similar to fs.readdir.\n\nOptions include:\n\n``` js\n{\n    cached: true|false, // default: false\n}\n```\n\nIf `cached` is set to `true`, this function returns results from the local version of the archive’s append-tree. Default behavior is to fetch the latest remote version of the archive before returning list of directories.\n\n#### `archive.stat(name, [options], callback)`\n\nStat an entry. Similar to fs.stat. Sample output:\n\n```\nStat {\n  dev: 0,\n  nlink: 1,\n  rdev: 0,\n  blksize: 0,\n  ino: 0,\n  mode: 16877,\n  uid: 0,\n  gid: 0,\n  size: 0,\n  offset: 0,\n  blocks: 0,\n  atime: 2017-04-10T18:59:00.147Z,\n  mtime: 2017-04-10T18:59:00.147Z,\n  ctime: 2017-04-10T18:59:00.147Z,\n  linkname: undefined }\n```\n\nThe output object includes methods similar to fs.stat:\n\n``` js\nvar stat = archive.stat('/hello.txt')\nstat.isDirectory()\nstat.isFile()\n```\n\nOptions include:\n```js\n{\n  cached: true|false // default: false,\n  wait: true|false // default: true\n}\n```\n\nIf `cached` is set to `true`, this function returns results only if they have already been downloaded.\n\nIf `wait` is set to `true`, this function will wait for data to be downloaded. If false, will return an error.\n\n#### `archive.lstat(name, [options], callback)`\n\nStat an entry but do not follow symlinks. Similar to fs.lstat.\n\nOptions include:\n```js\n{\n  cached: true|false // default: false,\n  wait: true|false // default: true\n}\n```\n\nIf `cached` is set to `true`, this function returns results only if they have already been downloaded.\n\nIf `wait` is set to `true`, this function will wait for data to be downloaded. If false, will return an error.\n\n#### `archive.access(name, [options], callback)`\n\nSimilar to fs.access.\n\nOptions include:\n```js\n{\n  cached: true|false // default: false,\n  wait: true|false // default: true\n}\n```\n\nIf `cached` is set to `true`, this function returns results only if they have already been downloaded.\n\nIf `wait` is set to `true`, this function will wait for data to be downloaded. If false, will return an error.\n\n#### `archive.open(name, flags, [mode], callback)`\n\nOpen a file and get a file descriptor back. Similar to fs.open.\n\nNote that currently only read mode is supported in this API.\n\n#### `archive.read(fd, buf, offset, len, position, callback)`\n\nRead from a file descriptor into a buffer. Similar to fs.read.\n\n#### `archive.close(fd, [callback])`\n\nClose a file. Similar to fs.close.\n\n#### `archive.close([callback])`\n\nCloses all open resources used by the archive.\nThe archive should no longer be used after calling this.\n\n### `const feed = Hypercore(key, opts)`\n\nInitializes a Hypercore (aka Feed) and begins replicating it.\n\n- `key`: This is the dat key for the feed, you can omit it if you want to create a new hypercore instance\n- `opts`: The options for configuring this feed\n  - `sparse: true`: Whether the history should be loaded on the fly instead of replicating the full history\n  - `persist: true`: Whether the data should be persisted to storage. Set to false to create in-memory feeds\n  - `extensions`: The set of extension message types to use with this feed when replicating.\n  - `valueEncoding: 'json' | 'utf-8' | 'binary'`: The encoding to use for the data stored in the hypercore. Use JSON to store / retrieve objects.\n  - `secretKey`: The secret key to use for the feed. Useful for restoring from backups.\n\n#### `feed.append(data, [callback])`\n\nAppend a block of data to the feed.\n\nCallback is called with `(err, seq)` when all data has been written at the returned `seq` or an error occurred.\n\n#### `feed.get(index, [options], callback)`\n\nGet a block of data.\nIf the data is not available locally this method will prioritize and wait for the data to be downloaded before calling the callback.\n\nOptions include\n\n``` js\n{\n  wait: true, // wait for index to be downloaded\n  timeout: 0, // wait at max some milliseconds (0 means no timeout)\n  valueEncoding: 'json' | 'utf-8' | 'binary' // defaults to the feed's valueEncoding\n}\n```\n\nCallback is called with `(err, data)`\n\n#### `feed.getBatch(start, end, [options], callback)`\n\nGet a range of blocks efficiently. Options include\n\n``` js\n{\n  wait: sameAsAbove,\n  timeout: sameAsAbove,\n  valueEncoding: sameAsAbove\n}\n```\n\n#### `feed.head([options], callback)`\n\nGet the block of data at the tip of the feed. This will be the most recently\nappended block.\n\nAccepts the same `options` as `feed.get()`.\n\n#### `feed.download([range], [callback])`\n\nDownload a range of data. Callback is called when all data has been downloaded.\nA range can have the following properties:\n\n``` js\n{\n  start: startIndex,\n  end: nonInclusiveEndIndex,\n  linear: false // download range linearly and not randomly\n}\n```\n\nIf you do not mark a range the entire feed will be marked for download.\n\nIf you have not enabled sparse mode (`sparse: true` in the feed constructor) then the entire\nfeed will be marked for download for you when the feed is created.\n\n#### `feed.undownload(range)`\n\nCancel a previous download request.\n\n#### `feed.signature([index], callback)`\n\nGet a signature proving the correctness of the block at index, or the whole stream.\n\nCallback is called with `(err, signature)`.\nThe signature has the following properties:\n``` js\n{\n  index: lastSignedBlock,\n  signature: Buffer\n}\n```\n\n#### `feed.verify(index, signature, callback)`\n\nVerify a signature is correct for the data up to index, which must be the last signed\nblock associated with the signature.\n\nCallback is called with `(err, success)` where success is true only if the signature is\ncorrect.\n\n#### `feed.rootHashes(index, callback)`\n\nRetrieve the root *hashes* for given `index`.\n\nCallback is called with `(err, roots)`; `roots` is an *Array* of *Node* objects:\n```\nNode {\n  index: location in the merkle tree of this root\n  size: total bytes in children of this root\n  hash: hash of the children of this root (32-byte buffer)\n}\n```\n\n\n#### `var number = feed.downloaded([start], [end])`\n\nReturns total number of downloaded blocks within range.\nIf `end` is not specified it will default to the total number of blocks.\nIf `start` is not specified it will default to 0.\n\n#### `var bool = feed.has(index)`\n\nReturn true if a data block is available locally.\nFalse otherwise.\n\n#### `var bool = feed.has(start, end)`\nReturn true if all data blocks within a range are available locally.\nFalse otherwise.\n\n#### `feed.clear(start, [end], [callback])`\n\nClear a range of data from the local cache.\nWill clear the data from the bitfield and make a call to the underlying storage provider to delete the byte range the range occupies.\n\n`end` defaults to `start + 1`.\n\n#### `feed.seek(byteOffset, callback)`\n\nSeek to a byte offset.\n\nCalls the callback with `(err, index, relativeOffset)`, where `index` is the data block the byteOffset is contained in and `relativeOffset` is\nthe relative byte offset in the data block.\n\n#### `feed.update([minLength], [callback])`\n\nWait for the feed to contain at least `minLength` elements.\nIf you do not provide `minLength` it will be set to current length + 1.\n\nDoes not download any data from peers except for a proof of the new feed length.\n\n``` js\nconsole.log('length is', feed.length)\nfeed.update(function () {\n  console.log('length has increased', feed.length)\n})\n```\n\n#### `var stream = feed.createReadStream([options])`\n\nCreate a readable stream of data.\n\nOptions include:\n\n``` js\n{\n  start: 0, // read from this index\n  end: feed.length, // read until this index\n  snapshot: true, // if set to false it will update `end` to `feed.length` on every read\n  tail: false, // sets `start` to `feed.length`\n  live: false, // set to true to keep reading forever\n  timeout: 0, // timeout for each data event (0 means no timeout)\n  wait: true // wait for data to be downloaded\n}\n```\n\n#### `var stream = feed.createWriteStream()`\n\nCreate a writable stream.\n\n#### `feed.close([callback])`\n\nFully close this feed.\n\nCalls the callback with `(err)` when all storage has been closed.\n\n#### `feed.audit([callback])`\n\nAudit all data in the feed. Will check that all current data stored\nmatches the hashes in the merkle tree and clear the bitfield if not.\n\nWhen done a report is passed to the callback that looks like this:\n\n```js\n{\n  valid: 10, // how many data blocks matches the hashes\n  invalid: 0, // how many did not\n}\n```\n\nIf a block does not match the hash it is cleared from the data bitfield.\n\n#### `feed.writable`\n\nCan we append to this feed?\n\nPopulated after `ready` has been emitted. Will be `false` before the event.\n\n#### `feed.readable`\n\nCan we read from this feed? After closing a feed this will be false.\n\nPopulated after `ready` has been emitted. Will be `false` before the event.\n\n#### `feed.key`\n\nBuffer containing the public key identifying this feed.\n\nPopulated after `ready` has been emitted. Will be `null` before the event.\n\n#### `feed.discoveryKey`\n\nBuffer containing a key derived from the feed.key.\nIn contrast to `feed.key` this key does not allow you to verify the data but can be used to announce or look for peers that are sharing the same feed, without leaking the feed key.\n\nPopulated after `ready` has been emitted. Will be `null` before the event.\n\n#### `feed.length`\n\nHow many blocks of data are available on this feed?\n\nPopulated after `ready` has been emitted. Will be `0` before the event.\n\n#### `feed.byteLength`\n\nHow much data is available on this feed in bytes?\n\nPopulated after `ready` has been emitted. Will be `0` before the event.\n\n#### `feed.stats`\n\nReturn per-peer and total upload/download counts.\n\nThe returned object is of the form:\n```js\n{\n  totals: {\n    uploadedBytes: 100,\n    uploadedBlocks: 1,\n    downloadedBytes: 0,\n    downloadedBlocks: 0\n  },\n  peers: [\n    {\n      uploadedBytes: 100,\n      uploadedBlocks: 1,\n      downloadedBytes: 0,\n      downloadedBlocks: 0\n    },\n    ...\n  ]\n}\n```\n\nStats will be collected by default, but this can be disabled by setting `opts.stats` to false.\n\n#### `feed.on('ready')`\n\nEmitted when the feed is ready and all properties have been populated.\n\n#### `feed.on('error', err)`\n\nEmitted when the feed experiences a critical error.\n\n#### `feed.on('download', index, data)`\n\nEmitted when a data block has been downloaded.\n\n#### `feed.on('upload', index, data)`\n\nEmitted when a data block is uploaded.\n\n#### `feed.on('append')`\n\nEmitted when the feed has been appended to (i.e. has a new length / byteLength)\n\n#### `feed.on('sync')`\n\nEmitted every time ALL data from `0` to `feed.length` has been downloaded.\n\n#### `feed.on('close')`\n\nEmitted when the feed has been fully closed\n\n---\n\n[Dat Project]: https://dat.foundation\n","browser":{"dat-dns":"./dns-web.js","hyperswarm":"hyperswarm-web","./localstorage":"./localstorage-web.js"},"gitHead":"1ae482be2f571810f5568ec8ea8de602cc7144a6","license":"MIT","scripts":{"test":"node test","build-test":"browserify -d test.js > test-bundle.js","build-test-promise":"browserify -d test-promise.js > test-bundle.js"},"_npmUser":{"name":"rangermauve","email":"rangermauve@hotmail.com"},"homepage":"https://github.com/datproject/sdk#readme","keywords":["dat","sdk","hyperdrive","hypercore","p2p"],"repository":{"url":"git+https://github.com/datproject/sdk.git","type":"git"},"_npmVersion":"6.9.0","description":"The official Dat SDK","directories":{},"maintainers":[{"name":"rangermauve","email":"rangermauve@hotmail.com"}],"_nodeVersion":"11.15.0","dependencies":{"global":"^4.4.0","dat-dns":"^4.0.0","corestore":"^5.0.8","hex-to-32":"^2.0.0","hypercore":"^8.7.0","url-parse":"^1.4.7","hyperdrive":"^10.8.10","dat-encoding":"^5.0.1","concat-stream":"^2.0.0","hyperswarm-web":"^1.0.1","dom-event-target":"^1.0.0","hypercore-crypto":"^1.0.0","universal-prompt":"^1.0.0","node-localstorage":"^2.1.5","hypercore-protocol":"^7.10.0","random-access-memory":"^3.1.1","universal-localstorage":"^1.0.2","@geut/hypercore-promise":"^1.1.0","@geut/hyperdrive-promise":"^3.0.0","random-access-application":"^1.0.0","corestore-swarm-networking":"^4.0.3"},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"tmp":"^0.1.0","tape":"^4.10.2","hypertrie":"^3.7.1","browserify":"^16.2.3"},"_npmOperationalInternal":{"tmp":"tmp/dat-sdk_2.0.0-2_1581450107252_0.029383652594809684","host":"s3://npm-registry-packages"},"_id":"dat-sdk@2.0.0-2","version":"2.0.0-2"}