Unverified Commit b9f067fb authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Remove worker helpers from the default runtime (#94372)

This PR is looking to reduce the size of the runtime we're shipping. The
goal is to not include worker helpers in the default runtime, if workers
aren't being used / imported.

The `createWorker()` function has been removed from the runtime. It now
exists in `turbopack-ecmascript/js/src/worker/browser/createWorker.ts`
and `turbopack-ecmascript/js/src/worker/node/createWorker.ts`. The
reason behind having them in `turbopack-ecmascript` is that in
`turbopack-ecmascript/src/worker_chunk/module.rs` we can then create a
worker module (see `create_worker_module()`). This is then returned by
`references()` as a `SingleChunkableModuleReference`.

Instead of using `createWorker()` from the runtime we can instead now
import it from that module.

There are a couple of things in this PR that I'd like to flag for
discussion:

1) The location of the JavaScript. Shipping it in `turbopack-ecmascript`
doesn't quite feel natural; however, `turbopack-ecmascript-runtime`
imports `turbopack-ecmascript` so I didn't want to create a circular
dependency by importing `turbopack-ecmascript-runtime` in
`turbopack-ecmascript`.

2) There a couple of things in the runtime that we need inside of
`createWorker()`, they are:

```javascript
TURBOPACK_ASSET_SUFFIX, TURBOPACK_CHUNK_BASE_PATH
```

which are values from the runtime we needed to references

and:

```javascript
function getChunkRelativeUrl(
  chunkPath: ChunkPath | ChunkListPath,
  basePath: string = CHUNK_BASE_PATH
): ChunkUrl
```

which is `TURBOPACK_CHUNK_RELATIVE_URL`.

These currently exist in the runtime. To make them available, I've
placed them in `browserContextPrototype` and `contextPrototype` in the
node version.

We also have a code gen that inserts the values of
`_TURBOPACK_WORKER_FORWARDED_GLOBALS_` and
`_TURBOPACK_WORKER_BASE_PATH_` during the analyzer's pass through free
variables (takes them out of the chunking context).

@lukesandberg curious to hear your thoughts about these!

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
parent 7e375d00
...@@ -11,6 +11,7 @@ use turbopack_core::{ ...@@ -11,6 +11,7 @@ use turbopack_core::{
ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, CrossOrigin, ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, CrossOrigin,
EntryChunkGroupResult, EvaluatableAsset, EvaluatableAssets, MinifyType, EntryChunkGroupResult, EvaluatableAsset, EvaluatableAssets, MinifyType,
SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior, SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior,
WorkerConfigurationOptions,
availability_info::AvailabilityInfo, availability_info::AvailabilityInfo,
chunk_group::{MakeChunkGroupResult, make_chunk_group}, chunk_group::{MakeChunkGroupResult, make_chunk_group},
chunk_id_strategy::ModuleIdStrategy, chunk_id_strategy::ModuleIdStrategy,
...@@ -475,14 +476,6 @@ impl BrowserChunkingContext { ...@@ -475,14 +476,6 @@ impl BrowserChunkingContext {
Vc::cell(self.chunk_base_path.clone()) Vc::cell(self.chunk_base_path.clone())
} }
/// Returns the worker base-path override. When `Some`, takes precedence
/// over `chunk_base_path` for the entrypoint URL and the module chunks
/// loaded inside the worker.
#[turbo_tasks::function]
pub fn worker_asset_prefix(&self) -> Vc<Option<RcStr>> {
Vc::cell(self.worker_asset_prefix.clone())
}
/// Returns the asset suffix path. /// Returns the asset suffix path.
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn asset_suffix(&self) -> Vc<AssetSuffix> { pub fn asset_suffix(&self) -> Vc<AssetSuffix> {
...@@ -1014,15 +1007,19 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -1014,15 +1007,19 @@ impl ChunkingContext for BrowserChunkingContext {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn worker_forwarded_globals(&self) -> Vc<Vec<RcStr>> { fn worker_configuration_options(&self) -> Vc<WorkerConfigurationOptions> {
Vc::cell(self.worker_forwarded_globals.clone()) WorkerConfigurationOptions {
asset_prefix: self.worker_asset_prefix.clone(),
forwarded_globals: self.worker_forwarded_globals.clone(),
}
.cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn worker_entrypoint(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> { async fn worker_entrypoint(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> {
let chunking_context: Vc<Box<dyn ChunkingContext>> = Vc::upcast(self); let chunking_context: Vc<Box<dyn ChunkingContext>> = Vc::upcast(self);
let resolved = chunking_context.to_resolved().await?; let resolved = chunking_context.to_resolved().await?;
let forwarded_globals = chunking_context.worker_forwarded_globals(); let forwarded_globals = Vc::cell(self.await?.worker_forwarded_globals.clone());
let entrypoint = EcmascriptBrowserWorkerEntrypoint::new(*resolved, forwarded_globals); let entrypoint = EcmascriptBrowserWorkerEntrypoint::new(*resolved, forwarded_globals);
Ok(Vc::upcast(entrypoint)) Ok(Vc::upcast(entrypoint))
} }
......
...@@ -186,9 +186,7 @@ impl EcmascriptBrowserEvaluateChunk { ...@@ -186,9 +186,7 @@ impl EcmascriptBrowserEvaluateChunk {
let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code( let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code(
asset_context, asset_context,
this.chunking_context.chunk_base_path(), this.chunking_context.chunk_base_path(),
this.chunking_context.worker_asset_prefix(),
this.chunking_context.asset_suffix(), this.chunking_context.asset_suffix(),
this.chunking_context.worker_forwarded_globals(),
runtime_type, runtime_type,
output_root_to_root_path, output_root_to_root_path,
source_maps, source_maps,
......
...@@ -279,6 +279,19 @@ pub enum SourceMapSourceType { ...@@ -279,6 +279,19 @@ pub enum SourceMapSourceType {
#[turbo_tasks::value(transparent, cell = "keyed")] #[turbo_tasks::value(transparent, cell = "keyed")]
pub struct UnusedReferences(FxHashSet<ResolvedVc<Box<dyn ModuleReference>>>); pub struct UnusedReferences(FxHashSet<ResolvedVc<Box<dyn ModuleReference>>>);
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone, Default)]
pub struct WorkerConfigurationOptions {
/// The worker base-path override. When `Some`, takes precedence over
/// `chunk_base_path` for the worker entrypoint URL and the module chunks
/// loaded inside the worker.
pub asset_prefix: Option<RcStr>,
/// The list of global variable names to forward to workers. These globals
/// are read from `globalThis` at worker creation time and passed to the
/// worker via URL params.
pub forwarded_globals: Vec<RcStr>,
}
/// A context for the chunking that influences the way chunks are created /// A context for the chunking that influences the way chunks are created
#[turbo_tasks::value_trait] #[turbo_tasks::value_trait]
pub trait ChunkingContext { pub trait ChunkingContext {
...@@ -481,12 +494,11 @@ pub trait ChunkingContext { ...@@ -481,12 +494,11 @@ pub trait ChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>; fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>;
/// Returns the list of global variable names to forward to workers. /// Returns the worker-related configuration: the base-path override and the
/// These globals are read from globalThis at worker creation time and passed /// list of globals to forward to workers.
/// to the worker via URL params.
#[turbo_tasks::function] #[turbo_tasks::function]
fn worker_forwarded_globals(self: Vc<Self>) -> Vc<Vec<RcStr>> { fn worker_configuration_options(self: Vc<Self>) -> Vc<WorkerConfigurationOptions> {
Vc::cell(vec![]) WorkerConfigurationOptions::default().cell()
} }
/// Returns the worker entrypoint for this chunking context. /// Returns the worker entrypoint for this chunking context.
......
...@@ -30,6 +30,7 @@ pub use crate::chunk::{ ...@@ -30,6 +30,7 @@ pub use crate::chunk::{
AssetSuffix, ChunkGroupResult, ChunkGroupType, ChunkingConfig, ChunkingConfigs, AssetSuffix, ChunkGroupResult, ChunkGroupType, ChunkingConfig, ChunkingConfigs,
ChunkingContext, ChunkingContextExt, EntryChunkGroupResult, MangleType, MinifyType, ChunkingContext, ChunkingContextExt, EntryChunkGroupResult, MangleType, MinifyType,
SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior, SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior,
WorkerConfigurationOptions,
}, },
data::{ChunkData, ChunkDataOption, ChunksData}, data::{ChunkData, ChunkDataOption, ChunksData},
evaluate::{EvaluatableAsset, EvaluatableAssetExt, EvaluatableAssets}, evaluate::{EvaluatableAsset, EvaluatableAssetExt, EvaluatableAssets},
......
...@@ -20,21 +20,8 @@ declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined ...@@ -20,21 +20,8 @@ declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined
// Injected by rust code // Injected by rust code
declare var CHUNK_BASE_PATH: string declare var CHUNK_BASE_PATH: string
/**
* Custom base path for Web Worker URLs (the entrypoint and the module
* chunks loaded inside the worker). Mirrors webpack's
* `output.workerPublicPath`. `null` means "use CHUNK_BASE_PATH"; an empty
* string is a literal empty prefix (not a fallback).
*
* The worker's bootstrap rejects module chunks whose origin differs from
* the worker's own origin, so the override has to apply to both — using
* `WORKER_BASE_PATH` only for the entrypoint would leave the worker unable
* to load any chunks when `CHUNK_BASE_PATH` is on a different origin.
*/
declare var WORKER_BASE_PATH: string | null
declare var ASSET_SUFFIX: string declare var ASSET_SUFFIX: string
declare var CROSS_ORIGIN: 'anonymous' | 'use-credentials' | null declare var CROSS_ORIGIN: 'anonymous' | 'use-credentials' | null
declare var WORKER_FORWARDED_GLOBALS: string[]
interface TurbopackBrowserBaseContext<M> extends TurbopackBaseContext<M> { interface TurbopackBrowserBaseContext<M> extends TurbopackBaseContext<M> {
R: ResolvePathFromModule R: ResolvePathFromModule
...@@ -315,62 +302,6 @@ function exportUrl( ...@@ -315,62 +302,6 @@ function exportUrl(
} }
browserContextPrototype.q = exportUrl browserContextPrototype.q = exportUrl
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/
function createWorker(
WorkerConstructor: { new (url: URL, options?: object): Worker },
entrypoint: ChunkPath,
moduleChunks: ChunkPath[],
workerOptions?: object
): Worker {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker'
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH
const chunkUrls = moduleChunks
.map((chunk) => getChunkRelativeUrl(chunk, workerBasePath))
.reverse()
const params: unknown[] = [chunkUrls, ASSET_SUFFIX]
for (const globalName of WORKER_FORWARDED_GLOBALS) {
params.push((globalThis as Record<string, unknown>)[globalName])
}
const url = new URL(
getChunkRelativeUrl(entrypoint, workerBasePath),
location.origin
)
const paramsJson = JSON.stringify(params)
if (isSharedWorker) {
url.searchParams.set('params', paramsJson)
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson)
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions
? { ...workerOptions, type: undefined }
: undefined
return new WorkerConstructor(url, options)
}
browserContextPrototype.b = createWorker
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ */
...@@ -393,6 +324,15 @@ function getChunkRelativeUrl( ...@@ -393,6 +324,15 @@ function getChunkRelativeUrl(
.join('/')}${ASSET_SUFFIX}` as ChunkUrl .join('/')}${ASSET_SUFFIX}` as ChunkUrl
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH as ChunkBasePath
browserContextPrototype.X = ASSET_SUFFIX as AssetSuffix
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl
/** /**
* Return the ChunkPath from a ChunkScript. * Return the ChunkPath from a ChunkScript.
*/ */
......
...@@ -27,7 +27,6 @@ nodeContextPrototype.M = moduleFactories ...@@ -27,7 +27,6 @@ nodeContextPrototype.M = moduleFactories
// Cast moduleCache to ModuleWithDirection for production mode // Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection> nodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection>
nodeContextPrototype.R = resolvePathFromModule nodeContextPrototype.R = resolvePathFromModule
nodeContextPrototype.b = createWorker
nodeContextPrototype.C = clearChunkCache nodeContextPrototype.C = clearChunkCache
function instantiateModule( function instantiateModule(
......
...@@ -36,7 +36,6 @@ nodeDevContextPrototype.q = exportUrl ...@@ -36,7 +36,6 @@ nodeDevContextPrototype.q = exportUrl
nodeDevContextPrototype.M = moduleFactories nodeDevContextPrototype.M = moduleFactories
nodeDevContextPrototype.c = devModuleCache nodeDevContextPrototype.c = devModuleCache
nodeDevContextPrototype.R = resolvePathFromModule nodeDevContextPrototype.R = resolvePathFromModule
nodeDevContextPrototype.b = createWorker
nodeDevContextPrototype.C = clearChunkCache nodeDevContextPrototype.C = clearChunkCache
/** /**
......
...@@ -164,38 +164,6 @@ function loadWebAssemblyModule( ...@@ -164,38 +164,6 @@ function loadWebAssemblyModule(
} }
contextPrototype.u = loadWebAssemblyModule contextPrototype.u = loadWebAssemblyModule
/**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor
* with the appropriate path and options, including forwarded globals.
*
* @param WorkerConstructor The Worker constructor from worker_threads
* @param workerPath Path to the worker entry chunk
* @param workerOptions options to pass to the Worker constructor (optional)
*/
function createWorker(
WorkerConstructor: { new (path: string, options?: object): unknown },
workerPath: string,
workerOptions?: { workerData?: unknown; [key: string]: unknown }
): unknown {
// Build the forwarded globals object
const forwardedGlobals: Record<string, unknown> = {}
for (const name of WORKER_FORWARDED_GLOBALS) {
forwardedGlobals[name] = (globalThis as Record<string, unknown>)[name]
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {}
const options = {
...workerOptions,
workerData: {
...(typeof existingWorkerData === 'object' ? existingWorkerData : {}),
__turbopack_globals__: forwardedGlobals,
},
}
return new WorkerConstructor(workerPath, options)
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/
/** /**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment. * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
......
...@@ -21,6 +21,14 @@ type ChunkScript = CurrentScript & { readonly brand: unique symbol } ...@@ -21,6 +21,14 @@ type ChunkScript = CurrentScript & { readonly brand: unique symbol }
* CHUNK_SUFFIX), e.g. `/_next/static/chunks/21a106126841c540.js?dpl=1123123` * CHUNK_SUFFIX), e.g. `/_next/static/chunks/21a106126841c540.js?dpl=1123123`
*/ */
type ChunkUrl = string & { readonly brand: unique symbol } type ChunkUrl = string & { readonly brand: unique symbol }
/**
* Stores CHUNK_BASE_PATH.
*/
type ChunkBasePath = string & { readonly brand: unique symbol }
/**
* Stores ASSET_SUFFIX.
*/
type AssetSuffix = string & { readonly brand: unique symbol }
/** The dependency specifier when importing externals */ /** The dependency specifier when importing externals */
type DependencySpecifier = string type DependencySpecifier = string
/** This is a string in development and a number in production (both arbitrary, implementation defined) */ /** This is a string in development and a number in production (both arbitrary, implementation defined) */
...@@ -41,6 +49,11 @@ type ChunkData = ...@@ -41,6 +49,11 @@ type ChunkData =
moduleChunks: ChunkPath[] moduleChunks: ChunkPath[]
} }
type GetChunkRelativeURL = (
chunkPath: ChunkPath | ChunkListPath,
basePath?: string
) => ChunkUrl
type CommonJsRequire = (moduleId: ModuleId) => Exports type CommonJsRequire = (moduleId: ModuleId) => Exports
type RuntimeRequire = (request: string) => Exports type RuntimeRequire = (request: string) => Exports
type ModuleContextFactory = (map: ModuleContextMap) => ModuleContext type ModuleContextFactory = (map: ModuleContextMap) => ModuleContext
...@@ -98,11 +111,6 @@ type AsyncModule = ( ...@@ -98,11 +111,6 @@ type AsyncModule = (
type ResolveAbsolutePath = (modulePath?: string) => string type ResolveAbsolutePath = (modulePath?: string) => string
type ResolveFileUrl = (modulePath?: string) => string type ResolveFileUrl = (modulePath?: string) => string
type GetWorkerURL = (
entrypoint: ChunkPath,
moduleChunks: ChunkPath[],
shared: boolean
) => URL
type ExternalRequire = ( type ExternalRequire = (
id: DependencySpecifier, id: DependencySpecifier,
...@@ -146,12 +154,14 @@ interface TurbopackBaseContext<M> { ...@@ -146,12 +154,14 @@ interface TurbopackBaseContext<M> {
M: ModuleFactories M: ModuleFactories
l: LoadChunk l: LoadChunk
L: LoadChunkByUrl L: LoadChunkByUrl
h: GetChunkRelativeURL
w: LoadWebAssembly w: LoadWebAssembly
u: LoadWebAssemblyModule u: LoadWebAssemblyModule
P: ResolveAbsolutePath P: ResolveAbsolutePath
F: ResolveFileUrl F: ResolveFileUrl
U: RelativeURL U: RelativeURL
b: GetWorkerURL b: ChunkBasePath
X: AssetSuffix
x: ExternalRequire x: ExternalRequire
y: ExternalImport y: ExternalImport
z: CommonJsRequire z: CommonJsRequire
......
...@@ -19,9 +19,7 @@ use crate::{RuntimeType, embed_js::embed_static_code}; ...@@ -19,9 +19,7 @@ use crate::{RuntimeType, embed_js::embed_static_code};
pub async fn get_browser_runtime_code( pub async fn get_browser_runtime_code(
asset_context: ResolvedVc<Box<dyn AssetContext>>, asset_context: ResolvedVc<Box<dyn AssetContext>>,
chunk_base_path: Vc<Option<RcStr>>, chunk_base_path: Vc<Option<RcStr>>,
worker_asset_prefix: Vc<Option<RcStr>>,
asset_suffix: Vc<AssetSuffix>, asset_suffix: Vc<AssetSuffix>,
worker_forwarded_globals: Vc<Vec<RcStr>>,
runtime_type: RuntimeType, runtime_type: RuntimeType,
output_root_to_root_path: RcStr, output_root_to_root_path: RcStr,
generate_source_map: bool, generate_source_map: bool,
...@@ -88,14 +86,6 @@ pub async fn get_browser_runtime_code( ...@@ -88,14 +86,6 @@ pub async fn get_browser_runtime_code(
let relative_root_path = output_root_to_root_path; let relative_root_path = output_root_to_root_path;
let chunk_base_path = chunk_base_path.await?; 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_base_path = chunk_base_path.as_ref().map_or_else(|| "", |f| f.as_str());
// `null` (no override) and `Some("")` (empty-string prefix) are distinct
// states, so inject as a JS literal — `null` for None and a quoted string
// for Some — instead of collapsing both to "".
let worker_asset_prefix = worker_asset_prefix.await?;
let worker_asset_prefix_js: String = worker_asset_prefix.as_ref().map_or_else(
|| "null".to_string(),
|f| format!("{}", StringifyJs(f.as_str())),
);
let asset_suffix = asset_suffix.await?; let asset_suffix = asset_suffix.await?;
let chunk_loading_global = chunk_loading_global.await?; let chunk_loading_global = chunk_loading_global.await?;
let cross_origin = *cross_origin.await?; let cross_origin = *cross_origin.await?;
...@@ -119,13 +109,11 @@ pub async fn get_browser_runtime_code( ...@@ -119,13 +109,11 @@ pub async fn get_browser_runtime_code(
}} }}
var CHUNK_BASE_PATH = {}; var CHUNK_BASE_PATH = {};
var WORKER_BASE_PATH = {};
var RELATIVE_ROOT_PATH = {}; var RELATIVE_ROOT_PATH = {};
var RUNTIME_PUBLIC_PATH = {}; var RUNTIME_PUBLIC_PATH = {};
"#, "#,
StringifyJs(&chunk_loading_global), StringifyJs(&chunk_loading_global),
StringifyJs(chunk_base_path), StringifyJs(chunk_base_path),
worker_asset_prefix_js,
StringifyJs(relative_root_path.as_str()), StringifyJs(relative_root_path.as_str()),
StringifyJs(chunk_base_path), StringifyJs(chunk_base_path),
)?; )?;
...@@ -179,16 +167,6 @@ pub async fn get_browser_runtime_code( ...@@ -179,16 +167,6 @@ pub async fn get_browser_runtime_code(
StringifyJs(&cross_origin) StringifyJs(&cross_origin)
)?; )?;
// Output the list of global variable names to forward to workers
let worker_forwarded_globals = worker_forwarded_globals.await?;
writedoc!(
code,
r#"
var WORKER_FORWARDED_GLOBALS = {};
"#,
StringifyJs(&*worker_forwarded_globals)
)?;
code.push_code(&*shared_runtime_utils_code.await?); code.push_code(&*shared_runtime_utils_code.await?);
// Only include the async-module (top-level await) machinery when the app uses it. // Only include the async-module (top-level await) machinery when the app uses it.
if has_async_modules { if has_async_modules {
......
// Embedded worker-runtime helper. This file is bundled as a regular module and
// `__turbopack_require__`d by the generated web-worker loader code.
//
// The chunk-URL builder, the chunk base path and the asset suffix are read from
// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`
// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path
// override and forwarded-global names are baked into this module at build time by
// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /
// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global
// values are read from `globalThis`.
declare const __turbopack_chunk_relative_url__: (
chunkPath: string,
basePath?: string
) => string
declare const __turbopack_chunk_base_path__: string
declare const __turbopack_chunk_asset_suffix__: string
declare const _TURBOPACK_WORKER_FORWARDED_GLOBALS_: string[]
declare const _TURBOPACK_WORKER_BASE_PATH_: string | null
type WorkerConstructor = new (url: URL, options?: object) => Worker
/**
* Creates a web worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/
function createWorker(
WorkerConstructor: WorkerConstructor,
entrypoint: string,
moduleChunks: string[],
workerOptions?: object
): Worker {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker'
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath =
_TURBOPACK_WORKER_BASE_PATH_ ?? __turbopack_chunk_base_path__
const chunkUrls = moduleChunks
.map((chunk) => __turbopack_chunk_relative_url__(chunk, workerBasePath))
.reverse()
const params: unknown[] = [chunkUrls, __turbopack_chunk_asset_suffix__]
const globals = _TURBOPACK_WORKER_FORWARDED_GLOBALS_
for (let i = 0; i < globals.length; i++) {
params.push((globalThis as Record<string, unknown>)[globals[i]])
}
const url = new URL(
__turbopack_chunk_relative_url__(entrypoint, workerBasePath),
location.origin
)
const paramsJson = JSON.stringify(params)
if (isSharedWorker) {
url.searchParams.set('params', paramsJson)
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson)
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions
? { ...workerOptions, type: undefined }
: undefined
return new WorkerConstructor(url, options)
}
/**
* Returns a function, that when called with the constructor + any options calls `createWorker()`.
* The worker configuration (`entrypoint`, `moduleChunks`) is passed by `turbopack-ecmascript`
* at build time, leaving the runtime caller to only supply the constructor and options.
*/
export default function generateCreateWorker(
entrypoint: string,
moduleChunks: string[]
) {
return (
WorkerConstructor: { new (url: URL, options?: object): Worker },
workerOptions?: object
) => createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions)
}
// Embedded worker-runtime helper. This file is bundled as a regular module and
// `__turbopack_require__`d by the generated Node.js worker-thread loader code.
//
// The list of globals to forward is baked into this module at build time by
// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_FORWARDED_GLOBALS_`
// free variable; the forwarded-global values are read from `globalThis`.
declare const _TURBOPACK_WORKER_FORWARDED_GLOBALS_: string[]
/**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor
* with the appropriate path and options, including forwarded globals.
*
* @param WorkerConstructor The Worker constructor from worker_threads
* @param workerPath Path to the worker entry chunk
* @param workerOptions options to pass to the Worker constructor (optional)
*/
function createWorker(
WorkerConstructor: { new (path: string, options?: object): unknown },
workerPath: string,
workerOptions?: { workerData?: unknown; [key: string]: unknown }
): unknown {
// Build the forwarded globals object
const forwardedGlobals: Record<string, unknown> = {}
const globals = _TURBOPACK_WORKER_FORWARDED_GLOBALS_
for (let i = 0; i < globals.length; i++) {
forwardedGlobals[globals[i]] = (globalThis as Record<string, unknown>)[
globals[i]
]
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {}
const options = {
...workerOptions,
workerData: {
...(typeof existingWorkerData === 'object' ? existingWorkerData : {}),
__turbopack_globals__: forwardedGlobals,
},
}
return new WorkerConstructor(workerPath, options)
}
/**
* Returns a function, that when called with the constructor + any options calls `createWorker()`.
* The worker configuration (`entrypoint`) is passed by `turbopack-ecmascript` at build time,
* leaving the runtime caller to only supply the constructor and options.
*/
export default function generateCreateWorker(entrypoint: string) {
return (
WorkerConstructor: { new (path: string, options?: object): unknown },
workerOptions?: { workerData?: unknown; [key: string]: unknown }
) => createWorker(WorkerConstructor, entrypoint, workerOptions)
}
...@@ -39,7 +39,7 @@ use crate::{ ...@@ -39,7 +39,7 @@ use crate::{
member::MemberReplacement, member::MemberReplacement,
require_context::RequireContextAssetReferenceCodeGen, require_context::RequireContextAssetReferenceCodeGen,
unreachable::Unreachable, unreachable::Unreachable,
worker::WorkerAssetReferenceCodeGen, worker::{WorkerAssetReferenceCodeGen, WorkerGlobalsReplacementCodeGen},
}, },
}; };
...@@ -203,6 +203,7 @@ pub enum CodeGen { ...@@ -203,6 +203,7 @@ pub enum CodeGen {
UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen), UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen),
WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen), WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen),
ModuleHotReferenceCodeGen(ModuleHotReferenceCodeGen), ModuleHotReferenceCodeGen(ModuleHotReferenceCodeGen),
WorkerGlobalsReplacementCodeGen(WorkerGlobalsReplacementCodeGen),
} }
impl CodeGen { impl CodeGen {
...@@ -239,6 +240,7 @@ impl CodeGen { ...@@ -239,6 +240,7 @@ impl CodeGen {
Self::ModuleHotReferenceCodeGen(v) => { Self::ModuleHotReferenceCodeGen(v) => {
v.code_generation(ctx, scope_hoisting_context).await v.code_generation(ctx, scope_hoisting_context).await
} }
Self::WorkerGlobalsReplacementCodeGen(v) => v.code_generation(ctx).await,
} }
} }
} }
......
use turbo_tasks::Vc;
use turbo_tasks_fs::{FileSystem, embed_directory};
#[turbo_tasks::function]
pub fn embed_fs() -> Vc<Box<dyn FileSystem>> {
embed_directory!("turbopack-ecmascript", "$CARGO_MANIFEST_DIR/js/src")
}
...@@ -13,6 +13,7 @@ pub mod async_chunk; ...@@ -13,6 +13,7 @@ pub mod async_chunk;
pub mod bytes_source_transform; pub mod bytes_source_transform;
pub mod chunk; pub mod chunk;
pub mod code_gen; pub mod code_gen;
pub mod embed_js;
mod errors; mod errors;
pub mod json_source_transform; pub mod json_source_transform;
pub mod magic_identifier; pub mod magic_identifier;
......
...@@ -91,7 +91,7 @@ use turbopack_core::{ ...@@ -91,7 +91,7 @@ use turbopack_core::{
use turbopack_resolve::{ecmascript::cjs_resolve_source, typescript::tsconfig}; use turbopack_resolve::{ecmascript::cjs_resolve_source, typescript::tsconfig};
use turbopack_swc_utils::emitter::IssueEmitter; use turbopack_swc_utils::emitter::IssueEmitter;
use unreachable::Unreachable; use unreachable::Unreachable;
use worker::WorkerAssetReference; use worker::{WorkerAssetReference, WorkerGlobalPlaceholder, WorkerGlobalsReplacementCodeGen};
pub use crate::references::esm::export::{FollowExportsResult, follow_reexports}; pub use crate::references::esm::export::{FollowExportsResult, follow_reexports};
use crate::{ use crate::{
...@@ -1165,6 +1165,23 @@ async fn analyze_ecmascript_module_internal( ...@@ -1165,6 +1165,23 @@ async fn analyze_ecmascript_module_internal(
"unexpected Effect::FreeVar in tracing mode" "unexpected Effect::FreeVar in tracing mode"
); );
// Worker runtime helpers reference these as free vars; replace each
// with the value baked from the chunking context's worker config.
let worker_placeholder = match &*var {
"_TURBOPACK_WORKER_FORWARDED_GLOBALS_" => {
Some(WorkerGlobalPlaceholder::ForwardedGlobals)
}
"_TURBOPACK_WORKER_BASE_PATH_" => Some(WorkerGlobalPlaceholder::BasePath),
_ => None,
};
if let Some(placeholder) = worker_placeholder {
analysis.add_code_gen(WorkerGlobalsReplacementCodeGen::new(
placeholder,
ast_path.into(),
));
continue;
}
if options.enable_exports_info_inlining && var == "__webpack_exports_info__" { if options.enable_exports_info_inlining && var == "__webpack_exports_info__" {
if analysis_state.first_webpack_exports_info { if analysis_state.first_webpack_exports_info {
analysis_state.first_webpack_exports_info = false; analysis_state.first_webpack_exports_info = false;
......
use anyhow::Result; use anyhow::Result;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use swc_core::{ use swc_core::{
common::util::take::Take, common::{DUMMY_SP, util::take::Take},
ecma::ast::{CallExpr, Callee, Expr, ExprOrSpread, Lit}, ecma::ast::{ArrayLit, CallExpr, Callee, Expr, ExprOrSpread, Lit, Null},
quote_expr, quote_expr,
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -400,3 +400,61 @@ impl WorkerAssetReferenceCodeGen { ...@@ -400,3 +400,61 @@ impl WorkerAssetReferenceCodeGen {
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
} }
} }
#[derive(
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode,
)]
pub enum WorkerGlobalPlaceholder {
/// `const _TURBOPACK_WORKER_FORWARDED_GLOBALS_ = []`
ForwardedGlobals,
/// `const _TURBOPACK_WORKER_BASE_PATH_ = '_TURBOPACK_WORKER_BASE_PATH_REPLACE_'`
BasePath,
}
#[derive(
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode,
)]
pub struct WorkerGlobalsReplacementCodeGen {
/// Which placeholder this codegen replaces (determines the injected value).
placeholder: WorkerGlobalPlaceholder,
path: AstPath,
}
impl WorkerGlobalsReplacementCodeGen {
pub fn new(placeholder: WorkerGlobalPlaceholder, path: AstPath) -> Self {
WorkerGlobalsReplacementCodeGen { placeholder, path }
}
pub async fn code_generation(
&self,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let options = chunking_context.worker_configuration_options().await?;
let value: Expr = match self.placeholder {
WorkerGlobalPlaceholder::ForwardedGlobals => Expr::Array(ArrayLit {
span: DUMMY_SP,
elems: options
.forwarded_globals
.iter()
.map(|global| Some(Expr::Lit(Lit::Str(global.as_str().into())).into()))
.collect(),
}),
WorkerGlobalPlaceholder::BasePath => match &options.asset_prefix {
Some(asset_prefix) => Expr::Lit(Lit::Str(asset_prefix.as_str().into())),
None => Expr::Lit(Lit::Null(Null { span: DUMMY_SP })),
},
};
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
*expr = value.clone();
});
Ok(CodeGeneration::visitors(vec![visitor]))
}
}
impl From<WorkerGlobalsReplacementCodeGen> for CodeGen {
fn from(val: WorkerGlobalsReplacementCodeGen) -> Self {
CodeGen::WorkerGlobalsReplacementCodeGen(val)
}
}
...@@ -84,7 +84,6 @@ pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = m ...@@ -84,7 +84,6 @@ pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = m
pub const TURBOPACK_RESOLVE_FILE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("F"); pub const TURBOPACK_RESOLVE_FILE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("F");
pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U"); pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U");
pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R"); pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R");
pub const TURBOPACK_CREATE_WORKER: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
pub const TURBOPACK_ASYNC_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("a"); pub const TURBOPACK_ASYNC_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("a");
pub const TURBOPACK_EXTERNAL_REQUIRE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("x"); pub const TURBOPACK_EXTERNAL_REQUIRE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("x");
pub const TURBOPACK_EXTERNAL_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("y"); pub const TURBOPACK_EXTERNAL_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("y");
...@@ -94,10 +93,13 @@ pub const TURBOPACK_REQUIRE_REAL: &TurbopackRuntimeFunctionShortcut = make_short ...@@ -94,10 +93,13 @@ pub const TURBOPACK_REQUIRE_REAL: &TurbopackRuntimeFunctionShortcut = make_short
pub const TURBOPACK_WASM: &TurbopackRuntimeFunctionShortcut = make_shortcut!("w"); pub const TURBOPACK_WASM: &TurbopackRuntimeFunctionShortcut = make_shortcut!("w");
pub const TURBOPACK_WASM_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("u"); pub const TURBOPACK_WASM_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("u");
pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("g"); pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("g");
pub const TURBOPACK_CHUNK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("h");
pub const TURBOPACK_CHUNK_BASE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
pub const TURBOPACK_ASSET_SUFFIX: &TurbopackRuntimeFunctionShortcut = make_shortcut!("X");
/// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called /// 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) /// from user code (by inserting a replacement into free_var_references)
pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 24] = [ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 26] = [
("__turbopack_require__", TURBOPACK_REQUIRE), ("__turbopack_require__", TURBOPACK_REQUIRE),
("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT), ("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT),
("__turbopack_import__", TURBOPACK_IMPORT), ("__turbopack_import__", TURBOPACK_IMPORT),
...@@ -119,7 +121,6 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio ...@@ -119,7 +121,6 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
"__turbopack_resolve_module_id_path__", "__turbopack_resolve_module_id_path__",
TURBOPACK_RESOLVE_MODULE_ID_PATH, TURBOPACK_RESOLVE_MODULE_ID_PATH,
), ),
("__turbopack_create_worker__", TURBOPACK_CREATE_WORKER),
("__turbopack_external_require__", TURBOPACK_EXTERNAL_REQUIRE), ("__turbopack_external_require__", TURBOPACK_EXTERNAL_REQUIRE),
("__turbopack_external_import__", TURBOPACK_EXTERNAL_IMPORT), ("__turbopack_external_import__", TURBOPACK_EXTERNAL_IMPORT),
("__turbopack_refresh__", TURBOPACK_REFRESH), ("__turbopack_refresh__", TURBOPACK_REFRESH),
...@@ -131,4 +132,10 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio ...@@ -131,4 +132,10 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
), ),
("__turbopack_wasm__", TURBOPACK_WASM), ("__turbopack_wasm__", TURBOPACK_WASM),
("__turbopack_wasm_module__", TURBOPACK_WASM_MODULE), ("__turbopack_wasm_module__", TURBOPACK_WASM_MODULE),
(
"__turbopack_chunk_relative_url__",
TURBOPACK_CHUNK_RELATIVE_URL,
),
("__turbopack_chunk_base_path__", TURBOPACK_CHUNK_BASE_PATH),
("__turbopack_chunk_asset_suffix__", TURBOPACK_ASSET_SUFFIX),
]; ];
...@@ -2,19 +2,22 @@ use anyhow::{Result, bail}; ...@@ -2,19 +2,22 @@ use anyhow::{Result, bail};
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::rcstr; use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::FileSystem;
use turbopack_core::{ use turbopack_core::{
chunk::{ chunk::{
AsyncModuleInfo, ChunkData, ChunkGroupType, ChunkableModule, ChunkingContext, AsyncModuleInfo, ChunkData, ChunkGroupType, ChunkableModule, ChunkingContext,
ChunkingContextExt, ChunkingType, ChunksData, EvaluatableAsset, ChunkingContextExt, ChunkingType, ChunksData, EvaluatableAsset, ModuleChunkItemIdExt,
availability_info::AvailabilityInfo, ModuleId, availability_info::AvailabilityInfo,
}, },
context::AssetContext, context::AssetContext,
file_source::FileSource,
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::{ModuleGraph, chunk_group_info::ChunkGroup}, module_graph::{ModuleGraph, chunk_group_info::ChunkGroup},
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences, SingleChunkableModuleReference},
resolve::ModuleResolveResult, reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
resolve::{ExportUsage, ModulePart, ModuleResolveResult},
}; };
use super::worker_type::WorkerType; use super::worker_type::WorkerType;
...@@ -23,8 +26,9 @@ use crate::{ ...@@ -23,8 +26,9 @@ use crate::{
EcmascriptChunkItemContent, EcmascriptChunkItemOptions, EcmascriptChunkPlaceable, EcmascriptChunkItemContent, EcmascriptChunkItemOptions, EcmascriptChunkPlaceable,
EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item, EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item,
}, },
runtime_functions::{TURBOPACK_CREATE_WORKER, TURBOPACK_EXPORT_VALUE}, embed_js::embed_fs,
utils::StringifyJs, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
utils::{StringifyJs, StringifyModuleId},
}; };
/// The WorkerLoaderModule is a module that creates a separate root chunk group for the given module /// The WorkerLoaderModule is a module that creates a separate root chunk group for the given module
...@@ -130,6 +134,28 @@ impl WorkerLoaderModule { ...@@ -130,6 +134,28 @@ impl WorkerLoaderModule {
)) ))
} }
/// `createWorker` is stored in a module; for each worker we need to
/// load, we require this module and then use it.
#[turbo_tasks::function]
async fn create_worker_module(self: Vc<Self>) -> Result<Vc<Box<dyn Module>>> {
let this = self.await?;
let helper = match this.worker_type {
WorkerType::WebWorker | WorkerType::SharedWebWorker => {
rcstr!("worker/browser/createWorker.ts")
}
WorkerType::NodeWorkerThread => rcstr!("worker/node/createWorker.ts"),
};
Ok(this
.asset_context
.process(
Vc::upcast(FileSource::new(embed_fs().root().await?.join(&helper)?)),
ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::ImportPart(
ModulePart::Export(rcstr!("default")),
)),
)
.module())
}
/// Returns output assets including the worker entrypoint for web workers. /// Returns output assets including the worker entrypoint for web workers.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn chunk_group_with_type( async fn chunk_group_with_type(
...@@ -171,11 +197,22 @@ impl Module for WorkerLoaderModule { ...@@ -171,11 +197,22 @@ impl Module for WorkerLoaderModule {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> { async fn references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> {
let this = self.await?; let this = self.await?;
Ok(Vc::cell(vec![ResolvedVc::upcast( Ok(Vc::cell(vec![
ResolvedVc::upcast(
WorkerModuleReference::new(*ResolvedVc::upcast(this.inner), this.worker_type) WorkerModuleReference::new(*ResolvedVc::upcast(this.inner), this.worker_type)
.to_resolved() .to_resolved()
.await?, .await?,
)])) ),
ResolvedVc::upcast(
SingleChunkableModuleReference::new(
self.create_worker_module(),
rcstr!("createWorker"),
ExportUsage::named(rcstr!("default")),
)
.to_resolved()
.await?,
),
]))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -226,14 +263,14 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -226,14 +263,14 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
// otherwise we will induce a turbo tasks cycle. But we only need an // otherwise we will induce a turbo tasks cycle. But we only need an
// approximate solution. We'll use the same estimate for both web // approximate solution. We'll use the same estimate for both web
// and Node.js workers. // and Node.js workers.
let fake_id = ModuleId::String(rcstr!("a_fake_module"));
return Ok(EcmascriptChunkItemContent { return Ok(EcmascriptChunkItemContent {
inner_code: formatdoc! { inner_code: formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{ {TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})["default"](__dirname + "/" + {worker_path:#}));
return {TURBOPACK_CREATE_WORKER}(Ctor, __dirname + "/" + {worker_path:#}, opts);
}});
"#, "#,
worker_path = StringifyJs(&"a_fake_path_for_size_estimation"), worker_path = StringifyJs(&"a_fake_path_for_size_estimation"),
workers_module = StringifyModuleId(&fake_id),
} }
.into(), .into(),
options, options,
...@@ -242,6 +279,11 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -242,6 +279,11 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
.cell()); .cell());
} }
let create_worker_id = self
.create_worker_module()
.chunk_item_id(chunking_context)
.await?;
let code = match this.worker_type { let code = match this.worker_type {
WorkerType::WebWorker | WorkerType::SharedWebWorker => { WorkerType::WebWorker | WorkerType::SharedWebWorker => {
// For web workers, generate code that exports a function to create the worker. // For web workers, generate code that exports a function to create the worker.
...@@ -266,12 +308,11 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -266,12 +308,11 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
formatdoc! { formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{ {TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})["default"]({entrypoint}, {chunks}));
return {TURBOPACK_CREATE_WORKER}(Ctor, {entrypoint}, {chunks}, opts);
}});
"#, "#,
entrypoint = StringifyJs(&entrypoint_path), entrypoint = StringifyJs(&entrypoint_path),
chunks = StringifyJs(&chunks_data), chunks = StringifyJs(&chunks_data),
workers_module = StringifyModuleId(&create_worker_id),
} }
} }
WorkerType::NodeWorkerThread => { WorkerType::NodeWorkerThread => {
...@@ -299,11 +340,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -299,11 +340,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
// directory // directory
formatdoc! { formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{ {TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})["default"](__dirname + "/" + {worker_path:#}));
return {TURBOPACK_CREATE_WORKER}(Ctor, __dirname + "/" + {worker_path:#}, opts);
}});
"#, "#,
worker_path = StringifyJs(entry_path.file_name()), worker_path = StringifyJs(entry_path.file_name()),
workers_module = StringifyModuleId(&create_worker_id),
} }
} }
}; };
......
...@@ -12,7 +12,7 @@ use turbopack_core::{ ...@@ -12,7 +12,7 @@ use turbopack_core::{
AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule, AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule,
ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, EntryChunkGroupResult, ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, EntryChunkGroupResult,
EvaluatableAsset, MinifyType, SourceMapSourceType, SourceMapsType, UnusedReferences, EvaluatableAsset, MinifyType, SourceMapSourceType, SourceMapsType, UnusedReferences,
UrlBehavior, UrlBehavior, WorkerConfigurationOptions,
availability_info::AvailabilityInfo, availability_info::AvailabilityInfo,
chunk_group::{MakeChunkGroupResult, make_chunk_group}, chunk_group::{MakeChunkGroupResult, make_chunk_group},
chunk_id_strategy::ModuleIdStrategy, chunk_id_strategy::ModuleIdStrategy,
...@@ -714,7 +714,11 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -714,7 +714,11 @@ impl ChunkingContext for NodeJsChunkingContext {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn worker_forwarded_globals(&self) -> Vc<Vec<RcStr>> { fn worker_configuration_options(&self) -> Vc<WorkerConfigurationOptions> {
Vc::cell(self.worker_forwarded_globals.clone()) WorkerConfigurationOptions {
asset_prefix: None,
forwarded_globals: self.worker_forwarded_globals.clone(),
}
.cell()
} }
} }
...@@ -64,9 +64,8 @@ impl EcmascriptBuildNodeRuntimeChunk { ...@@ -64,9 +64,8 @@ impl EcmascriptBuildNodeRuntimeChunk {
let asset_prefix = asset_prefix.as_deref().unwrap_or("/"); let asset_prefix = asset_prefix.as_deref().unwrap_or("/");
// Get the list of global variable names to forward to workers // Get the list of global variable names to forward to workers
let worker_forwarded_globals = let worker_config = Vc::upcast::<Box<dyn ChunkingContext>>(*this.chunking_context)
Vc::upcast::<Box<dyn ChunkingContext>>(*this.chunking_context) .worker_configuration_options()
.worker_forwarded_globals()
.await?; .await?;
writedoc!( writedoc!(
...@@ -75,16 +74,14 @@ impl EcmascriptBuildNodeRuntimeChunk { ...@@ -75,16 +74,14 @@ impl EcmascriptBuildNodeRuntimeChunk {
var RUNTIME_PUBLIC_PATH = {}; var RUNTIME_PUBLIC_PATH = {};
var RELATIVE_ROOT_PATH = {}; var RELATIVE_ROOT_PATH = {};
var ASSET_PREFIX = {}; var ASSET_PREFIX = {};
var WORKER_FORWARDED_GLOBALS = {};
"#, "#,
StringifyJs(runtime_public_path), StringifyJs(runtime_public_path),
StringifyJs(output_root_to_root_path.as_str()), StringifyJs(output_root_to_root_path.as_str()),
StringifyJs(asset_prefix), StringifyJs(asset_prefix),
StringifyJs(&*worker_forwarded_globals),
)?; )?;
// Add preamble to read forwarded globals from workerData (for worker_threads) // Add preamble to read forwarded globals from workerData (for worker_threads)
if !worker_forwarded_globals.is_empty() { if !worker_config.forwarded_globals.is_empty() {
writedoc!( writedoc!(
code, code,
r#" r#"
......
var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js"; var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var ASSET_PREFIX = "/"; var ASSET_PREFIX = "/";
var WORKER_FORWARDED_GLOBALS = [];
// Dummy runtime // Dummy runtime
\ No newline at end of file
var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js"; var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var ASSET_PREFIX = "/"; var ASSET_PREFIX = "/";
var WORKER_FORWARDED_GLOBALS = [];
// Dummy runtime // Dummy runtime
\ No newline at end of file
;!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]="85ec7745-dee3-171d-a84e-b72344bb90d4")}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]="10b725f6-0979-dcb8-6d04-f7f42400db60")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js",
{"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -9,12 +9,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -9,12 +9,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -752,50 +750,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -752,50 +750,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH;
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -806,6 +760,13 @@ browserContextPrototype.b = createWorker; ...@@ -806,6 +760,13 @@ browserContextPrototype.b = createWorker;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) { */ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`; return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
...@@ -2272,5 +2233,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2272,5 +2233,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=85ec7745-dee3-171d-a84e-b72344bb90d4 //# debugId=10b725f6-0979-dcb8-6d04-f7f42400db60
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map
\ No newline at end of file
var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js"; var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var ASSET_PREFIX = "/"; var ASSET_PREFIX = "/";
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -798,30 +797,6 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) { ...@@ -798,30 +797,6 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) {
return compileWebAssemblyFromPath(resolved); return compileWebAssemblyFromPath(resolved);
} }
contextPrototype.u = loadWebAssemblyModule; contextPrototype.u = loadWebAssemblyModule;
/**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor
* with the appropriate path and options, including forwarded globals.
*
* @param WorkerConstructor The Worker constructor from worker_threads
* @param workerPath Path to the worker entry chunk
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, workerPath, workerOptions) {
// Build the forwarded globals object
const forwardedGlobals = {};
for (const name of WORKER_FORWARDED_GLOBALS){
forwardedGlobals[name] = globalThis[name];
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {};
const options = {
...workerOptions,
workerData: {
...typeof existingWorkerData === 'object' ? existingWorkerData : {},
__turbopack_globals__: forwardedGlobals
}
};
return new WorkerConstructor(workerPath, options);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/** /**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment. * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
...@@ -1543,7 +1518,6 @@ nodeDevContextPrototype.q = exportUrl; ...@@ -1543,7 +1518,6 @@ nodeDevContextPrototype.q = exportUrl;
nodeDevContextPrototype.M = moduleFactories; nodeDevContextPrototype.M = moduleFactories;
nodeDevContextPrototype.c = devModuleCache; nodeDevContextPrototype.c = devModuleCache;
nodeDevContextPrototype.R = resolvePathFromModule; nodeDevContextPrototype.R = resolvePathFromModule;
nodeDevContextPrototype.b = createWorker;
nodeDevContextPrototype.C = clearChunkCache; nodeDevContextPrototype.C = clearChunkCache;
/** /**
* Instantiates a module in development mode using shared HMR logic. * Instantiates a module in development mode using shared HMR logic.
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0r_m8l7._.js", (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_1n6almu._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)", ((__turbopack_context__) => {
__turbopack_context__.v((parentImport) => { __turbopack_context__.v((parentImport) => {
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_1aqs1qt.js", "output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_1dyvkws.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0r_m8l7._.js","output/1do3_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_09jmqs-._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_1n6almu._.js","output/[root-of-the-server]__08ofy-h._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]}
]); ]);
// Dummy runtime // Dummy runtime
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs"],"sourcesContent":["module.exports = 'turbopack'\n"],"names":["module","exports"],"mappings":"AAAAA,OAAOC,OAAO,GAAG"}},
{"offset": {"line": 20, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import('./vercel.mjs').then(console.log)\nimport(/* webpackIgnore: false */ './vercel.mjs').then(console.log)\nconsole.log(require('./vercel.cjs'))\nnew Worker(\n /* turbopackIgnore: false */ new URL('./vercel.cjs', import.meta.url)\n)\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ './ignore.mjs')\nimport(/* turbopackIgnore: true */ './ignore.mjs')\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ './ignore.cjs')\nrequire(/* turbopackIgnore: true */ './ignore.cjs')\n\nnew Worker(\n /* turbopackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\nnew Worker(\n /* webpackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":["then","console","log","Worker","require","foo","plugin"],"mappings":";;;;;;;;;AAAA,gKAAuBA,IAAI,CAACC,QAAQC,GAAG;AACvC,gKAAkDF,IAAI,CAACC,QAAQC,GAAG;AAClED,QAAQC,GAAG;AACX,iKAAIC;AAIJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxCC,QAAQ,uBAAuB,GAAG;AAClCA,QAAQ,yBAAyB,GAAG;AAEpC,IAAID;AAGJ,IAAIA;AAIG,SAASE,IAAIC,MAAM;IACxB,OAAOF,QAAQ,yBAAyB,GAAGE;AAC7C"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_09jmqs-._.js", (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/[root-of-the-server]__08ofy-h._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)", ((__turbopack_context__, module, exports) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
module.exports = 'turbopack'; module.exports = 'turbopack';
...@@ -6,11 +6,74 @@ module.exports = 'turbopack'; ...@@ -6,11 +6,74 @@ module.exports = 'turbopack';
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs (static in ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/vercel.0kkt412gy5vj6.cjs");}), __turbopack_context__.q("/static/vercel.0kkt412gy5vj6.cjs");}),
"[turbopack-ecmascript]/worker/browser/createWorker.ts [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// Embedded worker-runtime helper. This file is bundled as a regular module and
// `__turbopack_require__`d by the generated web-worker loader code.
//
// The chunk-URL builder, the chunk base path and the asset suffix are read from
// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`
// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path
// override and forwarded-global names are baked into this module at build time by
// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /
// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global
// values are read from `globalThis`.
__turbopack_context__.s([
"default",
()=>generateCreateWorker
]);
/**
* Creates a web worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = null ?? /*TURBOPACK member replacement*/ __turbopack_context__.b;
const chunkUrls = moduleChunks.map((chunk)=>/*TURBOPACK member replacement*/ __turbopack_context__.h(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
/*TURBOPACK member replacement*/ __turbopack_context__.X
];
const globals = [];
for(let i = 0; i < globals.length; i++){
params.push(globalThis[globals[i]]);
}
const url = new URL(/*TURBOPACK member replacement*/ __turbopack_context__.h(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
function generateCreateWorker(entrypoint, moduleChunks) {
return (WorkerConstructor, workerOptions)=>createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions);
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(function(Ctor, opts) { __turbopack_context__.v(__turbopack_context__.r("[turbopack-ecmascript]/worker/browser/createWorker.ts [test] (ecmascript)")["default"]("output/0uxq_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_0uy0mni._.js", ["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_0j-fab5._.js","output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_02p77ng._.js"]));
return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_0uy0mni._.js", ["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_0j-fab5._.js","output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_02p77ng._.js"], opts);
});
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)", ((__turbopack_context__) => {
...@@ -45,4 +108,4 @@ function foo(plugin) { ...@@ -45,4 +108,4 @@ function foo(plugin) {
}), }),
]); ]);
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_09jmqs-._.js.map //# sourceMappingURL=%5Broot-of-the-server%5D__08ofy-h._.js.map
\ No newline at end of file \ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs"],"sourcesContent":["module.exports = 'turbopack'\n"],"names":["module","exports"],"mappings":"AAAAA,OAAOC,OAAO,GAAG"}},
{"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack-ecmascript]/worker/browser/createWorker.ts"],"sourcesContent":["// Embedded worker-runtime helper. This file is bundled as a regular module and\n// `__turbopack_require__`d by the generated web-worker loader code.\n//\n// The chunk-URL builder, the chunk base path and the asset suffix are read from\n// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`\n// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path\n// override and forwarded-global names are baked into this module at build time by\n// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /\n// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global\n// values are read from `globalThis`.\ndeclare const __turbopack_chunk_relative_url__: (\n chunkPath: string,\n basePath?: string\n) => string\n\ndeclare const __turbopack_chunk_base_path__: string\ndeclare const __turbopack_chunk_asset_suffix__: string\n\ndeclare const _TURBOPACK_WORKER_FORWARDED_GLOBALS_: string[]\ndeclare const _TURBOPACK_WORKER_BASE_PATH_: string | null\n\ntype WorkerConstructor = new (url: URL, options?: object) => Worker\n\n/**\n * Creates a web worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: WorkerConstructor,\n entrypoint: string,\n moduleChunks: string[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n // `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the\n // module chunks loaded inside the worker, keeping them same-origin to each\n // other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.\n // `null` falls back; an empty string is treated as a literal empty prefix.\n const workerBasePath =\n _TURBOPACK_WORKER_BASE_PATH_ ?? __turbopack_chunk_base_path__\n\n const chunkUrls = moduleChunks\n .map((chunk) => __turbopack_chunk_relative_url__(chunk, workerBasePath))\n .reverse()\n const params: unknown[] = [chunkUrls, __turbopack_chunk_asset_suffix__]\n const globals = _TURBOPACK_WORKER_FORWARDED_GLOBALS_\n for (let i = 0; i < globals.length; i++) {\n params.push((globalThis as Record<string, unknown>)[globals[i]])\n }\n\n const url = new URL(\n __turbopack_chunk_relative_url__(entrypoint, workerBasePath),\n location.origin\n )\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\n\n/**\n * Returns a function, that when called with the constructor + any options calls `createWorker()`.\n * The worker configuration (`entrypoint`, `moduleChunks`) is passed by `turbopack-ecmascript`\n * at build time, leaving the runtime caller to only supply the constructor and options.\n */\nexport default function generateCreateWorker(\n entrypoint: string,\n moduleChunks: string[]\n) {\n return (\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n workerOptions?: object\n ) => createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions)\n}\n"],"names":["createWorker","WorkerConstructor","entrypoint","moduleChunks","workerOptions","isSharedWorker","name","workerBasePath","chunkUrls","map","chunk","reverse","params","globals","i","length","push","globalThis","url","URL","location","origin","paramsJson","JSON","stringify","searchParams","set","hash","encodeURIComponent","options","type","undefined","generateCreateWorker"],"mappings":"AAAA,+EAA+E;AAC/E,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,kFAAkF;AAClF,gFAAgF;AAChF,kFAAkF;AAClF,wEAAwE;AACxE,kFAAkF;AAClF,qCAAqC;;;;;AAcrC;;;;;;;;;;;;;;CAcC,GACD,SAASA,aACPC,iBAAoC,EACpCC,UAAkB,EAClBC,YAAsB,EACtBC,aAAsB;IAEtB,MAAMC,iBAAiBJ,kBAAkBK,IAAI,KAAK;IAElD,4EAA4E;IAC5E,2EAA2E;IAC3E,wEAAwE;IACxE,2EAA2E;IAC3E,MAAMC,iBACJ;IAEF,MAAMC,YAAYL,aACfM,GAAG,CAAC,CAACC,QAAU,yDAAiCA,OAAOH,iBACvDI,OAAO;IACV,MAAMC,SAAoB;QAACJ;;KAA4C;IACvE,MAAMK;IACN,IAAK,IAAIC,IAAI,GAAGA,IAAID,QAAQE,MAAM,EAAED,IAAK;QACvCF,OAAOI,IAAI,CAAC,AAACC,UAAsC,CAACJ,OAAO,CAACC,EAAE,CAAC;IACjE;IAEA,MAAMI,MAAM,IAAIC,IACd,yDAAiCjB,YAAYK,iBAC7Ca,SAASC,MAAM;IAEjB,MAAMC,aAAaC,KAAKC,SAAS,CAACZ;IAClC,IAAIP,gBAAgB;QAClBa,IAAIO,YAAY,CAACC,GAAG,CAAC,UAAUJ;IACjC,OAAO;QACLJ,IAAIS,IAAI,GAAG,aAAaC,mBAAmBN;IAC7C;IAEA,iFAAiF;IACjF,MAAMO,UAAUzB,gBACZ;QAAE,GAAGA,aAAa;QAAE0B,MAAMC;IAAU,IACpCA;IACJ,OAAO,IAAI9B,kBAAkBiB,KAAKW;AACpC;AAOe,SAASG,qBACtB9B,UAAkB,EAClBC,YAAsB;IAEtB,OAAO,CACLF,mBACAG,gBACGJ,aAAaC,mBAAmBC,YAAYC,cAAcC;AACjE"}},
{"offset": {"line": 83, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import('./vercel.mjs').then(console.log)\nimport(/* webpackIgnore: false */ './vercel.mjs').then(console.log)\nconsole.log(require('./vercel.cjs'))\nnew Worker(\n /* turbopackIgnore: false */ new URL('./vercel.cjs', import.meta.url)\n)\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ './ignore.mjs')\nimport(/* turbopackIgnore: true */ './ignore.mjs')\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ './ignore.cjs')\nrequire(/* turbopackIgnore: true */ './ignore.cjs')\n\nnew Worker(\n /* turbopackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\nnew Worker(\n /* webpackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":["then","console","log","Worker","require","foo","plugin"],"mappings":";;;;;;;;;AAAA,gKAAuBA,IAAI,CAACC,QAAQC,GAAG;AACvC,gKAAkDF,IAAI,CAACC,QAAQC,GAAG;AAClED,QAAQC,GAAG;AACX,iKAAIC;AAIJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxCC,QAAQ,uBAAuB,GAAG;AAClCA,QAAQ,yBAAyB,GAAG;AAEpC,IAAID;AAGJ,IAAIA;AAIG,SAASE,IAAIC,MAAM;IACxB,OAAOF,QAAQ,yBAAyB,GAAGE;AAC7C"}}]
}
\ No newline at end of file
var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js"; var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var ASSET_PREFIX = "/"; var ASSET_PREFIX = "/";
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -666,30 +665,6 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) { ...@@ -666,30 +665,6 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) {
return compileWebAssemblyFromPath(resolved); return compileWebAssemblyFromPath(resolved);
} }
contextPrototype.u = loadWebAssemblyModule; contextPrototype.u = loadWebAssemblyModule;
/**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor
* with the appropriate path and options, including forwarded globals.
*
* @param WorkerConstructor The Worker constructor from worker_threads
* @param workerPath Path to the worker entry chunk
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, workerPath, workerOptions) {
// Build the forwarded globals object
const forwardedGlobals = {};
for (const name of WORKER_FORWARDED_GLOBALS){
forwardedGlobals[name] = globalThis[name];
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {};
const options = {
...workerOptions,
workerData: {
...typeof existingWorkerData === 'object' ? existingWorkerData : {},
__turbopack_globals__: forwardedGlobals
}
};
return new WorkerConstructor(workerPath, options);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/** /**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment. * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
...@@ -709,7 +684,6 @@ nodeContextPrototype.M = moduleFactories; ...@@ -709,7 +684,6 @@ nodeContextPrototype.M = moduleFactories;
// Cast moduleCache to ModuleWithDirection for production mode // Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache; nodeContextPrototype.c = moduleCache;
nodeContextPrototype.R = resolvePathFromModule; nodeContextPrototype.R = resolvePathFromModule;
nodeContextPrototype.b = createWorker;
nodeContextPrototype.C = clearChunkCache; nodeContextPrototype.C = clearChunkCache;
function instantiateModule(id, sourceType, sourceData) { function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id); const moduleFactory = moduleFactories.get(id);
......
...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH;
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker; ...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) { */ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`; return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
......
...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -737,58 +735,6 @@ function _async_to_generator(fn) { ...@@ -737,58 +735,6 @@ function _async_to_generator(fn) {
}); });
}; };
} }
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _ts_generator(thisArg, body) { function _ts_generator(thisArg, body) {
var f, y, t, _ = { var f, y, t, _ = {
label: 0, label: 0,
...@@ -1150,68 +1096,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -1150,68 +1096,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
var isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
var workerBasePath = WORKER_BASE_PATH !== null && WORKER_BASE_PATH !== void 0 ? WORKER_BASE_PATH : CHUNK_BASE_PATH;
var chunkUrls = moduleChunks.map(function(chunk) {
return getChunkRelativeUrl(chunk, workerBasePath);
}).reverse();
var params = [
chunkUrls,
ASSET_SUFFIX
];
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = WORKER_FORWARDED_GLOBALS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var globalName = _step.value;
params.push(globalThis[globalName]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
var paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
var options = workerOptions ? _object_spread_props(_object_spread({}, workerOptions), {
type: undefined
}) : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -1225,6 +1109,13 @@ browserContextPrototype.b = createWorker; ...@@ -1225,6 +1109,13 @@ browserContextPrototype.b = createWorker;
return encodeURIComponent(p); return encodeURIComponent(p);
}).join('/')}${ASSET_SUFFIX}`; }).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_09-gc7x.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_0ba9cj3.js",
{"otherChunks":["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/[root-of-the-server]__07l1lih._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)"]}
]); ]);
(() => { (() => {
if (!Array.isArray(globalThis["TURBOPACK"])) { if (!Array.isArray(globalThis["TURBOPACK"])) {
...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH;
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker; ...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) { */ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`; return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
...@@ -2271,4 +2232,4 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2271,4 +2232,4 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_09-gc7x.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_0ba9cj3.js.map
\ No newline at end of file \ No newline at end of file
...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH;
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker; ...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) { */ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`; return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/[root-of-the-server]__07l1lih._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/worker.2-qnq-strt8dn.js");}),
"[turbopack-ecmascript]/worker/browser/createWorker.ts [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// Embedded worker-runtime helper. This file is bundled as a regular module and
// `__turbopack_require__`d by the generated web-worker loader code.
//
// The chunk-URL builder, the chunk base path and the asset suffix are read from
// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`
// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path
// override and forwarded-global names are baked into this module at build time by
// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /
// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global
// values are read from `globalThis`.
__turbopack_context__.s([
"default",
()=>generateCreateWorker
]);
/**
* Creates a web worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = null ?? /*TURBOPACK member replacement*/ __turbopack_context__.b;
const chunkUrls = moduleChunks.map((chunk)=>/*TURBOPACK member replacement*/ __turbopack_context__.h(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
/*TURBOPACK member replacement*/ __turbopack_context__.X
];
const globals = [];
for(let i = 0; i < globals.length; i++){
params.push(globalThis[globals[i]]);
}
const url = new URL(/*TURBOPACK member replacement*/ __turbopack_context__.h(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
function generateCreateWorker(entrypoint, moduleChunks) {
return (WorkerConstructor, workerOptions)=>createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions);
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.r("[turbopack-ecmascript]/worker/browser/createWorker.ts [test] (ecmascript)")["default"]("output/0uxq_crates_turbopack-tests_tests_snapshot_workers_basic_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ygioo.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_0yr5fg0.js"]));
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
var __TURBOPACK__import$2e$meta__ = {
get url () {
return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js");
}
};
console.log('index.js');
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)")(Worker);
}),
]);
//# sourceMappingURL=%5Broot-of-the-server%5D__07l1lih._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 7, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack-ecmascript]/worker/browser/createWorker.ts"],"sourcesContent":["// Embedded worker-runtime helper. This file is bundled as a regular module and\n// `__turbopack_require__`d by the generated web-worker loader code.\n//\n// The chunk-URL builder, the chunk base path and the asset suffix are read from\n// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`\n// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path\n// override and forwarded-global names are baked into this module at build time by\n// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /\n// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global\n// values are read from `globalThis`.\ndeclare const __turbopack_chunk_relative_url__: (\n chunkPath: string,\n basePath?: string\n) => string\n\ndeclare const __turbopack_chunk_base_path__: string\ndeclare const __turbopack_chunk_asset_suffix__: string\n\ndeclare const _TURBOPACK_WORKER_FORWARDED_GLOBALS_: string[]\ndeclare const _TURBOPACK_WORKER_BASE_PATH_: string | null\n\ntype WorkerConstructor = new (url: URL, options?: object) => Worker\n\n/**\n * Creates a web worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: WorkerConstructor,\n entrypoint: string,\n moduleChunks: string[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n // `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the\n // module chunks loaded inside the worker, keeping them same-origin to each\n // other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.\n // `null` falls back; an empty string is treated as a literal empty prefix.\n const workerBasePath =\n _TURBOPACK_WORKER_BASE_PATH_ ?? __turbopack_chunk_base_path__\n\n const chunkUrls = moduleChunks\n .map((chunk) => __turbopack_chunk_relative_url__(chunk, workerBasePath))\n .reverse()\n const params: unknown[] = [chunkUrls, __turbopack_chunk_asset_suffix__]\n const globals = _TURBOPACK_WORKER_FORWARDED_GLOBALS_\n for (let i = 0; i < globals.length; i++) {\n params.push((globalThis as Record<string, unknown>)[globals[i]])\n }\n\n const url = new URL(\n __turbopack_chunk_relative_url__(entrypoint, workerBasePath),\n location.origin\n )\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\n\n/**\n * Returns a function, that when called with the constructor + any options calls `createWorker()`.\n * The worker configuration (`entrypoint`, `moduleChunks`) is passed by `turbopack-ecmascript`\n * at build time, leaving the runtime caller to only supply the constructor and options.\n */\nexport default function generateCreateWorker(\n entrypoint: string,\n moduleChunks: string[]\n) {\n return (\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n workerOptions?: object\n ) => createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions)\n}\n"],"names":["createWorker","WorkerConstructor","entrypoint","moduleChunks","workerOptions","isSharedWorker","name","workerBasePath","chunkUrls","map","chunk","reverse","params","globals","i","length","push","globalThis","url","URL","location","origin","paramsJson","JSON","stringify","searchParams","set","hash","encodeURIComponent","options","type","undefined","generateCreateWorker"],"mappings":"AAAA,+EAA+E;AAC/E,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,kFAAkF;AAClF,gFAAgF;AAChF,kFAAkF;AAClF,wEAAwE;AACxE,kFAAkF;AAClF,qCAAqC;;;;;AAcrC;;;;;;;;;;;;;;CAcC,GACD,SAASA,aACPC,iBAAoC,EACpCC,UAAkB,EAClBC,YAAsB,EACtBC,aAAsB;IAEtB,MAAMC,iBAAiBJ,kBAAkBK,IAAI,KAAK;IAElD,4EAA4E;IAC5E,2EAA2E;IAC3E,wEAAwE;IACxE,2EAA2E;IAC3E,MAAMC,iBACJ;IAEF,MAAMC,YAAYL,aACfM,GAAG,CAAC,CAACC,QAAU,yDAAiCA,OAAOH,iBACvDI,OAAO;IACV,MAAMC,SAAoB;QAACJ;;KAA4C;IACvE,MAAMK;IACN,IAAK,IAAIC,IAAI,GAAGA,IAAID,QAAQE,MAAM,EAAED,IAAK;QACvCF,OAAOI,IAAI,CAAC,AAACC,UAAsC,CAACJ,OAAO,CAACC,EAAE,CAAC;IACjE;IAEA,MAAMI,MAAM,IAAIC,IACd,yDAAiCjB,YAAYK,iBAC7Ca,SAASC,MAAM;IAEjB,MAAMC,aAAaC,KAAKC,SAAS,CAACZ;IAClC,IAAIP,gBAAgB;QAClBa,IAAIO,YAAY,CAACC,GAAG,CAAC,UAAUJ;IACjC,OAAO;QACLJ,IAAIS,IAAI,GAAG,aAAaC,mBAAmBN;IAC7C;IAEA,iFAAiF;IACjF,MAAMO,UAAUzB,gBACZ;QAAE,GAAGA,aAAa;QAAE0B,MAAMC;IAAU,IACpCA;IACJ,OAAO,IAAI9B,kBAAkBiB,KAAKW;AACpC;AAOe,SAASG,qBACtB9B,UAAkB,EAClBC,YAAsB;IAEtB,OAAO,CACLF,mBACAG,gBACGJ,aAAaC,mBAAmBC,YAAYC,cAAcC;AACjE"}},
{"offset": {"line": 75, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js"],"sourcesContent":["console.log('index.js')\nconst url = new URL('./worker.js', import.meta.url)\nnew Worker(url)\n"],"names":["console","log","url","Worker"],"mappings":";;;;;AAAAA,QAAQC,GAAG,CAAC;AACZ,MAAMC;AACN,sJAAIC"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/worker.2-qnq-strt8dn.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_basic_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ygioo.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_0yr5fg0.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
var __TURBOPACK__import$2e$meta__ = {
get url () {
return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js");
}
};
console.log('index.js');
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)")(Worker);
}),
]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js"],"sourcesContent":["console.log('index.js')\nconst url = new URL('./worker.js', import.meta.url)\nnew Worker(url)\n"],"names":["console","log","url","Worker"],"mappings":";;;;;AAAAA,QAAQC,GAAG,CAAC;AACZ,MAAMC;AACN,sJAAIC"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_0arnewp.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_1dpfh5i.js",
{"otherChunks":["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/[root-of-the-server]__0kx1kaj._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)"]}
]); ]);
(() => { (() => {
if (!Array.isArray(globalThis["TURBOPACK"])) { if (!Array.isArray(globalThis["TURBOPACK"])) {
...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH;
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker; ...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) { */ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`; return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
...@@ -2271,4 +2232,4 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2271,4 +2232,4 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_0arnewp.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_1dpfh5i.js.map
\ No newline at end of file \ No newline at end of file
...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) { ...@@ -8,12 +8,10 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
} }
var CHUNK_BASE_PATH = ""; var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl; ...@@ -751,50 +749,6 @@ browserContextPrototype.F = resolveFileUrl;
exportValue.call(this, `${url}${ASSET_SUFFIX}`, id); exportValue.call(this, `${url}${ASSET_SUFFIX}`, id);
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = WORKER_BASE_PATH ?? CHUNK_BASE_PATH;
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
browserContextPrototype.b = createWorker;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker; ...@@ -805,6 +759,13 @@ browserContextPrototype.b = createWorker;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) { */ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`; return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
} }
// Shared runtime primitives consumed by the bundled `createWorker` helper,
// exposed as `__turbopack_chunk_base_path__` and `__turbopack_chunk_asset_suffix__`.
browserContextPrototype.b = CHUNK_BASE_PATH;
browserContextPrototype.X = ASSET_SUFFIX;
// Shared runtime primitive: build a chunk's URL. Used by the bundled worker
// helper and the WASM helper, exposed as `__turbopack_chunk_relative_url__`.
browserContextPrototype.h = getChunkRelativeUrl;
function getPathFromScript(chunkScript) { function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/[root-of-the-server]__0kx1kaj._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/worker.1n36e5vaxakik.js");}),
"[turbopack-ecmascript]/worker/browser/createWorker.ts [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// Embedded worker-runtime helper. This file is bundled as a regular module and
// `__turbopack_require__`d by the generated web-worker loader code.
//
// The chunk-URL builder, the chunk base path and the asset suffix are read from
// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`
// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path
// override and forwarded-global names are baked into this module at build time by
// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /
// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global
// values are read from `globalThis`.
__turbopack_context__.s([
"default",
()=>generateCreateWorker
]);
/**
* Creates a web worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
// `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the
// module chunks loaded inside the worker, keeping them same-origin to each
// other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.
// `null` falls back; an empty string is treated as a literal empty prefix.
const workerBasePath = null ?? /*TURBOPACK member replacement*/ __turbopack_context__.b;
const chunkUrls = moduleChunks.map((chunk)=>/*TURBOPACK member replacement*/ __turbopack_context__.h(chunk, workerBasePath)).reverse();
const params = [
chunkUrls,
/*TURBOPACK member replacement*/ __turbopack_context__.X
];
const globals = [];
for(let i = 0; i < globals.length; i++){
params.push(globalThis[globals[i]]);
}
const url = new URL(/*TURBOPACK member replacement*/ __turbopack_context__.h(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
function generateCreateWorker(entrypoint, moduleChunks) {
return (WorkerConstructor, workerOptions)=>createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions);
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.r("[turbopack-ecmascript]/worker/browser/createWorker.ts [test] (ecmascript)")["default"]("output/0uxq_crates_turbopack-tests_tests_snapshot_workers_shared_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1u1i0a1.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1xw116u.js"]));
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
var __TURBOPACK__import$2e$meta__ = {
get url () {
return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js");
}
};
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)")(SharedWorker);
}),
]);
//# sourceMappingURL=%5Broot-of-the-server%5D__0kx1kaj._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 7, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack-ecmascript]/worker/browser/createWorker.ts"],"sourcesContent":["// Embedded worker-runtime helper. This file is bundled as a regular module and\n// `__turbopack_require__`d by the generated web-worker loader code.\n//\n// The chunk-URL builder, the chunk base path and the asset suffix are read from\n// the shared `__turbopack_chunk_relative_url__` / `__turbopack_chunk_base_path__`\n// / `__turbopack_chunk_asset_suffix__` runtime primitives. The worker base-path\n// override and forwarded-global names are baked into this module at build time by\n// `turbopack-ecmascript` replacing the `_TURBOPACK_WORKER_BASE_PATH_` /\n// `_TURBOPACK_WORKER_FORWARDED_GLOBALS_` free variables, and the forwarded-global\n// values are read from `globalThis`.\ndeclare const __turbopack_chunk_relative_url__: (\n chunkPath: string,\n basePath?: string\n) => string\n\ndeclare const __turbopack_chunk_base_path__: string\ndeclare const __turbopack_chunk_asset_suffix__: string\n\ndeclare const _TURBOPACK_WORKER_FORWARDED_GLOBALS_: string[]\ndeclare const _TURBOPACK_WORKER_BASE_PATH_: string | null\n\ntype WorkerConstructor = new (url: URL, options?: object) => Worker\n\n/**\n * Creates a web worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...workerForwardedGlobals values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: WorkerConstructor,\n entrypoint: string,\n moduleChunks: string[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n // `WORKER_BASE_PATH` overrides `CHUNK_BASE_PATH` for the entrypoint and the\n // module chunks loaded inside the worker, keeping them same-origin to each\n // other when `CHUNK_BASE_PATH` (= `assetPrefix`) is a cross-origin CDN.\n // `null` falls back; an empty string is treated as a literal empty prefix.\n const workerBasePath =\n _TURBOPACK_WORKER_BASE_PATH_ ?? __turbopack_chunk_base_path__\n\n const chunkUrls = moduleChunks\n .map((chunk) => __turbopack_chunk_relative_url__(chunk, workerBasePath))\n .reverse()\n const params: unknown[] = [chunkUrls, __turbopack_chunk_asset_suffix__]\n const globals = _TURBOPACK_WORKER_FORWARDED_GLOBALS_\n for (let i = 0; i < globals.length; i++) {\n params.push((globalThis as Record<string, unknown>)[globals[i]])\n }\n\n const url = new URL(\n __turbopack_chunk_relative_url__(entrypoint, workerBasePath),\n location.origin\n )\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\n\n/**\n * Returns a function, that when called with the constructor + any options calls `createWorker()`.\n * The worker configuration (`entrypoint`, `moduleChunks`) is passed by `turbopack-ecmascript`\n * at build time, leaving the runtime caller to only supply the constructor and options.\n */\nexport default function generateCreateWorker(\n entrypoint: string,\n moduleChunks: string[]\n) {\n return (\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n workerOptions?: object\n ) => createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions)\n}\n"],"names":["createWorker","WorkerConstructor","entrypoint","moduleChunks","workerOptions","isSharedWorker","name","workerBasePath","chunkUrls","map","chunk","reverse","params","globals","i","length","push","globalThis","url","URL","location","origin","paramsJson","JSON","stringify","searchParams","set","hash","encodeURIComponent","options","type","undefined","generateCreateWorker"],"mappings":"AAAA,+EAA+E;AAC/E,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,kFAAkF;AAClF,gFAAgF;AAChF,kFAAkF;AAClF,wEAAwE;AACxE,kFAAkF;AAClF,qCAAqC;;;;;AAcrC;;;;;;;;;;;;;;CAcC,GACD,SAASA,aACPC,iBAAoC,EACpCC,UAAkB,EAClBC,YAAsB,EACtBC,aAAsB;IAEtB,MAAMC,iBAAiBJ,kBAAkBK,IAAI,KAAK;IAElD,4EAA4E;IAC5E,2EAA2E;IAC3E,wEAAwE;IACxE,2EAA2E;IAC3E,MAAMC,iBACJ;IAEF,MAAMC,YAAYL,aACfM,GAAG,CAAC,CAACC,QAAU,yDAAiCA,OAAOH,iBACvDI,OAAO;IACV,MAAMC,SAAoB;QAACJ;;KAA4C;IACvE,MAAMK;IACN,IAAK,IAAIC,IAAI,GAAGA,IAAID,QAAQE,MAAM,EAAED,IAAK;QACvCF,OAAOI,IAAI,CAAC,AAACC,UAAsC,CAACJ,OAAO,CAACC,EAAE,CAAC;IACjE;IAEA,MAAMI,MAAM,IAAIC,IACd,yDAAiCjB,YAAYK,iBAC7Ca,SAASC,MAAM;IAEjB,MAAMC,aAAaC,KAAKC,SAAS,CAACZ;IAClC,IAAIP,gBAAgB;QAClBa,IAAIO,YAAY,CAACC,GAAG,CAAC,UAAUJ;IACjC,OAAO;QACLJ,IAAIS,IAAI,GAAG,aAAaC,mBAAmBN;IAC7C;IAEA,iFAAiF;IACjF,MAAMO,UAAUzB,gBACZ;QAAE,GAAGA,aAAa;QAAE0B,MAAMC;IAAU,IACpCA;IACJ,OAAO,IAAI9B,kBAAkBiB,KAAKW;AACpC;AAOe,SAASG,qBACtB9B,UAAkB,EAClBC,YAAsB;IAEtB,OAAO,CACLF,mBACAG,gBACGJ,aAAaC,mBAAmBC,YAAYC,cAAcC;AACjE"}},
{"offset": {"line": 75, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js"],"sourcesContent":["const url = new URL('./worker.js', import.meta.url)\nnew SharedWorker(url)\n"],"names":["url","SharedWorker"],"mappings":";;;;;AAAA,MAAMA;AACN,uJAAIC"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/worker.1n36e5vaxakik.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_shared_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1u1i0a1.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1xw116u.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
var __TURBOPACK__import$2e$meta__ = {
get url () {
return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js");
}
};
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)")(SharedWorker);
}),
]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js"],"sourcesContent":["const url = new URL('./worker.js', import.meta.url)\nnew SharedWorker(url)\n"],"names":["url","SharedWorker"],"mappings":";;;;;AAAA,MAAMA;AACN,uJAAIC"}}]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment