Unverified Commit 5c70b4be authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: add `?dpl=` to all asset urls returned by Turbopack (#88828)

### What?

Closes PACK-6554

All asset urls returned by Turbopack should include a `?dpl` suffix.
parent 1a2eccf3
......@@ -11,12 +11,12 @@ use turbopack::module_options::{
side_effect_free_packages_glob,
};
use turbopack_browser::{
BrowserChunkingContext, ChunkSuffix, ContentHashing, CurrentChunkMethod,
BrowserChunkingContext, ContentHashing, CurrentChunkMethod,
react_refresh::assert_can_resolve_react_refresh,
};
use turbopack_core::{
chunk::{
ChunkingConfig, ChunkingContext, MangleType, MinifyType, SourceMapSourceType,
AssetSuffix, ChunkingConfig, ChunkingContext, MangleType, MinifyType, SourceMapSourceType,
SourceMapsType, UnusedReferences, chunk_id_strategy::ModuleIdStrategy,
},
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
......@@ -26,7 +26,9 @@ use turbopack_core::{
resolve::{parse::Request, pattern::Pattern},
};
use turbopack_css::chunk::CssChunkType;
use turbopack_ecmascript::{AnalyzeMode, TypeofWindow, chunk::EcmascriptChunkType};
use turbopack_ecmascript::{
AnalyzeMode, TypeofWindow, chunk::EcmascriptChunkType, references::esm::UrlRewriteBehavior,
};
use turbopack_node::{
execution_context::ExecutionContext,
transforms::postcss::{PostCssConfigLocation, PostCssTransformOptions},
......@@ -323,6 +325,7 @@ pub async fn get_client_module_options_context(
let source_maps = *next_config.client_source_maps(mode).await?;
let module_options_context = ModuleOptionsContext {
ecmascript: EcmascriptOptionsContext {
esm_url_rewrite_behavior: Some(UrlRewriteBehavior::Relative),
enable_typeof_window_inlining: Some(TypeofWindow::Object),
source_maps,
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
......@@ -333,6 +336,7 @@ pub async fn get_client_module_options_context(
module_css_condition: Some(module_styles_rule_condition()),
..Default::default()
},
static_url_tag: Some(rcstr!("client")),
environment: Some(env),
execution_context: Some(execution_context),
tree_shaking_mode: tree_shaking_mode_for_user_code,
......@@ -468,7 +472,7 @@ pub async fn get_client_chunking_context(
next_mode.runtime_type(),
)
.chunk_base_path(Some(asset_prefix.clone()))
.chunk_suffix(ChunkSuffix::FromScriptSrc.resolved_cell())
.asset_suffix(AssetSuffix::Inferred.resolved_cell())
.minify_type(if *minify.await? {
MinifyType::Minify {
mangle: (!*no_mangling.await?).then_some(MangleType::OptimalSize),
......
......@@ -1766,7 +1766,7 @@ impl NextConfig {
/// Returns the suffix to use for chunk loading.
#[turbo_tasks::function]
pub async fn chunk_suffix_path(self: Vc<Self>) -> Result<Vc<Option<RcStr>>> {
pub async fn asset_suffix_path(self: Vc<Self>) -> Result<Vc<Option<RcStr>>> {
let this = self.await?;
match &this.deployment_id {
......
......@@ -6,8 +6,8 @@ use turbo_tasks_fs::FileSystemPath;
use turbopack_browser::BrowserChunkingContext;
use turbopack_core::{
chunk::{
ChunkingConfig, ChunkingContext, MangleType, MinifyType, SourceMapsType, UnusedReferences,
chunk_id_strategy::ModuleIdStrategy,
AssetSuffix, ChunkingConfig, ChunkingContext, MangleType, MinifyType, SourceMapsType,
UnusedReferences, UrlBehavior, chunk_id_strategy::ModuleIdStrategy,
},
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment, NodeJsVersion},
......@@ -324,6 +324,12 @@ pub async fn get_edge_chunking_context(
.client_roots_override(rcstr!("client"), client_root.clone())
.asset_root_path_override(rcstr!("client"), client_root.join("static/media")?)
.asset_base_path_override(rcstr!("client"), asset_prefix)
.url_behavior_override(
rcstr!("client"),
UrlBehavior {
suffix: AssetSuffix::FromGlobal(rcstr!("NEXT_CLIENT_ASSET_SUFFIX")),
},
)
// Since one can't read files in edge directly, any asset need to be fetched
// instead. This special blob url is handled by the custom fetch
// implementation in the edge sandbox. It will respond with the
......
......@@ -171,8 +171,8 @@ async fn build_manifest(
let runtime_server_deployment_id_available =
*next_config.runtime_server_deployment_id_available().await?;
let suffix_path = if !runtime_server_deployment_id_available {
let chunk_suffix_path = next_config.chunk_suffix_path().owned().await?;
chunk_suffix_path.unwrap_or_default()
let asset_suffix_path = next_config.asset_suffix_path().owned().await?;
asset_suffix_path.unwrap_or_default()
} else {
rcstr!("")
};
......
......@@ -15,8 +15,8 @@ use turbopack::{
};
use turbopack_core::{
chunk::{
ChunkingConfig, MangleType, MinifyType, SourceMapSourceType, SourceMapsType,
UnusedReferences, chunk_id_strategy::ModuleIdStrategy,
AssetSuffix, ChunkingConfig, MangleType, MinifyType, SourceMapSourceType, SourceMapsType,
UnusedReferences, UrlBehavior, chunk_id_strategy::ModuleIdStrategy,
},
compile_time_defines,
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReferences},
......@@ -632,20 +632,21 @@ pub async fn get_server_module_options_context(
foreign_next_server_rules.extend(internal_custom_rules);
let url_rewrite_behavior = Some(
let (url_rewrite_behavior, static_url_tag) = {
//https://github.com/vercel/next.js/blob/bbb730e5ef10115ed76434f250379f6f53efe998/packages/next/src/build/webpack-config.ts#L1384
if let ServerContextType::PagesApi { .. } = ty {
UrlRewriteBehavior::Full
(Some(UrlRewriteBehavior::Full), None)
} else {
UrlRewriteBehavior::Relative
},
);
(Some(UrlRewriteBehavior::Relative), Some(rcstr!("client")))
}
};
let module_options_context = ModuleOptionsContext {
ecmascript: EcmascriptOptionsContext {
esm_url_rewrite_behavior: url_rewrite_behavior,
..module_options_context.ecmascript
},
static_url_tag,
..module_options_context
};
......@@ -704,6 +705,15 @@ pub async fn get_server_module_options_context(
);
next_server_rules.extend(source_transform_rules);
let module_options_context = ModuleOptionsContext {
ecmascript: EcmascriptOptionsContext {
esm_url_rewrite_behavior: Some(UrlRewriteBehavior::Relative),
..module_options_context.ecmascript
},
static_url_tag: Some(rcstr!("client")),
..module_options_context
};
let foreign_code_module_options_context = ModuleOptionsContext {
module_rules: foreign_next_server_rules.clone(),
enable_webpack_loaders: foreign_enable_webpack_loaders,
......@@ -777,6 +787,15 @@ pub async fn get_server_module_options_context(
next_server_rules.extend(source_transform_rules);
let module_options_context = ModuleOptionsContext {
ecmascript: EcmascriptOptionsContext {
esm_url_rewrite_behavior: Some(UrlRewriteBehavior::Relative),
..module_options_context.ecmascript
},
static_url_tag: Some(rcstr!("client")),
..module_options_context
};
let foreign_code_module_options_context = ModuleOptionsContext {
module_rules: foreign_next_server_rules.clone(),
enable_webpack_loaders: foreign_enable_webpack_loaders,
......@@ -1044,6 +1063,12 @@ pub async fn get_server_chunking_context_with_client_assets(
next_mode.runtime_type(),
)
.asset_prefix(Some(asset_prefix))
.url_behavior_override(
rcstr!("client"),
UrlBehavior {
suffix: AssetSuffix::FromGlobal(rcstr!("NEXT_CLIENT_ASSET_SUFFIX")),
},
)
.minify_type(if *minify.await? {
MinifyType::Minify {
// React needs deterministic function names to work correctly.
......@@ -1129,6 +1154,12 @@ pub async fn get_server_chunking_context(
.client_roots_override(rcstr!("client"), client_root.clone())
.asset_root_path_override(rcstr!("client"), client_root.join("static/media")?)
.asset_prefix_override(rcstr!("client"), asset_prefix)
.url_behavior_override(
rcstr!("client"),
UrlBehavior {
suffix: AssetSuffix::FromGlobal(rcstr!("NEXT_CLIENT_ASSET_SUFFIX")),
},
)
.minify_type(if *minify.await? {
MinifyType::Minify {
mangle: (!*no_mangling.await?).then_some(MangleType::OptimalSize),
......
......@@ -407,7 +407,7 @@ export interface NapiNextTurbopackCallbacksJsObject {
opts: TurbopackInternalErrorOpts
) => never
}
/** Arguments for [`NapiNextTurbopackCallbacks::throw_turbopack_internal_error`]. */
/** Arguments for `NapiNextTurbopackCallbacks::throw_turbopack_internal_error`. */
export interface TurbopackInternalErrorOpts {
message: string
anonymizedLocation?: string
......
import { getDeploymentId } from '../shared/lib/deployment-id'
;(globalThis as any).NEXT_DEPLOYMENT_ID = getDeploymentId()
const deploymentId = getDeploymentId()
;(globalThis as any).NEXT_DEPLOYMENT_ID = deploymentId
......@@ -343,8 +343,14 @@ export async function exportPages(
nextConfig,
options,
renderResumeDataCachesByPage = {},
deploymentId,
} = input
// Set the global asset suffix for Turbopack compiled code to use during prerendering
;(globalThis as any).NEXT_CLIENT_ASSET_SUFFIX = deploymentId
? `?dpl=${deploymentId}`
: ''
installGlobalBehaviors(nextConfig)
if (nextConfig.enablePrerenderSourceMaps) {
......
......@@ -462,6 +462,9 @@ export default abstract class Server<
)
}
this.deploymentId = process.env.NEXT_DEPLOYMENT_ID
;(globalThis as any).NEXT_CLIENT_ASSET_SUFFIX = this.deploymentId
? `?dpl=${this.deploymentId}`
: ''
} else {
let id = this.nextConfig.experimental.useSkewCookie
? ''
......@@ -469,6 +472,7 @@ export default abstract class Server<
this.deploymentId = id
process.env.NEXT_DEPLOYMENT_ID = id
;(globalThis as any).NEXT_CLIENT_ASSET_SUFFIX = id ? `?dpl=${id}` : ''
}
this.hostname = hostname
......
......@@ -8,19 +8,6 @@ function defaultLoader({
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (
src.startsWith('/') &&
src.includes('?') &&
config.localPatterns?.length === 1 &&
config.localPatterns[0].pathname === '**' &&
config.localPatterns[0].search === ''
) {
throw new Error(
`Image with src "${src}" is using a query string which is not configured in images.localPatterns.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
......@@ -37,7 +24,35 @@ function defaultLoader({
)}`
)
}
}
// Extract dpl parameter early so validation uses the clean URL
let deploymentId = getDeploymentId()
if (src.startsWith('/')) {
const srcUrl = new URL(src, 'http://n')
const srcDpl = srcUrl.searchParams.get('dpl')
if (srcDpl) {
deploymentId = srcDpl
// Remove the dpl parameter from the src URL to avoid duplication
srcUrl.searchParams.delete('dpl')
src = srcUrl.href.slice('http://n'.length)
}
}
if (
src.startsWith('/') &&
src.includes('?') &&
config.localPatterns?.length === 1 &&
config.localPatterns[0].pathname === '**' &&
config.localPatterns[0].search === ''
) {
throw new Error(
`Image with src "${src}" is using a query string which is not configured in images.localPatterns.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
if (process.env.NODE_ENV !== 'production') {
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
......@@ -95,7 +110,6 @@ function defaultLoader({
const q = findClosestQuality(quality, config)
let deploymentId = getDeploymentId()
return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${q}${
src.startsWith('/') && deploymentId ? `&dpl=${deploymentId}` : ''
}`
......
import imported from '../../public/test.png'
const url = new URL('../../public/test.png', import.meta.url).toString()
export function GET() {
return Response.json({ imported, url })
}
'use client'
import imported from '../../public/test.png'
const url = new URL('../../public/test.png', import.meta.url).toString()
export default function Page() {
return (
<main>
<p id="imported-src">{imported.src}</p>
<p id="new-url">{url}</p>
</main>
)
}
import { headers } from 'next/headers'
export default async function Layout({ children }) {
// Use headers() to opt into dynamic rendering
await headers()
return children
}
'use client'
import imported from '../../public/test.png'
const url = new URL('../../public/test.png', import.meta.url).toString()
export default function Page() {
return (
<main>
<p id="imported-src">{imported.src}</p>
<p id="new-url">{url}</p>
</main>
)
}
import { headers } from 'next/headers'
import imported from '../../public/test.png'
const url = new URL('../../public/test.png', import.meta.url).toString()
export default async function Page() {
// Use headers() to opt into dynamic rendering
await headers()
return (
<main>
<p id="imported-src">{imported.src}</p>
<p id="new-url">{url}</p>
</main>
)
}
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import imported from '../public/test.png'
const url = new URL('../public/test.png', import.meta.url).toString()
export default function Page() {
return (
<main>
<p id="imported-src">{imported.src}</p>
<p id="new-url">{url}</p>
</main>
)
}
/** @type {import('next').NextConfig} */
module.exports = {
deploymentId: 'test-deployment-id',
}
import { nextTestSetup } from 'e2e-utils'
// Skip for webpack - dpl suffix in asset URLs is only implemented for Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'URL asset references with deploymentId',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
const deploymentId = 'test-deployment-id'
describe('import src attribute', () => {
it('should include dpl query in RSC page', async () => {
const $ = await next.render$('/')
const src = $('#imported-src').text()
expect(src).toContain('dpl=' + deploymentId)
})
it('should include dpl query in client page', async () => {
const $ = await next.render$('/client')
const src = $('#imported-src').text()
expect(src).toContain('dpl=' + deploymentId)
})
it('should include dpl query in client page (after hydration)', async () => {
const browser = await next.browser('/client')
const url = await browser.elementByCss('#imported-src').text()
expect(url).toContain('dpl=' + deploymentId)
})
})
describe('new URL() pattern', () => {
it('should include dpl query in RSC page', async () => {
const $ = await next.render$('/')
const url = $('#new-url').text()
expect(url).toContain('dpl=' + deploymentId)
})
it('should include dpl query in client page', async () => {
const $ = await next.render$('/client')
const url = $('#new-url').text()
expect(url).toContain('dpl=' + deploymentId)
})
it('should include dpl query in client page (after hydration)', async () => {
const browser = await next.browser('/client')
const url = await browser.elementByCss('#new-url').text()
expect(url).toContain('dpl=' + deploymentId)
})
})
describe('dynamic RSC page (headers)', () => {
it('should include dpl query in dynamic RSC page', async () => {
const $ = await next.render$('/dynamic')
const src = $('#imported-src').text()
expect(src).toContain('dpl=' + deploymentId)
})
it('should include dpl query in new URL pattern', async () => {
const $ = await next.render$('/dynamic')
const url = $('#new-url').text()
expect(url).toContain('dpl=' + deploymentId)
})
})
describe('dynamic client page (headers in layout)', () => {
it('should include dpl query in dynamic client page', async () => {
const $ = await next.render$('/dynamic-client')
const src = $('#imported-src').text()
expect(src).toContain('dpl=' + deploymentId)
})
it('should include dpl query in new URL pattern', async () => {
const $ = await next.render$('/dynamic-client')
const url = $('#new-url').text()
expect(url).toContain('dpl=' + deploymentId)
})
it('should include dpl query after hydration', async () => {
const browser = await next.browser('/dynamic-client')
const url = await browser.elementByCss('#imported-src').text()
expect(url).toContain('dpl=' + deploymentId)
})
})
describe('API route', () => {
it('should return import src with dpl query', async () => {
const data = await next
.fetch('/api')
.then((res) => res.ok && res.json())
expect(data.imported.src).toContain('dpl=' + deploymentId)
})
it('should return new URL with dpl query', async () => {
const data = await next
.fetch('/api')
.then((res) => res.ok && res.json())
expect(data.url).not.toContain('dpl=')
})
})
}
)
......@@ -11,9 +11,10 @@ use turbo_tasks_hash::{DeterministicHash, hash_xxh3_hash64};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{
Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule, ChunkingConfig,
ChunkingConfigs, ChunkingContext, EntryChunkGroupResult, EvaluatableAsset,
AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule,
ChunkingConfig, ChunkingConfigs, ChunkingContext, EntryChunkGroupResult, EvaluatableAsset,
EvaluatableAssets, MinifyType, SourceMapSourceType, SourceMapsType, UnusedReferences,
UrlBehavior,
availability_info::AvailabilityInfo,
chunk_group::{MakeChunkGroupResult, make_chunk_group},
chunk_id_strategy::ModuleIdStrategy,
......@@ -34,7 +35,7 @@ use turbopack_ecmascript::{
chunk::EcmascriptChunk,
manifest::{chunk_asset::ManifestAsyncModule, loader_item::ManifestLoaderChunkItem},
};
use turbopack_ecmascript_runtime::{ChunkSuffix, RuntimeType};
use turbopack_ecmascript_runtime::RuntimeType;
use crate::ecmascript::{
chunk::EcmascriptBrowserChunk,
......@@ -132,8 +133,8 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn chunk_suffix(mut self, chunk_suffix: ResolvedVc<ChunkSuffix>) -> Self {
self.chunking_context.chunk_suffix = Some(chunk_suffix);
pub fn asset_suffix(mut self, asset_suffix: ResolvedVc<AssetSuffix>) -> Self {
self.chunking_context.asset_suffix = Some(asset_suffix);
self
}
......@@ -206,6 +207,16 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn url_behavior_override(mut self, tag: RcStr, behavior: UrlBehavior) -> Self {
self.chunking_context.url_behaviors.insert(tag, behavior);
self
}
pub fn default_url_behavior(mut self, behavior: UrlBehavior) -> Self {
self.chunking_context.default_url_behavior = Some(behavior);
self
}
pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self
where
T: Upcast<Box<dyn ChunkType>>,
......@@ -261,7 +272,7 @@ pub struct BrowserChunkingContext {
chunk_base_path: Option<RcStr>,
/// Suffix that will be appended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
chunk_suffix: Option<ResolvedVc<ChunkSuffix>>,
asset_suffix: Option<ResolvedVc<AssetSuffix>>,
/// URL prefix that will be prepended to all static asset URLs when loading
/// them.
asset_base_path: Option<RcStr>,
......@@ -269,6 +280,11 @@ pub struct BrowserChunkingContext {
/// them.
#[bincode(with = "turbo_bincode::indexmap")]
asset_base_paths: FxIndexMap<RcStr, RcStr>,
/// URL behavior overrides for different tags.
#[bincode(with = "turbo_bincode::indexmap")]
url_behaviors: FxIndexMap<RcStr, UrlBehavior>,
/// Default URL behavior when no tag-specific override is found.
default_url_behavior: Option<UrlBehavior>,
/// Enable HMR for this chunking
enable_hot_module_replacement: bool,
/// Enable tracing for this chunking
......@@ -331,9 +347,11 @@ impl BrowserChunkingContext {
asset_root_path,
asset_root_paths: Default::default(),
chunk_base_path: None,
chunk_suffix: None,
asset_suffix: None,
asset_base_path: None,
asset_base_paths: Default::default(),
url_behaviors: Default::default(),
default_url_behavior: None,
enable_hot_module_replacement: false,
enable_tracing: false,
enable_nested_async_availability: false,
......@@ -435,11 +453,11 @@ impl BrowserChunkingContext {
/// Returns the asset suffix path.
#[turbo_tasks::function]
pub fn chunk_suffix(&self) -> Vc<ChunkSuffix> {
if let Some(chunk_suffix) = self.chunk_suffix {
*chunk_suffix
pub fn asset_suffix(&self) -> Vc<AssetSuffix> {
if let Some(asset_suffix) = self.asset_suffix {
*asset_suffix
} else {
ChunkSuffix::None.cell()
AssetSuffix::None.cell()
}
}
......@@ -626,6 +644,18 @@ impl ChunkingContext for BrowserChunkingContext {
Ok(asset_root_path.join(&asset_path)?.cell())
}
#[turbo_tasks::function]
fn url_behavior(&self, tag: Option<RcStr>) -> Vc<UrlBehavior> {
tag.as_ref()
.and_then(|tag| self.url_behaviors.get(tag))
.cloned()
.or_else(|| self.default_url_behavior.clone())
.unwrap_or(UrlBehavior {
suffix: AssetSuffix::Inferred,
})
.cell()
}
#[turbo_tasks::function]
fn is_hot_module_replacement_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_hot_module_replacement)
......
......@@ -173,7 +173,7 @@ impl EcmascriptBrowserEvaluateChunk {
let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code(
environment,
this.chunking_context.chunk_base_path(),
this.chunking_context.chunk_suffix(),
this.chunking_context.asset_suffix(),
runtime_type,
output_root_to_root_path,
source_maps,
......
......@@ -10,4 +10,3 @@ pub mod react_refresh;
pub use chunking_context::{
BrowserChunkingContext, BrowserChunkingContextBuilder, ContentHashing, CurrentChunkMethod,
};
pub use turbopack_ecmascript_runtime::ChunkSuffix;
......@@ -78,6 +78,29 @@ pub enum SourceMapsType {
None,
}
/// Suffix to append to asset URLs.
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone)]
pub enum AssetSuffix {
/// No suffix.
None,
/// A constant suffix to append to URLs.
Constant(RcStr),
/// Infer the suffix at runtime from the script src attribute.
/// Only valid in browser runtime for chunk loading, not for static asset URL generation.
Inferred,
/// Read the suffix from a global variable at runtime.
/// Used for server-side rendering where the suffix is set via `globalThis.{global_name}`.
FromGlobal(RcStr),
}
/// URL behavior configuration for static assets.
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone)]
pub struct UrlBehavior {
pub suffix: AssetSuffix,
}
#[derive(
Debug,
TaskInput,
......@@ -330,6 +353,16 @@ pub trait ChunkingContext {
tag: Option<RcStr>,
) -> Vc<FileSystemPath>;
/// Returns the URL behavior for a given tag.
/// This determines how asset URLs are suffixed (e.g., for deployment IDs).
#[turbo_tasks::function]
fn url_behavior(self: Vc<Self>, _tag: Option<RcStr>) -> Vc<UrlBehavior> {
UrlBehavior {
suffix: AssetSuffix::Inferred,
}
.cell()
}
#[turbo_tasks::function]
fn is_hot_module_replacement_enabled(self: Vc<Self>) -> Vc<bool> {
Vc::cell(false)
......
......@@ -27,9 +27,9 @@ pub use crate::chunk::{
ChunkItemOrBatchWithAsyncModuleInfo, batch_info,
},
chunking_context::{
ChunkGroupResult, ChunkGroupType, ChunkingConfig, ChunkingConfigs, ChunkingContext,
ChunkingContextExt, EntryChunkGroupResult, MangleType, MinifyType, SourceMapSourceType,
SourceMapsType, UnusedReferences,
AssetSuffix, ChunkGroupResult, ChunkGroupType, ChunkingConfig, ChunkingConfigs,
ChunkingContext, ChunkingContextExt, EntryChunkGroupResult, MangleType, MinifyType,
SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior,
},
data::{ChunkData, ChunkDataOption, ChunksData},
evaluate::{EvaluatableAsset, EvaluatableAssetExt, EvaluatableAssets},
......
......@@ -12,7 +12,7 @@
/// <reference path="../../../shared/runtime-utils.ts" />
// Used in WebWorkers to tell the runtime about the chunk suffix
declare var TURBOPACK_CHUNK_SUFFIX: string
declare var TURBOPACK_ASSET_SUFFIX: string
// Used in WebWorkers to tell the runtime about the current chunk url since it
// can't be detected via `document.currentScript`. Note it's stored in reversed
// order to use `push` and `pop`
......@@ -20,7 +20,7 @@ declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined
// Injected by rust code
declare var CHUNK_BASE_PATH: string
declare var CHUNK_SUFFIX: string
declare var ASSET_SUFFIX: string
interface TurbopackBrowserBaseContext<M> extends TurbopackBaseContext<M> {
R: ResolvePathFromModule
......@@ -313,6 +313,18 @@ function resolveAbsolutePath(modulePath?: string): string {
}
browserContextPrototype.P = resolveAbsolutePath
/**
* Exports a URL with the static suffix appended.
*/
function exportUrl(
this: TurbopackBrowserBaseContext<Module>,
url: string,
id: ModuleId | undefined
) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)
}
browserContextPrototype.q = exportUrl
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -330,7 +342,7 @@ function getWorkerURL(
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: (globalThis as any).NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk) => getChunkRelativeUrl(chunk)),
}
......@@ -361,7 +373,7 @@ function getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {
return `${CHUNK_BASE_PATH}${chunkPath
.split('/')
.map((p) => encodeURIComponent(p))
.join('/')}${CHUNK_SUFFIX}` as ChunkUrl
.join('/')}${ASSET_SUFFIX}` as ChunkUrl
}
/**
......
......@@ -3,7 +3,7 @@
*/
interface WorkerBootstrapConfig {
// TURBOPACK_CHUNK_SUFFIX
// TURBOPACK_ASSET_SUFFIX
S?: string
// NEXT_DEPLOYMENT_ID
N?: string
......@@ -42,7 +42,7 @@ interface WorkerBootstrapConfig {
// types and ensure that the next chunk URLs are same-origin.
const config: WorkerBootstrapConfig = JSON.parse(paramsString)
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''
const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : ''
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
......@@ -55,7 +55,7 @@ interface WorkerBootstrapConfig {
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_ASSET_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID,
})
......
......@@ -111,7 +111,7 @@ let DEV_BACKEND: DevRuntimeBackend
function _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {
code += `\n\n//# sourceURL=${encodeURI(
location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX
location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX
)}`
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(
......
......@@ -9,10 +9,10 @@
/// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (
(self.TURBOPACK_CHUNK_SUFFIX ??
(self.TURBOPACK_ASSET_SUFFIX ??
document?.currentScript
?.getAttribute?.('src')
?.replace(/^(.*(?=\?)|^.*$)/, '')) ||
......
......@@ -27,6 +27,7 @@ interface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
q: ExportUrl
}
const nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext
......@@ -63,6 +64,18 @@ function resolvePathFromModule(
}
nodeContextPrototype.R = resolvePathFromModule
/**
* Exports a URL value. No suffix is added in Node.js runtime.
*/
function exportUrl(
this: TurbopackBaseContext<Module>,
urlValue: string,
id: ModuleId | undefined
) {
exportValue.call(this, urlValue, id)
}
nodeContextPrototype.q = exportUrl
function loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {
if (typeof chunkData === 'string') {
loadRuntimeChunkPath(sourcePath, chunkData)
......
......@@ -46,6 +46,7 @@ type EsmExport = (
id: ModuleId | undefined
) => void
type ExportValue = (value: any, id: ModuleId | undefined) => void
type ExportUrl = (url: string, id: ModuleId | undefined) => void
type ExportNamespace = (namespace: any, id: ModuleId | undefined) => void
type DynamicExport = (
object: Record<string, any>,
......@@ -127,6 +128,7 @@ interface TurbopackBaseContext<M> {
s: EsmExport
j: DynamicExport
v: ExportValue
q: ExportUrl
n: ExportNamespace
m: Module
c: ModuleCache<M>
......
......@@ -5,22 +5,21 @@ use indoc::writedoc;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{
chunk::AssetSuffix,
code_builder::{Code, CodeBuilder},
context::AssetContext,
environment::{ChunkLoading, Environment},
};
use turbopack_ecmascript::utils::StringifyJs;
use crate::{
ChunkSuffix, RuntimeType, asset_context::get_runtime_asset_context, embed_js::embed_static_code,
};
use crate::{RuntimeType, asset_context::get_runtime_asset_context, embed_js::embed_static_code};
/// Returns the code for the ECMAScript runtime.
#[turbo_tasks::function]
pub async fn get_browser_runtime_code(
environment: ResolvedVc<Environment>,
chunk_base_path: Vc<Option<RcStr>>,
chunk_suffix: Vc<ChunkSuffix>,
asset_suffix: Vc<AssetSuffix>,
runtime_type: RuntimeType,
output_root_to_root_path: RcStr,
generate_source_map: bool,
......@@ -82,7 +81,7 @@ pub async fn get_browser_runtime_code(
let relative_root_path = output_root_to_root_path;
let chunk_base_path = chunk_base_path.await?;
let chunk_base_path = chunk_base_path.as_ref().map_or_else(|| "", |f| f.as_str());
let chunk_suffix = chunk_suffix.await?;
let asset_suffix = asset_suffix.await?;
writedoc!(
code,
......@@ -101,35 +100,44 @@ pub async fn get_browser_runtime_code(
StringifyJs(chunk_base_path),
)?;
match &*chunk_suffix {
ChunkSuffix::None => {
match &*asset_suffix {
AssetSuffix::None => {
writedoc!(
code,
r#"
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
"#
)?;
}
ChunkSuffix::Constant(suffix) => {
AssetSuffix::Constant(suffix) => {
writedoc!(
code,
r#"
const CHUNK_SUFFIX = {};
const ASSET_SUFFIX = {};
"#,
StringifyJs(suffix.as_str())
)?;
}
ChunkSuffix::FromScriptSrc => {
AssetSuffix::Inferred => {
if chunk_loading == &ChunkLoading::Edge {
panic!("ChunkSuffix::FromScriptSrc is not supported in Edge runtimes");
panic!("AssetSuffix::Inferred is not supported in Edge runtimes");
}
writedoc!(
code,
r#"
const CHUNK_SUFFIX = getChunkSuffixFromScriptSrc();
const ASSET_SUFFIX = getAssetSuffixFromScriptSrc();
"#
)?;
}
AssetSuffix::FromGlobal(global_name) => {
writedoc!(
code,
r#"
const ASSET_SUFFIX = globalThis[{}] || "";
"#,
StringifyJs(global_name)
)?;
}
}
code.push_code(&*shared_runtime_utils_code.await?);
......
use turbo_rcstr::RcStr;
#[turbo_tasks::value(shared)]
pub enum ChunkSuffix {
/// No suffix.
None,
/// A constant suffix to append to chunk URLs.
Constant(RcStr),
/// Use the query string of the `src` attribute of the current script tag as a suffix for chunk
/// loading.
FromScriptSrc,
}
......@@ -3,7 +3,6 @@
pub(crate) mod asset_context;
pub(crate) mod browser_runtime;
pub(crate) mod chunk_suffix;
#[cfg(feature = "test")]
pub(crate) mod dummy_runtime;
pub(crate) mod embed_js;
......@@ -11,7 +10,6 @@ pub(crate) mod nodejs_runtime;
pub(crate) mod runtime_type;
pub use browser_runtime::{get_browser_runtime_code, get_worker_runtime_code};
pub use chunk_suffix::ChunkSuffix;
#[cfg(feature = "test")]
pub use dummy_runtime::get_dummy_runtime_code;
pub use embed_js::{embed_file, embed_file_path, embed_fs};
......
......@@ -72,6 +72,7 @@ pub const TURBOPACK_MODULE_CONTEXT: &TurbopackRuntimeFunctionShortcut = make_sho
pub const TURBOPACK_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("i");
pub const TURBOPACK_ESM: &TurbopackRuntimeFunctionShortcut = make_shortcut!("s");
pub const TURBOPACK_EXPORT_VALUE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("v");
pub const TURBOPACK_EXPORT_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("q");
pub const TURBOPACK_EXPORT_NAMESPACE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("n");
pub const TURBOPACK_CACHE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("c");
pub const TURBOPACK_MODULES: &TurbopackRuntimeFunctionShortcut = make_shortcut!("M");
......@@ -95,11 +96,12 @@ pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("
/// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called
/// from user code (by inserting a replacement into free_var_references)
pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 22] = [
pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 23] = [
("__turbopack_require__", TURBOPACK_REQUIRE),
("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT),
("__turbopack_import__", TURBOPACK_IMPORT),
("__turbopack_export_value__", TURBOPACK_EXPORT_VALUE),
("__turbopack_export_url__", TURBOPACK_EXPORT_URL),
("__turbopack_export_namespace__", TURBOPACK_EXPORT_NAMESPACE),
("__turbopack_cache__", TURBOPACK_CACHE),
("__turbopack_modules__", TURBOPACK_MODULES),
......
......@@ -6,9 +6,9 @@ use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
asset::Asset,
chunk::{
Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule, ChunkingConfig,
ChunkingConfigs, ChunkingContext, EntryChunkGroupResult, EvaluatableAssets, MinifyType,
SourceMapSourceType, SourceMapsType, UnusedReferences,
AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule,
ChunkingConfig, ChunkingConfigs, ChunkingContext, EntryChunkGroupResult, EvaluatableAssets,
MinifyType, SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior,
availability_info::AvailabilityInfo,
chunk_group::{MakeChunkGroupResult, make_chunk_group},
chunk_id_strategy::ModuleIdStrategy,
......@@ -60,6 +60,16 @@ impl NodeJsChunkingContextBuilder {
self
}
pub fn url_behavior_override(mut self, tag: RcStr, behavior: UrlBehavior) -> Self {
self.chunking_context.url_behaviors.insert(tag, behavior);
self
}
pub fn default_url_behavior(mut self, behavior: UrlBehavior) -> Self {
self.chunking_context.default_url_behavior = Some(behavior);
self
}
pub fn minify_type(mut self, minify_type: MinifyType) -> Self {
self.chunking_context.minify_type = minify_type;
self
......@@ -172,6 +182,11 @@ pub struct NodeJsChunkingContext {
/// Static assets requested from this url base
#[bincode(with = "turbo_bincode::indexmap")]
asset_prefixes: FxIndexMap<RcStr, RcStr>,
/// URL behavior overrides for different tags.
#[bincode(with = "turbo_bincode::indexmap")]
url_behaviors: FxIndexMap<RcStr, UrlBehavior>,
/// Default URL behavior when no tag-specific override is found.
default_url_behavior: Option<UrlBehavior>,
/// The environment chunks will be evaluated in.
environment: ResolvedVc<Environment>,
/// The kind of runtime to include in the output.
......@@ -228,6 +243,8 @@ impl NodeJsChunkingContext {
asset_root_paths: Default::default(),
asset_prefix: None,
asset_prefixes: Default::default(),
url_behaviors: Default::default(),
default_url_behavior: None,
enable_file_tracing: false,
enable_nested_async_availability: false,
enable_module_merging: false,
......@@ -448,6 +465,18 @@ impl ChunkingContext for NodeJsChunkingContext {
Ok(asset_root_path.join(&asset_path)?.cell())
}
#[turbo_tasks::function]
fn url_behavior(&self, tag: Option<RcStr>) -> Vc<UrlBehavior> {
tag.as_ref()
.and_then(|tag| self.url_behaviors.get(tag))
.cloned()
.or_else(|| self.default_url_behavior.clone())
.unwrap_or(UrlBehavior {
suffix: AssetSuffix::Inferred,
})
.cell()
}
#[turbo_tasks::function]
async fn chunk_group(
self: ResolvedVc<Self>,
......
......@@ -3,7 +3,7 @@ use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkingContext},
chunk::{AssetSuffix, ChunkItem, ChunkType, ChunkableModule, ChunkingContext},
ident::AssetIdent,
module::{Module, ModuleSideEffects},
module_graph::ModuleGraph,
......@@ -15,7 +15,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable,
EcmascriptChunkType, EcmascriptExports,
},
runtime_functions::TURBOPACK_EXPORT_VALUE,
runtime_functions::{TURBOPACK_EXPORT_URL, TURBOPACK_EXPORT_VALUE},
utils::StringifyJs,
};
......@@ -154,17 +154,45 @@ impl ChunkItem for StaticUrlJsChunkItem {
impl EcmascriptChunkItem for StaticUrlJsChunkItem {
#[turbo_tasks::function]
async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> {
Ok(EcmascriptChunkItemContent {
inner_code: format!(
"{TURBOPACK_EXPORT_VALUE}({path});",
path = StringifyJs(
&self
.chunking_context
.asset_url(self.static_asset.path().owned().await?, self.tag.clone())
.await?
let url = self
.chunking_context
.asset_url(self.static_asset.path().owned().await?, self.tag.clone())
.await?;
let url_behavior = self.chunking_context.url_behavior(self.tag.clone()).await?;
let inner_code = match &url_behavior.suffix {
AssetSuffix::None => {
// No suffix, export as-is
format!(
"{TURBOPACK_EXPORT_VALUE}({path});",
path = StringifyJs(&url)
)
}
AssetSuffix::Constant(suffix) => {
// Append constant suffix
format!(
"{TURBOPACK_EXPORT_VALUE}({path} + {suffix});",
path = StringifyJs(&url),
suffix = StringifyJs(suffix.as_str())
)
}
AssetSuffix::Inferred => {
// The runtime logic will infer the suffix
format!("{TURBOPACK_EXPORT_URL}({path});", path = StringifyJs(&url))
}
AssetSuffix::FromGlobal(global_name) => {
// Read suffix from global at runtime
format!(
"{TURBOPACK_EXPORT_VALUE}({path} + (globalThis[{global}] || ''));",
path = StringifyJs(&url),
global = StringifyJs(global_name)
)
)
.into(),
}
};
Ok(EcmascriptChunkItemContent {
inner_code: inner_code.into(),
..Default::default()
}
.cell())
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="2edabdcd-1a50-190d-01a5-132504146b5c")}catch(e){}}();
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="aaeb9570-a56b-3d14-e7e3-4dfbc2550f68")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -11,7 +11,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -683,6 +683,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -694,7 +700,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
};
......@@ -715,7 +721,7 @@ browserContextPrototype.b = getWorkerURL;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX}`;
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1606,9 +1612,9 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return (self.TURBOPACK_CHUNK_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
let BACKEND;
/**
......@@ -1849,7 +1855,7 @@ let DEV_BACKEND;
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......@@ -1867,5 +1873,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=2edabdcd-1a50-190d-01a5-132504146b5c
//# debugId=aaeb9570-a56b-3d14-e7e3-4dfbc2550f68
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -621,6 +621,12 @@ nodeContextPrototype.c = moduleCache;
return url.pathToFileURL(resolved).href;
}
nodeContextPrototype.R = resolvePathFromModule;
/**
* Exports a URL value. No suffix is added in Node.js runtime.
*/ function exportUrl(urlValue, id) {
exportValue.call(this, urlValue, id);
}
nodeContextPrototype.q = exportUrl;
function loadRuntimeChunk(sourcePath, chunkData) {
if (typeof chunkData === 'string') {
loadRuntimeChunkPath(sourcePath, chunkData);
......
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_import-meta_url_input_3fece31c._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/asset.txt (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/static/asset.a5b1faf2.txt");}),
__turbopack_context__.q("/static/asset.a5b1faf2.txt");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/mod.mjs [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
......
......@@ -23,7 +23,7 @@
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config = JSON.parse(paramsString);
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : '';
const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : '';
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : '';
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
......@@ -35,7 +35,7 @@
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : [];
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_ASSET_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID
});
......
......@@ -5,14 +5,14 @@ module.exports = 'turbopack';
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/static/vercel.242d4ff2.cjs");}),
__turbopack_context__.q("/static/vercel.242d4ff2.cjs");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_2867ca5f._.js", ["output/bf321_tests_snapshot_imports_ignore-comments_input_vercel_cjs_422a38f6._.js","output/ad3e4_tests_snapshot_imports_ignore-comments_input_vercel_cjs_6f11dd5d._.js"], false));
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/static/ignore-worker.481250f3.cjs");}),
__turbopack_context__.q("/static/ignore-worker.481250f3.cjs");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
......
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_CHUNK_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_CHUNK_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_CHUNK_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_ASSET_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_ASSET_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_ASSET_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_imports_static_input_fb142aa8._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/static/input/vercel.svg (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/static/vercel.ede1923f.svg");}),
__turbopack_context__.q("/static/vercel.ede1923f.svg");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/static/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
......
......@@ -621,6 +621,12 @@ nodeContextPrototype.c = moduleCache;
return url.pathToFileURL(resolved).href;
}
nodeContextPrototype.R = resolvePathFromModule;
/**
* Exports a URL value. No suffix is added in Node.js runtime.
*/ function exportUrl(urlValue, id) {
exportValue.call(this, urlValue, id);
}
nodeContextPrototype.q = exportUrl;
function loadRuntimeChunk(sourcePath, chunkData) {
if (typeof chunkData === 'string') {
loadRuntimeChunkPath(sourcePath, chunkData);
......
......@@ -10,7 +10,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -682,6 +682,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -693,7 +699,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
};
......@@ -714,7 +720,7 @@ browserContextPrototype.b = getWorkerURL;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX}`;
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1605,9 +1611,9 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return (self.TURBOPACK_CHUNK_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
let BACKEND;
/**
......@@ -1848,7 +1854,7 @@ let DEV_BACKEND;
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......
......@@ -10,7 +10,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -1180,6 +1180,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath !== null && modulePath !== void 0 ? modulePath : ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -1191,7 +1197,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
var url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
var params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map(function(chunk) {
return getChunkRelativeUrl(chunk);
......@@ -1216,7 +1222,7 @@ browserContextPrototype.b = getWorkerURL;
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map(function(p) {
return encodeURIComponent(p);
}).join('/')}${CHUNK_SUFFIX}`;
}).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1452,11 +1458,11 @@ function _ts_generator(thisArg, body) {
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
var _self_TURBOPACK_CHUNK_SUFFIX;
function getAssetSuffixFromScriptSrc() {
var _self_TURBOPACK_ASSET_SUFFIX;
var _document_currentScript_getAttribute, _document_currentScript_getAttribute1, _document_currentScript, _document;
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return ((_self_TURBOPACK_CHUNK_SUFFIX = self.TURBOPACK_CHUNK_SUFFIX) !== null && _self_TURBOPACK_CHUNK_SUFFIX !== void 0 ? _self_TURBOPACK_CHUNK_SUFFIX : (_document = document) === null || _document === void 0 ? void 0 : (_document_currentScript = _document.currentScript) === null || _document_currentScript === void 0 ? void 0 : (_document_currentScript_getAttribute1 = _document_currentScript.getAttribute) === null || _document_currentScript_getAttribute1 === void 0 ? void 0 : (_document_currentScript_getAttribute = _document_currentScript_getAttribute1.call(_document_currentScript, 'src')) === null || _document_currentScript_getAttribute === void 0 ? void 0 : _document_currentScript_getAttribute.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
// TURBOPACK_ASSET_SUFFIX is set in web workers
return ((_self_TURBOPACK_ASSET_SUFFIX = self.TURBOPACK_ASSET_SUFFIX) !== null && _self_TURBOPACK_ASSET_SUFFIX !== void 0 ? _self_TURBOPACK_ASSET_SUFFIX : (_document = document) === null || _document === void 0 ? void 0 : (_document_currentScript = _document.currentScript) === null || _document_currentScript === void 0 ? void 0 : (_document_currentScript_getAttribute1 = _document_currentScript.getAttribute) === null || _document_currentScript_getAttribute1 === void 0 ? void 0 : (_document_currentScript_getAttribute = _document_currentScript_getAttribute1.call(_document_currentScript, 'src')) === null || _document_currentScript_getAttribute === void 0 ? void 0 : _document_currentScript_getAttribute.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
var BACKEND;
/**
......
......@@ -23,7 +23,7 @@
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config = JSON.parse(paramsString);
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : '';
const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : '';
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : '';
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
......@@ -35,7 +35,7 @@
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : [];
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_ASSET_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID
});
......
......@@ -10,7 +10,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -682,6 +682,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -693,7 +699,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
};
......@@ -714,7 +720,7 @@ browserContextPrototype.b = getWorkerURL;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX}`;
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1605,9 +1611,9 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return (self.TURBOPACK_CHUNK_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
let BACKEND;
/**
......@@ -1848,7 +1854,7 @@ let DEV_BACKEND;
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......
......@@ -10,7 +10,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -682,6 +682,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -693,7 +699,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
};
......@@ -714,7 +720,7 @@ browserContextPrototype.b = getWorkerURL;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX}`;
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1605,9 +1611,9 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return (self.TURBOPACK_CHUNK_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
let BACKEND;
/**
......@@ -1848,7 +1854,7 @@ let DEV_BACKEND;
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_73fc86c5._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/static/worker.60655f93.js");}),
__turbopack_context__.q("/static/worker.60655f93.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_workers_basic_output_2867ca5f._.js", ["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_841f9693.js","output/ba425_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_01a12aa6.js"], false));
......
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_CHUNK_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_CHUNK_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_CHUNK_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_ASSET_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_ASSET_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_ASSET_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
......@@ -23,7 +23,7 @@
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config = JSON.parse(paramsString);
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : '';
const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : '';
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : '';
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
......@@ -35,7 +35,7 @@
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : [];
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_ASSET_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID
});
......
......@@ -10,7 +10,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -682,6 +682,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -693,7 +699,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
};
......@@ -714,7 +720,7 @@ browserContextPrototype.b = getWorkerURL;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX}`;
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1605,9 +1611,9 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return (self.TURBOPACK_CHUNK_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
let BACKEND;
/**
......@@ -1848,7 +1854,7 @@ let DEV_BACKEND;
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......
......@@ -10,7 +10,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
const CHUNK_BASE_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
const CHUNK_SUFFIX = "";
const ASSET_SUFFIX = "";
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -682,6 +682,12 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`;
}
browserContextPrototype.P = resolveAbsolutePath;
/**
* Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) {
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* The entrypoint is a pre-compiled worker runtime file. The params configure
......@@ -693,7 +699,7 @@ browserContextPrototype.P = resolveAbsolutePath;
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const params = {
S: CHUNK_SUFFIX,
S: ASSET_SUFFIX,
N: globalThis.NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
};
......@@ -714,7 +720,7 @@ browserContextPrototype.b = getWorkerURL;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX}`;
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -1605,9 +1611,9 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime-types.d.ts" />
function getChunkSuffixFromScriptSrc() {
// TURBOPACK_CHUNK_SUFFIX is set in web workers
return (self.TURBOPACK_CHUNK_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers
return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || '';
}
let BACKEND;
/**
......@@ -1848,7 +1854,7 @@ let DEV_BACKEND;
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_3845375a._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/static/worker.35b5336b.js");}),
__turbopack_context__.q("/static/worker.35b5336b.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_workers_shared_output_2867ca5f._.js", ["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_e14430d8.js","output/ba425_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_87533493.js"], true));
......
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_CHUNK_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_CHUNK_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_CHUNK_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_ASSET_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_ASSET_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_ASSET_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_ASSET_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
......@@ -16,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable,
EcmascriptChunkType, EcmascriptExports,
},
runtime_functions::TURBOPACK_EXPORT_VALUE,
runtime_functions::TURBOPACK_EXPORT_URL,
utils::StringifyJs,
};
......@@ -159,11 +159,7 @@ impl EcmascriptChunkItem for RawModuleChunkItem {
};
Ok(EcmascriptChunkItemContent {
inner_code: format!(
"{TURBOPACK_EXPORT_VALUE}({path});",
path = StringifyJs(path)
)
.into(),
inner_code: format!("{TURBOPACK_EXPORT_URL}({path});", path = StringifyJs(path)).into(),
..Default::default()
}
.cell())
......
......@@ -12,7 +12,7 @@ use turbopack_core::{
ident::Layer,
resolve::options::{ImportMap, ImportMapping},
};
use turbopack_ecmascript::TreeShakingMode;
use turbopack_ecmascript::{TreeShakingMode, references::esm::UrlRewriteBehavior};
use turbopack_node::execution_context::ExecutionContext;
use turbopack_resolve::resolve_options_context::ResolveOptionsContext;
......@@ -105,6 +105,7 @@ pub async fn node_evaluate_asset_context(
ModuleOptionsContext {
tree_shaking_mode: Some(TreeShakingMode::ReexportsOnly),
ecmascript: EcmascriptOptionsContext {
esm_url_rewrite_behavior: Some(UrlRewriteBehavior::Full),
enable_typescript_transform: Some(
TypescriptTransformOptions::default().resolved_cell(),
),
......
......@@ -236,6 +236,7 @@ impl ModuleOptions {
ref module_css_condition,
..
},
ref static_url_tag,
ref enable_postcss_transform,
ref enable_webpack_loaders,
environment,
......@@ -454,13 +455,13 @@ impl ModuleOptions {
RuleCondition::ResourcePathEndsWith(".woff2".to_string()),
]),
vec![ModuleRuleEffect::ModuleType(ModuleType::StaticUrlJs {
tag: None,
tag: static_url_tag.clone(),
})],
),
ModuleRule::new(
RuleCondition::ReferenceType(ReferenceType::Url(UrlReferenceSubType::Undefined)),
vec![ModuleRuleEffect::ModuleType(ModuleType::StaticUrlJs {
tag: None,
tag: static_url_tag.clone(),
})],
),
ModuleRule::new(
......@@ -468,13 +469,13 @@ impl ModuleOptions {
UrlReferenceSubType::EcmaScriptNewUrl,
)),
vec![ModuleRuleEffect::ModuleType(ModuleType::StaticUrlJs {
tag: None,
tag: static_url_tag.clone(),
})],
),
ModuleRule::new(
RuleCondition::ReferenceType(ReferenceType::Url(UrlReferenceSubType::CssUrl)),
vec![ModuleRuleEffect::ModuleType(ModuleType::StaticUrlCss {
tag: None,
tag: static_url_tag.clone(),
})],
),
];
......
......@@ -202,6 +202,8 @@ pub struct ModuleOptionsContext {
pub side_effect_free_packages: Option<ResolvedVc<Glob>>,
pub tree_shaking_mode: Option<TreeShakingMode>,
pub static_url_tag: Option<RcStr>,
/// Generate (non-emitted) output assets for static assets and externals, to facilitate
/// generating a list of all non-bundled files that will be required at runtime.
pub enable_externals_tracing: Option<ResolvedVc<ExternalsTracingOptions>>,
......
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