Commit e5cff26b authored by Jimmy Lai's avatar Jimmy Lai

Add retry logic for chunk load errors

parent 42493fb3
......@@ -973,5 +973,6 @@
"972": "Failed to resolve pattern \"%s\": %s",
"973": "Server Actions are not enabled for this application. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"974": "Failed to find Server Action%s. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action"
"975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"976": "Chunk load failed after retry attempts"
}
/**
* Chunk load error handling with silent retry logic.
*
* This module provides retry orchestration for chunk/network loading failures.
* It tracks failures in sessionStorage per {route, buildId, chunkKey} and
* implements silent retry with jittered backoff.
*/
import { getAppBuildId } from '../../app-build-id'
import { isChunkLoadError, isNetworkError } from './is-chunk-load-error'
// Bundler-specific chunk cache clearing globals
declare global {
var __turbopack_clear_chunk_resolver__:
| ((chunkUrl: string) => void)
| undefined
}
/**
* Context for chunk error handling.
* Tracks where the error occurred and what kind of error it was.
*/
export interface ChunkErrorContext {
/** The current route/pathname */
route: string
/** Whether this error is blocking a user-visible operation (navigation, render) */
userVisible: boolean
/** Error message for generating chunk key */
message: string
/** URL of the failed chunk if extractable */
chunkUrl?: string
}
interface FailureState {
failCount: number
lastTs: number
retriedTs?: number
}
const STORAGE_PREFIX = '__next_chunk_fail:'
const RETRY_WINDOW_MS = 30_000 // Don't retry same chunk within 30s of a retry
const MAX_FAIL_COUNT_FOR_RETRY = 2 // After 2 failures, skip silent retry
/**
* Simple hash function for generating chunk keys when URL isn't available.
*/
function simpleHash(str: string): string {
let hash = 0
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
hash = ((hash << 5) - hash + char) | 0
}
return Math.abs(hash).toString(36)
}
/**
* Extract chunk URL from error message if possible.
* ChunkLoadError messages typically contain the URL.
*/
function extractChunkUrl(error: Error): string | undefined {
const message = error.message
// Turbopack format: "Failed to load chunk <url> from <reason>: <cause>"
// The URL can be relative (/_next/...) or absolute (http://...)
const turbopackMatch = message.match(
/Failed to load chunk ([^\s]+\.(?:js|css))/
)
if (turbopackMatch) {
return turbopackMatch[1]
}
// Webpack format: "Loading chunk <id> failed. (error: <url>)"
// Match absolute URLs (http/https), protocol-relative URLs, and relative URLs
const webpackMatch = message.match(
/(?:https?:)?\/\/[^\s)]+|\/[^\s)]+\.(?:js|css)/
)
return webpackMatch?.[0]
}
/**
* Clear the bundler's chunk cache so retry will fetch fresh.
*
* Note: Webpack automatically clears failed loads from installedChunks
* (sets to undefined on failure), so no clearing needed there.
* Turbopack caches rejected promises and needs explicit clearing.
*
* @param error - The chunk load error
* @returns true if cache was cleared, false otherwise
*/
export function clearChunkCache(error: Error): boolean {
const chunkUrl = extractChunkUrl(error)
if (!chunkUrl) return false
// Turbopack: clear by chunk URL
// (Webpack doesn't need this - it clears installedChunks[chunkId] = undefined on failure)
if (typeof globalThis.__turbopack_clear_chunk_resolver__ === 'function') {
// Extract the relative URL path that Turbopack uses as key
try {
const url = new URL(chunkUrl)
globalThis.__turbopack_clear_chunk_resolver__(url.pathname + url.search)
return true
} catch {
// Invalid URL, try using the full URL
globalThis.__turbopack_clear_chunk_resolver__(chunkUrl)
return true
}
}
return false
}
/**
* Generate a unique key for this chunk error, used for deduplication.
*/
function getChunkKey(ctx: ChunkErrorContext): string {
return ctx.chunkUrl ?? simpleHash(ctx.message)
}
/**
* Get the sessionStorage key for tracking this chunk failure.
*/
function getStorageKey(ctx: ChunkErrorContext): string {
const buildId = getAppBuildId()
const chunkKey = getChunkKey(ctx)
return `${STORAGE_PREFIX}${buildId}:${ctx.route}:${chunkKey}`
}
/**
* Read failure state from sessionStorage.
*/
function readFailureState(key: string): FailureState | null {
if (typeof sessionStorage === 'undefined') return null
try {
const stored = sessionStorage.getItem(key)
if (!stored) return null
return JSON.parse(stored) as FailureState
} catch {
return null
}
}
/**
* Write failure state to sessionStorage.
*/
function writeFailureState(key: string, state: FailureState): void {
if (typeof sessionStorage === 'undefined') return
try {
sessionStorage.setItem(key, JSON.stringify(state))
} catch {
// Storage might be full or disabled - continue without tracking
}
}
/**
* Clear failure state for a route (called on successful navigation).
*/
export function clearFailureState(route: string): void {
if (typeof sessionStorage === 'undefined') return
try {
const buildId = getAppBuildId()
const prefix = `${STORAGE_PREFIX}${buildId}:${route}:`
const keysToRemove: string[] = []
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i)
if (key?.startsWith(prefix)) {
keysToRemove.push(key)
}
}
keysToRemove.forEach((key) => sessionStorage.removeItem(key))
} catch {
// Ignore storage errors
}
}
/**
* Increment the failure count for this chunk.
*/
function bumpFailCount(ctx: ChunkErrorContext): FailureState {
const key = getStorageKey(ctx)
const existing = readFailureState(key)
const now = Date.now()
const state: FailureState = {
failCount: (existing?.failCount ?? 0) + 1,
lastTs: now,
retriedTs: existing?.retriedTs,
}
writeFailureState(key, state)
return state
}
/**
* Mark that a retry was attempted for this chunk.
*/
function markRetried(ctx: ChunkErrorContext): void {
const key = getStorageKey(ctx)
const existing = readFailureState(key)
const now = Date.now()
const state: FailureState = {
failCount: existing?.failCount ?? 1,
lastTs: existing?.lastTs ?? now,
retriedTs: now,
}
writeFailureState(key, state)
}
/**
* Check if we should attempt a silent retry for this chunk error.
*/
export function shouldSilentRetry(ctx: ChunkErrorContext): boolean {
// Don't retry if offline
if (typeof navigator !== 'undefined' && !navigator.onLine) {
return false
}
const key = getStorageKey(ctx)
const state = readFailureState(key)
const now = Date.now()
// If we already retried within the window, don't retry again
if (state?.retriedTs && now - state.retriedTs < RETRY_WINDOW_MS) {
return false
}
// Too many failures - skip silent retry to avoid annoying the user
if ((state?.failCount ?? 0) >= MAX_FAIL_COUNT_FOR_RETRY) {
return false
}
return true
}
/**
* Get the failure count for this chunk (for showing "hard refresh" hint).
*/
export function getFailCount(ctx: ChunkErrorContext): number {
const key = getStorageKey(ctx)
const state = readFailureState(key)
return state?.failCount ?? 0
}
/**
* Calculate retry delay with jitter based on RTT.
* Returns delay in milliseconds: 200 + random(0-400) + min(500, RTT)
*/
export function getRetryDelayMs(): number {
const baseDelay = 200
const jitter = Math.floor(Math.random() * 401) // 0-400ms
// Get RTT if available via Network Information API
let rtt = 0
if (typeof navigator !== 'undefined' && 'connection' in navigator) {
const connection = (navigator as any).connection
if (connection?.rtt) {
rtt = Math.min(500, connection.rtt) // Cap at 500ms
}
}
return Math.min(1500, baseDelay + jitter + rtt) // Cap total at 1500ms
}
/**
* Sleep for a given number of milliseconds.
*/
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* Create a ChunkErrorContext from an error.
*/
export function createChunkErrorContext(
error: Error,
route: string,
userVisible: boolean = true
): ChunkErrorContext | null {
if (!isChunkLoadError(error) && !isNetworkError(error)) {
return null
}
return {
route,
userVisible,
message: error.message,
chunkUrl: extractChunkUrl(error),
}
}
/**
* Handle a chunk load failure and determine if we should retry.
*
* Returns true if a silent retry should be attempted, false otherwise.
* This function updates the failure tracking state.
*/
export function handleChunkFailure(ctx: ChunkErrorContext): boolean {
// Don't count offline failures toward retry limit - they're expected
// and will succeed once connectivity is restored
if (typeof navigator !== 'undefined' && !navigator.onLine) {
return false
}
// Record failure for online attempts
bumpFailCount(ctx)
// Check if we should try a silent retry
if (shouldSilentRetry(ctx)) {
markRetried(ctx)
return true
}
return false
}
/**
* Attempt to retry a failed chunk import.
*
* @param ctx - The chunk error context
* @param importFn - The function that performs the import
* @returns The result of the import, or throws if retry also fails
*/
export async function retryChunkImport<T>(
ctx: ChunkErrorContext,
importFn: () => Promise<T>
): Promise<T> {
const shouldRetry = handleChunkFailure(ctx)
if (shouldRetry) {
const delay = getRetryDelayMs()
await sleep(delay)
return importFn()
}
// If we shouldn't retry, re-throw to trigger error boundary
throw new Error('Chunk load failed after retry attempts')
}
/**
* Utilities for detecting chunk load errors and network failures.
*
* ChunkLoadError can come from:
* - Turbopack: error.name === 'ChunkLoadError'
* - Webpack: error.name === 'ChunkLoadError'
*
* We intentionally keep detection narrow to avoid false positives:
* - Server 4xx/5xx responses don't throw (they return Response objects)
* - We should NOT retry CORS errors, AbortErrors, or parsing failures
*/
/**
* Detects if an error is a ChunkLoadError from Turbopack or webpack.
* This is the most reliable check - both bundlers explicitly set this error name.
*/
export function isChunkLoadError(error: unknown): error is Error {
if (!error || typeof error !== 'object') return false
return (error as Error).name === 'ChunkLoadError'
}
/**
* Detects network-level fetch failures that are worth retrying.
*
* We're intentionally conservative here to avoid retrying errors that won't benefit:
* - AbortError: Intentional cancellation, should not retry
* - CORS errors: Configuration issue, retry won't help
* - Server errors: These don't throw (return Response), but if they did, retry might not help
*
* We only catch errors that indicate the network request itself failed,
* not errors from processing the response.
*/
export function isNetworkError(error: unknown): error is Error {
if (!error || typeof error !== 'object') return false
const err = error as Error
// Never retry intentional aborts
if (err.name === 'AbortError') return false
// TypeError with specific fetch failure messages
// These occur when the network request itself fails (not CORS, not server error)
if (err.name === 'TypeError') {
const message = err.message || ''
// Browser-specific network failure messages
// Chrome/Edge: "Failed to fetch"
// Firefox: "NetworkError when attempting to fetch resource"
// Safari: "Load failed" or "The Internet connection appears to be offline"
if (
message === 'Failed to fetch' ||
message.startsWith('NetworkError when attempting to fetch') ||
message === 'Load failed' ||
message.includes('Internet connection appears to be offline') ||
message.includes('network connection was lost')
) {
return true
}
}
return false
}
/**
* Returns true if the error is a chunk load or network error worth retrying.
*/
export function isChunkOrNetworkError(error: unknown): boolean {
return isChunkLoadError(error) || isNetworkError(error)
}
......@@ -26,6 +26,13 @@ import {
NEXT_HTML_REQUEST_ID_HEADER,
NEXT_REQUEST_ID_HEADER,
} from '../app-router-headers'
import { isChunkOrNetworkError } from '../chunk-load-error/is-chunk-load-error'
import {
createChunkErrorContext,
handleChunkFailure,
getRetryDelayMs,
sleep,
} from '../chunk-load-error/chunk-load-error-handler'
import { callServer } from '../../app-call-server'
import { findSourceMapURL } from '../../app-find-source-map-url'
import {
......@@ -264,6 +271,44 @@ export async function fetchServerResponse(
debugInfo: flightResponsePromise._debugInfo ?? null,
}
} catch (err) {
// Check if this is a chunk/network error that we can retry
if (
err instanceof Error &&
isChunkOrNetworkError(err) &&
!isPageUnloading
) {
const ctx = createChunkErrorContext(
err,
originalUrl.pathname,
true // user-visible navigation
)
if (ctx) {
// handleChunkFailure updates failure tracking and returns whether to retry
const shouldRetry = handleChunkFailure(ctx)
if (shouldRetry) {
// Silent retry with jittered delay
const delay = getRetryDelayMs()
await sleep(delay)
try {
// Retry the fetch once (use originalUrl to ensure consistent error tracking)
return await fetchServerResponse(originalUrl, options)
} catch (retryErr) {
// Retry failed, fall through to MPA navigation
if (!isPageUnloading) {
console.error(
`Retry failed for RSC payload ${originalUrl}. Falling back to browser navigation.`,
retryErr
)
}
return originalUrl.toString()
}
}
}
}
if (!isPageUnloading) {
console.error(
`Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,
......
......@@ -30,6 +30,7 @@ import {
convertServerPatchToFullTree,
type NavigationSeed,
} from '../segment-cache/navigation'
import { clearFailureState } from '../chunk-load-error/chunk-load-error-handler'
// This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of
......@@ -1302,6 +1303,9 @@ async function finishNavigationTask(
case NavigationTaskExitStatus.Done: {
// The task has completely finished. There's no missing data. Exit.
previousNavigationDidMismatch = false
// Clear failure state for the successfully navigated route
const primaryRequestResult = await primaryRequestPromise
clearFailureState(primaryRequestResult.url.pathname)
return
}
case NavigationTaskExitStatus.SoftRetry: {
......
......@@ -2,6 +2,11 @@ import { Suspense, Fragment, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types'
import { PreloadChunks } from './preload-chunks'
import { isChunkLoadError } from '../../../client/components/chunk-load-error/is-chunk-load-error'
import {
clearChunkCache,
getRetryDelayMs,
} from '../../../client/components/chunk-load-error/chunk-load-error-handler'
// Normalize loader to return the module as form { default: Component } for `React.lazy`.
// Also for backward compatible since next/dynamic allows to resolve a component directly with loader
......@@ -25,6 +30,40 @@ function convertModule<P>(
}
}
/**
* Creates a loader function with automatic retry for chunk load errors.
* On first failure, clears the bundler cache and retries after a delay.
*/
function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> {
let hasRetried = false
return () =>
loader().catch((err) => {
// Only retry chunk load errors, and only once
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
!hasRetried
) {
hasRetried = true
// Clear bundler's chunk cache so retry will fetch fresh
clearChunkCache(err)
// Retry after a short delay with jitter
return new Promise<T>((resolve, reject) => {
const delay = getRetryDelayMs()
setTimeout(() => {
loader().then(resolve, reject)
}, delay)
})
}
// No retry - propagate error
throw err
})
}
const defaultOptions = {
loader: () => Promise.resolve(convertModule(() => null)),
loading: null,
......@@ -40,7 +79,11 @@ interface LoadableOptions {
function Loadable(options: LoadableOptions) {
const opts = { ...defaultOptions, ...options }
const Lazy = lazy(() => opts.loader().then(convertModule))
// Wrap loader with retry logic for chunk load errors (client-side only)
const retryableLoader = createRetryableLoader(() =>
opts.loader().then(convertModule)
)
const Lazy = lazy(retryableLoader)
const Loading = opts.loading
function LoadableComponent(props: any) {
......
......@@ -24,6 +24,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import React from 'react'
import { LoadableContext } from './loadable-context.shared-runtime'
import { isChunkLoadError } from '../../client/components/chunk-load-error/is-chunk-load-error'
import {
clearChunkCache,
getRetryDelayMs,
} from '../../client/components/chunk-load-error/chunk-load-error-handler'
function resolve(obj: any) {
return obj && obj.default ? obj.default : obj
......@@ -167,12 +172,14 @@ class LoadableSubscription {
_timeout: any
_res: any
_state: any
_hasAutoRetried: boolean
constructor(loadFn: any, opts: any) {
this._loadFn = loadFn
this._opts = opts
this._callbacks = new Set()
this._delay = null
this._timeout = null
this._hasAutoRetried = false
this.retry()
}
......@@ -217,7 +224,28 @@ class LoadableSubscription {
this._update({})
this._clearTimeouts()
})
.catch((_err: any) => {
.catch((err: any) => {
// Auto-retry for chunk load errors (once)
// This handles transient network failures during dynamic imports
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
!this._hasAutoRetried
) {
this._hasAutoRetried = true
// Clear bundler's chunk cache so retry will fetch fresh
clearChunkCache(err)
// Retry after a short delay with jitter
const delay = getRetryDelayMs()
setTimeout(() => {
this.retry()
}, delay)
return
}
// No more retries - propagate error
this._update({})
this._clearTimeouts()
})
......
'use client'
import dynamic from 'next/dynamic'
const LazyComponent = dynamic(() => import('../../components/lazy-component'), {
loading: () => <div data-testid="loading">Loading...</div>,
ssr: false,
})
export default function DynamicPage() {
return (
<main>
<h1>Dynamic Page</h1>
<LazyComponent />
</main>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<main>
<h1>Chunk Load Retry Test</h1>
<nav>
<Link href="/dynamic">Go to dynamic page</Link>
</nav>
</main>
)
}
import { nextTestSetup } from 'e2e-utils'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import path from 'path'
import fs from 'fs'
import { retry } from 'next-test-utils'
describe('chunk-load-retry', () => {
const { next } = nextTestSetup({
files: __dirname,
})
/**
* Find the chunk file that contains the lazy component
*/
async function getLazyComponentChunk() {
const chunksPath = path.join(next.testDir, '.next/static/')
const browserChunks = await recursiveReadDir(chunksPath, {
pathnameFilter: (f) => /\.js$/.test(f),
})
const lazyChunks = browserChunks.filter((f) =>
fs
.readFileSync(path.join(chunksPath, f), 'utf8')
.includes('CHUNK_LOAD_RETRY_TEST_MARKER')
)
expect(lazyChunks).toHaveLength(1)
return lazyChunks[0]
}
describe('Automatic Retry', () => {
it('should retry chunk load and succeed when first request fails but second succeeds', async () => {
const lazyChunk = await getLazyComponentChunk()
let requestCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
// Fail the first request, allow the second
page.route('**/' + lazyChunk, async (route) => {
requestCount++
if (requestCount === 1) {
// First request fails
await route.abort('connectionreset')
} else {
// Second request succeeds (retry)
await route.continue()
}
})
},
})
// Should eventually show the lazy component after retry
await retry(async () => {
const lazyComponent = await browser.elementByCss(
'[data-testid="lazy-component"]'
)
expect(await lazyComponent.text()).toContain(
'CHUNK_LOAD_RETRY_TEST_MARKER'
)
})
// Verify that retry actually happened (2 requests: 1 failed + 1 succeeded)
expect(requestCount).toBe(2)
})
it('should propagate error when both initial and retry requests fail', async () => {
const lazyChunk = await getLazyComponentChunk()
let pageError: Error | undefined
let requestCount = 0
const _browser = await next.browser('/dynamic', {
beforePageLoad(page) {
// Fail all requests
page.route('**/' + lazyChunk, async (route) => {
requestCount++
await route.abort('connectionreset')
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
// Wait for the error to occur
await retry(async () => {
expect(pageError).toBeDefined()
})
// Verify the error is a ChunkLoadError
expect(pageError!.name).toBe('ChunkLoadError')
// Verify that retry was attempted (at least 2 requests: initial + retry)
expect(requestCount).toBeGreaterThanOrEqual(2)
})
it('should not retry more than once per loader', async () => {
const lazyChunk = await getLazyComponentChunk()
let requestCount = 0
await next.browser('/dynamic', {
beforePageLoad(page) {
// Fail all requests
page.route('**/' + lazyChunk, async (route) => {
requestCount++
await route.abort('connectionreset')
})
},
})
// Wait a bit for all retries to complete
await new Promise((resolve) => setTimeout(resolve, 3000))
// Should only have 2 requests: initial + one retry
// (retry logic only retries once per loader instance)
expect(requestCount).toBe(2)
})
})
describe('Cache Clearing', () => {
it('should clear chunk cache before retry to allow fresh fetch', async () => {
const lazyChunk = await getLazyComponentChunk()
let requestCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
// Fail the first request, allow subsequent
page.route('**/' + lazyChunk, async (route) => {
requestCount++
if (requestCount === 1) {
await route.abort('connectionreset')
} else {
await route.continue()
}
})
},
})
// Should eventually load after retry
await retry(async () => {
const lazyComponent = await browser.elementByCss(
'[data-testid="lazy-component"]'
)
expect(await lazyComponent.text()).toContain(
'CHUNK_LOAD_RETRY_TEST_MARKER'
)
})
// The second request proves the cache was cleared,
// otherwise webpack would return the cached rejected promise
expect(requestCount).toBe(2)
})
})
})
'use client'
// Marker for finding the chunk in tests
const COMPONENT_MARKER = 'CHUNK_LOAD_RETRY_TEST_MARKER'
export default function LazyComponent() {
return (
<div data-testid="lazy-component">
<p>This is a lazy loaded async component - {COMPONENT_MARKER}</p>
</div>
)
}
/** @type {import('next').NextConfig} */
const nextConfig = {}
export default nextConfig
......@@ -93,6 +93,11 @@ interface RuntimeBackend {
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
) => Promise<WebAssembly.Module>
/**
* Clears a failed chunk resolver so it can be retried.
* Used by Next.js for chunk load error retry logic.
*/
clearChunkResolver?: (chunkUrl: ChunkUrl) => void
}
interface DevRuntimeBackend {
......@@ -418,3 +423,12 @@ function loadWebAssemblyModule(
)
}
contextPrototype.u = loadWebAssemblyModule
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;(globalThis as any).__turbopack_clear_chunk_resolver__ = (
chunkUrl: ChunkUrl
) => {
BACKEND.clearChunkResolver?.(chunkUrl)
}
}
......@@ -94,6 +94,37 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
return await WebAssembly.compileStreaming(req)
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/
clearChunkResolver(chunkUrl: ChunkUrl) {
const resolver = chunkResolvers.get(chunkUrl)
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl)
// Remove failed script/link tag so it can be re-added on retry
const decodedChunkUrl = decodeURI(chunkUrl)
// Escape URLs for safe use in CSS selectors
const escapedChunkUrl = CSS.escape(chunkUrl)
const escapedDecodedChunkUrl = CSS.escape(decodedChunkUrl)
if (isJs(chunkUrl)) {
const scripts = document.querySelectorAll(
`script[src="${escapedChunkUrl}"],script[src^="${escapedChunkUrl}?"],script[src="${escapedDecodedChunkUrl}"],script[src^="${escapedDecodedChunkUrl}?"]`
)
for (const script of Array.from(scripts)) {
script.remove()
}
} else if (isCss(chunkUrl)) {
const links = document.querySelectorAll(
`link[rel=stylesheet][href="${escapedChunkUrl}"],link[rel=stylesheet][href^="${escapedChunkUrl}?"],link[rel=stylesheet][href="${escapedDecodedChunkUrl}"],link[rel=stylesheet][href^="${escapedDecodedChunkUrl}?"]`
)
for (const link of Array.from(links)) {
link.remove()
}
}
}
},
}
function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {
......@@ -163,10 +194,13 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
} else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl)
// Escape URLs for safe use in CSS selectors
const escapedChunkUrl = CSS.escape(chunkUrl)
const escapedDecodedChunkUrl = CSS.escape(decodedChunkUrl)
if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(
`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`
`link[rel=stylesheet][href="${escapedChunkUrl}"],link[rel=stylesheet][href^="${escapedChunkUrl}?"],link[rel=stylesheet][href="${escapedDecodedChunkUrl}"],link[rel=stylesheet][href^="${escapedDecodedChunkUrl}?"]`
)
if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as
......@@ -189,7 +223,7 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
}
} else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(
`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`
`script[src="${escapedChunkUrl}"],script[src^="${escapedChunkUrl}?"],script[src="${escapedDecodedChunkUrl}"],script[src^="${escapedDecodedChunkUrl}?"]`
)
if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
......
;!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]="daa7096d-88eb-4aef-8d70-6aae41560fce")}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]="ea8c7f06-bd06-8c68-dd64-026f2dc028cc")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -740,6 +740,13 @@ function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(1, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;
globalThis.__turbopack_clear_chunk_resolver__ = (chunkUrl)=>{
BACKEND.clearChunkResolver?.(chunkUrl);
};
}
/// <reference path="./dev-globals.d.ts" />
/// <reference path="./dev-protocol.d.ts" />
/// <reference path="./dev-extensions.ts" />
......@@ -1642,6 +1649,28 @@ let BACKEND;
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/ clearChunkResolver (chunkUrl) {
const resolver = chunkResolvers.get(chunkUrl);
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl);
// Remove failed script/link tag so it can be re-added on retry
const decodedChunkUrl = decodeURI(chunkUrl);
if (isJs(chunkUrl)) {
const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
for (const script of Array.from(scripts)){
script.remove();
}
} else if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
for (const link of Array.from(links)){
link.remove();
}
}
}
}
};
function getOrCreateResolver(chunkUrl) {
......@@ -1858,5 +1887,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=daa7096d-88eb-4aef-8d70-6aae41560fce
//# debugId=ea8c7f06-bd06-8c68-dd64-026f2dc028cc
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -739,6 +739,13 @@ function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(1, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;
globalThis.__turbopack_clear_chunk_resolver__ = (chunkUrl)=>{
BACKEND.clearChunkResolver?.(chunkUrl);
};
}
/// <reference path="./dev-globals.d.ts" />
/// <reference path="./dev-protocol.d.ts" />
/// <reference path="./dev-extensions.ts" />
......@@ -1641,6 +1648,28 @@ let BACKEND;
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/ clearChunkResolver (chunkUrl) {
const resolver = chunkResolvers.get(chunkUrl);
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl);
// Remove failed script/link tag so it can be re-added on retry
const decodedChunkUrl = decodeURI(chunkUrl);
if (isJs(chunkUrl)) {
const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
for (const script of Array.from(scripts)){
script.remove();
}
} else if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
for (const link of Array.from(links)){
link.remove();
}
}
}
}
};
function getOrCreateResolver(chunkUrl) {
......
......@@ -1223,6 +1223,14 @@ function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(1, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;
globalThis.__turbopack_clear_chunk_resolver__ = function(chunkUrl) {
var _BACKEND_clearChunkResolver, _BACKEND;
(_BACKEND_clearChunkResolver = (_BACKEND = BACKEND).clearChunkResolver) === null || _BACKEND_clearChunkResolver === void 0 ? void 0 : _BACKEND_clearChunkResolver.call(_BACKEND, chunkUrl);
};
}
/// <reference path="./runtime-base.ts" />
/// <reference path="./dummy.ts" />
var moduleCache = {};
......@@ -1548,6 +1556,62 @@ var BACKEND;
}
});
})();
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/ clearChunkResolver: function clearChunkResolver(chunkUrl) {
var resolver = chunkResolvers.get(chunkUrl);
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl);
// Remove failed script/link tag so it can be re-added on retry
var decodedChunkUrl = decodeURI(chunkUrl);
if (isJs(chunkUrl)) {
var scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = Array.from(scripts)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var script = _step.value;
script.remove();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
} else if (isCss(chunkUrl)) {
var links = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
try {
for(var _iterator1 = Array.from(links)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
var link = _step1.value;
link.remove();
}
} catch (err) {
_didIteratorError1 = true;
_iteratorError1 = err;
} finally{
try {
if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
_iterator1.return();
}
} finally{
if (_didIteratorError1) {
throw _iteratorError1;
}
}
}
}
}
}
};
function getOrCreateResolver(chunkUrl) {
......
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