turbopack_ecmascript/references/esm/
meta.rs1use std::borrow::Cow;
2
3use anyhow::Result;
4use bincode::{Decode, Encode};
5use swc_core::{
6 common::DUMMY_SP,
7 ecma::ast::{Expr, Ident},
8 quote,
9};
10use turbo_rcstr::{RcStr, rcstr};
11use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat};
12use turbo_tasks_fs::{DiskFileSystem, FileSystemPath};
13use turbopack_core::chunk::ChunkingContext;
14
15use crate::{
16 ast_path_trie::{AstPathId, AstPathTrie},
17 code_gen::{CodeGen, CodeGeneration},
18 create_visitor, magic_identifier,
19 runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_FILE_URL},
20};
21
22#[derive(PartialEq, Eq, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode)]
30pub struct ImportMetaBinding {
31 path: FileSystemPath,
32 hmr_enabled: bool,
33 mode: RcStr,
34 base_url: RcStr,
35 is_ssr: bool,
36}
37
38impl ImportMetaBinding {
39 pub fn new(
40 path: FileSystemPath,
41 hmr_enabled: bool,
42 mode: RcStr,
43 base_url: RcStr,
44 is_ssr: bool,
45 ) -> Self {
46 ImportMetaBinding {
47 path,
48 hmr_enabled,
49 mode,
50 base_url,
51 is_ssr,
52 }
53 }
54
55 pub async fn code_generation(
56 &self,
57 _trie: &AstPathTrie,
58 chunking_context: Vc<Box<dyn ChunkingContext>>,
59 ) -> Result<CodeGeneration> {
60 let root_path = chunking_context.root_path().await?;
61 let (root, rel_path) = if self.path.fs != root_path.fs
64 && let Some(fs) = ResolvedVc::try_downcast_type::<DiskFileSystem>(self.path.fs)
65 {
66 (Some(fs.await?.name().clone()), Some(self.path.path.clone()))
67 } else {
68 (None, root_path.get_relative_path_to(&self.path))
69 };
70 let path = rel_path.map_or_else(
71 || {
72 quote!(
73 "(() => { throw new Error('could not convert import.meta.url to filepath') })()"
74 as Expr
75 )
76 },
77 |path| {
78 let formatted = encode_path(path.trim_start_matches("./")).to_string();
82 if let Some(root) = &root {
83 quote!(
84 "$turbopack_resolve_file_url($formatted, $root)" as Expr,
85 turbopack_resolve_file_url: Expr = TURBOPACK_RESOLVE_FILE_URL.into(),
86 formatted: Expr = formatted.into(),
87 root: Expr = root.as_str().into()
88 )
89 } else {
90 quote!(
91 "$turbopack_resolve_file_url($formatted)" as Expr,
92 turbopack_resolve_file_url: Expr = TURBOPACK_RESOLVE_FILE_URL.into(),
93 formatted: Expr = formatted.into()
94 )
95 }
96 },
97 );
98
99 let hmr_enabled = self.hmr_enabled;
100 let mode: Expr = self.mode.as_str().into();
101 let is_prod: Expr = (self.mode == "production").into();
102 let is_dev: Expr = (self.mode != "production").into();
103 let is_ssr: Expr = self.is_ssr.into();
104 let base_url: Expr = self.base_url.as_str().into();
105
106 let stmt = if hmr_enabled {
109 let turbopack_module: Expr = TURBOPACK_MODULE.into();
111 quote!(
112 "var $name = { get url() { return $path }, env: { DEV: $is_dev, PROD: \
113 $is_prod, MODE: $mode, BASE_URL: $base_url, SSR: $is_ssr }, get turbopackHot() { \
114 return $m.hot } };" as Stmt,
115 name = meta_ident(),
116 path: Expr = path,
117 is_dev: Expr = is_dev,
118 is_prod: Expr = is_prod,
119 mode: Expr = mode,
120 base_url: Expr = base_url,
121 is_ssr: Expr = is_ssr,
122 m: Expr = turbopack_module,
123 )
124 } else {
125 quote!(
126 "var $name = { get url() { return $path }, env: { DEV: $is_dev, PROD: \
127 $is_prod, MODE: $mode, BASE_URL: $base_url, SSR: $is_ssr } };" as Stmt,
128 name = meta_ident(),
129 path: Expr = path,
130 is_dev: Expr = is_dev,
131 is_prod: Expr = is_prod,
132 mode: Expr = mode,
133 base_url: Expr = base_url,
134 is_ssr: Expr = is_ssr,
135 )
136 };
137
138 Ok(CodeGeneration::hoisted_stmt(rcstr!("import.meta"), stmt))
139 }
140}
141
142impl From<ImportMetaBinding> for CodeGen {
143 fn from(val: ImportMetaBinding) -> Self {
144 CodeGen::ImportMetaBinding(val)
145 }
146}
147
148#[derive(PartialEq, Eq, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode)]
154pub struct ImportMetaRef {
155 ast_path: AstPathId,
156}
157
158impl ImportMetaRef {
159 pub fn new(ast_path: AstPathId) -> Self {
160 ImportMetaRef { ast_path }
161 }
162
163 pub async fn code_generation(
164 &self,
165 trie: &AstPathTrie,
166 _chunking_context: Vc<Box<dyn ChunkingContext>>,
167 ) -> Result<CodeGeneration> {
168 let visitor = create_visitor!(trie, self.ast_path, visit_mut_expr, |expr: &mut Expr| {
169 *expr = Expr::Ident(meta_ident());
170 });
171
172 Ok(CodeGeneration::visitors(vec![visitor]))
173 }
174}
175
176impl From<ImportMetaRef> for CodeGen {
177 fn from(val: ImportMetaRef) -> Self {
178 CodeGen::ImportMetaRef(val)
179 }
180}
181
182fn encode_path(path: &'_ str) -> Cow<'_, str> {
185 let mut encoded = String::new();
186 let mut start = 0;
187 for (i, c) in path.char_indices() {
188 let mapping = match c {
189 '%' => "%25",
190 '\\' => "%5C",
191 '\n' => "%0A",
192 '\r' => "%0D",
193 '\t' => "%09",
194 _ => continue,
195 };
196
197 if encoded.is_empty() {
198 encoded.reserve(path.len());
199 }
200
201 encoded += &path[start..i];
202 encoded += mapping;
203 start = i + 1;
204 }
205
206 if encoded.is_empty() {
207 return Cow::Borrowed(path);
208 }
209 encoded += &path[start..];
210 Cow::Owned(encoded)
211}
212
213fn meta_ident() -> Ident {
214 Ident::new(
215 magic_identifier::mangle("import.meta").into(),
216 DUMMY_SP,
217 Default::default(),
218 )
219}
220
221#[cfg(test)]
222mod test {
223 use super::encode_path;
224
225 #[test]
226 fn test_encode_path_regular() {
227 let input = "abc";
228 assert_eq!(encode_path(input), "abc");
229 }
230
231 #[test]
232 fn test_encode_path_special_chars() {
233 let input = "abc%def\\ghi\njkl\rmno\tpqr";
234 assert_eq!(encode_path(input), "abc%25def%5Cghi%0Ajkl%0Dmno%09pqr");
235 }
236
237 #[test]
238 fn test_encode_path_special_char_start() {
239 let input = "%abc";
240 assert_eq!(encode_path(input), "%25abc");
241 }
242
243 #[test]
244 fn test_encode_path_special_char_end() {
245 let input = "abc%";
246 assert_eq!(encode_path(input), "abc%25");
247 }
248
249 #[test]
250 fn test_encode_path_special_char_contiguous() {
251 let input = "%%%";
252 assert_eq!(encode_path(input), "%25%25%25");
253 }
254}