-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathumd.ex
More file actions
106 lines (98 loc) · 3.3 KB
/
umd.ex
File metadata and controls
106 lines (98 loc) · 3.3 KB
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
defmodule ElixirScript.ModuleSystems.UMD do
@moduledoc false
alias ESTree.Tools.Builder, as: JS
def build(imports, js_imports, body, exports) do
module_imports = Enum.map(imports, fn
{module, path} -> import_module(module, path)
end)
imports = js_imports
|> Enum.map(fn
{_module, name, path} -> import_module(name, path)
end)
imports = Enum.uniq(imports ++ module_imports)
export = export_module(exports)
List.wrap(make_umd(imports, body, export))
end
defp import_module(module_name, from) do
js_module_name = JS.identifier(module_name)
{js_module_name, JS.literal(from)}
end
defp export_module(exported_object) do
exported_object
end
defp make_umd(imports, body, exports) do
import_paths = Enum.map(imports, fn({_, path}) -> path end)
import_identifiers = Enum.map(imports, fn({id, _}) -> id end)
exports = if is_nil(exports), do: [], else: [JS.return_statement(exports)]
JS.expression_statement(
JS.call_expression(
JS.function_expression([JS.identifier("root"), JS.identifier("factory")], [], JS.block_statement([
JS.if_statement(
JS.logical_expression(
:&&,
JS.binary_expression(
:===,
JS.unary_expression(:typeof, true, JS.identifier("define")),
JS.literal("function")
),
JS.member_expression(
JS.identifier("define"),
JS.identifier("amd")
)
),
JS.block_statement([
JS.call_expression(
JS.identifier("define"),
[JS.array_expression(import_paths), JS.identifier("factory")]
)
]),
JS.if_statement(
JS.binary_expression(
:===,
JS.unary_expression(:typeof, true, JS.identifier("exports")),
JS.literal("object")
),
JS.block_statement([
JS.assignment_expression(
:=,
JS.member_expression(
JS.identifier("module"),
JS.identifier("exports")
),
JS.call_expression(
JS.identifier("factory"),
Enum.map(import_paths, fn x ->
JS.call_expression(
JS.identifier("require"),
[x]
)
end)
)
)
]),
JS.block_statement([
JS.assignment_expression(
:=,
JS.member_expression(
JS.identifier("root"),
JS.identifier("Elixir")
),
JS.call_expression(
JS.identifier("factory"),
Enum.map(import_identifiers, fn x ->
JS.member_expression(
JS.identifier("root"),
x
)
end)
)
)
])
)
)
])),
[JS.this_expression(), JS.function_expression(import_identifiers, [], JS.block_statement(body ++ exports))]
)
)
end
end