import * as crypto from 'crypto' ; import { FilterTypes } from '../constants' ; import { Filter } from '../common-interfaces' ; const algorithm = 'aes-256-ctr' ; export function range ( begin , end ) { if ( begin >= end ) { throw new Error ( 'begin >= end' ) ; } return Array . from ( { length : end - begin } , ( v , k ) => begin + k ) ; } export function random ( seed , min = 0 , max = 1 ) { if ( min >= max ) { throw new Error ( 'min >= max' ) ; } let lastseed = ( Math . round ( seed ) * 9301 + 49297 ) % 233280 ; let rnd = lastseed / 233280 ; return min + rnd * ( ( max || 1 ) - ( min || 0 ) ) ; } export function hash ( text ) { let ret = 0 ; for ( let i = 0 , len = text . length ; i < len ; i ++ ) { ret = ( 31 * ret + text . charCodeAt ( i ) ) << 0 ; } return ret ; } export function encrypt ( text , passphrase ) { let cipher = crypto . createCipher ( algorithm , passphrase ) ; let crypted = cipher . update ( text , 'utf8' , 'base64' ) ; return crypted + cipher . final ( 'base64' ) ; } export function decrypt ( text , passphrase ) { let decipher = crypto . createDecipher ( algorithm , passphrase ) ; let decrypted = decipher . update ( text , 'base64' , 'utf8' ) ; return decrypted + decipher . final ( 'utf8' ) ; } param jsonstr param key returns export function extractJson ( jsonstr , key ) { try { let val = JSON . parse ( jsonstr ) [ key ] ; if ( val === undefined ) { return jsonstr ; } return ( typeof val === 'string' ) ? val : JSON . stringify ( val ) ; } catch ( e ) { return jsonstr ; } } returns export function progressAt ( t , startTime , endTime ) { let progress = ( t . getTime ( ) - startTime . getTime ( ) ) / ( endTime . getTime ( ) - startTime . getTime ( ) ) ; return Math . min ( Math . max ( 0 , progress ) , 1.0 ) ; } param inner return export function safeFilter < T > ( inner ) { return ( t ) => { try { return inner ( t ) ; } catch { return t ; } } ; } param filters return export function mergeFilters ( filters ) { let funcs = filters . map ( f => { switch ( f . type ) { case FilterTypes . FILTER_REGEX : return ( line ) => new RegExp ( f . pattern , 'm' ) . test ( line ) ? line : undefined ; case FilterTypes . REPLACE_REGEX : return ( line ) => line . replace ( new RegExp ( f . pattern , 'm' ) , f . replacement ) ; case FilterTypes . EXTRACT_JSON : return ( line ) => extractJson ( line , f . key ) ; default : throw new Error ( 'error detected, invalid filter type.' ) ; } } ) ; return funcs . reduce ( ( pre , cur ) => ( line ) => { let evaluated = pre ( line ) ; return evaluated !== undefined ? cur ( evaluated ) : undefined ; } , ( line ) => line ) ; }