-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
216 lines (190 loc) · 5.87 KB
/
index.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/* eslint-disable import/no-dynamic-require, global-require */
/* eslint-disable max-classes-per-file, no-underscore-dangle */
const cp = require('child_process')
const os = require('os')
const fs = require('fs')
const path = require('path')
const repl = require('repl')
const crypto = require('crypto')
const { promisify } = require('util')
const { Readable, Writable } = require('stream')
const parsePkg = require('parse-package-name')
const AdmZip = require('adm-zip')
const _ = require('lodash')
const Koa = require('koa')
const Router = require('koa-router')
const koaBody = require('koa-body')
const indexHtml = _.template(fs.readFileSync('./template.html'))
const app = new Koa()
const router = new Router()
const sleep = promisify(setTimeout)
cp.execAsync = promisify(cp.exec).bind(cp)
const Installer = path.join(__dirname, fs.existsSync('node_modules') ? 'node_modules' : '../node_modules', '.bin', 'yarn')
class ReplReadStream extends Readable {
// eslint-disable-next-line class-methods-use-this
_read() {}
}
class ReplWriteStream extends Writable {
constructor(opts, maxLine = 9999) {
super(opts)
this.flush()
this.maxLine = maxLine
}
_write(chunk, encoding, next) {
// console.log('chunk', chunk.toString())
if (this.content.length < this.maxLine) {
this.content.push(chunk)
} else if (this.content.length < this.maxLine + 1) {
this.content.push(Buffer.from('...'))
}
next()
}
dump() { return Buffer.concat(this.content).toString() }
flush() { this.content = [] }
}
function resolve(name) {
try {
require.resolve(name)
return true
} catch (e) {
return false
}
}
class Repl {
static getInstance(hash) {
return Repl.instances[hash] || new Repl(hash)
}
static deleteInstance(hash) {
delete Repl.instances[hash]
}
constructor(hash) {
console.log('new instance', hash)
this.readStream = new ReplReadStream()
this.writeStream = new ReplWriteStream()
const r = repl.start({ prompt: '', input: this.readStream, output: this.writeStream, ignoreUndefined: true })
r.context.require = this.requireModule.bind(this)
r.context.require.resolve = require.resolve.bind(require)
this.hash = hash
Repl.instances[this.hash] = this
this.logs = []
this.cwd = path.join(path.resolve(os.tmpdir()), this.hash)
this.reloadPackageJson()
}
reloadPackageJson() {
try {
this.packageJson = JSON.parse(fs.readFileSync(path.join(this.cwd, 'package.json')))
} catch (e) {
this.packageJson = { name: this.hash }
}
}
requireModule(moduleName) {
const { name, path: pkgPath, version } = parsePkg(moduleName)
if (resolve(name)) {
return require(name)
}
const { cwd } = this
if (!fs.existsSync(cwd)) {
fs.mkdirSync(cwd, { recursive: true })
cp.execSync('npm init -y', { cwd })
}
const fullPath = path.join(cwd, 'node_modules', name, pkgPath)
if (!resolve(fullPath)) {
const content = cp.execSync(`${Installer} add --registry https://registry.npmmirror.com/ ${name}@${version || 'latest'}`, { cwd })
this.reloadPackageJson()
this.logs.push({ type: 'output', timestamp: Date.now(), content })
}
return require(fullPath)
}
async input(script, logScript, wait = 0) {
// console.log('script' script)
this.readStream.push(`${script}\n`)
await sleep(wait)
const timestamp = Date.now()
this.logs.push({ type: 'input', timestamp, content: `${logScript || script}\n` })
this.fetchOutput(timestamp)
}
fetchOutput(timestamp = Date.now()) {
const output = this.writeStream.dump()
if (output) {
this.logs.push({ type: 'output', timestamp, content: output })
this.writeStream.flush()
}
}
getLogs() {
this.fetchOutput()
return this.logs
}
clearLogs() {
this.logs = []
}
}
Repl.instances = {}
router.get('/', async (ctx) => {
const hash = crypto.createHash('md5').update(String(Math.random())).digest('hex').substring(8, 24)
Repl.getInstance(hash)
console.log('create instance', hash)
ctx.redirect(hash)
})
router.get('/:hash', async (ctx) => {
const { hash } = ctx.params
const theRepl = Repl.getInstance(hash)
console.log('get instance', hash)
ctx.body = indexHtml({ repl: theRepl })
})
async function deleteRepl(ctx) {
const { hash } = ctx.params
const theRepl = Repl.getInstance(hash)
await theRepl.input('.exit')
console.log('delete instance', hash)
theRepl.clearLogs()
ctx.body = indexHtml({ repl: theRepl })
Repl.deleteInstance(hash)
}
router.post('/:hash/npm/install', async (ctx) => {
const { hash } = ctx.params
const theRepl = Repl.getInstance(hash)
const { packageJson } = ctx.request.body
if (typeof packageJson !== 'object') {
ctx.status = 400
return
}
console.log('npm install for', hash, JSON.stringify(packageJson))
const { cwd } = theRepl
if (!fs.existsSync(cwd)) {
fs.mkdirSync(cwd, { recursive: true })
}
fs.writeFileSync(path.join(cwd, 'package.json'), JSON.stringify(packageJson, null, 4))
const { stderr, stdout } = await cp.execAsync(`${Installer} install --production --registry https://registry.npmmirror.com/`, { cwd })
if (stderr) {
theRepl.logs.push({ type: 'output', timestamp: Date.now(), content: stderr })
}
if (stdout) {
theRepl.logs.push({ type: 'output', timestamp: Date.now(), content: stdout })
}
theRepl.reloadPackageJson()
const zip = new AdmZip()
zip.addLocalFolder(path.join(cwd))
ctx.body = zip.toBuffer()
})
router.post('/:hash', async (ctx) => {
const { hash } = ctx.params
const theRepl = Repl.getInstance(hash)
const { logScript, wait } = ctx.request.body
const script = String(ctx.request.body.script).trim()
console.log('run instance', hash, JSON.stringify(script))
if (script === '.exit') {
await deleteRepl(ctx)
return
}
if (script === '.clear') {
theRepl.clearLogs()
} else if (script) {
await theRepl.input(script, logScript, Number(wait))
}
ctx.body = indexHtml({ repl: theRepl })
})
router.delete('/:hash', deleteRepl)
app.use(koaBody())
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(8080, () => console.log('Server start'))