aboutsummaryrefslogtreecommitdiff
path: root/src/eval-env/node.ts
blob: 5e739877db8852e9236e4e23649f1fd21a1962b8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Type } from 'ts-morph'
import { promises as fs } from 'fs'
import readline from 'readline'
import { Ctx } from '../types'

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
})

const readLineFromStdin = (): Promise<string> =>
  new Promise((res) => rl.on('line', res))

export const cleanup = () => {
  rl.close()
}

export default (ctx: Ctx, args: Type[]) => ({
  ReadFile: async () => {
    const [pathTyp] = args
    const filePath = ctx.getTypeValue(pathTyp)
    const contents = await fs.readFile(filePath, 'utf-8')
    const [resultKey, _] = ctx.createResult(JSON.stringify(contents))
    return [resultKey]
  },

  WriteFile: async () => {
    const [pathTyp, contentsTyp] = args
    const filePath = ctx.getTypeValue(pathTyp)
    const contents = ctx.getTypeValue(contentsTyp)
    await fs.writeFile(filePath, contents)
    return []
  },

  GetEnv: async () => {
    const [envTyp] = args
    const envName = ctx.getTypeValue(envTyp)
    const [resultKey, _] = ctx.createResult(
      `${JSON.stringify(process.env[envName] ?? '')}`
    )
    return [resultKey]
  },

  GetArgs: async () => {
    const [resultKey, _] = ctx.createResult(
      `${JSON.stringify(process.argv.slice(2))}`
    )
    return [resultKey]
  },

  Exit: async () => {
    process.exit(args[0] && ctx.getTypeValue(args[0]))
  },

  ReadLine: async () => {
    const line = await readLineFromStdin()
    const [resultKey, _] = ctx.createResult(`${JSON.stringify(line)}`)
    return [resultKey]
  },
})