npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@p2pcommons/sdk-js

v0.9.2

Published

The SDK for the p2p commons

Downloads

47

Readme

@p2pcommons/sdk-js

All Contributors

npm version license downloads total downloads yearly downloads monthly downloads weekly

ci

NodeJS development kit (sdk-js) for the peer-to-peer commons (p2pcommons). More information on this infrastructure is available in this conceptual publication and this technical publication (note these might have been extended by now).

The specifications for sdk-js are available from @p2pcommons/specs.

:warning: Work In Progress

Install

npm install @p2pcommons/sdk-js

Usage

This is an npm module that does not export any processes to your global environment. In other words, it is a module that you can use in your NodeJS packages, but does not provide any direct functionality outside of it.

Example

const P2PCommons = require('@p2pcommons/sdk-js')

const p2p = new P2PCommons()

;(async () => {
  // create a content module
  await p2p.init({ type: 'content' }) // ~/.p2pcommons/hash/index.json --> type: content
  // create a profile module
  await p2p.init({ type: 'profile' }) // ~/.p2pcommons/hash/index.json --> type: profile
})()

Table of Contents

API

const P2PCommons = require('@p2pcommons/sdk-js')

constructor

P2PCommons(opts)

Returns a new instance of the sdk.

  • opts can include the following:
{
  baseDir: // defaults to '~/.p2pcommons'
  persist: // Indicates if the drives should be persisted - defaults to true
  storage: // Accepts a storage function - defaults to undefined
  disableSwarm: // defaults to undefined
  swarm: // swarm options - defaults to undefined
}

init

async init(data: object)

Creates a new folder for 'content' or 'profile' according to the received data.type value.

Returns an object with:

  • rawJSON: flattened indexJSON data
  • metadata: (version, lastModified, isWritable)

get

async get(key: string)

Retrieves raw indexJSON item and metadata from the local db.

  • key: represents the key or hyper url to be looked for. It is the buffer archive key .toString('hex')

Returns an object with:

  • rawJSON: flattened indexJSON data
  • metadata: (version, lastModified, isWritable)

set

async set(metadata: object)

Used to update an existing module.

  • metadata: object with updated or added values. The only required field is the url property, which is used to identify the module to update.

refreshDrive

async refreshDrive(key: string|buffer, opts: object)

Synchronize a hyperdrive with a module directory to ensure that the sdk is aware of the latest changes to files. Optionally accepts an opts object. These are passed to dft.

filter

async filter(feature: string, criteria: string)

Handy method for querying content values from the local db.

Returns a promise which can resolve to an array of 0 or more values (flattened rawJSON data) together with their metadata.

  • feature: indicates the filter property, e.g.: filter by title or description (currently supported filter types)
  • criteria: it is the filter value.

listContent

async listContent()

Returns an array containing all the content modules (flattened rawJSON data) together with metadata saved in the local db.

listProfiles

async listProfiles()

Returns an array containing all the profile modules (flattened rawJSON data) together with metadata saved in the local db.

list

async list()

Returns an array containing all the modules (flattened rawJSON data) and metadata saved in the local db.

openFile

async openFile(key: string)

Used to obtain a file descriptor from the main file of a module.

  • key: represents the module key (url) to be looked for. It is the buffer archive key .toString('hex')

register

async register(contentKey: string or buffer, profileKey: string or buffer)

Register (add) new content into a profile. The new content is added to the profile's p2pcommons.contents. See p2pcommons specs on registration

  • contentKey: versioned or unversioned key to be registered (origin module)
  • profileKey: unversioned profile key (destination module)

deregister

async deregister(contentKey: string or buffer, profileKey: string or buffer)

Deregister (remove) content from a profile.

  • contentKey: versioned or unversioned key of content at the version that is registered
  • profileKey: unversioned profile key (destination module)

follow

async follow(localProfileKey: string, targetProfileKey: string)

Get a local profile and update its follows property adding a new profile (targetProfile)

  • localProfileKey: unversioned key of local profile
  • targetProfileKey: versioned or unversioned key of profile to follow

unfollow

async unfollow(localProfileKey: string, targetProfileKey: string)

Undo the follow operation.

  • localProfileKey: unversioned key of local profile
  • targetProfileKey: versioned or unversioned key of profile at the version that is followed

verify

async verify(versionedKey: string)

Verifies a module. See p2pcommons specs on verification

Returns a boolean indicating whether the module is verified.

clone

async clone(mKey: string or buffer, mVersion: number, opts: object)

Get a module from the local db or the swarm. If the module is not present on the local db and the swarm is enabled (disableSwarm === false) then it will query the swarm.

:warning: NOTE: versioned module directories are read-only.

  • mKey: module url
  • mVersion: module version. [OPTIONAL]
  • opts: options modifiers passed to getFromSwarm [OPTIONAL]
    • download: a boolean indicating if module directory needs to be saved on disk. [DEFAULT=TRUE]
    • latestFallback: a boolean indicating if the sdk should try fetching latest version from swarm if passed version is unavailable. [DEFAULT=TRUE]

Returns a cancelable promise. When fullfiled returns an object with multiple values:

  • rawJSON: the module index.json content (flattened)
  • metadata: an object with module's metadata
  • versionedKey: an string indicating the full module url obtained. E.g: hyper://${mKey}+${version}
  • dlInfo: an object containin download info and a function resume that can be used to force resuming a download.
  • dlHandle: it contains a download event emitter, you can listen to end event to know when the download has been completed. It's defined only if download === true. [DEPRECATED]

delete

async delete(key: string or buffer, deleteFiles: boolean)

Removes a module and all its versions from the local db and seed db. If it was open in memory, its closed. Only removes unversioned keys, it will throw an error (code: only_unversioned) if it receives a version with the key. This method would also call deregister if passed key belongs to a content module. It will deregister the content module only from writable (local) profiles.

Note: While this will stop the file from being seeded, that does not means that the content won't still be available on the network. This is due to the P2P file sharing dynamics.

If deleteFiles option is true, then the target folder and all its versions will be moved to the trash bin.

destroy

async destroy()

Closes the swarm instance (if created) and the local db.

Validations

The SDK exports many validation methods as SDK.validations that throw ValidationErrors when validation fails

Full validations

async validate({ indexMetadata: object, dbMetadata: object, key: string, p2pcommonsDir: string })

Fully validates a module against the p2pcommons module specs

  • indexMetadata: metadata from index.json (=rawJSON)
  • dbMetadata: metadata from the database (=metadata)
  • key: versioned or unversioned Hyperdrive key
  • p2pcommonsDir: path to p2pcommons directory [OPTIONAL]

Partial validations

async validatePartial({ indexMetadata: object, dbMetadata: object, key: string, p2pcommonsDir: string} )

Validates all present data (not undefined or null) against the p2pcommons specs. Can be used for validating unfinished modules. If p2pcommons.main is present, but empty, it will not be validated.

The following only validate a specific part of the supplied metadata:

async validateTitle({ indexMetadata: object })

async validateDescription({ indexMetadata: object })

async validateUrl({ indexMetadata: object, key: string })

async validateLinks({ indexMetadata: object })

async validateP2Pcommons({ indexMetadata: object })

Validates the p2pcommons object structure (not its contents)

async validateType({ indexMetadata: object })

async validateSubtype({ indexMetadata: object })

async validateMain({ indexMetadata: object, key: string, p2pcommonsDir: string })

Also checks the existence of the specified main file

async validateAvatar({ indexMetadata: object })

async validateAuthors({ indexMetadata: object })

async validateParents({ indexMetadata: object, dbMetadata: object, key: string })

async validateFollows({ indexMetadata: object, key: string })

async validateContents({ indexMetadata: object })

Special validations

async validateOnRegister({ contentIndexMetadata: object, contentDbMetadata: object, contentKey: string, profileIndexMetadata: object, profileDbMetadata: object, profileKey: string, p2pcommonsDir: string })

Fully validates a content module and a profile module upon registration. Includes cross-validation of module types and presence of the author in the content's metadata.

async validateOnFollow({ followedIndexMetadata: object })

Validates whether the followed module is a profile. This validation is only relevant at time of updating follows and is not included in any of the other validations.

async validateParentsOnUpdate({ indexMetadata: object, p2pcommons: SDK })

Validates whether parents are registered. This validation is only relevant at time of updating parents and is not included in any of the other validations.

  • p2pcommons: active instance of the p2pcommons SDK

Events

The following events are emitted by the SDK:

download-started

download-started ({key})

Emitted usually after cloning a new module. It passes the key of the drive.

download-progress

download-progress ({key})

Event used to track download progress of a new module.

download-drive-completed

download-drive-completed ({key})

Emitted when a drive has finished downloading. Drive has not been synced yet.

download-resume

download-resume ({key})

Emitted at SDK restart if some module has not finished its download. This means that the download is resuming.

download-resume-completed

download-resume-completed ({key})

Emitted when a resume download has been completed and the drive is synced to the disk.

update-profile

update-profile (rawJSON)

Emitted when an external profile has been updated. This will automatically update the local db. You don't need to do anything special. The event also emits the updated profile with the same rawJSON format.

update-content

update-content (rawJSON)

Emitted when an external content module has been updated. This will automatically update the local db. You don't need to do anything special. The event also emits the updated content with the same rawJSON format.

warn

warn (msg)

Emitted on unusual ocassions when a soft error happens. Used for logging purposes mostly.

error

error (err)

Emitted on unexpected circumstances, this can be emitted by our local db if something goes wrong.

Errors

The SDK exports some custom errors: SDK.errors

ValidationError

Indicates that metadata of a given module is invalid.

Error object contains some useful properties:

  • description: Description of the error - may change across versions
  • code: Error code - stable across versions
  • property: A string indicating the property in question

TypeError

Indicates that an input parameter is of an incorrect type.

Error object contains some useful properties:

  • expected: Expected value
  • received: Received value
  • key: A string indicating the property in question

InvalidKeyError

Some keys are read only. This error indicates the user is trying to modify a read only property.

Error object contains some useful properties:

  • invalid: A string indicating the invalid property

MissingParam

A more general error, used to indicate if something is missing.

Error object contains some useful properties:

  • key: A string indicating the missing param

EBUSYError

Triggered usually when there are conflicts with other apps watching the FS.

Error object contains some useful properties:

  • description: A string indicating the error message
  • key: A string indicating the hyperdrive involved

Release

  1. npm run release
  2. :tada:

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome! See also our contributing guidelines.