UNPKG

hyperpubee

Version:

Self-publishing over the decentralised internet

67 lines (54 loc) 1.64 kB
const { isValidHyperHash, isValidPubeeLocation } = require('./utils') const { EmbeddingValidationError } = require('../exceptions') const { applyDiffToText } = require('./diff-patch') class Embedding { constructor ({ referencedHash, referencedLocation, patch }) { if (!isValidHyperHash(referencedHash)) { throw new EmbeddingValidationError( `referencedHash must be a valid hypercore hash (${referencedHash})` ) } this.referencedHash = referencedHash if (!isValidPubeeLocation(referencedLocation)) { throw new EmbeddingValidationError( `Invalid referenced location (${referencedLocation})` ) } this.referencedLocation = referencedLocation validatePatch(patch) this.patch = JSON.parse(JSON.stringify(patch)) } applyPatch (text) { return applyDiffToText(this.patch, text) } } function validatePatch (patch) { if (!Array.isArray(patch)) { throw new EmbeddingValidationError( 'patch must be an array (use empty array if none to apply)' ) } for (const diffElem of patch) { const error = new Error( `Invalid patch structure for element '${JSON.stringify(diffElem)}'` ) if (diffElem.length !== 2) { throw error } if (![0, -1, 1].includes(diffElem[0])) { throw error } if (typeof (diffElem[1]) !== 'string') { throw error } } } function validateEmbedding (embedding) { // Creating a new embedding runs all validation tests // (throws when finding an issue) new Embedding(embedding) // eslint-disable-line no-new } module.exports = { validateEmbedding, Embedding }