-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ls
85 lines (67 loc) · 3.02 KB
/
index.ls
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
require! \babel-standalone
{compile} = require \livescript-standalone
{foldr1, keys, map} = require \prelude-ls
# execute-javascript :: String -> object -> [Error, a]
export execute-javascript-sync = (code, context) -->
try
result = do ->
if !!@window
# use eval in the browser
context-code = context
|> keys
|> map (key) ->
mapped-key = key.replace \-, \_
"var #{mapped-key} = context['#{key}'];"
|> foldr1 (+)
|> -> it ? ""
eval """
#{context-code}
#{code}
"""
else
# use vm module for nodejs
(require \vm).run-in-new-context code, context
[null, result]
catch err
["javascript runtime error: #{err.to-string!}", null]
# compile-and-execute-javascript :: String -> object -> [Error, a]
export compile-and-execute-babel-sync = (code, context) -->
try
javascript-code = (babel-standalone.transform code, {presets: ["es2015", "react"], compact: false, minified: false}) .code
.replace '"use strict";', '' .trim!
.replace "'use strict';", '' .trim!
catch err
return ["babel compilation error: #{err.to-string!}", null]
execute-javascript-sync javascript-code, context
# compile-and-execute-livescript-sync :: String -> object -> [Error, a]
export compile-and-execute-livescript-sync = (livescript-code, context) -->
try
javascript-code = (compile livescript-code, {bare: true, header: false})
catch err
return ["livescript transpilation error: #{err.to-string!}", null]
execute-javascript-sync javascript-code, context
# compile-and-execute-sync :: String -> String -> object -> [Error, a]
export compile-and-execute-sync = (code, language, context) ->
# select the compiler based on the language
(switch language
| \livescript => compile-and-execute-livescript-sync
| \javascript => execute-javascript-sync
| \babel => compile-and-execute-babel-sync) do
"(\n#code\n)"
context
# from-error-value-tuple :: (... -> [Error, a]) -> (... -> p a)
export from-error-value-tuple = (f) ->
->
args = arguments
context = @
new Promise (res, rej) ->
[err, result] = f.apply context, args
if !!err then rej err else res result
# execute-javascript :: String, object -> p a
export execute-javascript = from-error-value-tuple execute-javascript-sync
# compile-and-execute-babel :: String, object -> p a
export compile-and-execute-babel = from-error-value-tuple compile-and-execute-babel-sync
# compile-and-execute-livescript :: String, object -> p a
export compile-and-execute-livescript = from-error-value-tuple compile-and-execute-livescript-sync
# compile-and-execute :: String, String, object -> p a
export compile-and-execute = from-error-value-tuple compile-and-execute-sync