UNPKG

hyperpubee

Version:

Self-publishing over the decentralised internet

130 lines (108 loc) 2.52 kB
const b4a = require('b4a') const { EMPTY, CONTENT, STRUCTURE, HYPERHASH_REGEX, PUBEE_LOCATION_REGEX, EMBEDDING, ROOT, LINK } = require('./constants') const hexlexi = require('./hexlexi') function getAbsoluteKey (...components) { return [...components].join(EMPTY) } function getIndexedKeyFromComponents (components) { const index = Number(components.slice(-1)) const indexAshexlexi = hexlexi.pack(index) const rest = [...components.slice(0, -1)] return getAbsoluteKey(...rest, indexAshexlexi) } function getRootKey () { return getAbsoluteKey(STRUCTURE, ROOT) } async function createArrayFromStream (stream) { const content = [] for await (const { value } of stream) { content.push(value) } return content } function isKeyFor (key, sub) { const pieces = key.split(EMPTY) if (pieces.length === 1) { return false } return pieces[0] === sub } function isKeyForContent (key) { return isKeyFor(key, CONTENT) } function isKeyForStructure (key) { return isKeyFor(key, STRUCTURE) } function isKeyForEmbedding (key) { return isKeyFor(key, EMBEDDING) } function isKeyForLink (key) { return isKeyFor(key, LINK) } function getSubstructureNameFromKey (key) { if (!isKeyForStructure(key)) { throw new Error(`Key '${key} is not valid for a structure`) } const pieces = key.split(EMPTY) return pieces[1] } function splitKeyInComponents (key) { return key.split(EMPTY) } function isValidHyperHash (hyperHash) { try { return HYPERHASH_REGEX.test(hyperHash) } catch { return false } } function isValidPubeeLocation (location) { try { return PUBEE_LOCATION_REGEX.test(location) } catch { return false } } function createHexLexedReference (key, index) { const res = [key, hexlexi.pack(index)].join(EMPTY) return res } function getKeyAsBuffer (key) { const res = typeof key === 'string' ? b4a.from(key, 'hex') : key return res } function getKeyAsStr (key) { const res = typeof key === 'string' ? key : b4a.toString(key, 'hex') return res } function areEqualKeys (key1, key2) { const res = getKeyAsStr(key1) === getKeyAsStr(key2) return res } module.exports = { getAbsoluteKey, createArrayFromStream, isKeyForContent, isKeyForStructure, isKeyForEmbedding, isKeyForLink, getSubstructureNameFromKey, splitKeyInComponents, isValidHyperHash, isValidPubeeLocation, getRootKey, createHexLexedReference, getKeyAsBuffer, getKeyAsStr, areEqualKeys, getIndexedKeyFromComponents }