Unverified Commit b3449ee2 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbopack: map dynamic new URL requests at runtime

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 7ece5e6e
...@@ -380,7 +380,9 @@ impl ReferencedAsset { ...@@ -380,7 +380,9 @@ impl ReferencedAsset {
impl ReferencedAsset { impl ReferencedAsset {
pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Self> { pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Self> {
// TODO handle multiple keyed results // Only the first matching result is used. Callers whose request can match multiple keyed
// results (e.g. a dynamic `new URL()`, see `UrlAssetReferenceCodeGen`) have to map them
// with `PatternMapping` instead.
let result = resolve_result.await?; let result = resolve_result.await?;
if result.is_unresolvable() { if result.is_unresolvable() {
return Ok(ReferencedAsset::Unresolvable); return Ok(ReferencedAsset::Unresolvable);
......
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use swc_core::{ use swc_core::{
common::util::take::Take,
ecma::ast::{Expr, ExprOrSpread, NewExpr}, ecma::ast::{Expr, ExprOrSpread, NewExpr},
quote, quote,
}; };
...@@ -21,7 +22,10 @@ use crate::{ ...@@ -21,7 +22,10 @@ use crate::{
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder}, ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::esm::base::ReferencedAsset, references::{
esm::base::ReferencedAsset,
pattern_mapping::{PatternMapping, ResolveType, UrlModuleMode},
},
runtime_functions::{ runtime_functions::{
TURBOPACK_RELATIVE_URL, TURBOPACK_REQUIRE, TURBOPACK_RESOLVE_MODULE_ID_PATH, TURBOPACK_RELATIVE_URL, TURBOPACK_REQUIRE, TURBOPACK_RESOLVE_MODULE_ID_PATH,
}, },
...@@ -152,15 +156,26 @@ impl UrlAssetReferenceCodeGen { ...@@ -152,15 +156,26 @@ impl UrlAssetReferenceCodeGen {
│ None │ new URL(url, base) │ new URL(url, base) │ new URL(url, base) │ │ None │ new URL(url, base) │ new URL(url, base) │ new URL(url, base) │
└───────────────────────────────┴─────────────────────────────────────────────────────────────────────────┴────────────────────────────────────────────────┴───────────────────────┘ └───────────────────────────────┴─────────────────────────────────────────────────────────────────────────┴────────────────────────────────────────────────┴───────────────────────┘
*/ */
/// When the request is dynamic (e.g. `new URL(`./${name}`, import.meta.url)`) or resolves to
/// multiple assets, the asset is instead picked at runtime from a request -> URL map (see
/// [`Self::dynamic_code_generation`]).
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie, trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = vec![];
let reference = self.reference.await?; let reference = self.reference.await?;
if reference.url_rewrite_behavior != UrlRewriteBehavior::None
&& let Some(code_generation) = self
.dynamic_code_generation(&reference, trie, chunking_context)
.await?
{
return Ok(code_generation);
}
let mut visitors = vec![];
match reference.url_rewrite_behavior { match reference.url_rewrite_behavior {
UrlRewriteBehavior::Relative => { UrlRewriteBehavior::Relative => {
let referenced_asset = self.reference.get_referenced_asset().await?; let referenced_asset = self.reference.get_referenced_asset().await?;
...@@ -346,4 +361,88 @@ impl UrlAssetReferenceCodeGen { ...@@ -346,4 +361,88 @@ impl UrlAssetReferenceCodeGen {
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors))
} }
/// Rewrites a `new URL()` call whose request has dynamic parts or resolves to multiple
/// assets, so that the asset matching the request is looked up at runtime instead of always
/// using a single one (a request that matched nothing throws `MODULE_NOT_FOUND` at runtime).
/// Returns `None` for a constant request with at most one result, which is handled by
/// [`Self::code_generation`].
///
/// The first argument becomes `__turbopack_module_context__(map)(url)`, which evaluates to
/// the same URL the corresponding single match would be rewritten to:
/// - `Relative`: `new __turbopack_relative_url__(<lookup>)`
/// - `Full` + client rendering: `new URL(<lookup>, location.origin)`
/// - `Full` otherwise: `new URL(<lookup>, base)`, where modules map to
/// `__turbopack_resolve_module_id_path__(id)` (which is absolute, so the base only applies to
/// URL externals).
async fn dynamic_code_generation(
&self,
reference: &UrlAssetReference,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Option<CodeGeneration>> {
let resolve_result = self.reference.resolve_reference();
if !reference
.request
.request_pattern()
.await?
.has_dynamic_parts()
&& resolve_result.await?.primary.len() <= 1
{
return Ok(None);
}
let pattern_mapping = PatternMapping::resolve_request(
*reference.request,
*reference.origin,
chunking_context,
resolve_result,
ResolveType::ChunkItem,
Some(Vc::upcast(*self.reference)),
)
.await?;
let rewrite_url_base = match (reference.url_rewrite_behavior, reference.rendering) {
(UrlRewriteBehavior::Full, Rendering::Client) => {
Some(quote!("location.origin" as Expr))
}
_ => None,
};
let module_mode = match (reference.url_rewrite_behavior, reference.rendering) {
(UrlRewriteBehavior::Full, Rendering::None | Rendering::Server) => {
UrlModuleMode::ResolveModuleIdPath
}
_ => UrlModuleMode::Require,
};
let relative = reference.url_rewrite_behavior == UrlRewriteBehavior::Relative;
let visitor = create_visitor!(trie, self.path, visit_mut_expr, |new_expr: &mut Expr| {
let Expr::New(NewExpr {
args: Some(args), ..
}) = new_expr
else {
return;
};
let Some(ExprOrSpread { expr, spread: None }) = args.get_mut(0) else {
return;
};
let lookup = pattern_mapping.create_url_lookup(*expr.take(), module_mode);
if relative {
*new_expr = quote!(
"new $turbopack_relative_url($lookup)" as Expr,
turbopack_relative_url: Expr = TURBOPACK_RELATIVE_URL.into(),
lookup: Expr = lookup,
);
return;
}
**expr = lookup;
if let Some(rewrite) = &rewrite_url_base
&& let Some(ExprOrSpread { expr, spread: None }) = args.get_mut(1)
{
**expr = rewrite.clone();
}
});
Ok(Some(CodeGeneration::visitors(vec![visitor])))
}
} }
...@@ -38,6 +38,7 @@ use crate::{ ...@@ -38,6 +38,7 @@ use crate::{
runtime_functions::{ runtime_functions::{
TURBOPACK_ASYNC_LOADER, TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE, TURBOPACK_ASYNC_LOADER, TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE,
TURBOPACK_IMPORT, TURBOPACK_MODULE_CONTEXT, TURBOPACK_REQUIRE, TURBOPACK_IMPORT, TURBOPACK_MODULE_CONTEXT, TURBOPACK_REQUIRE,
TURBOPACK_RESOLVE_MODULE_ID_PATH,
}, },
utils::module_id_to_lit, utils::module_id_to_lit,
}; };
...@@ -258,9 +259,53 @@ impl SinglePatternMapping { ...@@ -258,9 +259,53 @@ impl SinglePatternMapping {
} }
} }
/// How a module entry of a `new URL()` pattern mapping is turned into the URL of its asset.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum UrlModuleMode {
/// `__turbopack_require__(id)`, which evaluates to the asset path exported by the module.
Require,
/// `__turbopack_resolve_module_id_path__(id)`, which evaluates to the full output path of
/// the asset.
ResolveModuleIdPath,
}
impl SinglePatternMapping {
/// Creates an expression evaluating to the URL (the first `new URL()` argument) this mapping
/// points to. URL externals evaluate to their request, as with a single `new URL()` match.
fn create_url(&self, module_mode: UrlModuleMode) -> Expr {
match self {
Self::Invalid => quote!(
"(() => {throw new Error('could not resolve the new URL() request into an \
asset');})()" as Expr
),
Self::Unresolvable(request) => throw_module_not_found_expr(request),
Self::Ignored => quote!("{}" as Expr),
Self::Dropped => quote!("0" as Expr),
Self::Module(module_id) | Self::ModuleLoader(module_id) => match module_mode {
UrlModuleMode::Require => quote!(
"$turbopack_require($id)" as Expr,
turbopack_require: Expr = TURBOPACK_REQUIRE.into(),
id: Expr = module_id_to_lit(module_id),
),
UrlModuleMode::ResolveModuleIdPath => quote!(
"$turbopack_resolve_module_id_path($id)" as Expr,
turbopack_resolve_module_id_path: Expr = TURBOPACK_RESOLVE_MODULE_ID_PATH.into(),
id: Expr = module_id_to_lit(module_id),
),
},
Self::External(request, ExternalType::Url) => request.as_str().into(),
Self::External(request, ty) => throw_module_not_found_error_expr(
request,
&format!("Unsupported external type {ty:?} for URL reference"),
),
}
}
}
enum ImportMode { enum ImportMode {
Require, Require,
Import { import_externals: bool }, Import { import_externals: bool },
Url(UrlModuleMode),
} }
fn create_context_map( fn create_context_map(
...@@ -275,7 +320,8 @@ fn create_context_map( ...@@ -275,7 +320,8 @@ fn create_context_map(
"{id: () => $id, module: () => $module}", "{id: () => $id, module: () => $module}",
id: Expr = v.create_id(Cow::Borrowed(key_expr)), id: Expr = v.create_id(Cow::Borrowed(key_expr)),
module: Expr = match import_mode {ImportMode::Require => v.create_require(Cow::Borrowed(key_expr)), module: Expr = match import_mode {ImportMode::Require => v.create_require(Cow::Borrowed(key_expr)),
ImportMode::Import {import_externals} => v.create_import(Cow::Borrowed(key_expr), import_externals),}, ImportMode::Import {import_externals} => v.create_import(Cow::Borrowed(key_expr), import_externals),
ImportMode::Url(module_mode) => v.create_url(module_mode),},
),})))}) ),})))})
.collect(); .collect();
...@@ -316,6 +362,26 @@ impl PatternMapping { ...@@ -316,6 +362,26 @@ impl PatternMapping {
} }
} }
/// Creates an expression that looks up, at runtime, the URL (the first `new URL()` argument)
/// of the asset matching `key_expr`. It throws `MODULE_NOT_FOUND` when nothing matches, and
/// `key_expr` is evaluated exactly once.
///
/// Only used for dynamic or multi-result requests, so a [`PatternMapping::Single`] here means
/// that the request matched nothing and is mapped to an empty context.
pub fn create_url_lookup(&self, key_expr: Expr, module_mode: UrlModuleMode) -> Expr {
let empty = FxIndexMap::default();
let map = match self {
PatternMapping::Single(_) => &empty,
PatternMapping::Map(map) => map,
};
quote!(
"$turbopack_module_context($map)($key)" as Expr,
turbopack_module_context: Expr = TURBOPACK_MODULE_CONTEXT.into(),
map: Expr = create_context_map(map, &key_expr, ImportMode::Url(module_mode)),
key: Expr = key_expr
)
}
pub fn create_import(&self, key_expr: Expr, import_externals: bool) -> Expr { pub fn create_import(&self, key_expr: Expr, import_externals: bool) -> Expr {
match self { match self {
PatternMapping::Single(pm) => pm.create_import(Cow::Owned(key_expr), import_externals), PatternMapping::Single(pm) => pm.create_import(Cow::Owned(key_expr), import_externals),
......
...@@ -58,7 +58,7 @@ use turbopack_core::{ ...@@ -58,7 +58,7 @@ use turbopack_core::{
virtual_source::VirtualSource, virtual_source::VirtualSource,
}; };
use turbopack_css::chunk::CssChunkType; use turbopack_css::chunk::CssChunkType;
use turbopack_ecmascript::chunk::EcmascriptChunkType; use turbopack_ecmascript::{chunk::EcmascriptChunkType, references::esm::UrlRewriteBehavior};
use turbopack_ecmascript_runtime::RuntimeType; use turbopack_ecmascript_runtime::RuntimeType;
use turbopack_node::{ use turbopack_node::{
child_process_backend, child_process_backend,
...@@ -312,6 +312,38 @@ struct TestOptions { ...@@ -312,6 +312,38 @@ struct TestOptions {
/// such requests would, which makes them unresolvable. /// such requests would, which makes them unresolvable.
#[serde(default = "default_true")] #[serde(default = "default_true")]
server_relative_root: bool, server_relative_root: bool,
/// How `new URL(..., import.meta.url)` calls are rewritten.
#[serde(default)]
url_rewrite_behavior: TestUrlRewriteBehavior,
}
#[derive(
Copy,
Clone,
Default,
PartialEq,
Eq,
Debug,
Deserialize,
ValueDebugFormat,
NonLocalValue,
Encode,
Decode,
)]
#[serde(rename_all = "camelCase")]
enum TestUrlRewriteBehavior {
#[default]
Relative,
Full,
}
impl From<TestUrlRewriteBehavior> for UrlRewriteBehavior {
fn from(value: TestUrlRewriteBehavior) -> Self {
match value {
TestUrlRewriteBehavior::Relative => UrlRewriteBehavior::Relative,
TestUrlRewriteBehavior::Full => UrlRewriteBehavior::Full,
}
}
} }
fn default_true() -> bool { fn default_true() -> bool {
...@@ -338,6 +370,7 @@ impl Default for TestOptions { ...@@ -338,6 +370,7 @@ impl Default for TestOptions {
numeric_module_ids: false, numeric_module_ids: false,
side_effect_free_packages: Vec::new(), side_effect_free_packages: Vec::new(),
server_relative_root: default_true(), server_relative_root: default_true(),
url_rewrite_behavior: TestUrlRewriteBehavior::default(),
} }
} }
} }
...@@ -514,6 +547,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -514,6 +547,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
cjs_scope_hoisting: options.cjs_scope_hoisting, cjs_scope_hoisting: options.cjs_scope_hoisting,
cross_module_constants: options.cross_module_constants, cross_module_constants: options.cross_module_constants,
infer_module_side_effects: options.infer_module_side_effects, infer_module_side_effects: options.infer_module_side_effects,
esm_url_rewrite_behavior: Some(options.url_rewrite_behavior.into()),
..Default::default() ..Default::default()
}, },
environment: Some(env), environment: Some(env),
......
let evaluations = 0
const track = (name) => {
evaluations++
return name
}
const assetUrl = (name) =>
new URL(`./assets/${track(name)}`, import.meta.url).toString()
const singleUrl = (name) =>
new URL(`./single/${track(name)}`, import.meta.url).toString()
const noMatchUrl = (name) => {
try {
return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
} catch (e) {
return e
}
}
const expectModuleNotFound = (fn) => {
const before = evaluations
let error
try {
fn()
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1)
}
it('should resolve each runtime request of a dynamic new URL to its own asset', () => {
const alpha = assetUrl('alpha.txt')
const beta = assetUrl('beta.txt')
const gamma = assetUrl('gamma.txt')
expect(alpha).toMatch(/alpha\.[^/]*txt$/)
expect(beta).toMatch(/beta\.[^/]*txt$/)
expect(gamma).toMatch(/gamma\.[^/]*txt$/)
expect(new Set([alpha, beta, gamma]).size).toBe(3)
})
it('should resolve a dynamic new URL that matches a single file', () => {
expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/)
})
it('should throw MODULE_NOT_FOUND for a request that matched no file', () => {
expectModuleNotFound(() => assetUrl('missing.txt'))
expectModuleNotFound(() => singleUrl('missing.txt'))
})
it('should throw MODULE_NOT_FOUND for a pattern that matched nothing', () => {
const before = evaluations
const error = noMatchUrl('anything.txt')
expect(error).toBeInstanceOf(Error)
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1)
})
it('should evaluate the request expression exactly once', () => {
const before = evaluations
assetUrl('beta.txt')
expect(evaluations - before).toBe(1)
})
warning - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js:13:11 Module not found: Can't resolve './no-match/' <dynamic>
9 | const singleUrl = (name) =>
10 | new URL(`./single/${track(name)}`, import.meta.url).toString()
11 | const noMatchUrl = (name) => {
12 | try {
+ v---------------------------------------------------v
13 + return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^
14 | } catch (e) {
15 | return e
16 | }
17 | }
| It was not possible to find the requested file.
| Parsed request as written in source code: relative './no-match/' <dynamic>
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js
| Type of request: url request
|
\ No newline at end of file
let evaluations = 0
const track = (name) => {
evaluations++
return name
}
const assetUrl = (name) =>
new URL(`./assets/${track(name)}`, import.meta.url).toString()
const singleUrl = (name) =>
new URL(`./single/${track(name)}`, import.meta.url).toString()
const noMatchUrl = (name) => {
try {
return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
} catch (e) {
return e
}
}
const expectModuleNotFound = (fn) => {
const before = evaluations
let error
try {
fn()
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1)
}
it('should resolve each runtime request of a dynamic new URL to its own asset', () => {
const alpha = assetUrl('alpha.txt')
const beta = assetUrl('beta.txt')
const gamma = assetUrl('gamma.txt')
expect(alpha).toMatch(/alpha\.[^/]*txt$/)
expect(beta).toMatch(/beta\.[^/]*txt$/)
expect(gamma).toMatch(/gamma\.[^/]*txt$/)
expect(new Set([alpha, beta, gamma]).size).toBe(3)
})
it('should resolve a dynamic new URL that matches a single file', () => {
expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/)
})
it('should throw MODULE_NOT_FOUND for a request that matched no file', () => {
expectModuleNotFound(() => assetUrl('missing.txt'))
expectModuleNotFound(() => singleUrl('missing.txt'))
})
it('should throw MODULE_NOT_FOUND for a pattern that matched nothing', () => {
const before = evaluations
const error = noMatchUrl('anything.txt')
expect(error).toBeInstanceOf(Error)
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1)
})
it('should evaluate the request expression exactly once', () => {
const before = evaluations
assetUrl('beta.txt')
expect(evaluations - before).toBe(1)
})
warning - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js:13:11 Module not found: Can't resolve './no-match/' <dynamic>
9 | const singleUrl = (name) =>
10 | new URL(`./single/${track(name)}`, import.meta.url).toString()
11 | const noMatchUrl = (name) => {
12 | try {
+ v---------------------------------------------------v
13 + return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^
14 | } catch (e) {
15 | return e
16 | }
17 | }
| It was not possible to find the requested file.
| Parsed request as written in source code: relative './no-match/' <dynamic>
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js
| Type of request: url request
|
\ No newline at end of file
...@@ -57,6 +57,7 @@ use turbopack_core::{ ...@@ -57,6 +57,7 @@ use turbopack_core::{
use turbopack_ecmascript::{ use turbopack_ecmascript::{
AnalyzeMode, CustomTransformer, EcmascriptInputTransform, TransformPlugin, AnalyzeMode, CustomTransformer, EcmascriptInputTransform, TransformPlugin,
chunk::EcmascriptChunkType, chunk::EcmascriptChunkType,
references::esm::UrlRewriteBehavior,
transform::{ReactCompilerCompilationMode, ReactCompilerTransformOptions}, transform::{ReactCompilerCompilationMode, ReactCompilerTransformOptions},
}; };
use turbopack_ecmascript_plugins::transform::{ use turbopack_ecmascript_plugins::transform::{
...@@ -118,6 +119,26 @@ struct SnapshotOptions { ...@@ -118,6 +119,26 @@ struct SnapshotOptions {
chunk_loading_global: String, chunk_loading_global: String,
#[serde(default)] #[serde(default)]
enable_rust_react_compiler: bool, enable_rust_react_compiler: bool,
/// How `new URL(..., import.meta.url)` calls are rewritten.
#[serde(default)]
url_rewrite_behavior: SnapshotUrlRewriteBehavior,
}
#[derive(Debug, Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "camelCase")]
enum SnapshotUrlRewriteBehavior {
#[default]
Relative,
Full,
}
impl From<SnapshotUrlRewriteBehavior> for UrlRewriteBehavior {
fn from(value: SnapshotUrlRewriteBehavior) -> Self {
match value {
SnapshotUrlRewriteBehavior::Relative => UrlRewriteBehavior::Relative,
SnapshotUrlRewriteBehavior::Full => UrlRewriteBehavior::Full,
}
}
} }
#[derive(Debug, Deserialize, Default)] #[derive(Debug, Deserialize, Default)]
...@@ -159,6 +180,7 @@ impl Default for SnapshotOptions { ...@@ -159,6 +180,7 @@ impl Default for SnapshotOptions {
source_map_source_type: SourceMapSourceType::default(), source_map_source_type: SourceMapSourceType::default(),
chunk_loading_global: default_chunk_loading_global(), chunk_loading_global: default_chunk_loading_global(),
enable_rust_react_compiler: false, enable_rust_react_compiler: false,
url_rewrite_behavior: SnapshotUrlRewriteBehavior::default(),
} }
} }
} }
...@@ -424,6 +446,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -424,6 +446,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
..Default::default() ..Default::default()
})), })),
ignore_dynamic_requests: true, ignore_dynamic_requests: true,
esm_url_rewrite_behavior: Some(options.url_rewrite_behavior.into()),
infer_module_side_effects: true, infer_module_side_effects: true,
cjs_tree_shaking: options.cjs_tree_shaking, cjs_tree_shaking: options.cjs_tree_shaking,
mangle_export_names: options.mangle_export_names, mangle_export_names: options.mangle_export_names,
......
const name = globalThis.assetName
const assetUrl = new URL(`./assets/${name}`, import.meta.url)
const staticUrl = new URL('./assets/a.txt', import.meta.url)
console.log(assetUrl, staticUrl)
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_import-meta_url-dynamic-full_input_05at1jd_1vmxn._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/a.1iv57-cn_fwh5.txt");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/b.txt (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/b.3bxlg_6wd90g2.txt");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
var __TURBOPACK__import$2e$meta__ = {
get url () {
return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/index.js");
},
env: {
DEV: true,
PROD: false,
MODE: "development",
BASE_URL: "/",
SSR: false
}
};
const name = globalThis.assetName;
const assetUrl = new URL(__turbopack_context__.f({
"./assets/a.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)")
},
"./assets/b.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/b.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/b.txt (static in ecmascript)")
}
})(`./assets/${name}`), location.origin);
const staticUrl = new URL(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)"), location.origin);
console.log(assetUrl, staticUrl);
}),
]);
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_import-meta_url-dynamic-full_input_05at1jd_1vmxn._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/index.js"],"sourcesContent":["const name = globalThis.assetName\nconst assetUrl = new URL(`./assets/${name}`, import.meta.url)\nconst staticUrl = new URL('./assets/a.txt', import.meta.url)\n\nconsole.log(assetUrl, staticUrl)\n"],"names":["name","globalThis","assetName","assetUrl","URL","staticUrl","console","log"],"mappings":";;;;;;;;;;;;AAAA,MAAMA,OAAOC,WAAWC,SAAS;AACjC,MAAMC,WAAW,IAAIC;;;;;;;;;GAAI,CAAC,SAAS,EAAEJ,MAAM;AAC3C,MAAMK,YAAY,IAAID;AAEtBE,QAAQC,GAAG,CAACJ,UAAUE"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_import-meta_url-dynamic-full_input_index_0e3ijahpkordk.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_import-meta_url-dynamic-full_input_05at1jd_1vmxn._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
const name = globalThis.assetName
const assetUrl = new URL(`./assets/${name}`, import.meta.url)
const staticUrl = new URL('./assets/a.txt', import.meta.url)
console.log(assetUrl, staticUrl)
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_import-meta_url-dynamic_input_1y_lpid7pdf49._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/a.1iv57-cn_fwh5.txt");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/b.txt (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/b.3bxlg_6wd90g2.txt");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
var __TURBOPACK__import$2e$meta__ = {
get url () {
return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/index.js");
},
env: {
DEV: true,
PROD: false,
MODE: "development",
BASE_URL: "/",
SSR: false
}
};
const name = globalThis.assetName;
const assetUrl = new __turbopack_context__.U(__turbopack_context__.f({
"./assets/a.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)")
},
"./assets/b.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/b.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/b.txt (static in ecmascript)")
}
})(`./assets/${name}`));
const staticUrl = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)"));
console.log(assetUrl, staticUrl);
}),
]);
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_import-meta_url-dynamic_input_1y_lpid7pdf49._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/index.js"],"sourcesContent":["const name = globalThis.assetName\nconst assetUrl = new URL(`./assets/${name}`, import.meta.url)\nconst staticUrl = new URL('./assets/a.txt', import.meta.url)\n\nconsole.log(assetUrl, staticUrl)\n"],"names":["name","globalThis","assetName","assetUrl","staticUrl","console","log"],"mappings":";;;;;;;;;;;;AAAA,MAAMA,OAAOC,WAAWC,SAAS;AACjC,MAAMC;;;;;;;;;GAAmB,CAAC,SAAS,EAAEH,MAAM;AAC3C,MAAMI;AAENC,QAAQC,GAAG,CAACH,UAAUC"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_import-meta_url-dynamic_input_index_0kkthcbbgos2u.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_import-meta_url-dynamic_input_1y_lpid7pdf49._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment