import { _ } from 'streamline-runtime' ; import { fixOptions } from './node' ; import { Reader } from '../reader' ; import { Writer } from '../writer' ; import * as http from 'http' ; import { HttpProxyClientRequest , HttpClientRequest , HttpClientResponse , HttpClientOptions , HttpServer , HttpServerRequest , HttpServerResponse , HttpServerOptions , createHttpServer , httpRequest , httpListener , } from '../node-wrappers' ; export { HttpProxyClientRequest , HttpClientRequest , HttpClientResponse , HttpClientOptions , HttpServer , HttpServerRequest , HttpServerResponse , HttpServerOptions , } ; function endWrite ( _ , cli ) { const resp = cli . end ( ) . response ( _ ) ; if ( resp . statusCode != 201 ) throw new Error ( "Request return status code: " + resp . statusCode ) ; const data = resp . readAll ( _ ) ; return ( typeof data === 'string' && /^application\/json/ . test ( resp . headers [ 'content-type' ] ) ) ? JSON . parse ( data ) : data ; } function guessType ( data ) { if ( ! data ) return null ; if ( Buffer . isBuffer ( data ) ) return "application/octet-stream" ; if ( typeof data === "object" ) return "application/json" ; if ( typeof data !== "string" ) throw new TypeError ( "invalid data type: " + typeof data ) ; const text = data ; if ( text [ 0 ] === "<" ) { if ( text . slice ( 0 , 9 ) . toLowerCase ( ) === "<!doctype" ) return "text/html" ; else return "application/xml" ; } return "text/plain" ; } export function server ( listener , options ? ) { return createHttpServer ( listener , fixOptions ( options ) ) ; } export function client ( options ? ) { return httpRequest ( fixOptions ( options ) ) ; } export interface HttpListenerOption { } export function listener ( listener , options ? ) { return httpListener ( listener , fixOptions ( options ) ) ; } export type FactoryWriter = Writer < any > & { _result : any ; } ; export function factory ( url ) { return { reader ( _ ) { var response = module . exports . client ( { url : url , method : "GET" } ) . end ( ) . response ( _ ) ; if ( response . statusCode !== 200 ) { var payload = response . readAll ( _ ) ; throw new Error ( "Error reading '" + url + "'; Status " + response . statusCode + ": " + payload ) ; } return response ; } , writer ( _ ) { var cli ; var type ; return { write ( this , _ , data ) { const opt = { url : url , method : "POST" , headers : { } } ; if ( ! cli ) { type = guessType ( data ) ; if ( type ) opt . headers ! [ "content-type" ] = type ; cli = client ( opt ) . proxyConnect ( _ ) ; } if ( data === undefined ) return this . _result = endWrite ( _ , cli ) ; else return cli . write ( _ , type === "application/json" ? JSON . stringify ( data ) : data ) ; } , get result ( this ) { return this . _result ; } } ; } } ; }