import { Manipulator , FiredRule , FeatureMap , WhenCause , SqrlKey , ManipulatorCallback , } from "sqrl" ; import { mapObject } from "sqrl-common" ; import { bufferHumanJson } from "./bufferHumanJson" ; /**
 * Copyright 2018 Twitter, Inc.
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 */ export class CliManipulator extends Manipulator { public sqrlKeys : Set < string > = new Set ( ) ; public kafkaOutput : { [ topic ] : Buffer [ ] ; } = { } ; public blocked : boolean = false ; public whitelisted : boolean = false ; public blockedRules : FiredRule [ ] = [ ] ; public whitelistedRules : FiredRule [ ] = [ ] ; readonly loggedErrors : Error [ ] = [ ] ; public loggedFeatures : FeatureMap = { } ; public logged : string [ ] = [ ] ; addKafka ( topic , message ) { this . kafkaOutput [ topic ] = this . kafkaOutput [ topic ] || [ ] ; this . kafkaOutput [ topic ] . push ( message ) ; } setBlocked ( context ) { this . blocked = true ; if ( context ) { this . blockedRules . push ( ... context . firedRules ) ; } } setWhitelisted ( context ) { this . whitelisted = true ; if ( context ) { this . whitelistedRules . push ( ... context . firedRules ) ; } } wasBlocked ( ) { return this . blocked && ! this . whitelisted ; } getCurrentHumanOutput ( ) { return { kafka : mapObject ( this . kafkaOutput , ( messages , topic ) => { return messages . map ( ( msg ) => { return bufferHumanJson ( msg ) ; } ) ; } ) , } ; } trackSqrlKey ( key ) { this . sqrlKeys . add ( key . getDebugString ( ) ) ; } log ( message ) { this . logged . push ( message ) ; } logFeature ( name , value ) { this . loggedFeatures [ name ] = value ; } logError ( err ) { this . loggedErrors . push ( err ) ; } throwFirstError ( ) { if ( this . loggedErrors . length ) { throw this . loggedErrors [ 0 ] ; } } async mutate ( ctx ) { await Promise . all ( this . callbacks . map ( ( cb ) => cb ( ctx ) ) ) ; } private callbacks : ManipulatorCallback [ ] = [ ] ; addCallback ( cb ) { this . callbacks . push ( cb ) ; } }