forked from scala-js/scala-js-env-jsdom-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSDOMNodeJSEnv.scala
241 lines (211 loc) · 7.46 KB
/
JSDOMNodeJSEnv.scala
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/* __ *\
** ________ ___ / / ___ __ ____ Scala.js JS envs **
** / __/ __// _ | / / / _ | __ / // __/ (c) 2013-2017, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \ http://scala-js.org/ **
** /____/\___/_/ |_/____/_/ | |__/ /____/ **
** |/____/ **
\* */
package org.scalajs.jsenv.jsdomnodejs
import scala.annotation.tailrec
import scala.collection.immutable
import scala.util.control.NonFatal
import java.io._
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, StandardCopyOption}
import java.net.URI
import com.google.common.jimfs.Jimfs
import org.scalajs.jsenv._
import org.scalajs.jsenv.nodejs._
import org.scalajs.jsenv.JSUtils.escapeJS
class JSDOMNodeJSEnv(config: JSDOMNodeJSEnv.Config) extends JSEnv {
def this() = this(JSDOMNodeJSEnv.Config())
val name: String = "Node.js with JSDOM"
def start(input: Seq[Input], runConfig: RunConfig): JSRun = {
JSDOMNodeJSEnv.validator.validate(runConfig)
val scripts = validateInput(input)
try {
internalStart(codeWithJSDOMContext(scripts), runConfig)
} catch {
case NonFatal(t) =>
JSRun.failed(t)
}
}
def startWithCom(input: Seq[Input], runConfig: RunConfig,
onMessage: String => Unit): JSComRun = {
JSDOMNodeJSEnv.validator.validate(runConfig)
val scripts = validateInput(input)
ComRun.start(runConfig, onMessage) { comLoader =>
internalStart(comLoader :: codeWithJSDOMContext(scripts), runConfig)
}
}
private def validateInput(input: Seq[Input]): List[Path] = {
input.map {
case Input.Script(script) =>
script
case _ =>
throw new UnsupportedInputException(input)
}.toList
}
private def internalStart(files: List[Path], runConfig: RunConfig): JSRun = {
val command = config.executable :: config.args
val externalConfig = ExternalJSRun.Config()
.withEnv(env)
.withRunConfig(runConfig)
ExternalJSRun.start(command, externalConfig)(JSDOMNodeJSEnv.write(files))
}
private def env: Map[String, String] =
Map("NODE_MODULE_CONTEXTS" -> "0") ++ config.env
private def codeWithJSDOMContext(scripts: List[Path]): List[Path] = {
val scriptsURIs = scripts.map(JSDOMNodeJSEnv.materialize(_))
val scriptsURIsAsJSStrings =
scriptsURIs.map(uri => "\"" + escapeJS(uri.toASCIIString) + "\"")
val scriptsURIsJSArray = scriptsURIsAsJSStrings.mkString("[", ", ", "]")
val jsDOMCode = {
s"""
|(function () {
| var jsdom = require("jsdom");
|
| var virtualConsole = new jsdom.VirtualConsole()
| .sendTo(console, { omitJSDOMErrors: true });
| virtualConsole.on("jsdomError", function (error) {
| try {
| // Display as much info about the error as possible
| if (error.detail && error.detail.stack) {
| console.error("" + error.detail);
| console.error(error.detail.stack);
| } else {
| console.error(error);
| }
| } finally {
| // Whatever happens, kill the process so that the run fails
| process.exit(1);
| }
| });
|
| var dom = new jsdom.JSDOM("", {
| virtualConsole: virtualConsole,
| url: "http://localhost/",
|
| /* Allow unrestricted <script> tags. This is exactly as
| * "dangerous" as the arbitrary execution of script files we
| * do in the non-jsdom Node.js env.
| */
| resources: "usable",
| runScripts: "dangerously"
| });
|
| var window = dom.window;
| window["scalajsCom"] = global.scalajsCom;
|
| var scriptsSrcs = $scriptsURIsJSArray;
| for (var i = 0; i < scriptsSrcs.length; i++) {
| var script = window.document.createElement("script");
| script.src = scriptsSrcs[i];
| window.document.body.appendChild(script);
| }
|})();
|""".stripMargin
}
List(Files.write(
Jimfs.newFileSystem().getPath("codeWithJSDOMContext.js"),
jsDOMCode.getBytes(StandardCharsets.UTF_8)))
}
}
object JSDOMNodeJSEnv {
private lazy val validator = ExternalJSRun.supports(RunConfig.Validator())
// Copied from NodeJSEnv.scala upstream
private def write(files: List[Path])(out: OutputStream): Unit = {
val p = new PrintStream(out, false, "UTF8")
try {
def writeRunScript(path: Path): Unit = {
try {
val f = path.toFile
val pathJS = "\"" + escapeJS(f.getAbsolutePath) + "\""
p.println(s"""
require('vm').runInThisContext(
require('fs').readFileSync($pathJS, { encoding: "utf-8" }),
{ filename: $pathJS, displayErrors: true }
);
""")
} catch {
case _: UnsupportedOperationException =>
val code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8)
val codeJS = "\"" + escapeJS(code) + "\""
val pathJS = "\"" + escapeJS(path.toString) + "\""
p.println(s"""
require('vm').runInThisContext(
$codeJS,
{ filename: $pathJS, displayErrors: true }
);
""")
}
}
for (file <- files)
writeRunScript(file)
} finally {
p.close()
}
}
// tmpSuffixRE and tmpFile copied from HTMLRunnerBuilder.scala in Scala.js
private val tmpSuffixRE = """[a-zA-Z0-9-_.]*$""".r
private def tmpFile(path: String, in: InputStream): URI = {
try {
/* - createTempFile requires a prefix of at least 3 chars
* - we use a safe part of the path as suffix so the extension stays (some
* browsers need that) and there is a clue which file it came from.
*/
val suffix = tmpSuffixRE.findFirstIn(path).orNull
val f = File.createTempFile("tmp-", suffix)
f.deleteOnExit()
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING)
f.toURI()
} finally {
in.close()
}
}
private def materialize(path: Path): URI = {
try {
path.toFile.toURI
} catch {
case _: UnsupportedOperationException =>
tmpFile(path.toString, Files.newInputStream(path))
}
}
final class Config private (
val executable: String,
val args: List[String],
val env: Map[String, String]
) {
private def this() = {
this(
executable = "node",
args = Nil,
env = Map.empty
)
}
def withExecutable(executable: String): Config =
copy(executable = executable)
def withArgs(args: List[String]): Config =
copy(args = args)
def withEnv(env: Map[String, String]): Config =
copy(env = env)
private def copy(
executable: String = executable,
args: List[String] = args,
env: Map[String, String] = env
): Config = {
new Config(executable, args, env)
}
}
object Config {
/** Returns a default configuration for a [[JSDOMNodeJSEnv]].
*
* The defaults are:
*
* - `executable`: `"node"`
* - `args`: `Nil`
* - `env`: `Map.empty`
*/
def apply(): Config = new Config()
}
}