import Fs from 'fs' ; import mime from 'mime-types' ; import { RepoFrontend , HyperfileUrl } from 'hypermerge' ; import { Readable } from 'stream' ; import { FILE_SERVER_PATH } from './constants' ; const repo = new RepoFrontend ( ) ; repo . files . setServerPath ( FILE_SERVER_PATH ) ; export interface HyperfileResult { data : Readable ; mimeType : string ; size : number ; } export interface BufferedHyperfileResult { data : Buffer ; mimeType : string ; } export function isHyperfileUrl ( str ) { return str . startsWith ( 'hyperfile:/' ) ; } export function write ( stream , size , mimeType ) { return repo . files . write ( stream , size , mimeType ) ; } export function writeFromPath ( filePath ) { return new Promise ( ( res , rej ) => { Fs . lstat ( filePath , async ( err , stats ) => { if ( err ) return rej ( err ) ; const stream = Fs . createReadStream ( filePath ) ; const mimeType = mime . lookup ( filePath ) || 'application/octet-stream' ; const hyperfileUrl = await repo . files . write ( stream , stats . size , mimeType ) ; return res ( hyperfileUrl ) ; } ) ; } ) ; } export function writeBuffer ( buffer , mimeType = 'application/octet-stream' ) { return new Promise ( async ( res ) => { const stream = bufferToStream ( Buffer . from ( buffer ) ) ; const size = buffer . length ; const hyperfileUrl = await repo . files . write ( stream , size , mimeType ) ; res ( hyperfileUrl ) ; } ) ; } export async function fetch ( hyperfileUrl ) { return repo . files . read ( hyperfileUrl ) ; } export function bufferToStream ( buffer ) { return new Readable ( { read ( ) { this . push ( buffer ) ; this . push ( null ) ; } } ) ; } export function streamToBuffer ( stream ) { return new Promise ( ( res , rej ) => { const buffers = [ ] ; stream . on ( 'data' , ( data ) => buffers . push ( data ) ) . on ( 'error' , ( err ) => rej ( err ) ) . on ( 'end' , ( ) => res ( Buffer . concat ( buffers ) ) ) ; } ) ; }