import { CID } from "multiformats/basics.js" ; import type { Query , Datastore , Pair } from "interface-datastore" ; import { Key } from "interface-datastore" ; /**
 * Block represents an immutable block of data that is uniquely referenced with a cid.
 *
 * It satisfies the default IPFS IPLD block interface: https://github.com/ipld/js-ipld-block.
 */ export class Block { param { Uint8Array } data param { CID } cid constructor ( readonly data , readonly cid ) { } } /**
 * BlockStore is a simple key/value store for adding, deleting, and retrieving immutable blocks of data.
 *
 * It satisfies the default IPFS block store interface: https://github.com/ipfs/js-ipfs-repo.
 */ export class BlockStore { param { Datastore } store constructor ( private store ) { } param { CID } cid static cidToKey = ( cid ) : Key => { const wrap = CID . asCID ( cid ) ; if ( ! wrap ) { throw new Error ( "Not a valid CID" ) ; } return new Key ( "/" + wrap . toV1 ( ) . toString ( ) , false ) ; } ; param { Key } key static keyToCid = ( key ) : CID => { return new CID ( key . toString ( ) . slice ( 1 ) ) ; } ; param { Block } block async put ( block ) { const k = BlockStore . cidToKey ( block . cid ) ; if ( await this . store . has ( k ) ) { return ; } return this . store . put ( k , block . data ) ; } param { Iterable < Block > } blocks async putMany ( blocks ) { const batch = this . store . batch ( ) ; for await ( const block of blocks ) { const k = BlockStore . cidToKey ( block . cid ) ; if ( await this . store . has ( k ) ) { continue ; } batch . put ( k , block . data ) ; } return await batch . commit ( ) ; } param { CID } cid async get ( cid ) { const k = BlockStore . cidToKey ( cid ) ; return new Block ( await this . store . get ( k ) , cid ) ; } param { CID } cid async delete ( cid ) { return this . store . delete ( BlockStore . cidToKey ( cid ) ) ; } param { CID } cid async has ( cid ) { return this . store . has ( BlockStore . cidToKey ( cid ) ) ; } param { Query } query async * query ( query ) { for await ( const result of this . store . query ( query ) ) { yield result ; } } }