This repository was archived by the owner on Jun 19, 2021. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +48
-4
lines changed
Expand file tree Collapse file tree 2 files changed +48
-4
lines changed Original file line number Diff line number Diff line change 1+ type Response = string | void
2+ type Callback = ( query ?: string ) => ( Response | Promise < Response > )
3+ type EventHandler < T extends string > = { [ key in T ] ?: Callback }
4+
5+ export type Question = 'passphrase' | 'devicename'
6+ export type ErrorEvent = Question | keyof Event
7+ export interface Event {
8+ started : Callback ,
9+ answered : Callback ,
10+ onAsking : EventHandler < Question >
11+ onError : EventHandler < ErrorEvent >
12+ }
13+
14+ // #region where the event handler being stored
15+ export const bot : Event = {
16+ started : ( ) => { } ,
17+ answered : ( ) => { } ,
18+ onAsking : { } ,
19+ onError : { }
20+ }
21+ // #endregion
22+
23+ /**
24+ * Register event handler
25+ * each event represent the lifecycle of the bot
26+ * and each handler support both normal and async function
27+ */
28+ export default {
29+ started : ( callback : Callback ) => ( bot . started = callback ) ,
30+ onAsking : ( question : Question , callback : Callback ) => ( bot . onAsking [ question ] = callback ) ,
31+ onError : ( event : ErrorEvent , callback : Callback ) => ( bot . onError [ event ] = callback )
32+ }
Original file line number Diff line number Diff line change 11import { ReadLineOptions } from 'readline'
22
3+ import { bot , Question } from './event-handler'
4+
35/**
46 * Shim readline.createInterface()
57 * @see https://nodejs.org/api/readline.html#readline_readline_createinterface_options
68 */
79export function createInterface ( _options : ReadLineOptions ) {
810 return {
9- question ( _query : string , answering : ( response : string | void ) => void ) {
10- answering ( )
11- } ,
12- close ( ) { }
11+ close : bot . answered ,
12+ question ( query : string , answering : ( response : string | void ) => void ) {
13+ // #region helpers
14+ query = query . toLocaleLowerCase ( )
15+ const on = ( event : Question ) => Promise . resolve ( bot . onAsking [ event ] ! ( ) )
16+ const questionIncludes = ( keywords : string [ ] ) => keywords . every ( keyword => query . includes ( keyword ) )
17+ // #endregion helpers
18+
19+ Promise . resolve ( bot . started ( query ) ) . then ( async ( ) => {
20+ if ( questionIncludes ( [ 'passphrase' ] ) ) answering ( await on ( 'passphrase' ) )
21+ else if ( questionIncludes ( [ 'device' , 'name' ] ) ) answering ( await on ( 'devicename' ) )
22+ else answering ( )
23+ } ) . catch ( bot . onError . started )
24+ }
1325 }
1426}
You can’t perform that action at this time.
0 commit comments