chore: update aegir and jsdocs for eslint changes (#773)

This commit is contained in:
Vasco Santos 2020-10-06 14:59:43 +02:00 committed by GitHub
parent bb59b518f1
commit 96df4b7dc4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 425 additions and 263 deletions

View File

@ -84,7 +84,7 @@
"devDependencies": { "devDependencies": {
"@nodeutils/defaults-deep": "^1.1.0", "@nodeutils/defaults-deep": "^1.1.0",
"abortable-iterator": "^3.0.0", "abortable-iterator": "^3.0.0",
"aegir": "^26.0.0", "aegir": "^27.0.0",
"chai": "^4.2.0", "chai": "^4.2.0",
"chai-as-promised": "^7.1.1", "chai-as-promised": "^7.1.1",
"chai-bytes": "^0.1.2", "chai-bytes": "^0.1.2",

View File

@ -15,11 +15,11 @@ const multiaddr = require('multiaddr')
*/ */
class AddressManager { class AddressManager {
/** /**
* @constructor * @class
* @param {object} [options] * @param {object} [options]
* @param {Array<string>} [options.listen = []] list of multiaddrs string representation to listen. * @param {Array<string>} [options.listen = []] - list of multiaddrs string representation to listen.
* @param {Array<string>} [options.announce = []] list of multiaddrs string representation to announce. * @param {Array<string>} [options.announce = []] - list of multiaddrs string representation to announce.
* @param {Array<string>} [options.noAnnounce = []] list of multiaddrs string representation to not announce. * @param {Array<string>} [options.noAnnounce = []] - list of multiaddrs string representation to not announce.
*/ */
constructor ({ listen = [], announce = [], noAnnounce = [] } = {}) { constructor ({ listen = [], announce = [], noAnnounce = [] } = {}) {
this.listen = new Set(listen) this.listen = new Set(listen)
@ -29,7 +29,8 @@ class AddressManager {
/** /**
* Get peer listen multiaddrs. * Get peer listen multiaddrs.
* @return {Array<Multiaddr>} *
* @returns {Array<Multiaddr>}
*/ */
getListenAddrs () { getListenAddrs () {
return Array.from(this.listen).map((a) => multiaddr(a)) return Array.from(this.listen).map((a) => multiaddr(a))
@ -37,7 +38,8 @@ class AddressManager {
/** /**
* Get peer announcing multiaddrs. * Get peer announcing multiaddrs.
* @return {Array<Multiaddr>} *
* @returns {Array<Multiaddr>}
*/ */
getAnnounceAddrs () { getAnnounceAddrs () {
return Array.from(this.announce).map((a) => multiaddr(a)) return Array.from(this.announce).map((a) => multiaddr(a))
@ -45,7 +47,8 @@ class AddressManager {
/** /**
* Get peer noAnnouncing multiaddrs. * Get peer noAnnouncing multiaddrs.
* @return {Array<Multiaddr>} *
* @returns {Array<Multiaddr>}
*/ */
getNoAnnounceAddrs () { getNoAnnounceAddrs () {
return Array.from(this.noAnnounce).map((a) => multiaddr(a)) return Array.from(this.noAnnounce).map((a) => multiaddr(a))

View File

@ -90,9 +90,8 @@ module.exports.handleHop = async function handleHop ({
* peer. A new, virtual, connection will be created between the two via the relay. * peer. A new, virtual, connection will be created between the two via the relay.
* *
* @param {object} options * @param {object} options
* @param {Connection} options.connection Connection to the relay * @param {Connection} options.connection - Connection to the relay
* @param {*} options.request * @param {*} options.request
* @param {Circuit} options.circuit
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
module.exports.hop = async function hop ({ module.exports.hop = async function hop ({
@ -119,6 +118,11 @@ module.exports.hop = async function hop ({
/** /**
* Creates an unencoded CAN_HOP response based on the Circuits configuration * Creates an unencoded CAN_HOP response based on the Circuits configuration
*
* @param {Object} options
* @param {Connection} options.connection
* @param {StreamHandler} options.streamHandler
* @param {Circuit} options.circuit
* @private * @private
*/ */
module.exports.handleCanHop = function handleCanHop ({ module.exports.handleCanHop = function handleCanHop ({

View File

@ -15,7 +15,7 @@ log.error = debug('libp2p:circuit:stop:error')
* @private * @private
* @param {*} options * @param {*} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {*} options.request The CircuitRelay protobuf request (unencoded) * @param {*} options.request - The CircuitRelay protobuf request (unencoded)
* @param {StreamHandler} options.streamHandler * @param {StreamHandler} options.streamHandler
* @returns {Promise<*>} Resolves a duplex iterable * @returns {Promise<*>} Resolves a duplex iterable
*/ */
@ -42,10 +42,11 @@ module.exports.handleStop = function handleStop ({
/** /**
* Creates a STOP request * Creates a STOP request
*
* @private * @private
* @param {*} options * @param {*} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {*} options.request The CircuitRelay protobuf request (unencoded) * @param {*} options.request - The CircuitRelay protobuf request (unencoded)
* @returns {Promise<*>} Resolves a duplex iterable * @returns {Promise<*>} Resolves a duplex iterable
*/ */
module.exports.stop = async function stop ({ module.exports.stop = async function stop ({

View File

@ -14,7 +14,7 @@ class StreamHandler {
* *
* @param {object} options * @param {object} options
* @param {*} options.stream - A duplex iterable * @param {*} options.stream - A duplex iterable
* @param {Number} options.maxLength - max bytes length of message * @param {number} options.maxLength - max bytes length of message
*/ */
constructor ({ stream, maxLength = 4096 }) { constructor ({ stream, maxLength = 4096 }) {
this.stream = stream this.stream = stream
@ -25,6 +25,7 @@ class StreamHandler {
/** /**
* Read and decode message * Read and decode message
*
* @async * @async
* @returns {void} * @returns {void}
*/ */
@ -44,7 +45,7 @@ class StreamHandler {
/** /**
* Encode and write array of buffers * Encode and write array of buffers
* *
* @param {*} msg An unencoded CircuitRelay protobuf message * @param {*} msg - An unencoded CircuitRelay protobuf message
*/ */
write (msg) { write (msg) {
log('write message type %s', msg.type) log('write message type %s', msg.type)
@ -54,7 +55,7 @@ class StreamHandler {
/** /**
* Return the handshake rest stream and invalidate handler * Return the handshake rest stream and invalidate handler
* *
* @return {*} A duplex iterable * @returns {*} A duplex iterable
*/ */
rest () { rest () {
this.shake.rest() this.shake.rest()

View File

@ -19,7 +19,7 @@ function writeResponse (streamHandler, status) {
/** /**
* Validate incomming HOP/STOP message * Validate incomming HOP/STOP message
* *
* @param {*} msg A CircuitRelay unencoded protobuf message * @param {*} msg - A CircuitRelay unencoded protobuf message
* @param {StreamHandler} streamHandler * @param {StreamHandler} streamHandler
*/ */
function validateAddrs (msg, streamHandler) { function validateAddrs (msg, streamHandler) {

View File

@ -21,7 +21,7 @@ class Circuit {
/** /**
* Creates an instance of Circuit. * Creates an instance of Circuit.
* *
* @constructor * @class
* @param {object} options * @param {object} options
* @param {Libp2p} options.libp2p * @param {Libp2p} options.libp2p
* @param {Upgrader} options.upgrader * @param {Upgrader} options.upgrader
@ -152,7 +152,7 @@ class Circuit {
* *
* @param {any} options * @param {any} options
* @param {Function} handler * @param {Function} handler
* @return {listener} * @returns {listener}
*/ */
createListener (options, handler) { createListener (options, handler) {
if (typeof options === 'function') { if (typeof options === 'function') {

View File

@ -19,7 +19,7 @@ module.exports = (circuit) => {
* Add swarm handler and listen for incoming connections * Add swarm handler and listen for incoming connections
* *
* @param {Multiaddr} addr * @param {Multiaddr} addr
* @return {void} * @returns {void}
*/ */
listener.listen = async (addr) => { listener.listen = async (addr) => {
const addrString = String(addr).split('/p2p-circuit').find(a => a !== '') const addrString = String(addr).split('/p2p-circuit').find(a => a !== '')
@ -34,7 +34,7 @@ module.exports = (circuit) => {
/** /**
* TODO: Remove the peers from our topology * TODO: Remove the peers from our topology
* *
* @return {void} * @returns {void}
*/ */
listener.close = () => {} listener.close = () => {}
@ -52,7 +52,7 @@ module.exports = (circuit) => {
* the encapsulated transport address. This is useful when for example, a peer should only * the encapsulated transport address. This is useful when for example, a peer should only
* be dialed over TCP rather than any other transport * be dialed over TCP rather than any other transport
* *
* @return {Multiaddr[]} * @returns {Multiaddr[]}
*/ */
listener.getAddrs = () => { listener.getAddrs = () => {
const addrs = [] const addrs = []

View File

@ -32,25 +32,26 @@ const defaultOptions = {
/** /**
* Responsible for managing known connections. * Responsible for managing known connections.
*
* @fires ConnectionManager#peer:connect Emitted when a new peer is connected. * @fires ConnectionManager#peer:connect Emitted when a new peer is connected.
* @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected. * @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected.
*/ */
class ConnectionManager extends EventEmitter { class ConnectionManager extends EventEmitter {
/** /**
* @constructor * @class
* @param {Libp2p} libp2p * @param {Libp2p} libp2p
* @param {object} options * @param {object} options
* @param {Number} options.maxConnections The maximum number of connections allowed. Default=Infinity * @param {number} options.maxConnections - The maximum number of connections allowed. Default=Infinity
* @param {Number} options.minConnections The minimum number of connections to avoid pruning. Default=0 * @param {number} options.minConnections - The minimum number of connections to avoid pruning. Default=0
* @param {Number} options.maxData The max data (in and out), per average interval to allow. Default=Infinity * @param {number} options.maxData - The max data (in and out), per average interval to allow. Default=Infinity
* @param {Number} options.maxSentData The max outgoing data, per average interval to allow. Default=Infinity * @param {number} options.maxSentData - The max outgoing data, per average interval to allow. Default=Infinity
* @param {Number} options.maxReceivedData The max incoming data, per average interval to allow.. Default=Infinity * @param {number} options.maxReceivedData - The max incoming data, per average interval to allow.. Default=Infinity
* @param {Number} options.maxEventLoopDelay The upper limit the event loop can take to run. Default=Infinity * @param {number} options.maxEventLoopDelay - The upper limit the event loop can take to run. Default=Infinity
* @param {Number} options.pollInterval How often, in milliseconds, metrics and latency should be checked. Default=2000 * @param {number} options.pollInterval - How often, in milliseconds, metrics and latency should be checked. Default=2000
* @param {Number} options.movingAverageInterval How often, in milliseconds, to compute averages. Default=60000 * @param {number} options.movingAverageInterval - How often, in milliseconds, to compute averages. Default=60000
* @param {Number} options.defaultPeerValue The value of the peer. Default=1 * @param {number} options.defaultPeerValue - The value of the peer. Default=1
* @param {boolean} options.autoDial Should preemptively guarantee connections are above the low watermark. Default=true * @param {boolean} options.autoDial - Should preemptively guarantee connections are above the low watermark. Default=true
* @param {Number} options.autoDialInterval How often, in milliseconds, it should preemptively guarantee connections are above the low watermark. Default=10000 * @param {number} options.autoDialInterval - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark. Default=10000
*/ */
constructor (libp2p, options) { constructor (libp2p, options) {
super() super()
@ -69,12 +70,14 @@ class ConnectionManager extends EventEmitter {
/** /**
* Map of peer identifiers to their peer value for pruning connections. * Map of peer identifiers to their peer value for pruning connections.
*
* @type {Map<string, number>} * @type {Map<string, number>}
*/ */
this._peerValues = new Map() this._peerValues = new Map()
/** /**
* Map of connections per peer * Map of connections per peer
*
* @type {Map<string, Array<conn>>} * @type {Map<string, Array<conn>>}
*/ */
this.connections = new Map() this.connections = new Map()
@ -119,6 +122,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Stops the Connection Manager * Stops the Connection Manager
*
* @async * @async
*/ */
async stop () { async stop () {
@ -133,6 +137,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Cleans up the connections * Cleans up the connections
*
* @async * @async
*/ */
async _close () { async _close () {
@ -151,8 +156,9 @@ class ConnectionManager extends EventEmitter {
/** /**
* Sets the value of the given peer. Peers with lower values * Sets the value of the given peer. Peers with lower values
* will be disconnected first. * will be disconnected first.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {number} value A number between 0 and 1 * @param {number} value - A number between 0 and 1
*/ */
setPeerValue (peerId, value) { setPeerValue (peerId, value) {
if (value < 0 || value > 1) { if (value < 0 || value > 1) {
@ -167,6 +173,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Checks the libp2p metrics to determine if any values have exceeded * Checks the libp2p metrics to determine if any values have exceeded
* the configured maximums. * the configured maximums.
*
* @private * @private
*/ */
_checkMetrics () { _checkMetrics () {
@ -183,6 +190,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Tracks the incoming connection and check the connection limit * Tracks the incoming connection and check the connection limit
*
* @param {Connection} connection * @param {Connection} connection
*/ */
onConnect (connection) { onConnect (connection) {
@ -208,6 +216,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Removes the connection from tracking * Removes the connection from tracking
*
* @param {Connection} connection * @param {Connection} connection
*/ */
onDisconnect (connection) { onDisconnect (connection) {
@ -226,6 +235,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Get a connection with a peer. * Get a connection with a peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Connection} * @returns {Connection}
*/ */
@ -239,6 +249,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Get all open connections with a peer. * Get all open connections with a peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<Connection>} * @returns {Array<Connection>}
*/ */
@ -259,8 +270,9 @@ class ConnectionManager extends EventEmitter {
/** /**
* If the event loop is slow, maybe close a connection * If the event loop is slow, maybe close a connection
*
* @private * @private
* @param {*} summary The LatencyMonitor summary * @param {*} summary - The LatencyMonitor summary
*/ */
_onLatencyMeasure (summary) { _onLatencyMeasure (summary) {
this._checkMaxLimit('maxEventLoopDelay', summary.avgMs) this._checkMaxLimit('maxEventLoopDelay', summary.avgMs)
@ -268,9 +280,10 @@ class ConnectionManager extends EventEmitter {
/** /**
* If the `value` of `name` has exceeded its limit, maybe close a connection * If the `value` of `name` has exceeded its limit, maybe close a connection
*
* @private * @private
* @param {string} name The name of the field to check limits for * @param {string} name - The name of the field to check limits for
* @param {number} value The current value of the field * @param {number} value - The current value of the field
*/ */
_checkMaxLimit (name, value) { _checkMaxLimit (name, value) {
const limit = this._options[name] const limit = this._options[name]
@ -285,6 +298,7 @@ class ConnectionManager extends EventEmitter {
* Proactively tries to connect to known peers stored in the PeerStore. * Proactively tries to connect to known peers stored in the PeerStore.
* It will keep the number of connections below the upper limit and sort * It will keep the number of connections below the upper limit and sort
* the peers to connect based on wether we know their keys and protocols. * the peers to connect based on wether we know their keys and protocols.
*
* @async * @async
* @private * @private
*/ */
@ -330,6 +344,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* If we have more connections than our maximum, close a connection * If we have more connections than our maximum, close a connection
* to the lowest valued peer. * to the lowest valued peer.
*
* @private * @private
*/ */
_maybeDisconnectOne () { _maybeDisconnectOne () {

View File

@ -12,11 +12,11 @@ const debug = require('debug')('latency-monitor:LatencyMonitor')
/** /**
* @typedef {Object} SummaryObject * @typedef {Object} SummaryObject
* @property {Number} events How many events were called * @property {number} events How many events were called
* @property {Number} minMS What was the min time for a cb to be called * @property {number} minMS What was the min time for a cb to be called
* @property {Number} maxMS What was the max time for a cb to be called * @property {number} maxMS What was the max time for a cb to be called
* @property {Number} avgMs What was the average time for a cb to be called * @property {number} avgMs What was the average time for a cb to be called
* @property {Number} lengthMs How long this interval was in ms * @property {number} lengthMs How long this interval was in ms
*/ */
/** /**
@ -37,10 +37,11 @@ const debug = require('debug')('latency-monitor:LatencyMonitor')
*/ */
class LatencyMonitor extends EventEmitter { class LatencyMonitor extends EventEmitter {
/** /**
* @param {Number} [latencyCheckIntervalMs=500] How often to add a latency check event (ms) * @param {object} [options]
* @param {Number} [dataEmitIntervalMs=5000] How often to summarize latency check events. null or 0 disables event firing * @param {number} [options.latencyCheckIntervalMs=500] - How often to add a latency check event (ms)
* @param {function} [asyncTestFn] What cb-style async function to use * @param {number} [options.dataEmitIntervalMs=5000] - How often to summarize latency check events. null or 0 disables event firing
* @param {Number} [latencyRandomPercentage=5] What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events. * @param {Function} [options.asyncTestFn] - What cb-style async function to use
* @param {number} [options.latencyRandomPercentage=5] - What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.
*/ */
constructor ({ latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = {}) { constructor ({ latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = {}) {
super() super()
@ -107,6 +108,7 @@ class LatencyMonitor extends EventEmitter {
/** /**
* Start internal timers * Start internal timers
*
* @private * @private
*/ */
_startTimers () { _startTimers () {
@ -125,6 +127,7 @@ class LatencyMonitor extends EventEmitter {
/** /**
* Stop internal timers * Stop internal timers
*
* @private * @private
*/ */
_stopTimers () { _stopTimers () {
@ -140,6 +143,7 @@ class LatencyMonitor extends EventEmitter {
/** /**
* Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show
*
* @private * @private
*/ */
_emitSummary () { _emitSummary () {
@ -152,6 +156,7 @@ class LatencyMonitor extends EventEmitter {
/** /**
* Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue, * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,
* it will not count for this time period * it will not count for this time period
*
* @returns {SummaryObject} * @returns {SummaryObject}
*/ */
getSummary () { getSummary () {

View File

@ -52,6 +52,7 @@ module.exports = class VisibilityChangeEmitter extends EventEmitter {
* the appropriate name based on the browser being used. Once executed, tha actual names of * the appropriate name based on the browser being used. Once executed, tha actual names of
* document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange
* respectively * respectively
*
* @private * @private
*/ */
_initializeVisibilityVarNames () { _initializeVisibilityVarNames () {
@ -77,6 +78,7 @@ module.exports = class VisibilityChangeEmitter extends EventEmitter {
/** /**
* Adds an event listener on the document that listens to changes in document.visibilityChange * Adds an event listener on the document that listens to changes in document.visibilityChange
* (or whatever name by which the visibilityChange variable is known in the browser) * (or whatever name by which the visibilityChange variable is known in the browser)
*
* @private * @private
*/ */
_addVisibilityChangeListener () { _addVisibilityChangeListener () {
@ -92,7 +94,8 @@ module.exports = class VisibilityChangeEmitter extends EventEmitter {
/** /**
* The function returns ```true``` if the page is visible or ```false``` if the page is not visible and * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and
* ```undefined``` if the page visibility API is not supported by the browser. * ```undefined``` if the page visibility API is not supported by the browser.
* @returns {Boolean|void} whether the page is now visible or not (undefined is unknown) *
* @returns {boolean | void} whether the page is now visible or not (undefined is unknown)
*/ */
isVisible () { isVisible () {
if (this._hidden === undefined || document[this._hidden] === undefined) { if (this._hidden === undefined || document[this._hidden] === undefined) {

View File

@ -20,9 +20,9 @@ module.exports = (node) => {
* Iterates over all content routers in series to find providers of the given key. * Iterates over all content routers in series to find providers of the given key.
* Once a content router succeeds, iteration will stop. * Once a content router succeeds, iteration will stop.
* *
* @param {CID} key The CID key of the content to find * @param {CID} key - The CID key of the content to find
* @param {object} [options] * @param {object} [options]
* @param {number} [options.timeout] How long the query should run * @param {number} [options.timeout] - How long the query should run
* @param {number} [options.maxNumProviders] - maximum number of providers to find * @param {number} [options.maxNumProviders] - maximum number of providers to find
* @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} * @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>}
*/ */
@ -51,7 +51,7 @@ module.exports = (node) => {
* Iterates over all content routers in parallel to notify it is * Iterates over all content routers in parallel to notify it is
* a provider of the given key. * a provider of the given key.
* *
* @param {CID} key The CID key of the content to find * @param {CID} key - The CID key of the content to find
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async provide (key) { // eslint-disable-line require-await async provide (key) { // eslint-disable-line require-await
@ -64,6 +64,7 @@ module.exports = (node) => {
/** /**
* Store the given key/value pair in the DHT. * Store the given key/value pair in the DHT.
*
* @param {Uint8Array} key * @param {Uint8Array} key
* @param {Uint8Array} value * @param {Uint8Array} value
* @param {Object} [options] - put options * @param {Object} [options] - put options
@ -81,6 +82,7 @@ module.exports = (node) => {
/** /**
* Get the value to the given key. * Get the value to the given key.
* Times out after 1 minute by default. * Times out after 1 minute by default.
*
* @param {Uint8Array} key * @param {Uint8Array} key
* @param {Object} [options] - get options * @param {Object} [options] - get options
* @param {number} [options.timeout] - optional timeout (default: 60000) * @param {number} [options.timeout] - optional timeout (default: 60000)
@ -96,6 +98,7 @@ module.exports = (node) => {
/** /**
* Get the `n` values to the given key without sorting. * Get the `n` values to the given key without sorting.
*
* @param {Uint8Array} key * @param {Uint8Array} key
* @param {number} nVals * @param {number} nVals
* @param {Object} [options] - get options * @param {Object} [options] - get options

View File

@ -16,6 +16,7 @@ class DialRequest {
* from `dialer.getTokens`. Once a DialRequest is created, it can be * from `dialer.getTokens`. Once a DialRequest is created, it can be
* started using `DialRequest.run(options)`. Once a single dial has succeeded, * started using `DialRequest.run(options)`. Once a single dial has succeeded,
* all other dials in the request will be cancelled. * all other dials in the request will be cancelled.
*
* @param {object} options * @param {object} options
* @param {Multiaddr[]} options.addrs * @param {Multiaddr[]} options.addrs
* @param {function(Multiaddr):Promise<Connection>} options.dialAction * @param {function(Multiaddr):Promise<Connection>} options.dialAction
@ -34,7 +35,7 @@ class DialRequest {
/** /**
* @async * @async
* @param {object} options * @param {object} options
* @param {AbortSignal} options.signal An AbortController signal * @param {AbortSignal} options.signal - An AbortController signal
* @returns {Connection} * @returns {Connection}
*/ */
async run (options) { async run (options) {

View File

@ -20,12 +20,13 @@ const {
class Dialer { class Dialer {
/** /**
* @constructor * @class
* @param {object} options * @param {object} options
* @param {TransportManager} options.transportManager * @param {TransportManager} options.transportManager
* @param {Peerstore} peerStore * @param {Peerstore} options.peerStore
* @param {number} options.concurrency Number of max concurrent dials. Defaults to `MAX_PARALLEL_DIALS` * @param {number} [options.concurrency = MAX_PARALLEL_DIALS] - Number of max concurrent dials.
* @param {number} options.timeout How long a dial attempt is allowed to take. Defaults to `DIAL_TIMEOUT` * @param {number} [options.perPeerLimit = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer.
* @param {number} [options.timeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take.
*/ */
constructor ({ constructor ({
transportManager, transportManager,
@ -62,9 +63,9 @@ class Dialer {
* The dial to the first address that is successfully able to upgrade a connection * The dial to the first address that is successfully able to upgrade a connection
* will be used. * will be used.
* *
* @param {PeerId|Multiaddr|string} peer The peer to dial * @param {PeerId|Multiaddr|string} peer - The peer to dial
* @param {object} [options] * @param {object} [options]
* @param {AbortSignal} [options.signal] An AbortController signal * @param {AbortSignal} [options.signal] - An AbortController signal
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
async connectToPeer (peer, options = {}) { async connectToPeer (peer, options = {}) {
@ -101,8 +102,9 @@ class Dialer {
* Creates a DialTarget. The DialTarget is used to create and track * Creates a DialTarget. The DialTarget is used to create and track
* the DialRequest to a given peer. * the DialRequest to a given peer.
* If a multiaddr is received it should be the first address attempted. * If a multiaddr is received it should be the first address attempted.
*
* @private * @private
* @param {PeerId|Multiaddr|string} peer A PeerId or Multiaddr * @param {PeerId|Multiaddr|string} peer - A PeerId or Multiaddr
* @returns {DialTarget} * @returns {DialTarget}
*/ */
_createDialTarget (peer) { _createDialTarget (peer) {
@ -137,10 +139,11 @@ class Dialer {
/** /**
* Creates a PendingDial that wraps the underlying DialRequest * Creates a PendingDial that wraps the underlying DialRequest
*
* @private * @private
* @param {DialTarget} dialTarget * @param {DialTarget} dialTarget
* @param {object} [options] * @param {object} [options]
* @param {AbortSignal} [options.signal] An AbortController signal * @param {AbortSignal} [options.signal] - An AbortController signal
* @returns {PendingDial} * @returns {PendingDial}
*/ */
_createPendingDial (dialTarget, options) { _createPendingDial (dialTarget, options) {

View File

@ -9,8 +9,8 @@ const { codes } = require('./errors')
/** /**
* Converts the given `peer` to a `Peer` object. * Converts the given `peer` to a `Peer` object.
* If a multiaddr is received, the addressBook is updated. * If a multiaddr is received, the addressBook is updated.
*
* @param {PeerId|Multiaddr|string} peer * @param {PeerId|Multiaddr|string} peer
* @param {PeerStore} peerStore
* @returns {{ id: PeerId, multiaddrs: Array<Multiaddr> }} * @returns {{ id: PeerId, multiaddrs: Array<Multiaddr> }}
*/ */
function getPeer (peer) { function getPeer (peer) {

View File

@ -32,7 +32,8 @@ const { codes } = require('../errors')
class IdentifyService { class IdentifyService {
/** /**
* Takes the `addr` and converts it to a Multiaddr if possible * Takes the `addr` and converts it to a Multiaddr if possible
* @param {Uint8Array|String} addr *
* @param {Uint8Array | string} addr
* @returns {Multiaddr|null} * @returns {Multiaddr|null}
*/ */
static getCleanMultiaddr (addr) { static getCleanMultiaddr (addr) {
@ -47,10 +48,10 @@ class IdentifyService {
} }
/** /**
* @constructor * @class
* @param {object} options * @param {object} options
* @param {Libp2p} options.libp2p * @param {Libp2p} options.libp2p
* @param {Map<string, handler>} options.protocols A reference to the protocols we support * @param {Map<string, handler>} options.protocols - A reference to the protocols we support
*/ */
constructor ({ libp2p, protocols }) { constructor ({ libp2p, protocols }) {
/** /**
@ -86,6 +87,7 @@ class IdentifyService {
/** /**
* Send an Identify Push update to the list of connections * Send an Identify Push update to the list of connections
*
* @param {Array<Connection>} connections * @param {Array<Connection>} connections
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
@ -119,6 +121,7 @@ class IdentifyService {
/** /**
* Calls `push` for all peers in the `peerStore` that are connected * Calls `push` for all peers in the `peerStore` that are connected
*
* @param {PeerStore} peerStore * @param {PeerStore} peerStore
*/ */
pushToPeerStore (peerStore) { pushToPeerStore (peerStore) {
@ -209,7 +212,7 @@ class IdentifyService {
* A handler to register with Libp2p to process identify messages. * A handler to register with Libp2p to process identify messages.
* *
* @param {object} options * @param {object} options
* @param {String} options.protocol * @param {string} options.protocol
* @param {*} options.stream * @param {*} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
* @returns {Promise<void>} * @returns {Promise<void>}
@ -228,6 +231,7 @@ class IdentifyService {
/** /**
* Sends the `Identify` response with the Signed Peer Record * Sends the `Identify` response with the Signed Peer Record
* to the requesting peer over the given `connection` * to the requesting peer over the given `connection`
*
* @private * @private
* @param {object} options * @param {object} options
* @param {*} options.stream * @param {*} options.stream
@ -265,6 +269,7 @@ class IdentifyService {
/** /**
* Reads the Identify Push message from the given `connection` * Reads the Identify Push message from the given `connection`
*
* @private * @private
* @param {object} options * @param {object} options
* @param {*} options.stream * @param {*} options.stream
@ -311,7 +316,8 @@ class IdentifyService {
/** /**
* Get self signed peer record raw envelope. * Get self signed peer record raw envelope.
* @return {Uint8Array} *
* @returns {Uint8Array}
*/ */
async _getSelfPeerRecord () { async _getSelfPeerRecord () {
const selfSignedPeerRecord = this.peerStore.addressBook.getRawEnvelope(this.peerId) const selfSignedPeerRecord = this.peerStore.addressBook.getRawEnvelope(this.peerId)
@ -340,6 +346,7 @@ class IdentifyService {
module.exports.IdentifyService = IdentifyService module.exports.IdentifyService = IdentifyService
/** /**
* The protocols the IdentifyService supports * The protocols the IdentifyService supports
*
* @property multicodecs * @property multicodecs
*/ */
module.exports.multicodecs = { module.exports.multicodecs = {

View File

@ -206,6 +206,7 @@ class Libp2p extends EventEmitter {
/** /**
* Overrides EventEmitter.emit to conditionally emit errors * Overrides EventEmitter.emit to conditionally emit errors
* if there is a handler. If not, errors will be logged. * if there is a handler. If not, errors will be logged.
*
* @param {string} eventName * @param {string} eventName
* @param {...any} args * @param {...any} args
* @returns {void} * @returns {void}
@ -240,6 +241,7 @@ class Libp2p extends EventEmitter {
/** /**
* Stop the libp2p node by closing its listeners and open connections * Stop the libp2p node by closing its listeners and open connections
*
* @async * @async
* @returns {void} * @returns {void}
*/ */
@ -281,6 +283,7 @@ class Libp2p extends EventEmitter {
/** /**
* Load keychain keys from the datastore. * Load keychain keys from the datastore.
* Imports the private key as 'self', if needed. * Imports the private key as 'self', if needed.
*
* @async * @async
* @returns {void} * @returns {void}
*/ */
@ -299,6 +302,7 @@ class Libp2p extends EventEmitter {
/** /**
* Gets a Map of the current connections. The keys are the stringified * Gets a Map of the current connections. The keys are the stringified
* `PeerId` of the peer. The value is an array of Connections to that peer. * `PeerId` of the peer. The value is an array of Connections to that peer.
*
* @returns {Map<string, Connection[]>} * @returns {Map<string, Connection[]>}
*/ */
get connections () { get connections () {
@ -308,7 +312,8 @@ class Libp2p extends EventEmitter {
/** /**
* Dials to the provided peer. If successful, the known metadata of the * Dials to the provided peer. If successful, the known metadata of the
* peer will be added to the nodes `peerStore` * peer will be added to the nodes `peerStore`
* @param {PeerId|Multiaddr|string} peer The peer to dial *
* @param {PeerId|Multiaddr|string} peer - The peer to dial
* @param {object} options * @param {object} options
* @param {AbortSignal} [options.signal] * @param {AbortSignal} [options.signal]
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
@ -321,8 +326,9 @@ class Libp2p extends EventEmitter {
* Dials to the provided peer and handshakes with the given protocol. * Dials to the provided peer and handshakes with the given protocol.
* If successful, the known metadata of the peer will be added to the nodes `peerStore`, * If successful, the known metadata of the peer will be added to the nodes `peerStore`,
* and the `Connection` will be returned * and the `Connection` will be returned
*
* @async * @async
* @param {PeerId|Multiaddr|string} peer The peer to dial * @param {PeerId|Multiaddr|string} peer - The peer to dial
* @param {string[]|string} protocols * @param {string[]|string} protocols
* @param {object} options * @param {object} options
* @param {AbortSignal} [options.signal] * @param {AbortSignal} [options.signal]
@ -350,7 +356,8 @@ class Libp2p extends EventEmitter {
* Get peer advertising multiaddrs by concating the addresses used * Get peer advertising multiaddrs by concating the addresses used
* by transports to listen with the announce addresses. * by transports to listen with the announce addresses.
* Duplicated addresses and noAnnounce addresses are filtered out. * Duplicated addresses and noAnnounce addresses are filtered out.
* @return {Array<Multiaddr>} *
* @returns {Array<Multiaddr>}
*/ */
get multiaddrs () { get multiaddrs () {
// Filter noAnnounce multiaddrs // Filter noAnnounce multiaddrs
@ -376,7 +383,8 @@ class Libp2p extends EventEmitter {
/** /**
* Disconnects all connections to the given `peer` * Disconnects all connections to the given `peer`
* @param {PeerId|multiaddr|string} peer the peer to close connections to *
* @param {PeerId|multiaddr|string} peer - the peer to close connections to
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async hangUp (peer) { async hangUp (peer) {
@ -397,7 +405,8 @@ class Libp2p extends EventEmitter {
/** /**
* Pings the given peer in order to obtain the operation latency. * Pings the given peer in order to obtain the operation latency.
* @param {PeerId|Multiaddr|string} peer The peer to ping *
* @param {PeerId|Multiaddr|string} peer - The peer to ping
* @returns {Promise<number>} * @returns {Promise<number>}
*/ */
ping (peer) { ping (peer) {
@ -413,6 +422,7 @@ class Libp2p extends EventEmitter {
/** /**
* Registers the `handler` for each protocol * Registers the `handler` for each protocol
*
* @param {string[]|string} protocols * @param {string[]|string} protocols
* @param {function({ connection:*, stream:*, protocol:string })} handler * @param {function({ connection:*, stream:*, protocol:string })} handler
*/ */
@ -431,6 +441,7 @@ class Libp2p extends EventEmitter {
/** /**
* Removes the handler for each protocol. The protocol * Removes the handler for each protocol. The protocol
* will no longer be supported on streams. * will no longer be supported on streams.
*
* @param {string[]|string} protocols * @param {string[]|string} protocols
*/ */
unhandle (protocols) { unhandle (protocols) {
@ -471,6 +482,7 @@ class Libp2p extends EventEmitter {
/** /**
* Called when libp2p has started and before it returns * Called when libp2p has started and before it returns
*
* @private * @private
*/ */
async _onDidStart () { async _onDidStart () {
@ -496,6 +508,7 @@ class Libp2p extends EventEmitter {
/** /**
* Called whenever peer discovery services emit `peer` events. * Called whenever peer discovery services emit `peer` events.
* Known peers may be emitted. * Known peers may be emitted.
*
* @private * @private
* @param {{ id: PeerId, multiaddrs: Array<Multiaddr>, protocols: Array<string> }} peer * @param {{ id: PeerId, multiaddrs: Array<Multiaddr>, protocols: Array<string> }} peer
*/ */
@ -513,6 +526,7 @@ class Libp2p extends EventEmitter {
* Will dial to the given `peerId` if the current number of * Will dial to the given `peerId` if the current number of
* connected peers is less than the configured `ConnectionManager` * connected peers is less than the configured `ConnectionManager`
* minConnections. * minConnections.
*
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
*/ */
@ -586,7 +600,8 @@ class Libp2p extends EventEmitter {
/** /**
* Like `new Libp2p(options)` except it will create a `PeerId` * Like `new Libp2p(options)` except it will create a `PeerId`
* instance if one is not provided in options. * instance if one is not provided in options.
* @param {object} options Libp2p configuration options *
* @param {object} options - Libp2p configuration options
* @returns {Libp2p} * @returns {Libp2p}
*/ */
Libp2p.create = async function create (options = {}) { Libp2p.create = async function create (options = {}) {

View File

@ -77,7 +77,7 @@ exports.certificateForKey = (key, privateKey) => {
* resolve to either `true` or `false`. * resolve to either `true` or `false`.
* *
* @param {Array} array * @param {Array} array
* @param {function(*)} asyncCompare An async function that returns a boolean * @param {function(*)} asyncCompare - An async function that returns a boolean
*/ */
async function findAsync (array, asyncCompare) { async function findAsync (array, asyncCompare) {
const promises = array.map(asyncCompare) const promises = array.map(asyncCompare)

View File

@ -66,6 +66,7 @@ class Metrics {
/** /**
* Gets the global `Stats` object * Gets the global `Stats` object
*
* @returns {Stats} * @returns {Stats}
*/ */
get global () { get global () {
@ -74,6 +75,7 @@ class Metrics {
/** /**
* Returns a list of `PeerId` strings currently being tracked * Returns a list of `PeerId` strings currently being tracked
*
* @returns {Array<string>} * @returns {Array<string>}
*/ */
get peers () { get peers () {
@ -83,6 +85,7 @@ class Metrics {
/** /**
* Returns the `Stats` object for the given `PeerId` whether it * Returns the `Stats` object for the given `PeerId` whether it
* is a live peer, or in the disconnected peer LRU cache. * is a live peer, or in the disconnected peer LRU cache.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Stats} * @returns {Stats}
*/ */
@ -93,6 +96,7 @@ class Metrics {
/** /**
* Returns a list of all protocol strings currently being tracked. * Returns a list of all protocol strings currently being tracked.
*
* @returns {Array<string>} * @returns {Array<string>}
*/ */
get protocols () { get protocols () {
@ -101,6 +105,7 @@ class Metrics {
/** /**
* Returns the `Stats` object for the given `protocol`. * Returns the `Stats` object for the given `protocol`.
*
* @param {string} protocol * @param {string} protocol
* @returns {Stats} * @returns {Stats}
*/ */
@ -112,6 +117,7 @@ class Metrics {
* Should be called when all connections to a given peer * Should be called when all connections to a given peer
* have closed. The `Stats` collection for the peer will * have closed. The `Stats` collection for the peer will
* be stopped and moved to an LRU for temporary retention. * be stopped and moved to an LRU for temporary retention.
*
* @param {PeerId} peerId * @param {PeerId} peerId
*/ */
onPeerDisconnected (peerId) { onPeerDisconnected (peerId) {
@ -131,10 +137,10 @@ class Metrics {
* *
* @private * @private
* @param {object} params * @param {object} params
* @param {PeerId} params.remotePeer Remote peer * @param {PeerId} params.remotePeer - Remote peer
* @param {string} [params.protocol] Protocol string the stream is running * @param {string} [params.protocol] - Protocol string the stream is running
* @param {string} params.direction One of ['in','out'] * @param {string} params.direction - One of ['in','out']
* @param {number} params.dataLength Size of the message * @param {number} params.dataLength - Size of the message
* @returns {void} * @returns {void}
*/ */
_onMessage ({ remotePeer, protocol, direction, dataLength }) { _onMessage ({ remotePeer, protocol, direction, dataLength }) {
@ -167,7 +173,8 @@ class Metrics {
* Replaces the `PeerId` string with the given `peerId`. * Replaces the `PeerId` string with the given `peerId`.
* If stats are already being tracked for the given `peerId`, the * If stats are already being tracked for the given `peerId`, the
* placeholder stats will be merged with the existing stats. * placeholder stats will be merged with the existing stats.
* @param {PeerId} placeholder A peerId string *
* @param {PeerId} placeholder - A peerId string
* @param {PeerId} peerId * @param {PeerId} peerId
*/ */
updatePlaceholder (placeholder, peerId) { updatePlaceholder (placeholder, peerId) {
@ -198,9 +205,9 @@ class Metrics {
* with the placeholder string returned from here, and the known `PeerId`. * with the placeholder string returned from here, and the known `PeerId`.
* *
* @param {Object} options * @param {Object} options
* @param {{ sink: function(*), source: function() }} options.stream A duplex iterable stream * @param {{ sink: function(*), source: function() }} options.stream - A duplex iterable stream
* @param {PeerId} [options.peerId] The id of the remote peer that's connected * @param {PeerId} [options.remotePeer] - The id of the remote peer that's connected
* @param {string} [options.protocol] The protocol the stream is running * @param {string} [options.protocol] - The protocol the stream is running
* @returns {string} The peerId string or placeholder string * @returns {string} The peerId string or placeholder string
*/ */
trackStream ({ stream, remotePeer, protocol }) { trackStream ({ stream, remotePeer, protocol }) {
@ -233,6 +240,7 @@ class Metrics {
/** /**
* Merges `other` into `target`. `target` will be modified * Merges `other` into `target`. `target` will be modified
* and returned. * and returned.
*
* @param {Stats} target * @param {Stats} target
* @param {Stats} other * @param {Stats} other
* @returns {Stats} * @returns {Stats}

View File

@ -5,7 +5,7 @@ const LRU = require('hashlru')
/** /**
* Creates and returns a Least Recently Used Cache * Creates and returns a Least Recently Used Cache
* *
* @param {Number} maxSize * @param {number} maxSize
* @returns {LRUCache} * @returns {LRUCache}
*/ */
module.exports = (maxSize) => { module.exports = (maxSize) => {

View File

@ -196,8 +196,8 @@ class Stats extends EventEmitter {
* *
* @private * @private
* @param {string} key * @param {string} key
* @param {number} timeDiffMS Time in milliseconds * @param {number} timeDiffMS - Time in milliseconds
* @param {Timestamp} latestTime Time in ticks * @param {Timestamp} latestTime - Time in ticks
* @returns {void} * @returns {void}
*/ */
_updateFrequencyFor (key, timeDiffMS, latestTime) { _updateFrequencyFor (key, timeDiffMS, latestTime) {

View File

@ -15,9 +15,9 @@ module.exports = (node) => {
/** /**
* Iterates over all peer routers in series to find the given peer. * Iterates over all peer routers in series to find the given peer.
* *
* @param {String} id The id of the peer to find * @param {string} id - The id of the peer to find
* @param {object} [options] * @param {object} [options]
* @param {number} [options.timeout] How long the query should run * @param {number} [options.timeout] - How long the query should run
* @returns {Promise<{ id: PeerId, multiaddrs: Multiaddr[] }>} * @returns {Promise<{ id: PeerId, multiaddrs: Multiaddr[] }>}
*/ */
findPeer: async (id, options) => { // eslint-disable-line require-await findPeer: async (id, options) => { // eslint-disable-line require-await

View File

@ -23,6 +23,7 @@ const Envelope = require('../record/envelope')
class AddressBook extends Book { class AddressBook extends Book {
/** /**
* Address object * Address object
*
* @typedef {Object} Address * @typedef {Object} Address
* @property {Multiaddr} multiaddr peer multiaddr. * @property {Multiaddr} multiaddr peer multiaddr.
* @property {boolean} isCertified obtained from a signed peer record. * @property {boolean} isCertified obtained from a signed peer record.
@ -30,6 +31,7 @@ class AddressBook extends Book {
/** /**
* CertifiedRecord object * CertifiedRecord object
*
* @typedef {Object} CertifiedRecord * @typedef {Object} CertifiedRecord
* @property {Uint8Array} raw raw envelope. * @property {Uint8Array} raw raw envelope.
* @property {number} seqNumber seq counter. * @property {number} seqNumber seq counter.
@ -37,13 +39,14 @@ class AddressBook extends Book {
/** /**
* Entry object for the addressBook * Entry object for the addressBook
*
* @typedef {Object} Entry * @typedef {Object} Entry
* @property {Array<Address>} addresses peer Addresses. * @property {Array<Address>} addresses peer Addresses.
* @property {CertifiedRecord} record certified peer record. * @property {CertifiedRecord} record certified peer record.
*/ */
/** /**
* @constructor * @class
* @param {PeerStore} peerStore * @param {PeerStore} peerStore
*/ */
constructor (peerStore) { constructor (peerStore) {
@ -66,6 +69,7 @@ class AddressBook extends Book {
/** /**
* Map known peers to their known Address Entries. * Map known peers to their known Address Entries.
*
* @type {Map<string, Array<Entry>>} * @type {Map<string, Array<Entry>>}
*/ */
this.data = new Map() this.data = new Map()
@ -75,8 +79,9 @@ class AddressBook extends Book {
* ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope. * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope.
* This will return a boolean that indicates if the record was successfully processed and added * This will return a boolean that indicates if the record was successfully processed and added
* into the AddressBook. * into the AddressBook.
*
* @param {Envelope} envelope * @param {Envelope} envelope
* @return {boolean} * @returns {boolean}
*/ */
consumePeerRecord (envelope) { consumePeerRecord (envelope) {
let peerRecord let peerRecord
@ -127,8 +132,9 @@ class AddressBook extends Book {
/** /**
* Get the raw Envelope for a peer. Returns * Get the raw Envelope for a peer. Returns
* undefined if no Envelope is found. * undefined if no Envelope is found.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @return {Uint8Array|undefined} * @returns {Uint8Array|undefined}
*/ */
getRawEnvelope (peerId) { getRawEnvelope (peerId) {
const entry = this.data.get(peerId.toB58String()) const entry = this.data.get(peerId.toB58String())
@ -143,8 +149,9 @@ class AddressBook extends Book {
/** /**
* Get an Envelope containing a PeerRecord for the given peer. * Get an Envelope containing a PeerRecord for the given peer.
* Returns undefined if no record exists. * Returns undefined if no record exists.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @return {Promise<Envelope|void>} * @returns {Promise<Envelope|void>}
*/ */
getPeerRecord (peerId) { getPeerRecord (peerId) {
const raw = this.getRawEnvelope(peerId) const raw = this.getRawEnvelope(peerId)
@ -161,6 +168,7 @@ class AddressBook extends Book {
* This will replace previously stored multiaddrs, if available. * This will replace previously stored multiaddrs, if available.
* Replacing stored multiaddrs might result in losing obtained certified addresses. * Replacing stored multiaddrs might result in losing obtained certified addresses.
* If you are not sure, it's recommended to use `add` instead. * If you are not sure, it's recommended to use `add` instead.
*
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<Multiaddr>} multiaddrs * @param {Array<Multiaddr>} multiaddrs
@ -211,6 +219,7 @@ class AddressBook extends Book {
/** /**
* Add known addresses of a provided peer. * Add known addresses of a provided peer.
* If the peer is not known, it is set with the given addresses. * If the peer is not known, it is set with the given addresses.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<Multiaddr>} multiaddrs * @param {Array<Multiaddr>} multiaddrs
* @returns {AddressBook} * @returns {AddressBook}
@ -258,6 +267,7 @@ class AddressBook extends Book {
/** /**
* Get the known data of a provided peer. * Get the known data of a provided peer.
*
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<data>} * @returns {Array<data>}
@ -274,6 +284,7 @@ class AddressBook extends Book {
/** /**
* Transforms received multiaddrs into Address. * Transforms received multiaddrs into Address.
*
* @private * @private
* @param {Array<Multiaddr>} multiaddrs * @param {Array<Multiaddr>} multiaddrs
* @param {boolean} [isCertified] * @param {boolean} [isCertified]
@ -306,6 +317,7 @@ class AddressBook extends Book {
* Get the known multiaddrs for a given peer. All returned multiaddrs * Get the known multiaddrs for a given peer. All returned multiaddrs
* will include the encapsulated `PeerId` of the peer. * will include the encapsulated `PeerId` of the peer.
* Returns `undefined` if there are no known multiaddrs for the given peer. * Returns `undefined` if there are no known multiaddrs for the given peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<Multiaddr>|undefined} * @returns {Array<Multiaddr>|undefined}
*/ */

View File

@ -14,12 +14,12 @@ const passthrough = data => data
*/ */
class Book { class Book {
/** /**
* @constructor * @class
* @param {Object} properties * @param {Object} properties
* @param {PeerStore} properties.peerStore PeerStore instance. * @param {PeerStore} properties.peerStore - PeerStore instance.
* @param {string} properties.eventName Name of the event to emit by the PeerStore. * @param {string} properties.eventName - Name of the event to emit by the PeerStore.
* @param {string} properties.eventProperty Name of the property to emit by the PeerStore. * @param {string} properties.eventProperty - Name of the property to emit by the PeerStore.
* @param {function} [properties.eventTransformer] Transformer function of the provided data for being emitted. * @param {Function} [properties.eventTransformer] - Transformer function of the provided data for being emitted.
*/ */
constructor ({ peerStore, eventName, eventProperty, eventTransformer = passthrough }) { constructor ({ peerStore, eventName, eventProperty, eventTransformer = passthrough }) {
this._ps = peerStore this._ps = peerStore
@ -29,6 +29,7 @@ class Book {
/** /**
* Map known peers to their data. * Map known peers to their data.
*
* @type {Map<string, Array<Data>} * @type {Map<string, Array<Data>}
*/ */
this.data = new Map() this.data = new Map()
@ -36,6 +37,7 @@ class Book {
/** /**
* Set known data of a provided peer. * Set known data of a provided peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<Data>|Data} data * @param {Array<Data>|Data} data
*/ */
@ -45,12 +47,13 @@ class Book {
/** /**
* Set data into the datastructure, persistence and emit it using the provided transformers. * Set data into the datastructure, persistence and emit it using the provided transformers.
*
* @private * @private
* @param {PeerId} peerId peerId of the data to store * @param {PeerId} peerId - peerId of the data to store
* @param {*} data data to store. * @param {*} data - data to store.
* @param {Object} [options] storing options. * @param {Object} [options] - storing options.
* @param {boolean} [options.emit = true] emit the provided data. * @param {boolean} [options.emit = true] - emit the provided data.
* @return {void} * @returns {void}
*/ */
_setData (peerId, data, { emit = true } = {}) { _setData (peerId, data, { emit = true } = {}) {
const b58key = peerId.toB58String() const b58key = peerId.toB58String()
@ -64,6 +67,7 @@ class Book {
/** /**
* Emit data. * Emit data.
*
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {*} data * @param {*} data
@ -78,6 +82,7 @@ class Book {
/** /**
* Get the known data of a provided peer. * Get the known data of a provided peer.
* Returns `undefined` if there is no available data for the given peer. * Returns `undefined` if there is no available data for the given peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<Data>|undefined} * @returns {Array<Data>|undefined}
*/ */
@ -93,6 +98,7 @@ class Book {
/** /**
* Deletes the provided peer from the book. * Deletes the provided peer from the book.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {boolean} * @returns {boolean}
*/ */

View File

@ -19,6 +19,7 @@ const {
/** /**
* Responsible for managing known peers, as well as their addresses, protocols and metadata. * Responsible for managing known peers, as well as their addresses, protocols and metadata.
*
* @fires PeerStore#peer Emitted when a new peer is added. * @fires PeerStore#peer Emitted when a new peer is added.
* @fires PeerStore#change:protocols Emitted when a known peer supports a different set of protocols. * @fires PeerStore#change:protocols Emitted when a known peer supports a different set of protocols.
* @fires PeerStore#change:multiaddrs Emitted when a known peer has a different set of multiaddrs. * @fires PeerStore#change:multiaddrs Emitted when a known peer has a different set of multiaddrs.
@ -28,6 +29,7 @@ const {
class PeerStore extends EventEmitter { class PeerStore extends EventEmitter {
/** /**
* Peer object * Peer object
*
* @typedef {Object} Peer * @typedef {Object} Peer
* @property {PeerId} id peer's peer-id instance. * @property {PeerId} id peer's peer-id instance.
* @property {Array<Address>} addresses peer's addresses containing its multiaddrs and metadata. * @property {Array<Address>} addresses peer's addresses containing its multiaddrs and metadata.
@ -36,7 +38,9 @@ class PeerStore extends EventEmitter {
*/ */
/** /**
* @constructor * @param {object} options
* @param {PeerId} options.peerId
* @class
*/ */
constructor ({ peerId }) { constructor ({ peerId }) {
super() super()
@ -76,6 +80,7 @@ class PeerStore extends EventEmitter {
/** /**
* Get all the stored information of every peer known. * Get all the stored information of every peer known.
*
* @returns {Map<string, Peer>} * @returns {Map<string, Peer>}
*/ */
get peers () { get peers () {
@ -99,6 +104,7 @@ class PeerStore extends EventEmitter {
/** /**
* Delete the information of the given peer in every book. * Delete the information of the given peer in every book.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {boolean} true if found and removed * @returns {boolean} true if found and removed
*/ */
@ -113,6 +119,7 @@ class PeerStore extends EventEmitter {
/** /**
* Get the stored information of a given peer. * Get the stored information of a given peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Peer} * @returns {Peer}
*/ */

View File

@ -18,7 +18,7 @@ const {
*/ */
class KeyBook extends Book { class KeyBook extends Book {
/** /**
* @constructor * @class
* @param {PeerStore} peerStore * @param {PeerStore} peerStore
*/ */
constructor (peerStore) { constructor (peerStore) {
@ -31,6 +31,7 @@ class KeyBook extends Book {
/** /**
* Map known peers to their known Public Key. * Map known peers to their known Public Key.
*
* @type {Map<string, PeerId>} * @type {Map<string, PeerId>}
*/ */
this.data = new Map() this.data = new Map()
@ -38,10 +39,11 @@ class KeyBook extends Book {
/** /**
* Set the Peer public key. * Set the Peer public key.
*
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey} publicKey * @param {RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey} publicKey
* @return {KeyBook} * @returns {KeyBook}
*/ */
set (peerId, publicKey) { set (peerId, publicKey) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {
@ -67,9 +69,10 @@ class KeyBook extends Book {
/** /**
* Get Public key of the given PeerId, if stored. * Get Public key of the given PeerId, if stored.
*
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @return {RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey} * @returns {RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey}
*/ */
get (peerId) { get (peerId) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {

View File

@ -17,11 +17,12 @@ const {
/** /**
* The MetadataBook is responsible for keeping the known supported * The MetadataBook is responsible for keeping the known supported
* protocols of a peer. * protocols of a peer.
*
* @fires MetadataBook#change:metadata * @fires MetadataBook#change:metadata
*/ */
class MetadataBook extends Book { class MetadataBook extends Book {
/** /**
* @constructor * @class
* @param {PeerStore} peerStore * @param {PeerStore} peerStore
*/ */
constructor (peerStore) { constructor (peerStore) {
@ -37,6 +38,7 @@ class MetadataBook extends Book {
/** /**
* Map known peers to their known protocols. * Map known peers to their known protocols.
*
* @type {Map<string, Map<string, Uint8Array>>} * @type {Map<string, Map<string, Uint8Array>>}
*/ */
this.data = new Map() this.data = new Map()
@ -44,10 +46,11 @@ class MetadataBook extends Book {
/** /**
* Set metadata key and value of a provided peer. * Set metadata key and value of a provided peer.
*
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {string} key metadata key * @param {string} key - metadata key
* @param {Uint8Array} value metadata value * @param {Uint8Array} value - metadata value
* @returns {ProtoBook} * @returns {ProtoBook}
*/ */
set (peerId, key, value) { set (peerId, key, value) {
@ -68,6 +71,7 @@ class MetadataBook extends Book {
/** /**
* Set data into the datastructure * Set data into the datastructure
*
* @override * @override
*/ */
_setValue (peerId, key, value, { emit = true } = {}) { _setValue (peerId, key, value, { emit = true } = {}) {
@ -89,6 +93,7 @@ class MetadataBook extends Book {
/** /**
* Get the known data of a provided peer. * Get the known data of a provided peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Map<string, Uint8Array>} * @returns {Map<string, Uint8Array>}
*/ */
@ -102,6 +107,7 @@ class MetadataBook extends Book {
/** /**
* Get specific metadata value, if it exists * Get specific metadata value, if it exists
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {string} key * @param {string} key
* @returns {Uint8Array} * @returns {Uint8Array}
@ -117,6 +123,7 @@ class MetadataBook extends Book {
/** /**
* Deletes the provided peer from the book. * Deletes the provided peer from the book.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {boolean} * @returns {boolean}
*/ */
@ -136,6 +143,7 @@ class MetadataBook extends Book {
/** /**
* Deletes the provided peer metadata key from the book. * Deletes the provided peer metadata key from the book.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {string} key * @param {string} key
* @returns {boolean} * @returns {boolean}

View File

@ -26,11 +26,11 @@ const Protocols = require('./pb/proto-book.proto')
*/ */
class PersistentPeerStore extends PeerStore { class PersistentPeerStore extends PeerStore {
/** /**
* @constructor * @class
* @param {Object} properties * @param {Object} properties
* @param {PeerId} properties.peerId * @param {PeerId} properties.peerId
* @param {Datastore} properties.datastore Datastore to persist data. * @param {Datastore} properties.datastore - Datastore to persist data.
* @param {number} [properties.threshold = 5] Number of dirty peers allowed before commit data. * @param {number} [properties.threshold = 5] - Number of dirty peers allowed before commit data.
*/ */
constructor ({ peerId, datastore, threshold = 5 }) { constructor ({ peerId, datastore, threshold = 5 }) {
super({ peerId }) super({ peerId })
@ -47,6 +47,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Peers metadata changed mapping peer identifers to metadata changed. * Peers metadata changed mapping peer identifers to metadata changed.
*
* @type {Map<string, Set<string>>} * @type {Map<string, Set<string>>}
*/ */
this._dirtyMetadata = new Map() this._dirtyMetadata = new Map()
@ -57,7 +58,8 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Start Persistent PeerStore. * Start Persistent PeerStore.
* @return {Promise<void>} *
* @returns {Promise<void>}
*/ */
async start () { async start () {
log('PeerStore is starting') log('PeerStore is starting')
@ -76,6 +78,11 @@ class PersistentPeerStore extends PeerStore {
log('PeerStore started') log('PeerStore started')
} }
/**
* Stop Persistent PeerStore.
*
* @returns {Promise<void>}
*/
async stop () { async stop () {
log('PeerStore is stopping') log('PeerStore is stopping')
this.removeAllListeners() this.removeAllListeners()
@ -85,6 +92,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add modified peer to the dirty set * Add modified peer to the dirty set
*
* @private * @private
* @param {Object} params * @param {Object} params
* @param {PeerId} params.peerId * @param {PeerId} params.peerId
@ -105,6 +113,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add modified metadata peer to the set. * Add modified metadata peer to the set.
*
* @private * @private
* @param {Object} params * @param {Object} params
* @param {PeerId} params.peerId * @param {PeerId} params.peerId
@ -131,9 +140,9 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add all the peers current data to a datastore batch and commit it. * Add all the peers current data to a datastore batch and commit it.
*
* @private * @private
* @param {Array<string>} peers * @returns {Promise<void>}
* @return {Promise<void>}
*/ */
async _commitData () { async _commitData () {
const commitPeers = Array.from(this._dirtyPeers) const commitPeers = Array.from(this._dirtyPeers)
@ -170,6 +179,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add address book data of the peer to the batch. * Add address book data of the peer to the batch.
*
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Object} batch * @param {Object} batch
@ -206,6 +216,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add Key book data of the peer to the batch. * Add Key book data of the peer to the batch.
*
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Object} batch * @param {Object} batch
@ -231,6 +242,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add metadata book data of the peer to the batch. * Add metadata book data of the peer to the batch.
*
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Object} batch * @param {Object} batch
@ -257,6 +269,7 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Add proto book data of the peer to the batch. * Add proto book data of the peer to the batch.
*
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Object} batch * @param {Object} batch
@ -284,11 +297,12 @@ class PersistentPeerStore extends PeerStore {
/** /**
* Process datastore entry and add its data to the correct book. * Process datastore entry and add its data to the correct book.
*
* @private * @private
* @param {Object} params * @param {Object} params
* @param {Key} params.key datastore key * @param {Key} params.key - datastore key
* @param {Uint8Array} params.value datastore value stored * @param {Uint8Array} params.value - datastore value stored
* @return {Promise<void>} * @returns {Promise<void>}
*/ */
async _processDatastoreEntry ({ key, value }) { async _processDatastoreEntry ({ key, value }) {
try { try {

View File

@ -16,11 +16,12 @@ const {
/** /**
* The ProtoBook is responsible for keeping the known supported * The ProtoBook is responsible for keeping the known supported
* protocols of a peer. * protocols of a peer.
*
* @fires ProtoBook#change:protocols * @fires ProtoBook#change:protocols
*/ */
class ProtoBook extends Book { class ProtoBook extends Book {
/** /**
* @constructor * @class
* @param {PeerStore} peerStore * @param {PeerStore} peerStore
*/ */
constructor (peerStore) { constructor (peerStore) {
@ -37,6 +38,7 @@ class ProtoBook extends Book {
/** /**
* Map known peers to their known protocols. * Map known peers to their known protocols.
*
* @type {Map<string, Set<string>>} * @type {Map<string, Set<string>>}
*/ */
this.data = new Map() this.data = new Map()
@ -45,6 +47,7 @@ class ProtoBook extends Book {
/** /**
* Set known protocols of a provided peer. * Set known protocols of a provided peer.
* If the peer was not known before, it will be added. * If the peer was not known before, it will be added.
*
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<string>} protocols * @param {Array<string>} protocols
@ -83,6 +86,7 @@ class ProtoBook extends Book {
/** /**
* Adds known protocols of a provided peer. * Adds known protocols of a provided peer.
* If the peer was not known before, it will be added. * If the peer was not known before, it will be added.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<string>} protocols * @param {Array<string>} protocols
* @returns {ProtoBook} * @returns {ProtoBook}

View File

@ -14,9 +14,10 @@ const { PROTOCOL, PING_LENGTH } = require('./constants')
/** /**
* Ping a given peer and wait for its response, getting the operation latency. * Ping a given peer and wait for its response, getting the operation latency.
*
* @param {Libp2p} node * @param {Libp2p} node
* @param {PeerId|multiaddr} peer * @param {PeerId|multiaddr} peer
* @returns {Promise<Number>} * @returns {Promise<number>}
*/ */
async function ping (node, peer) { async function ping (node, peer) {
log('dialing %s to %s', PROTOCOL, peer.toB58String ? peer.toB58String() : peer) log('dialing %s to %s', PROTOCOL, peer.toB58String ? peer.toB58String() : peer)
@ -44,6 +45,7 @@ async function ping (node, peer) {
/** /**
* Subscribe ping protocol handler. * Subscribe ping protocol handler.
*
* @param {Libp2p} node * @param {Libp2p} node
*/ */
function mount (node) { function mount (node) {
@ -52,6 +54,7 @@ function mount (node) {
/** /**
* Unsubscribe ping protocol handler. * Unsubscribe ping protocol handler.
*
* @param {Libp2p} node * @param {Libp2p} node
*/ */
function unmount (node) { function unmount (node) {

View File

@ -14,8 +14,8 @@ log.error = debug('libp2p:pnet:err')
/** /**
* Creates a stream iterable to encrypt messages in a private network * Creates a stream iterable to encrypt messages in a private network
* *
* @param {Uint8Array} nonce The nonce to use in encryption * @param {Uint8Array} nonce - The nonce to use in encryption
* @param {Uint8Array} psk The private shared key to use in encryption * @param {Uint8Array} psk - The private shared key to use in encryption
* @returns {*} a through iterable * @returns {*} a through iterable
*/ */
module.exports.createBoxStream = (nonce, psk) => { module.exports.createBoxStream = (nonce, psk) => {
@ -30,8 +30,8 @@ module.exports.createBoxStream = (nonce, psk) => {
/** /**
* Creates a stream iterable to decrypt messages in a private network * Creates a stream iterable to decrypt messages in a private network
* *
* @param {Uint8Array} nonce The nonce of the remote peer * @param {Uint8Array} nonce - The nonce of the remote peer
* @param {Uint8Array} psk The private shared key to use in decryption * @param {Uint8Array} psk - The private shared key to use in decryption
* @returns {*} a through iterable * @returns {*} a through iterable
*/ */
module.exports.createUnboxStream = (nonce, psk) => { module.exports.createUnboxStream = (nonce, psk) => {

View File

@ -25,8 +25,8 @@ log.error = debug('libp2p:pnet:err')
*/ */
class Protector { class Protector {
/** /**
* @param {Uint8Array} keyBuffer The private shared key buffer * @param {Uint8Array} keyBuffer - The private shared key buffer
* @constructor * @class
*/ */
constructor (keyBuffer) { constructor (keyBuffer) {
const decodedPSK = decodeV1PSK(keyBuffer) const decodedPSK = decodeV1PSK(keyBuffer)
@ -39,7 +39,7 @@ class Protector {
* between its two peers from the PSK the Protector instance was * between its two peers from the PSK the Protector instance was
* created with. * created with.
* *
* @param {Connection} connection The connection to protect * @param {Connection} connection - The connection to protect
* @returns {*} A protected duplex iterable * @returns {*} A protected duplex iterable
*/ */
async protect (connection) { async protect (connection) {

View File

@ -7,7 +7,8 @@ const uint8ArrayFromString = require('uint8arrays/from-string')
/** /**
* Generates a PSK that can be used in a libp2p-pnet private network * Generates a PSK that can be used in a libp2p-pnet private network
* @param {Uint8Array} bytes An object to write the psk into *
* @param {Uint8Array} bytes - An object to write the psk into
* @returns {void} * @returns {void}
*/ */
function generate (bytes) { function generate (bytes) {

View File

@ -5,6 +5,7 @@ module.exports = (PubsubRouter, libp2p, options) => {
class Pubsub extends PubsubRouter { class Pubsub extends PubsubRouter {
/** /**
* Subscribes to a given topic. * Subscribes to a given topic.
*
* @override * @override
* @param {string} topic * @param {string} topic
* @param {function(msg: InMessage)} [handler] * @param {function(msg: InMessage)} [handler]
@ -18,6 +19,7 @@ module.exports = (PubsubRouter, libp2p, options) => {
/** /**
* Unsubscribe from the given topic. * Unsubscribe from the given topic.
*
* @override * @override
* @param {string} topic * @param {string} topic
* @param {function(msg: InMessage)} [handler] * @param {function(msg: InMessage)} [handler]

View File

@ -20,12 +20,12 @@ const Protobuf = require('./envelope.proto')
*/ */
class Envelope { class Envelope {
/** /**
* @constructor * @class
* @param {object} params * @param {object} params
* @param {PeerId} params.peerId * @param {PeerId} params.peerId
* @param {Uint8Array} params.payloadType * @param {Uint8Array} params.payloadType
* @param {Uint8Array} params.payload marshaled record * @param {Uint8Array} params.payload - marshaled record
* @param {Uint8Array} params.signature signature of the domain string :: type hint :: payload. * @param {Uint8Array} params.signature - signature of the domain string :: type hint :: payload.
*/ */
constructor ({ peerId, payloadType, payload, signature }) { constructor ({ peerId, payloadType, payload, signature }) {
this.peerId = peerId this.peerId = peerId
@ -39,7 +39,8 @@ class Envelope {
/** /**
* Marshal the envelope content. * Marshal the envelope content.
* @return {Uint8Array} *
* @returns {Uint8Array}
*/ */
marshal () { marshal () {
if (this._marshal) { if (this._marshal) {
@ -60,8 +61,9 @@ class Envelope {
/** /**
* Verifies if the other Envelope is identical to this one. * Verifies if the other Envelope is identical to this one.
*
* @param {Envelope} other * @param {Envelope} other
* @return {boolean} * @returns {boolean}
*/ */
equals (other) { equals (other) {
return uint8arraysEquals(this.peerId.pubKey.bytes, other.peerId.pubKey.bytes) && return uint8arraysEquals(this.peerId.pubKey.bytes, other.peerId.pubKey.bytes) &&
@ -72,8 +74,9 @@ class Envelope {
/** /**
* Validate envelope data signature for the given domain. * Validate envelope data signature for the given domain.
*
* @param {string} domain * @param {string} domain
* @return {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
validate (domain) { validate (domain) {
const signData = formatSignaturePayload(domain, this.payloadType, this.payload) const signData = formatSignaturePayload(domain, this.payloadType, this.payload)
@ -84,10 +87,11 @@ class Envelope {
/** /**
* Helper function that prepares a Uint8Array to sign or verify a signature. * Helper function that prepares a Uint8Array to sign or verify a signature.
*
* @param {string} domain * @param {string} domain
* @param {Uint8Array} payloadType * @param {Uint8Array} payloadType
* @param {Uint8Array} payload * @param {Uint8Array} payload
* @return {Uint8Array} * @returns {Uint8Array}
*/ */
const formatSignaturePayload = (domain, payloadType, payload) => { const formatSignaturePayload = (domain, payloadType, payload) => {
// When signing, a peer will prepare a Uint8Array by concatenating the following: // When signing, a peer will prepare a Uint8Array by concatenating the following:
@ -115,8 +119,9 @@ const formatSignaturePayload = (domain, payloadType, payload) => {
/** /**
* Unmarshal a serialized Envelope protobuf message. * Unmarshal a serialized Envelope protobuf message.
*
* @param {Uint8Array} data * @param {Uint8Array} data
* @return {Promise<Envelope>} * @returns {Promise<Envelope>}
*/ */
Envelope.createFromProtobuf = async (data) => { Envelope.createFromProtobuf = async (data) => {
const envelopeData = Protobuf.decode(data) const envelopeData = Protobuf.decode(data)
@ -133,10 +138,11 @@ Envelope.createFromProtobuf = async (data) => {
/** /**
* Seal marshals the given Record, places the marshaled bytes inside an Envelope * Seal marshals the given Record, places the marshaled bytes inside an Envelope
* and signs it with the given peerId's private key. * and signs it with the given peerId's private key.
*
* @async * @async
* @param {Record} record * @param {Record} record
* @param {PeerId} peerId * @param {PeerId} peerId
* @return {Envelope} * @returns {Envelope}
*/ */
Envelope.seal = async (record, peerId) => { Envelope.seal = async (record, peerId) => {
const domain = record.domain const domain = record.domain
@ -157,9 +163,10 @@ Envelope.seal = async (record, peerId) => {
/** /**
* Open and certify a given marshalled envelope. * Open and certify a given marshalled envelope.
* Data is unmarshalled and the signature validated for the given domain. * Data is unmarshalled and the signature validated for the given domain.
*
* @param {Uint8Array} data * @param {Uint8Array} data
* @param {string} domain * @param {string} domain
* @return {Envelope} * @returns {Envelope}
*/ */
Envelope.openAndCertify = async (data, domain) => { Envelope.openAndCertify = async (data, domain) => {
const envelope = await Envelope.createFromProtobuf(data) const envelope = await Envelope.createFromProtobuf(data)

View File

@ -17,11 +17,11 @@ const {
*/ */
class PeerRecord extends Record { class PeerRecord extends Record {
/** /**
* @constructor * @class
* @param {object} params * @param {object} params
* @param {PeerId} params.peerId * @param {PeerId} params.peerId
* @param {Array<multiaddr>} params.multiaddrs addresses of the associated peer. * @param {Array<multiaddr>} params.multiaddrs - addresses of the associated peer.
* @param {number} [params.seqNumber] monotonically-increasing sequence counter that's used to order PeerRecords in time. * @param {number} [params.seqNumber] - monotonically-increasing sequence counter that's used to order PeerRecords in time.
*/ */
constructor ({ peerId, multiaddrs = [], seqNumber = Date.now() }) { constructor ({ peerId, multiaddrs = [], seqNumber = Date.now() }) {
super(ENVELOPE_DOMAIN_PEER_RECORD, ENVELOPE_PAYLOAD_TYPE_PEER_RECORD) super(ENVELOPE_DOMAIN_PEER_RECORD, ENVELOPE_PAYLOAD_TYPE_PEER_RECORD)
@ -36,7 +36,8 @@ class PeerRecord extends Record {
/** /**
* Marshal a record to be used in an envelope. * Marshal a record to be used in an envelope.
* @return {Uint8Array} *
* @returns {Uint8Array}
*/ */
marshal () { marshal () {
if (this._marshal) { if (this._marshal) {
@ -56,8 +57,9 @@ class PeerRecord extends Record {
/** /**
* Returns true if `this` record equals the `other`. * Returns true if `this` record equals the `other`.
*
* @param {Record} other * @param {Record} other
* @return {boolean} * @returns {boolean}
*/ */
equals (other) { equals (other) {
// Validate PeerId // Validate PeerId
@ -81,8 +83,9 @@ class PeerRecord extends Record {
/** /**
* Unmarshal Peer Record Protobuf. * Unmarshal Peer Record Protobuf.
* @param {Uint8Array} buf marshaled peer record. *
* @return {PeerRecord} * @param {Uint8Array} buf - marshaled peer record.
* @returns {PeerRecord}
*/ */
PeerRecord.createFromProtobuf = (buf) => { PeerRecord.createFromProtobuf = (buf) => {
// Decode // Decode

View File

@ -18,7 +18,7 @@ class Registrar {
* @param {Object} props * @param {Object} props
* @param {PeerStore} props.peerStore * @param {PeerStore} props.peerStore
* @param {connectionManager} props.connectionManager * @param {connectionManager} props.connectionManager
* @constructor * @class
*/ */
constructor ({ peerStore, connectionManager }) { constructor ({ peerStore, connectionManager }) {
// Used on topology to listen for protocol changes // Used on topology to listen for protocol changes
@ -49,6 +49,7 @@ class Registrar {
/** /**
* Get a connection with a peer. * Get a connection with a peer.
*
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Connection} * @returns {Connection}
*/ */
@ -58,8 +59,9 @@ class Registrar {
/** /**
* Register handlers for a set of multicodecs given * Register handlers for a set of multicodecs given
* @param {Topology} topology protocol topology *
* @return {string} registrar identifier * @param {Topology} topology - protocol topology
* @returns {string} registrar identifier
*/ */
register (topology) { register (topology) {
if (!Topology.isTopology(topology)) { if (!Topology.isTopology(topology)) {
@ -79,8 +81,9 @@ class Registrar {
/** /**
* Unregister topology. * Unregister topology.
* @param {string} id registrar identifier *
* @return {boolean} unregistered successfully * @param {string} id - registrar identifier
* @returns {boolean} unregistered successfully
*/ */
unregister (id) { unregister (id) {
return this.topologies.delete(id) return this.topologies.delete(id)
@ -88,6 +91,7 @@ class Registrar {
/** /**
* Remove a disconnected peer from the record * Remove a disconnected peer from the record
*
* @param {Connection} connection * @param {Connection} connection
* @param {Error} [error] * @param {Error} [error]
* @returns {void} * @returns {void}

View File

@ -9,11 +9,11 @@ log.error = debug('libp2p:transports:error')
class TransportManager { class TransportManager {
/** /**
* @constructor * @class
* @param {object} options * @param {object} options
* @param {Libp2p} options.libp2p The Libp2p instance. It will be passed to the transports. * @param {Libp2p} options.libp2p - The Libp2p instance. It will be passed to the transports.
* @param {Upgrader} options.upgrader The upgrader to provide to the transports * @param {Upgrader} options.upgrader - The upgrader to provide to the transports
* @param {boolean} [options.faultTolerance = FAULT_TOLERANCE.FATAL_ALL] Address listen error tolerance. * @param {boolean} [options.faultTolerance = FAULT_TOLERANCE.FATAL_ALL] - Address listen error tolerance.
*/ */
constructor ({ libp2p, upgrader, faultTolerance = FAULT_TOLERANCE.FATAL_ALL }) { constructor ({ libp2p, upgrader, faultTolerance = FAULT_TOLERANCE.FATAL_ALL }) {
this.libp2p = libp2p this.libp2p = libp2p
@ -26,9 +26,9 @@ class TransportManager {
/** /**
* Adds a `Transport` to the manager * Adds a `Transport` to the manager
* *
* @param {String} key * @param {string} key
* @param {Transport} Transport * @param {Transport} Transport
* @param {*} transportOptions Additional options to pass to the transport * @param {*} transportOptions - Additional options to pass to the transport
* @returns {void} * @returns {void}
*/ */
add (key, Transport, transportOptions = {}) { add (key, Transport, transportOptions = {}) {
@ -54,6 +54,7 @@ class TransportManager {
/** /**
* Stops all listeners * Stops all listeners
*
* @async * @async
*/ */
async close () { async close () {
@ -75,6 +76,7 @@ class TransportManager {
/** /**
* Dials the given Multiaddr over it's supported transport * Dials the given Multiaddr over it's supported transport
*
* @param {Multiaddr} ma * @param {Multiaddr} ma
* @param {*} options * @param {*} options
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
@ -95,6 +97,7 @@ class TransportManager {
/** /**
* Returns all Multiaddr's the listeners are using * Returns all Multiaddr's the listeners are using
*
* @returns {Multiaddr[]} * @returns {Multiaddr[]}
*/ */
getAddrs () { getAddrs () {
@ -109,6 +112,7 @@ class TransportManager {
/** /**
* Returns all the transports instances. * Returns all the transports instances.
*
* @returns {Iterator<Transport>} * @returns {Iterator<Transport>}
*/ */
getTransports () { getTransports () {
@ -117,6 +121,7 @@ class TransportManager {
/** /**
* Finds a transport that matches the given Multiaddr * Finds a transport that matches the given Multiaddr
*
* @param {Multiaddr} ma * @param {Multiaddr} ma
* @returns {Transport|null} * @returns {Transport|null}
*/ */
@ -130,6 +135,7 @@ class TransportManager {
/** /**
* Starts listeners for each listen Multiaddr. * Starts listeners for each listen Multiaddr.
*
* @async * @async
*/ */
async listen () { async listen () {
@ -206,6 +212,7 @@ class TransportManager {
/** /**
* Removes all transports from the manager. * Removes all transports from the manager.
* If any listeners are running, they will be closed. * If any listeners are running, they will be closed.
*
* @async * @async
*/ */
async removeAll () { async removeAll () {
@ -222,6 +229,7 @@ class TransportManager {
* Enum Transport Manager Fault Tolerance values. * Enum Transport Manager Fault Tolerance values.
* FATAL_ALL should be used for failing in any listen circumstance. * FATAL_ALL should be used for failing in any listen circumstance.
* NO_FATAL should be used for not failing when not listening. * NO_FATAL should be used for not failing when not listening.
*
* @readonly * @readonly
* @enum {number} * @enum {number}
*/ */

View File

@ -14,7 +14,7 @@ const { codes } = require('./errors')
/** /**
* @typedef MultiaddrConnection * @typedef MultiaddrConnection
* @property {function} sink * @property {Function} sink
* @property {AsyncIterator} source * @property {AsyncIterator} source
* @property {*} conn * @property {*} conn
* @property {Multiaddr} remoteAddr * @property {Multiaddr} remoteAddr
@ -34,7 +34,7 @@ class Upgrader {
* @param {Metrics} options.metrics * @param {Metrics} options.metrics
* @param {Map<string, Crypto>} options.cryptos * @param {Map<string, Crypto>} options.cryptos
* @param {Map<string, Muxer>} options.muxers * @param {Map<string, Muxer>} options.muxers
* @param {function(Connection)} options.onConnection Called when a connection is upgraded * @param {function(Connection)} options.onConnection - Called when a connection is upgraded
* @param {function(Connection)} options.onConnectionEnd * @param {function(Connection)} options.onConnectionEnd
*/ */
constructor ({ constructor ({
@ -57,6 +57,7 @@ class Upgrader {
/** /**
* Upgrades an inbound connection * Upgrades an inbound connection
*
* @async * @async
* @param {MultiaddrConnection} maConn * @param {MultiaddrConnection} maConn
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
@ -124,6 +125,7 @@ class Upgrader {
/** /**
* Upgrades an outbound connection * Upgrades an outbound connection
*
* @async * @async
* @param {MultiaddrConnection} maConn * @param {MultiaddrConnection} maConn
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
@ -198,14 +200,15 @@ class Upgrader {
/** /**
* A convenience method for generating a new `Connection` * A convenience method for generating a new `Connection`
*
* @private * @private
* @param {object} options * @param {object} options
* @param {string} cryptoProtocol The crypto protocol that was negotiated * @param {string} options.cryptoProtocol - The crypto protocol that was negotiated
* @param {string} direction One of ['inbound', 'outbound'] * @param {string} options.direction - One of ['inbound', 'outbound']
* @param {MultiaddrConnection} maConn The transport layer connection * @param {MultiaddrConnection} options.maConn - The transport layer connection
* @param {*} upgradedConn A duplex connection returned from multiplexer and/or crypto selection * @param {*} options.upgradedConn - A duplex connection returned from multiplexer and/or crypto selection
* @param {Muxer} Muxer The muxer to be used for muxing * @param {Muxer} options.Muxer - The muxer to be used for muxing
* @param {PeerId} remotePeer The peer the connection is with * @param {PeerId} options.remotePeer - The peer the connection is with
* @returns {Connection} * @returns {Connection}
*/ */
_createConnection ({ _createConnection ({
@ -302,9 +305,10 @@ class Upgrader {
/** /**
* Routes incoming streams to the correct handler * Routes incoming streams to the correct handler
*
* @private * @private
* @param {object} options * @param {object} options
* @param {Connection} options.connection The connection the stream belongs to * @param {Connection} options.connection - The connection the stream belongs to
* @param {Stream} options.stream * @param {Stream} options.stream
* @param {string} options.protocol * @param {string} options.protocol
*/ */
@ -315,9 +319,10 @@ class Upgrader {
/** /**
* Attempts to encrypt the incoming `connection` with the provided `cryptos`. * Attempts to encrypt the incoming `connection` with the provided `cryptos`.
*
* @private * @private
* @async * @async
* @param {PeerId} localPeer The initiators PeerId * @param {PeerId} localPeer - The initiators PeerId
* @param {*} connection * @param {*} connection
* @param {Map<string, Crypto>} cryptos * @param {Map<string, Crypto>} cryptos
* @returns {CryptoResult} An encrypted connection, remote peer `PeerId` and the protocol of the `Crypto` used * @returns {CryptoResult} An encrypted connection, remote peer `PeerId` and the protocol of the `Crypto` used
@ -344,9 +349,10 @@ class Upgrader {
/** /**
* Attempts to encrypt the given `connection` with the provided `cryptos`. * Attempts to encrypt the given `connection` with the provided `cryptos`.
* The first `Crypto` module to succeed will be used * The first `Crypto` module to succeed will be used
*
* @private * @private
* @async * @async
* @param {PeerId} localPeer The initiators PeerId * @param {PeerId} localPeer - The initiators PeerId
* @param {*} connection * @param {*} connection
* @param {PeerId} remotePeerId * @param {PeerId} remotePeerId
* @param {Map<string, Crypto>} cryptos * @param {Map<string, Crypto>} cryptos
@ -374,10 +380,11 @@ class Upgrader {
/** /**
* Selects one of the given muxers via multistream-select. That * Selects one of the given muxers via multistream-select. That
* muxer will be used for all future streams on the connection. * muxer will be used for all future streams on the connection.
*
* @private * @private
* @async * @async
* @param {*} connection A basic duplex connection to multiplex * @param {*} connection - A basic duplex connection to multiplex
* @param {Map<string, Muxer>} muxers The muxers to attempt multiplexing with * @param {Map<string, Muxer>} muxers - The muxers to attempt multiplexing with
* @returns {*} A muxed connection * @returns {*} A muxed connection
*/ */
async _multiplexOutbound (connection, muxers) { async _multiplexOutbound (connection, muxers) {
@ -397,10 +404,11 @@ class Upgrader {
/** /**
* Registers support for one of the given muxers via multistream-select. The * Registers support for one of the given muxers via multistream-select. The
* selected muxer will be used for all future streams on the connection. * selected muxer will be used for all future streams on the connection.
*
* @private * @private
* @async * @async
* @param {*} connection A basic duplex connection to multiplex * @param {*} connection - A basic duplex connection to multiplex
* @param {Map<string, Muxer>} muxers The muxers to attempt multiplexing with * @param {Map<string, Muxer>} muxers - The muxers to attempt multiplexing with
* @returns {*} A muxed connection * @returns {*} A muxed connection
*/ */
async _multiplexInbound (connection, muxers) { async _multiplexInbound (connection, muxers) {

View File

@ -13,13 +13,14 @@ const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
/** /**
* Create libp2p nodes. * Create libp2p nodes.
*
* @param {Object} [properties] * @param {Object} [properties]
* @param {Object} [properties.config] * @param {Object} [properties.config]
* @param {number} [properties.number] number of peers (default: 1). * @param {number} [properties.number] - number of peers (default: 1).
* @param {boolean} [properties.fixture] use fixture for peer-id generation (default: true) * @param {boolean} [properties.fixture] - use fixture for peer-id generation (default: true)
* @param {boolean} [properties.started] nodes should start (default: true) * @param {boolean} [properties.started] - nodes should start (default: true)
* @param {boolean} [properties.populateAddressBooks] nodes addressBooks should be populated with other peers (default: true) * @param {boolean} [properties.populateAddressBooks] - nodes addressBooks should be populated with other peers (default: true)
* @return {Promise<Array<Libp2p>>} * @returns {Promise<Array<Libp2p>>}
*/ */
async function createPeer ({ number = 1, fixture = true, started = true, populateAddressBooks = true, config = {} } = {}) { async function createPeer ({ number = 1, fixture = true, started = true, populateAddressBooks = true, config = {} } = {}) {
const peerIds = await createPeerId({ number, fixture }) const peerIds = await createPeerId({ number, fixture })
@ -53,10 +54,11 @@ function _populateAddressBooks (peers) {
/** /**
* Create Peer-ids. * Create Peer-ids.
*
* @param {Object} [properties] * @param {Object} [properties]
* @param {number} [properties.number] number of peers (default: 1). * @param {number} [properties.number] - number of peers (default: 1).
* @param {boolean} [properties.fixture] use fixture for peer-id generation (default: true) * @param {boolean} [properties.fixture] - use fixture for peer-id generation (default: true)
* @return {Promise<Array<PeerId>>} * @returns {Promise<Array<PeerId>>}
*/ */
function createPeerId ({ number = 1, fixture = true } = {}) { function createPeerId ({ number = 1, fixture = true } = {}) {
return pTimes(number, (i) => fixture return pTimes(number, (i) => fixture

View File

@ -58,9 +58,9 @@ module.exports = async (properties = {}) => {
* Creates a full connection pair, without the transport or encryption * Creates a full connection pair, without the transport or encryption
* *
* @param {object} options * @param {object} options
* @param {Multiaddr[]} options.addrs Should contain two addresses for the local and remote peer respectively * @param {Multiaddr[]} options.addrs - Should contain two addresses for the local and remote peer respectively
* @param {PeerId[]} options.remotePeer Should contain two peer ids, for the local and remote peer respectively * @param {Array<PeerId>} options.peers - Array containing local and remote peer ids
* @param {Map<string, function>} options.protocols The protocols the connections should support * @param {Map<string, Function>} options.protocols - The protocols the connections should support
* @returns {{inbound:Connection, outbound:Connection}} * @returns {{inbound:Connection, outbound:Connection}}
*/ */
module.exports.pair = function connectionPair ({ addrs, peers, protocols }) { module.exports.pair = function connectionPair ({ addrs, peers, protocols }) {

View File

@ -6,9 +6,10 @@ const AbortController = require('abort-controller')
/** /**
* Returns both sides of a mocked MultiaddrConnection * Returns both sides of a mocked MultiaddrConnection
*
* @param {object} options * @param {object} options
* @param {Multiaddr[]} options.addrs Should contain two addresses for the local and remote peer * @param {Multiaddr[]} options.addrs - Should contain two addresses for the local and remote peer
* @param {PeerId} options.remotePeer The peer that is being "dialed" * @param {PeerId} options.remotePeer - The peer that is being "dialed"
* @returns {{inbound:MultiaddrConnection, outbound:MultiaddrConnection}} * @returns {{inbound:MultiaddrConnection, outbound:MultiaddrConnection}}
*/ */
module.exports = function mockMultiaddrConnPair ({ addrs, remotePeer }) { module.exports = function mockMultiaddrConnPair ({ addrs, remotePeer }) {