forked from swc-project/swc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundle.rs
234 lines (212 loc) · 7.34 KB
/
bundle.rs
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
use crate::{
get_compiler,
util::{MapErr},
};
use anyhow::{bail, Error};
use fxhash::FxHashMap;
use napi::{CallContext, Env, JsObject, Status, Task};
use spack::resolvers::NodeResolver;
use std::{
panic::{catch_unwind, AssertUnwindSafe},
sync::Arc,
};
use swc::{config::SourceMapsConfig, Compiler, TransformOutput};
use swc_atoms::js_word;
use swc_bundler::{BundleKind, Bundler, Load, ModuleRecord, Resolve};
use swc_common::Span;
use swc_ecma_ast::{
Bool, Expr, ExprOrSuper, Ident, KeyValueProp, Lit, MemberExpr, MetaPropExpr, PropName, Str,
};
struct BundleTask {
swc: Arc<swc::Compiler>,
config: spack::config::Config,
loader: Box<dyn Load>,
resolver: Box<dyn Resolve>,
}
impl Task for BundleTask {
type Output = FxHashMap<String, TransformOutput>;
type JsValue = JsObject;
fn compute(&mut self) -> napi::Result<Self::Output> {
// Defaults to es3
let codegen_target = self
.config
.codegen_target()
.unwrap_or_default();
let res = catch_unwind(AssertUnwindSafe(|| {
let bundler = Bundler::new(
self.swc.globals(),
self.swc.cm.clone(),
&self.loader,
&self.resolver,
swc_bundler::Config {
require: true,
external_modules: vec![
"assert",
"buffer",
"child_process",
"console",
"cluster",
"crypto",
"dgram",
"dns",
"events",
"fs",
"http",
"http2",
"https",
"net",
"os",
"path",
"perf_hooks",
"process",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"timers",
"tls",
"tty",
"url",
"util",
"v8",
"vm",
"wasi",
"worker",
"zlib",
]
.into_iter()
.map(From::from)
.collect(),
..Default::default()
},
Box::new(Hook),
);
let result = bundler
.bundle(self.config.entry.clone().into())
.convert_err()?;
let result = result
.into_iter()
.map(|bundle| match bundle.kind {
BundleKind::Named { name } | BundleKind::Lib { name } => {
Ok((name, bundle.module))
}
BundleKind::Dynamic => bail!("unimplemented: dynamic code splitting"),
})
.map(|res| {
res.and_then(|(k, m)| {
// TODO: Source map
let minify = self
.config
.options
.as_ref()
.map(|v| {
v.config
.as_ref()
.map(|v| v.minify)
.flatten()
.unwrap_or(false)
})
.unwrap_or(false);
let output = self.swc.print(
&m,
codegen_target,
SourceMapsConfig::Bool(true),
None,
minify,
)?;
Ok((k, output))
})
})
.collect::<Result<_, _>>()
.convert_err()?;
Ok(result)
}));
let err = match res {
Ok(v) => return v,
Err(err) => err,
};
if let Some(s) = err.downcast_ref::<String>() {
return Err(napi::Error::new(
Status::GenericFailure,
format!("panic detected: {}", s),
));
}
Err(napi::Error::new(
Status::GenericFailure,
format!("panic detected"),
))
}
fn resolve(self, env: Env, output: Self::Output) -> napi::Result<Self::JsValue> {
env.to_js_value(&output)?.coerce_to_object()
}
}
#[js_function(1)]
pub(crate) fn bundle(cx: CallContext) -> napi::Result<JsObject> {
let c: Arc<Compiler> = get_compiler(&cx);
let jsconf = cx.get::<JsObject>(0)?;
// Execute plugins, if present.
if jsconf.has_named_property("plugins")? {
let plugins = jsconf.get_named_property::<napi::JsArrayBuffer>("plugins")?;
for i in 0..plugins.get_array_length()? {
let func = plugins.get_element::<napi::JsFunction>(i)?;
// println!("{:?}", func.coerce_to_string()?.into_utf8()?.as_str()?.to_string());
let _ = func.call(None, &[])?;
}
}
let config: spack::config::Config = cx.env.from_js_value(jsconf)?;
let loader = Box::new(spack::loaders::swc::SwcLoader::new(
c.clone(),
config
.options
.as_ref()
.cloned()
.unwrap_or_else(|| {
serde_json::from_value(serde_json::Value::Object(Default::default())).unwrap()
}),
));
cx.env
.spawn(BundleTask {
swc: c.clone(),
config,
loader,
resolver: Box::new(NodeResolver::new()) as Box<_>,
})
.map(|t| t.promise_object())
}
struct Hook;
impl swc_bundler::Hook for Hook {
fn get_import_meta_props(
&self,
span: Span,
module_record: &ModuleRecord,
) -> Result<Vec<KeyValueProp>, Error> {
Ok(vec![
KeyValueProp {
key: PropName::Ident(Ident::new(js_word!("url"), span)),
value: Box::new(Expr::Lit(Lit::Str(Str {
span,
value: module_record.file_name.to_string().into(),
has_escape: false,
kind: Default::default(),
}))),
},
KeyValueProp {
key: PropName::Ident(Ident::new(js_word!("main"), span)),
value: Box::new(if module_record.is_entry {
Expr::Member(MemberExpr {
span,
obj: ExprOrSuper::Expr(Box::new(Expr::MetaProp(MetaPropExpr {
meta: Ident::new(js_word!("import"), span),
prop: Ident::new(js_word!("meta"), span),
}))),
prop: Box::new(Expr::Ident(Ident::new(js_word!("main"), span))),
computed: false,
})
} else {
Expr::Lit(Lit::Bool(Bool { span, value: false }))
}),
},
])
}
}