Unverified Commit 668094ed authored by 张昊's avatar 张昊 Committed by GitHub

Turbopack: add `experimental.turbopackWorkerAssetPrefix` to keep Workers…

Turbopack: add `experimental.turbopackWorkerAssetPrefix` to keep Workers same-origin when `assetPrefix` is a CDN (#93271)

### What?

Adds `experimental.turbopackWorkerAssetPrefix` — a Turbopack counterpart
to webpack's
[`output.workerPublicPath`](https://webpack.js.org/configuration/output/#outputworkerpublicpath).
Opt-in, off by default, fully backward compatible.

```js
// next.config.js
module.exports = {
  assetPrefix: 'https://cdn.example.com',
  experimental: {
    // Same shape as `assetPrefix`: bare prefix, no trailing slash, no `/_next`.
    // `/_next/` is appended automatically. `''` → same-origin `/_next/...`.
    turbopackWorkerAssetPrefix: '',
  },
}
```

### Why?

When `assetPrefix` points to a cross-origin CDN (common production
setup), Turbopack emits Worker URLs under that CDN origin. Browsers
reject cross-origin `new Worker(url)` with `SecurityError`, breaking
every feature that uses `new Worker(new URL('./worker.ts',
import.meta.url))` — image decoders, WebP/GIF renderers, compression,
OffscreenCanvas, etc.

webpack solved this with `output.workerPublicPath`. Turbopack ignores
the `webpack()` callback in `next.config.js`, so the existing
same-origin workaround silently breaks when projects switch to
Turbopack.

Full design doc, alternatives considered, related issues (#88602,
#92676, #74621, #29468): **#93044**

Repro repo (`pnpm dev` reproduces, `pnpm dev:webpack` works):
https://github.com/GuinsooRocky/next-turbopack-worker-cdn-repro

### How?

Threads a new optional `turbopack_worker_asset_prefix: Option<RcStr>`
from `ExperimentalConfig` → `BrowserChunkingContext` → the JS runtime,
where `createWorker` reads it via a new `WORKER_BASE_PATH` global
emitted alongside the existing `CHUNK_BASE_PATH`. When unset, behavior
is identical to today.

Semantics, modeled on `assetPrefix`:

- **Bare prefix.** `/_next/` is appended automatically (same as
`computed_asset_prefix`); the user supplies just the origin (or empty
string for same-origin).
- **`undefined` vs `''`.** `undefined` falls back to the regular chunk
base path; `''` is a literal empty prefix that resolves to same-origin
`/_next/...`. The runtime distinguishes the two by injecting a JS `null`
literal vs a quoted string, and uses `WORKER_BASE_PATH ??
CHUNK_BASE_PATH` (not `||`).
- **Applies to entrypoint and module chunks.** The Turbopack worker
bootstrap rejects cross-origin module chunks (`Refusing to load script
from foreign origin`), so the override has to cover both — overriding
only the entrypoint would leave the worker unable to load any chunks
under a cross-origin `assetPrefix`.

Touchpoints:

- `packages/next/src/server/config-{shared,schema}.ts` — public option +
zod under `experimental`
- `crates/next-{api,core}/...` — wiring through to
`ClientChunkingContextOptions`;
`NextConfig::turbopack_worker_asset_prefix()` resolves to
`Some("<prefix>/_next/")` or `None`
- `turbopack/crates/turbopack-browser/src/chunking_context.rs` — new
field + builder + getter
- `turbopack/crates/turbopack-ecmascript-runtime/src/browser_runtime.rs`
— emit `WORKER_BASE_PATH` declaration as `null` or a quoted string
- `turbopack/.../runtime-base.ts` — `createWorker` resolves
`workerBasePath` and uses it for both the entrypoint URL and
module-chunk URLs delivered via params
- `test/e2e/turbopack-worker-asset-prefix/` — e2e fixture using real
cross-origin (`localhost` page, `127.0.0.1` `assetPrefix`); intercepts
`new Worker()` to assert on the URL the runtime helper resolved. Three
cases: no override (cross-origin URL → `SecurityError`), explicit
override origin, and `''` (relative `/_next/...`).
- `docs/01-app/03-api-reference/08-turbopack.mdx` — option reference
- `telemetry/events/version.ts` — `useTurbopackWorkerAssetPrefix:
boolean` (set on any explicit value, including empty string)

### Notes

- Opening as **Draft** to invite API-shape feedback before going to
review. Per the contributing guide, the design discussion is at #93044.
- All checklist items the PR template requires for a feature are
covered: e2e tests, docs, telemetry, no error-link path applies.

cc @sokra

Closes #93044

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent 8e4cfc50
......@@ -1589,6 +1589,7 @@ impl Project {
.next_config()
.turbo_nested_async_chunking(self.next_mode(), true),
debug_ids: self.next_config().turbopack_debug_ids(),
worker_asset_prefix: self.next_config().turbopack_worker_asset_prefix(),
should_use_absolute_url_references: self.next_config().inline_css(),
css_url_suffix,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
......
......@@ -477,6 +477,7 @@ pub struct ClientChunkingContextOptions {
pub scope_hoisting: Vc<bool>,
pub nested_async_chunking: Vc<bool>,
pub debug_ids: Vc<bool>,
pub worker_asset_prefix: Vc<Option<RcStr>>,
pub should_use_absolute_url_references: Vc<bool>,
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
......@@ -504,6 +505,7 @@ pub async fn get_client_chunking_context(
scope_hoisting,
nested_async_chunking,
debug_ids,
worker_asset_prefix,
should_use_absolute_url_references,
css_url_suffix,
hash_salt,
......@@ -544,6 +546,7 @@ pub async fn get_client_chunking_context(
.unused_references(unused_references.to_resolved().await?)
.module_id_strategy(module_id_strategy.to_resolved().await?)
.debug_ids(*debug_ids.await?)
.worker_asset_prefix(worker_asset_prefix.owned().await?)
.should_use_absolute_url_references(*should_use_absolute_url_references.await?)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals())
......
......@@ -1157,6 +1157,17 @@ pub struct ExperimentalConfig {
turbopack_input_source_maps: Option<bool>,
turbopack_tree_shaking: Option<bool>,
turbopack_scope_hoisting: Option<bool>,
/// Custom URL prefix for Web Worker URLs (the entrypoint and the module
/// chunks loaded inside the worker) produced by
/// `new Worker(new URL(..., import.meta.url))`. Mirrors webpack's
/// `output.workerPublicPath`. When unset, Worker URLs use the regular
/// chunk base path (i.e. `assetPrefix` + `/_next/`).
///
/// Like `assetPrefix`, the value is a prefix without a trailing slash
/// and without `/_next` — `/_next/` is appended automatically. An empty
/// string is a literal empty prefix; only `None` falls back to
/// `assetPrefix`.
turbopack_worker_asset_prefix: Option<RcStr>,
turbopack_client_side_nested_async_chunking: Option<bool>,
turbopack_server_side_nested_async_chunking: Option<bool>,
turbopack_import_type_bytes: Option<bool>,
......@@ -2273,6 +2284,18 @@ impl NextConfig {
)
}
/// Returns the resolved worker chunk base path with `/_next/` appended,
/// or `None` to fall back to the regular chunk base path.
#[turbo_tasks::function]
pub fn turbopack_worker_asset_prefix(&self) -> Vc<Option<RcStr>> {
Vc::cell(
self.experimental
.turbopack_worker_asset_prefix
.as_ref()
.map(|prefix| format!("{}/_next/", prefix.trim_end_matches('/')).into()),
)
}
#[turbo_tasks::function]
pub fn typescript_tsconfig_path(&self) -> Result<Vc<Option<RcStr>>> {
Ok(Vc::cell(
......
......@@ -362,6 +362,7 @@ export const experimentalSchema = {
turbopackRemoveUnusedImports: z.boolean().optional(),
turbopackRemoveUnusedExports: z.boolean().optional(),
turbopackScopeHoisting: z.boolean().optional(),
turbopackWorkerAssetPrefix: z.string().optional(),
turbopackClientSideNestedAsyncChunking: z.boolean().optional(),
turbopackServerSideNestedAsyncChunking: z.boolean().optional(),
turbopackImportTypeBytes: z.boolean().optional(),
......
......@@ -674,6 +674,37 @@ export interface ExperimentalConfig {
*/
turbopackScopeHoisting?: boolean
/**
* (`next --turbopack` only) A custom URL prefix for Web Worker URLs
* produced by `new Worker(new URL(..., import.meta.url))` — both the
* entrypoint URL and the module chunks loaded inside the worker —
* overriding `assetPrefix` for those URLs.
*
* Use this when `assetPrefix` points to a cross-origin CDN: browsers
* reject cross-origin Worker construction, so the entrypoint must stay
* same-origin. Module chunks loaded inside the worker are also routed
* through this prefix because the worker bootstrap requires them to be
* same-origin with the entrypoint. Mirrors webpack's
* `output.workerPublicPath`.
*
* Like `assetPrefix`, the value is a prefix without a trailing slash and
* without `/_next` — `/_next/` is appended automatically. An empty
* string is treated as a literal empty prefix (resulting in same-origin
* `/_next/...` URLs); only `undefined` falls back to `assetPrefix`.
*
* @example
* ```js
* // next.config.js
* module.exports = {
* assetPrefix: 'https://cdn.example.com',
* experimental: {
* turbopackWorkerAssetPrefix: '',
* },
* }
* ```
*/
turbopackWorkerAssetPrefix?: string
/**
* Enable nested async chunking for client side assets. Defaults to true in build mode and false in dev mode.
* This optimization computes all possible paths through dynamic imports in the applications to figure out the modules needed at dynamic imports for every path.
......
......@@ -32,6 +32,7 @@ type EventCliSessionStarted = {
reactStrictMode: boolean
webpackVersion: number | null
turboFlag: boolean
useTurbopackWorkerAssetPrefix: boolean
isRspack: boolean
appDir: boolean | null
pagesDir: boolean | null
......@@ -77,6 +78,7 @@ export function eventCliSession(
| 'reactCompilerPanicThreshold'
| 'isRspack'
| 'adapterPath'
| 'useTurbopackWorkerAssetPrefix'
>
): { eventName: string; payload: EventCliSessionStarted }[] {
// This should be an invariant, if it fails our build tooling is broken.
......@@ -120,6 +122,8 @@ export function eventCliSession(
reactStrictMode: !!nextConfig?.reactStrictMode,
webpackVersion: event.webpackVersion || null,
turboFlag: event.turboFlag || false,
useTurbopackWorkerAssetPrefix:
nextConfig?.experimental?.turbopackWorkerAssetPrefix !== undefined,
isRspack: process.env.NEXT_RSPACK !== undefined,
appDir: event.appDir,
pagesDir: event.pagesDir,
......
'use client'
import { useEffect, useState } from 'react'
const NONE = '(none)'
export default function ClientComponent() {
const [pageOrigin, setPageOrigin] = useState<string>(NONE)
const [workerCtorUrl, setWorkerCtorUrl] = useState<string>(NONE)
const [workerCtorError, setWorkerCtorError] = useState<string>(NONE)
useEffect(() => {
setPageOrigin(window.location.origin)
// Capture the URL the Worker constructor receives (computed by the
// turbopack runtime helper from `turbopackWorkerAssetPrefix`), so the
// test can assert on it. Browsers reject cross-origin Worker URLs
// synchronously, so we surface that too.
const OriginalWorker = window.Worker
;(window as any).Worker = function PatchedWorker(
url: URL | string,
options?: object
) {
const urlString = typeof url === 'string' ? url : url.toString()
setWorkerCtorUrl(urlString)
try {
return new OriginalWorker(url, options)
} catch (err) {
setWorkerCtorError(err instanceof Error ? err.name : String(err))
throw err
}
}
try {
// Trigger the turbopack `new Worker(new URL(..., import.meta.url))`
// pattern. Result is intercepted by the patched Worker above.
new Worker(new URL('./worker.ts', import.meta.url))
} catch {
// Already captured by the patched constructor; React state will
// reflect it on the next render.
}
;(window as any).Worker = OriginalWorker
}, [])
return (
<>
<p>page origin:</p>
<pre id="page-origin">{pageOrigin}</pre>
<p>URL passed to the Worker constructor (from runtime helper):</p>
<pre id="worker-ctor-url">{workerCtorUrl}</pre>
<p>Worker constructor error (if any):</p>
<pre id="worker-ctor-error">{workerCtorError}</pre>
</>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import ClientComponent from './client'
export default function Page() {
return <ClientComponent />
}
// Post back the worker's own origin so the main thread can verify whether the
// worker entrypoint was loaded same-origin or cross-origin.
self.postMessage(self.location.origin)
import { createNext, isNextDeploy } from 'e2e-utils'
import type { NextInstance } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
// `experimental.turbopackWorkerAssetPrefix` is turbopack-only.
const isTurbopack = !process.env.IS_WEBPACK_TEST
const describeTurbopack =
isTurbopack && !isNextDeploy ? describe : describe.skip
// CORS so cross-origin script tags from `assetPrefix` can be fetched. Workers
// are NOT covered by CORS — `new Worker(crossOriginUrl)` is rejected
// regardless — so this only unblocks regular script loading.
const corsHeaders = () => ({
async headers() {
return [
{
source: '/:path*',
headers: [{ key: 'Access-Control-Allow-Origin', value: '*' }],
},
]
},
})
/**
* Real cross-origin setup: the page is served at `http://localhost:PORT/`,
* `assetPrefix` points to `http://127.0.0.1:PORT` (different origin —
* browsers treat `localhost` and `127.0.0.1` as distinct origins). Both
* resolve to the same Next.js server bound to all interfaces.
*
* The fixture intercepts `new Worker()` to capture the URL the turbopack
* runtime helper resolved from `turbopackWorkerAssetPrefix`, so each test
* can assert on that URL directly.
*/
describeTurbopack('turbopack-worker-asset-prefix', () => {
describe('without turbopackWorkerAssetPrefix (cross-origin assetPrefix)', () => {
let next: NextInstance
let forcedPort: string
beforeAll(async () => {
forcedPort = String((await findPort()) ?? '54321')
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://127.0.0.1:${forcedPort}`,
...corsHeaders(),
},
})
})
afterAll(() => next.destroy())
it('Worker URL inherits assetPrefix and the browser rejects construction', async () => {
const browser = await next.browser('/')
await retry(async () => {
const url = await browser.elementByCss('#worker-ctor-url').text()
expect(url).toContain('http://127.0.0.1:')
expect(url).toContain(`:${forcedPort}/`)
})
// Cross-origin Worker construction throws SecurityError synchronously.
await retry(async () => {
const error = await browser.elementByCss('#worker-ctor-error').text()
expect(error).toBe('SecurityError')
})
})
})
describe('with turbopackWorkerAssetPrefix overriding assetPrefix', () => {
let next: NextInstance
let forcedPort: string
beforeAll(async () => {
forcedPort = String((await findPort()) ?? '54322')
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://127.0.0.1:${forcedPort}`,
experimental: {
// Route Worker URLs through the page's own origin
// (`http://localhost:PORT`) instead of the cross-origin assetPrefix.
turbopackWorkerAssetPrefix: `http://localhost:${forcedPort}`,
},
...corsHeaders(),
},
})
})
afterAll(() => next.destroy())
it('Worker URL uses the override origin and construction succeeds', async () => {
const browser = await next.browser('/')
await retry(async () => {
const pageOrigin = await browser.elementByCss('#page-origin').text()
const url = await browser.elementByCss('#worker-ctor-url').text()
expect(pageOrigin).toBe(`http://localhost:${forcedPort}`)
expect(url.startsWith(pageOrigin)).toBe(true)
expect(url).not.toContain('127.0.0.1')
})
const error = await browser.elementByCss('#worker-ctor-error').text()
expect(error).toBe('(none)')
})
})
describe('with turbopackWorkerAssetPrefix: "" (literal empty prefix)', () => {
let next: NextInstance
let forcedPort: string
beforeAll(async () => {
forcedPort = String((await findPort()) ?? '54323')
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://127.0.0.1:${forcedPort}`,
experimental: {
// Empty string is a literal empty prefix (only `/_next/` is
// appended). It does NOT fall back to assetPrefix — only
// `undefined` does.
turbopackWorkerAssetPrefix: '',
},
...corsHeaders(),
},
})
})
afterAll(() => next.destroy())
it('Worker URL is a relative /_next/ URL (resolved same-origin)', async () => {
const browser = await next.browser('/')
await retry(async () => {
const pageOrigin = await browser.elementByCss('#page-origin').text()
const url = await browser.elementByCss('#worker-ctor-url').text()
expect(pageOrigin).toBe(`http://localhost:${forcedPort}`)
// URL passed to `new Worker(...)` lives on the page's origin, not
// assetPrefix. (Internally the runtime resolves the relative
// `/_next/...` against `location.origin`.)
expect(url.startsWith(pageOrigin)).toBe(true)
expect(url).not.toContain('127.0.0.1')
})
const error = await browser.elementByCss('#worker-ctor-error').text()
expect(error).toBe('(none)')
})
})
})
......@@ -103,6 +103,11 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn worker_asset_prefix(mut self, worker_asset_prefix: Option<RcStr>) -> Self {
self.chunking_context.worker_asset_prefix = worker_asset_prefix;
self
}
pub fn asset_suffix(mut self, asset_suffix: ResolvedVc<AssetSuffix>) -> Self {
self.chunking_context.asset_suffix = Some(asset_suffix);
self
......@@ -267,6 +272,14 @@ pub struct BrowserChunkingContext {
/// Base path that will be prepended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
chunk_base_path: Option<RcStr>,
/// Base path for Web Worker URLs (the entrypoint and the module chunks
/// loaded inside the worker). When `Some`, overrides `chunk_base_path`
/// for those URLs. Mirrors webpack's `output.workerPublicPath`. Primary
/// use case: keep Worker URLs same-origin when
/// `chunk_base_path`/`assetPrefix` points to a cross-origin CDN
/// (browsers reject cross-origin Worker construction, and the worker
/// bootstrap rejects cross-origin module chunks).
worker_asset_prefix: Option<RcStr>,
/// Suffix that will be appended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
asset_suffix: Option<ResolvedVc<AssetSuffix>>,
......@@ -355,6 +368,7 @@ impl BrowserChunkingContext {
asset_root_path,
asset_root_paths: Default::default(),
chunk_base_path: None,
worker_asset_prefix: None,
asset_suffix: None,
asset_base_path: None,
asset_base_paths: Default::default(),
......@@ -469,6 +483,14 @@ impl BrowserChunkingContext {
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.
#[turbo_tasks::function]
pub fn asset_suffix(&self) -> Vc<AssetSuffix> {
......
......@@ -179,6 +179,7 @@ impl EcmascriptBrowserEvaluateChunk {
let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code(
asset_context,
this.chunking_context.chunk_base_path(),
this.chunking_context.worker_asset_prefix(),
this.chunking_context.asset_suffix(),
this.chunking_context.worker_forwarded_globals(),
runtime_type,
......
......@@ -20,6 +20,18 @@ declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined
// Injected by rust code
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 CROSS_ORIGIN: 'anonymous' | 'use-credentials' | null
declare var WORKER_FORWARDED_GLOBALS: string[]
......@@ -312,15 +324,24 @@ function createWorker(
): 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))
.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), location.origin)
const url = new URL(
getChunkRelativeUrl(entrypoint, workerBasePath),
location.origin
)
const paramsJson = JSON.stringify(params)
if (isSharedWorker) {
url.searchParams.set('params', paramsJson)
......@@ -348,8 +369,11 @@ function instantiateRuntimeModule(
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/
function getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {
return `${CHUNK_BASE_PATH}${chunkPath
function getChunkRelativeUrl(
chunkPath: ChunkPath | ChunkListPath,
basePath: string = CHUNK_BASE_PATH
): ChunkUrl {
return `${basePath}${chunkPath
.split('/')
.map((p) => encodeURIComponent(p))
.join('/')}${ASSET_SUFFIX}` as ChunkUrl
......
......@@ -19,6 +19,7 @@ use crate::{RuntimeType, embed_js::embed_static_code};
pub async fn get_browser_runtime_code(
asset_context: ResolvedVc<Box<dyn AssetContext>>,
chunk_base_path: Vc<Option<RcStr>>,
worker_asset_prefix: Vc<Option<RcStr>>,
asset_suffix: Vc<AssetSuffix>,
worker_forwarded_globals: Vc<Vec<RcStr>>,
runtime_type: RuntimeType,
......@@ -86,6 +87,14 @@ pub async fn get_browser_runtime_code(
let relative_root_path = output_root_to_root_path;
let chunk_base_path = chunk_base_path.await?;
let chunk_base_path = chunk_base_path.as_ref().map_or_else(|| "", |f| f.as_str());
// `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 chunk_loading_global = chunk_loading_global.await?;
let cross_origin = *cross_origin.await?;
......@@ -109,11 +118,13 @@ pub async fn get_browser_runtime_code(
}}
var CHUNK_BASE_PATH = {};
var WORKER_BASE_PATH = {};
var RELATIVE_ROOT_PATH = {};
var RUNTIME_PUBLIC_PATH = {};
"#,
StringifyJs(&chunk_loading_global),
StringifyJs(chunk_base_path),
worker_asset_prefix_js,
StringifyJs(relative_root_path.as_str()),
StringifyJs(chunk_base_path),
)?;
......
;!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]="6a138f62-859e-e13c-84a0-d111b048d46a")}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]="63d3116b-6e4c-29e3-253a-989477151583")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"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)"]}
......@@ -9,6 +9,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -748,7 +749,12 @@ browserContextPrototype.q = exportUrl;
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
// `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
......@@ -756,7 +762,7 @@ browserContextPrototype.q = exportUrl;
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -778,8 +784,8 @@ browserContextPrototype.b = createWorker;
}
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......@@ -2247,5 +2253,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=6a138f62-859e-e13c-84a0-d111b048d46a
//# debugId=63d3116b-6e4c-29e3-253a-989477151583
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map
\ No newline at end of file
......@@ -8,6 +8,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -747,7 +748,12 @@ browserContextPrototype.q = exportUrl;
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
// `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
......@@ -755,7 +761,7 @@ browserContextPrototype.q = exportUrl;
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -777,8 +783,8 @@ browserContextPrototype.b = createWorker;
}
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......
......@@ -8,6 +8,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -1297,8 +1298,13 @@ browserContextPrototype.q = exportUrl;
* @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);
return getChunkRelativeUrl(chunk, workerBasePath);
}).reverse();
var params = [
chunkUrls,
......@@ -1324,7 +1330,7 @@ browserContextPrototype.q = exportUrl;
}
}
}
var url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
var url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
var paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -1346,7 +1352,8 @@ browserContextPrototype.b = createWorker;
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map(function(p) {
var basePath = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : CHUNK_BASE_PATH;
return `${basePath}${chunkPath.split('/').map(function(p) {
return encodeURIComponent(p);
}).join('/')}${ASSET_SUFFIX}`;
}
......
......@@ -8,6 +8,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -747,7 +748,12 @@ browserContextPrototype.q = exportUrl;
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
// `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
......@@ -755,7 +761,7 @@ browserContextPrototype.q = exportUrl;
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -777,8 +783,8 @@ browserContextPrototype.b = createWorker;
}
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......
......@@ -8,6 +8,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -747,7 +748,12 @@ browserContextPrototype.q = exportUrl;
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
// `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
......@@ -755,7 +761,7 @@ browserContextPrototype.q = exportUrl;
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -777,8 +783,8 @@ browserContextPrototype.b = createWorker;
}
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......
......@@ -8,6 +8,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -747,7 +748,12 @@ browserContextPrototype.q = exportUrl;
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
// `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
......@@ -755,7 +761,7 @@ browserContextPrototype.q = exportUrl;
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -777,8 +783,8 @@ browserContextPrototype.b = createWorker;
}
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......
......@@ -8,6 +8,7 @@ if (!Array.isArray(globalThis["TURBOPACK"])) {
}
var CHUNK_BASE_PATH = "";
var WORKER_BASE_PATH = null;
var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = "";
......@@ -747,7 +748,12 @@ browserContextPrototype.q = exportUrl;
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
// `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
......@@ -755,7 +761,7 @@ browserContextPrototype.q = exportUrl;
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const url = new URL(getChunkRelativeUrl(entrypoint, workerBasePath), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
......@@ -777,8 +783,8 @@ browserContextPrototype.b = createWorker;
}
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
*/ function getChunkRelativeUrl(chunkPath, basePath = CHUNK_BASE_PATH) {
return `${basePath}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${ASSET_SUFFIX}`;
}
function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') {
......
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