-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.js
101 lines (98 loc) · 2.66 KB
/
handlers.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
import * as fs from 'fs'
import * as path from 'path'
import * as url from 'url'
import { killBrowser } from './util.js'
// Route called by finishTest. Prints test results and initializes cleanup.
export function finishTestHandler (req, res) {
var urlParts = url.parse(req.url, true)
var query = urlParts.query
if (process.env.DEBUG) {
process.stdout.write(`query:\t${JSON.stringify(query, null, 2)}
`)
}
if (query && query.code === '0' && query.message.startsWith('pass')) {
// pass
process.stdout.write(
`(browser)\tpass\t${query.message.replace(/pass */, '')}
`
)
res.writeHead(200)
res.end()
} else if (query.message === 'kill') {
// done testing, kill the browser
killBrowser(0)
} else {
// fail
if (query && query.message) {
process.stderr.write(
`(browser)\tfail:\t${query.message}
`
)
} else {
process.stderr.write(
`(browser)\tfail:\t${query}
`
)
}
res.writeHead(200)
res.end()
killBrowser(1)
}
}
// Dynamic html generator to load test case.
// Creates a plain html file with only the iso-test module and your test.
export function testPageHandler (req, res, testscript, toload, inject='') {
var content = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="module">
import global from '../always-global/global.js'
import { Process } from '../iso-process/process.js'
global.process = Process.getProcess()
global.process.options.env = global.process.options.env || {}
global.process.options.env = Object.assign(global.process.options.env, ${JSON.stringify(process.env)})
${inject}
import '${testscript}'
</script>
</head>
<body></body>
<script type="module" src="${toload}"></script>
</html>
`
res.writeHead(200, { 'content-type': 'text/html' })
res.end(content)
}
// Serve static files
export async function filehandler (req, res, root) {
// forbid dotfiles in root
if (req.pathname.startsWith('/.')) {
res.writeHead(401)
res.end('Forbidden')
} else {
// send the file
// Support guld scoped path
var fp = path.join(root, req.pathname)
if (process.env.DEBUG) {
process.stdout.write(`Request for file:\t${fp}
`)
}
fs.readFile(fp, { encoding: 'utf8' }, (e, f) => {
if (f) {
// try to guess mime type, at least supporting JS...
var mime = 'text/plain'
if (fp.endsWith('js')) mime = 'application/javascript'
res.writeHead(200, { 'Content-Type': mime })
res.end(f)
} else {
res.writeHead(404)
res.end(`No ${req.pathname} found`)
if (process.env.DEBUG) {
process.stdout.write(`No ${fp} found
`)
}
}
})
}
}