Files
str/src/vm/input.ts

51 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-11-10 23:54:20 -06:00
import * as readline from 'node:readline'
import {BehaviorSubject} from "../util/subject.js";
import {Lifecycle, LifecycleAware} from "../util/lifecycle.js";
2026-02-22 16:43:47 -06:00
import {StreamLogger} from "../util/log.js";
import {log} from "../log.js";
2025-11-10 23:54:20 -06:00
export class Input extends BehaviorSubject<string> implements LifecycleAware {
private rl?: readline.Interface
2026-02-22 16:43:47 -06:00
private log: StreamLogger = log.getStreamLogger('input')
public hasPrompt(): boolean {
return !!this.rl
}
2025-11-10 23:54:20 -06:00
public setupPrompt(): void {
2026-02-22 16:43:47 -06:00
this.log.verbose({
setupPrompt: { hasExistingPrompt: !!this.rl },
})
2025-11-10 23:54:20 -06:00
if ( this.rl ) {
this.closePrompt()
}
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'str %> ',
})
this.rl.prompt()
this.rl.on('line', async (line) => {
await this.next(line + '\n')
this.rl?.prompt(true)
})
}
public closePrompt(): void {
2026-02-22 16:43:47 -06:00
this.log.verbose({
closePrompt: { hasExistingPrompt: !!this.rl },
})
2025-11-10 23:54:20 -06:00
this.rl?.close()
this.rl = undefined
}
adoptLifecycle(lifecycle: Lifecycle): void {
lifecycle.onClose(() => this.closePrompt())
}
}