import { CID } from "multiformats/basics.js" ; import importer , { Options as AddOptions , File , Result , } from "ipfs-unixfs-importer" ; import { Buffer } from "buffer" ; import exporter , { Options as GetOptions } from "ipfs-unixfs-exporter" ; import { Peer } from "./core" ; import Ipld from "ipld" ; export { Options as AddOptions , File , Result } from "ipfs-unixfs-importer" ; export { Options as GetOptions } from "ipfs-unixfs-exporter" ; declare module "./core" { interface Peer { addFile ( source , options ? ) : Promise < Result | undefined > ; getFile ( cid , options ? ) : Promise < Buffer > ; } } const wrap = ( ipld ) => { return { put : async ( buf , { cid } ) => { await ipld . put ( buf , cid . code ?? ( cid as any ) . codec , { cidVersion : cid . version , } ) ; return { cid , data : buf } ; } , get : async ( cid ) => { const node = await ipld . get ( cid ) ; if ( cid . code === 112 || ( cid as any ) . codec === "dag-pb" ) { return node . serialize ( ) ; } return { cid , data : node } ; } , } ; } ; param source param options example Peer . prototype . addFile = async function ( source , options ? ) { let result ; for await ( const entry of importer ( source , ( wrap ( this ) as unknown ) as Ipld , { cidVersion : 1 , codec : "dag-pb" , ... options , } ) ) { result = entry ; } return result ; } ; param cid example Peer . prototype . getFile = async function ( cid , options ? ) { const file = await exporter ( cid as never , ( wrap ( this ) as unknown ) as Ipld ) ; if ( file . unixfs && file . unixfs . type . includes ( "dir" ) ) { throw new Error ( "this dag node is a directory" ) ; } if ( ! file . content ) { throw new Error ( "this dag node has no content" ) ; } const arr = [ ] ; for await ( const entry of file . content ( options ) ) { if ( entry instanceof Uint8Array ) { arr . push ( Buffer . from ( entry ) ) ; } else { arr . push ( Buffer . from ( entry . data ) ) ; } } return Buffer . concat ( arr ) ; } ; export { Peer } ;