Unverified Commit ce9c8008 authored by Jamiboy Mohammad's avatar Jamiboy Mohammad Committed by GitHub

Remove unnecessary `as any` casts (#100418)

## Summary

Deletes 69 `as any` casts from `packages/next/src` (466 → 397) where the
existing types already make the cast unnecessary.

Each change only removes ` as any`, plus any parentheses that become
redundant. Nothing else is added or changed: no new declarations,
fields, annotations, helpers, or replacement assertions. The emitted
JavaScript is identical, so there is no runtime change.

How the casts were found:

1. Delete every `as any` in `packages/next/src`, locating them through
the TypeScript AST rather than text search.
2. Run `tsc`, put back each cast whose removal caused an error, and
repeat until clean.
3. Retry the casts that were put back one at a time, so removals in the
same file can't mask each other.

Casts that need a type change, a declaration, or code changes to go away
are left to #100419.

## Verification

- Transpiled each changed file on `canary` and on this branch with
`ts.transpileModule` (the package's compiler options, comments stripped)
and compared the output, ignoring whitespace and semicolons: 44/44
identical.
- `tsc --noEmit` passes for `packages/next` and for the root project.
- Colocated jest suites for the touched files pass (9 suites).

<!-- NEXT_JS_LLM -->
parent 9ff8ba95
...@@ -111,7 +111,7 @@ class NextRootCommand extends Command { ...@@ -111,7 +111,7 @@ class NextRootCommand extends Command {
// production mode merely because they were launched through this CLI. // production mode merely because they were launched through this CLI.
if (commandName !== 'upgrade' || !event.getOptionValue('agent')) { if (commandName !== 'upgrade' || !event.getOptionValue('agent')) {
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv ;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs' process.env.NEXT_RUNTIME = 'nodejs'
} }
if ( if (
......
...@@ -361,7 +361,7 @@ export default function nextTransformSsg({ ...@@ -361,7 +361,7 @@ export default function nextTransformSsg({
} }
do { do {
;(path.scope as any).crawl() path.scope.crawl()
count = 0 count = 0
path.traverse({ path.traverse({
......
...@@ -1080,7 +1080,7 @@ export function createAppPageEntrypoint({ ...@@ -1080,7 +1080,7 @@ export function createAppPageEntrypoint({
cachedNavigations: cachedNavigations:
nextConfig.experimental.cachedNavigations ?? false, nextConfig.experimental.cachedNavigations ?? false,
clientTraceMetadata: clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any), nextConfig.experimental.clientTraceMetadata || [],
clientParamParsingOrigins: clientParamParsingOrigins:
nextConfig.experimental.clientParamParsingOrigins, nextConfig.experimental.clientParamParsingOrigins,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
......
...@@ -337,7 +337,7 @@ async function handleRequest( ...@@ -337,7 +337,7 @@ async function handleRequest(
? await routeModule.handle(nextReq, context) ? await routeModule.handle(nextReq, context)
: await routeModule.prerender(nextReq, context) : await routeModule.prerender(nextReq, context)
;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics ;(req as any).fetchMetrics = context.renderOpts.fetchMetrics
let pendingWaitUntil = context.renderOpts.pendingWaitUntil let pendingWaitUntil = context.renderOpts.pendingWaitUntil
// Attempt using provided waitUntil if available // Attempt using provided waitUntil if available
......
...@@ -213,8 +213,7 @@ async function requestHandler( ...@@ -213,8 +213,7 @@ async function requestHandler(
nextConfig.experimental.durableUseCacheEntries nextConfig.experimental.durableUseCacheEntries
), ),
cachedNavigations: nextConfig.experimental.cachedNavigations ?? false, cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,
clientTraceMetadata: clientTraceMetadata: nextConfig.experimental.clientTraceMetadata || [],
nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins: clientParamParsingOrigins:
nextConfig.experimental.clientParamParsingOrigins, nextConfig.experimental.clientParamParsingOrigins,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
...@@ -273,7 +272,7 @@ async function requestHandler( ...@@ -273,7 +272,7 @@ async function requestHandler(
const headers = new Headers() const headers = new Headers()
finalStatus = metadata.statusCode || baseRes.statusCode || 200 finalStatus = metadata.statusCode || baseRes.statusCode || 200
// Pull any fetch metrics from the render onto the request. // Pull any fetch metrics from the render onto the request.
;(req as any).fetchMetrics = metadata.fetchMetrics req.fetchMetrics = metadata.fetchMetrics
// Set content type // Set content type
const contentType = result.contentType || 'text/html; charset=utf-8' const contentType = result.contentType || 'text/html; charset=utf-8'
......
...@@ -804,7 +804,7 @@ export default async function getBaseWebpackConfig( ...@@ -804,7 +804,7 @@ export default async function getBaseWebpackConfig(
plugins: [ plugins: [
isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined, isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined,
].filter(Boolean) as webpack.ResolvePluginInstance[], ].filter(Boolean) as webpack.ResolvePluginInstance[],
...((isRspack && jsConfigPath ...(isRspack && jsConfigPath
? { ? {
// Skip paths that are routed to a .d.ts file // Skip paths that are routed to a .d.ts file
restrictions: [/^(?!.*\.d\.ts$).*$/], restrictions: [/^(?!.*\.d\.ts$).*$/],
...@@ -812,7 +812,7 @@ export default async function getBaseWebpackConfig( ...@@ -812,7 +812,7 @@ export default async function getBaseWebpackConfig(
configFile: jsConfigPath, configFile: jsConfigPath,
}, },
} }
: {}) as any), : {}),
} }
// Resolve server-relative imports (e.g. `/styles/foo`) from the app // Resolve server-relative imports (e.g. `/styles/foo`) from the app
...@@ -2733,7 +2733,7 @@ export default async function getBaseWebpackConfig( ...@@ -2733,7 +2733,7 @@ export default async function getBaseWebpackConfig(
} }
webpackConfig.module.rules = [ webpackConfig.module.rules = [
...(topRules as any), ...topRules,
{ {
oneOf: [...innerRules, fileLoader], oneOf: [...innerRules, fileLoader],
}, },
......
...@@ -47,7 +47,7 @@ const createLazyPostCssPlugin = ( ...@@ -47,7 +47,7 @@ const createLazyPostCssPlugin = (
): import('postcss').AcceptedPlugin => { ): import('postcss').AcceptedPlugin => {
let result: any = undefined let result: any = undefined
const plugin = (...args: any[]) => { const plugin = (...args: any[]) => {
if (result === undefined) result = fn() as any if (result === undefined) result = fn()
if (result.postcss === true) { if (result.postcss === true) {
return result(...args) return result(...args)
} else if (result.postcss) { } else if (result.postcss) {
......
...@@ -799,8 +799,7 @@ export class FlightClientEntryPlugin { ...@@ -799,8 +799,7 @@ export class FlightClientEntryPlugin {
} }
if (isCSSMod(mod)) { if (isCSSMod(mod)) {
const sideEffectFree = const sideEffectFree = mod.factoryMeta && mod.factoryMeta.sideEffectFree
mod.factoryMeta && (mod.factoryMeta as any).sideEffectFree
if (sideEffectFree) { if (sideEffectFree) {
const unused = !compilation.moduleGraph const unused = !compilation.moduleGraph
......
...@@ -344,8 +344,10 @@ async function printVerboseInfo() { ...@@ -344,8 +344,10 @@ async function printVerboseInfo() {
} }
} }
const { header, javascriptHeap, sharedObjects } = const { header, javascriptHeap, sharedObjects } = report as Record<
report as any as Record<string, any> string,
any
>
// Delete some fields potentially containing sensitive information. // Delete some fields potentially containing sensitive information.
delete header?.cwd delete header?.cwd
delete header?.commandLine delete header?.commandLine
...@@ -370,7 +372,7 @@ async function printVerboseInfo() { ...@@ -370,7 +372,7 @@ async function printVerboseInfo() {
title: 'next-swc installation', title: 'next-swc installation',
scripts: { scripts: {
default: async () => { default: async () => {
const output = [] as any const output = []
// First, try to load next-swc via loadBindings. // First, try to load next-swc via loadBindings.
try { try {
......
...@@ -336,7 +336,7 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -336,7 +336,7 @@ export const publicAppRouterInstance: AppRouterInstance = {
// Conditionally add experimental_gesturePush when gestureTransition is enabled // Conditionally add experimental_gesturePush when gestureTransition is enabled
if (process.env.__NEXT_GESTURE_TRANSITION) { if (process.env.__NEXT_GESTURE_TRANSITION) {
;(publicAppRouterInstance as any).experimental_gesturePush = gesturePush publicAppRouterInstance.experimental_gesturePush = gesturePush
} }
// Exists for debugging purposes. Don't use in application code. // Exists for debugging purposes. Don't use in application code.
......
...@@ -383,7 +383,7 @@ function renderError(renderErrorProps: RenderErrorProps): Promise<any> { ...@@ -383,7 +383,7 @@ function renderError(renderErrorProps: RenderErrorProps): Promise<any> {
? import('../pages/_error') ? import('../pages/_error')
.then((errorModule) => { .then((errorModule) => {
return import('../pages/_app').then((appModule) => { return import('../pages/_app').then((appModule) => {
App = appModule.default as any as AppComponent App = appModule.default as AppComponent
renderErrorProps.App = App renderErrorProps.App = App
return errorModule return errorModule
}) })
...@@ -578,7 +578,7 @@ function renderReactElement( ...@@ -578,7 +578,7 @@ function renderReactElement(
// TODO: Remove shouldHydrate variable when React 18 is stable as it can depend on `reactRoot` existing // TODO: Remove shouldHydrate variable when React 18 is stable as it can depend on `reactRoot` existing
shouldHydrate = false shouldHydrate = false
} else { } else {
const startTransition = (React as any).startTransition const startTransition = React.startTransition
startTransition(() => { startTransition(() => {
reactRoot.render(reactEl) reactRoot.render(reactEl)
}) })
......
...@@ -8,7 +8,7 @@ import { ...@@ -8,7 +8,7 @@ import {
import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime' import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime'
// This is replaced by the bundler define plugin. // This is replaced by the bundler define plugin.
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as const configEnv = process.env.__NEXT_IMAGE_OPTS as
| ImageConfigForRendering | ImageConfigForRendering
| undefined | undefined
......
...@@ -504,7 +504,7 @@ function processRoutes<T>( ...@@ -504,7 +504,7 @@ function processRoutes<T>(
config: NextConfig, config: NextConfig,
type: 'redirect' | 'rewrite' | 'header' type: 'redirect' | 'rewrite' | 'header'
): T { ): T {
const _routes = routes as any as Array<{ const _routes = routes as Array<{
source: string source: string
locale?: false locale?: false
basePath?: false basePath?: false
...@@ -580,7 +580,7 @@ function processRoutes<T>( ...@@ -580,7 +580,7 @@ function processRoutes<T>(
} }
newRoutes.push(r) newRoutes.push(r)
} }
return newRoutes as any as T return newRoutes as T
} }
async function loadRedirects(config: NextConfig): Promise<{ async function loadRedirects(config: NextConfig): Promise<{
......
function resolveArray<T>(value: T | T[]): T[] { function resolveArray<T>(value: T | T[]): T[] {
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value as any return value
} }
return [value] as any return [value]
} }
function resolveAsArrayOrUndefined<T>( function resolveAsArrayOrUndefined<T>(
......
...@@ -182,7 +182,7 @@ export function getRequiredConfiguration( ...@@ -182,7 +182,7 @@ export function getRequiredConfiguration(
nodenext: typescript.ModuleResolutionKind.NodeNext, nodenext: typescript.ModuleResolutionKind.NodeNext,
node12: (typescript.ModuleResolutionKind as any).Node12, node12: (typescript.ModuleResolutionKind as any).Node12,
node: node:
(typescript.ModuleResolutionKind as any).Node10 ?? typescript.ModuleResolutionKind.Node10 ??
typescript.ModuleResolutionKind.NodeJs, typescript.ModuleResolutionKind.NodeJs,
} }
res[optionKey] = moduleResolutionMap[value.toLowerCase()] ?? value res[optionKey] = moduleResolutionMap[value.toLowerCase()] ?? value
......
...@@ -197,7 +197,7 @@ export async function verifyAndRunTypeScript({ ...@@ -197,7 +197,7 @@ export async function verifyAndRunTypeScript({
if (err && typeof err === 'object' && 'command' in err) { if (err && typeof err === 'object' && 'command' in err) {
console.error( console.error(
`Failed to install required TypeScript dependencies, please install them manually to continue:\n` + `Failed to install required TypeScript dependencies, please install them manually to continue:\n` +
(err as any).command + err.command +
'\n' '\n'
) )
} }
......
...@@ -125,7 +125,7 @@ export class Worker { ...@@ -125,7 +125,7 @@ export class Worker {
const createWorker = () => { const createWorker = () => {
const workerEnv: NodeJS.ProcessEnv = { const workerEnv: NodeJS.ProcessEnv = {
...process.env, ...process.env,
...((farmOptions.forkOptions?.env || {}) as any), ...(farmOptions.forkOptions?.env || {}),
IS_NEXT_WORKER: 'true', IS_NEXT_WORKER: 'true',
NODE_OPTIONS: formattedNodeOptions, NODE_OPTIONS: formattedNodeOptions,
} }
......
...@@ -32,7 +32,7 @@ export function tryGetPreviewData( ...@@ -32,7 +32,7 @@ export function tryGetPreviewData(
// Read cached preview data if present // Read cached preview data if present
// TODO: use request metadata instead of a symbol // TODO: use request metadata instead of a symbol
if (SYMBOL_PREVIEW_DATA in req) { if (SYMBOL_PREVIEW_DATA in req) {
return (req as any)[SYMBOL_PREVIEW_DATA] as any return req[SYMBOL_PREVIEW_DATA] as any
} }
const headers = HeadersAdapter.from(req.headers) const headers = HeadersAdapter.from(req.headers)
......
...@@ -1304,8 +1304,8 @@ export async function createCombinedPayloadAtDepth( ...@@ -1304,8 +1304,8 @@ export async function createCombinedPayloadAtDepth(
instantConfig === true || instantConfig === true ||
(typeof instantConfig === 'object' && instantConfig !== null) (typeof instantConfig === 'object' && instantConfig !== null)
) { ) {
const rawFactory: unknown = (layoutOrPageMod as any) const rawFactory: unknown =
.__debugCreateInstantConfigStack layoutOrPageMod.__debugCreateInstantConfigStack
localCreateInstantStack = localCreateInstantStack =
typeof rawFactory === 'function' ? (rawFactory as () => Error) : null typeof rawFactory === 'function' ? (rawFactory as () => Error) : null
} }
......
...@@ -49,5 +49,5 @@ export function preconnect( ...@@ -49,5 +49,5 @@ export function preconnect(
if (typeof nonce === 'string') { if (typeof nonce === 'string') {
opts.nonce = nonce opts.nonce = nonce
} }
;(ReactDOM as any).preconnect(href, opts) ReactDOM.preconnect(href, opts)
} }
...@@ -2975,7 +2975,7 @@ export default abstract class Server< ...@@ -2975,7 +2975,7 @@ export default abstract class Server<
}, },
set(target: any, prop, value) { set(target: any, prop, value) {
if (prop === 'fetchMetrics') { if (prop === 'fetchMetrics') {
;(req as any).fetchMetrics = value req.fetchMetrics = value
} }
target[prop] = value target[prop] = value
return true return true
......
...@@ -429,7 +429,7 @@ async function handleDefaultConsole( ...@@ -429,7 +429,7 @@ async function handleDefaultConsole(
const withStackEntry = await withLocation( const withStackEntry = await withLocation(
{ {
original: consoleArgs, original: consoleArgs,
stack: (entry as any).consoleMethodStack || null, stack: entry.consoleMethodStack || null,
}, },
ctx, ctx,
distDir, distDir,
......
...@@ -1411,7 +1411,7 @@ export async function createHotReloaderTurbopack( ...@@ -1411,7 +1411,7 @@ export async function createHotReloaderTurbopack(
page: name, page: name,
bundlePath: `app${name}`, bundlePath: `app${name}`,
filename: '', filename: '',
} as any, },
} }
break break
} }
......
...@@ -561,7 +561,7 @@ export function onDemandEntryHandler({ ...@@ -561,7 +561,7 @@ export function onDemandEntryHandler({
let curInvalidator: Invalidator = getInvalidator( let curInvalidator: Invalidator = getInvalidator(
multiCompiler.outputPath multiCompiler.outputPath
) as any ) as any
const curEntries = getEntries(multiCompiler.outputPath) as any const curEntries = getEntries(multiCompiler.outputPath)
if (!curInvalidator) { if (!curInvalidator) {
curInvalidator = new Invalidator(multiCompiler) curInvalidator = new Invalidator(multiCompiler)
...@@ -639,7 +639,7 @@ export function onDemandEntryHandler({ ...@@ -639,7 +639,7 @@ export function onDemandEntryHandler({
} }
const startBuilding = (compilation: webpack.Compilation) => { const startBuilding = (compilation: webpack.Compilation) => {
const compilationName = compilation.name as any as CompilerNameValues const compilationName = compilation.name as CompilerNameValues
curInvalidator.startBuilding(compilationName) curInvalidator.startBuilding(compilationName)
// Reset deferred entries state for this compilation cycle // Reset deferred entries state for this compilation cycle
// This ensures onBeforeDeferredEntries will be called again during HMR // This ensures onBeforeDeferredEntries will be called again during HMR
......
...@@ -777,7 +777,7 @@ export async function initialize(opts: { ...@@ -777,7 +777,7 @@ export async function initialize(opts: {
// normalize non-allowed status codes // normalize non-allowed status codes
if (!validErrorStatus) { if (!validErrorStatus) {
;(err as any).statusCode = 400 err.statusCode = 400
} }
if (typeof err.statusCode === 'number') { if (typeof err.statusCode === 'number') {
......
...@@ -173,7 +173,7 @@ export function getResolveRoutes( ...@@ -173,7 +173,7 @@ export function getResolveRoutes(
: 'http' : 'http'
// When there are hostname and port we build an absolute URL // When there are hostname and port we build an absolute URL
const initUrl = (config.experimental as any).trustHostHeader const initUrl = config.experimental.trustHostHeader
? `https://${req.headers.host || 'localhost'}${req.url}` ? `https://${req.headers.host || 'localhost'}${req.url}`
: opts.port : opts.port
? `${protocol}://${formatHostname(opts.hostname || 'localhost')}:${ ? `${protocol}://${formatHostname(opts.hostname || 'localhost')}:${
......
...@@ -397,6 +397,6 @@ export function getMaxOldSpaceSize() { ...@@ -397,6 +397,6 @@ export function getMaxOldSpaceSize() {
// does this for terminals. // does this for terminals.
export function blockOnOutputWrites() { export function blockOnOutputWrites() {
for (const stream of [process.stdout, process.stderr]) { for (const stream of [process.stdout, process.stderr]) {
;(stream as any)._handle?.setBlocking?.(true) stream._handle?.setBlocking?.(true)
} }
} }
...@@ -8,7 +8,7 @@ if (typeof (globalThis as any).AsyncLocalStorage !== 'function') { ...@@ -8,7 +8,7 @@ if (typeof (globalThis as any).AsyncLocalStorage !== 'function') {
;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage ;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage
} }
if (typeof (globalThis as any).WebSocket !== 'function') { if (typeof globalThis.WebSocket !== 'function') {
Object.defineProperty(globalThis, 'WebSocket', { Object.defineProperty(globalThis, 'WebSocket', {
configurable: true, configurable: true,
get() { get() {
......
...@@ -283,11 +283,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED ...@@ -283,11 +283,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED
`Removing 'unhandledRejection' listener with name \`${listener.name}\`.` `Removing 'unhandledRejection' listener with name \`${listener.name}\`.`
) )
// We remove the listener on a dummy event in case it throws. We don't catch it intentionally // We remove the listener on a dummy event in case it throws. We don't catch it intentionally
originalProcessRemoveListener.call( originalProcessRemoveListener.call(process, MACGUFFIN_EVENT, listener)
process,
MACGUFFIN_EVENT as any,
listener
)
const index = underlyingListeners.lastIndexOf(listener) const index = underlyingListeners.lastIndexOf(listener)
if (index > -1) { if (index > -1) {
debug?.(`listener found index ${index} and removed.`) debug?.(`listener found index ${index} and removed.`)
...@@ -317,7 +313,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED ...@@ -317,7 +313,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED
) )
// We add the listener to a dummy event in case it throws. We don't catch it intentionally // We add the listener to a dummy event in case it throws. We don't catch it intentionally
try { try {
originalProcessOn.call(process, MACGUFFIN_EVENT as any, listener) originalProcessOn.call(process, MACGUFFIN_EVENT, listener)
} finally { } finally {
// We clean up the added event // We clean up the added event
originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT) originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)
...@@ -358,7 +354,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED ...@@ -358,7 +354,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED
`Removing 'unhandledRejection' listener with name \`${listener.name}\`.` `Removing 'unhandledRejection' listener with name \`${listener.name}\`.`
) )
// We remove the listener on a dummy event in case it throws. We don't catch it intentionally // We remove the listener on a dummy event in case it throws. We don't catch it intentionally
originalProcessOff.call(process, MACGUFFIN_EVENT as any, listener) originalProcessOff.call(process, MACGUFFIN_EVENT, listener)
const index = underlyingListeners.lastIndexOf(listener) const index = underlyingListeners.lastIndexOf(listener)
if (index > -1) { if (index > -1) {
debug?.(`listener found index ${index} and removed.`) debug?.(`listener found index ${index} and removed.`)
...@@ -421,7 +417,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED ...@@ -421,7 +417,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED
) )
// We add the listener to a dummy event in case it throws. We don't catch it intentionally // We add the listener to a dummy event in case it throws. We don't catch it intentionally
try { try {
originalProcessOnce.call(process, MACGUFFIN_EVENT as any, listener) originalProcessOnce.call(process, MACGUFFIN_EVENT, listener)
} finally { } finally {
// We clean up the added event // We clean up the added event
originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT) originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)
......
...@@ -465,7 +465,7 @@ export async function renderToHTMLImpl( ...@@ -465,7 +465,7 @@ export async function renderToHTMLImpl(
renderContext: PagesRenderContext renderContext: PagesRenderContext
): Promise<RenderResult> { ): Promise<RenderResult> {
// Adds support for reading `cookies` in `getServerSideProps` when SSR. // Adds support for reading `cookies` in `getServerSideProps` when SSR.
setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers)) setLazyProp({ req: req }, 'cookies', getCookieParser(req.headers))
// cssCacheBuster is a workaround for a Safari bug // cssCacheBuster is a workaround for a Safari bug
// (https://bugs.webkit.org/show_bug.cgi?id=187726) where preloaded CSS // (https://bugs.webkit.org/show_bug.cgi?id=187726) where preloaded CSS
...@@ -1401,7 +1401,7 @@ export async function renderToHTMLImpl( ...@@ -1401,7 +1401,7 @@ export async function renderToHTMLImpl(
} }
// @ts-ignore: documentInitialPropsRes is set // @ts-ignore: documentInitialPropsRes is set
const { docProps } = (documentInitialPropsRes as any) || {} const { docProps } = documentInitialPropsRes || {}
const documentElement = (htmlProps: any) => { const documentElement = (htmlProps: any) => {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
return (Document as any)() return (Document as any)()
......
...@@ -630,7 +630,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -630,7 +630,7 @@ export class AppRouteRouteModule extends RouteModule<
) { ) {
// The handler returned a Thenable. We'll listen for rejections to determine // The handler returned a Thenable. We'll listen for rejections to determine
// if the route is erroring for dynamic reasons. // if the route is erroring for dynamic reasons.
;(prospectiveResult as any as Promise<unknown>).then( ;(prospectiveResult as Promise<unknown>).then(
() => {}, () => {},
(err) => { (err) => {
if (prospectiveController.signal.aborted) { if (prospectiveController.signal.aborted) {
......
...@@ -361,7 +361,7 @@ export const getHandler = ({ ...@@ -361,7 +361,7 @@ export const getHandler = ({
nextConfig.assetPrefix nextConfig.assetPrefix
), ),
previewProps, previewProps,
images: nextConfig.images as any, images: nextConfig.images,
nextConfigOutput: nextConfig.output, nextConfigOutput: nextConfig.output,
optimizeCss: Boolean(nextConfig.experimental.optimizeCss), optimizeCss: Boolean(nextConfig.experimental.optimizeCss),
nextScriptWorkers: Boolean( nextScriptWorkers: Boolean(
...@@ -381,8 +381,7 @@ export const getHandler = ({ ...@@ -381,8 +381,7 @@ export const getHandler = ({
experimental: { experimental: {
clientTraceMetadata: clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || nextConfig.experimental.clientTraceMetadata || [],
([] as any),
}, },
locale, locale,
......
...@@ -626,7 +626,7 @@ export abstract class RouteModule< ...@@ -626,7 +626,7 @@ export abstract class RouteModule<
) )
} }
let serverFilesManifest = self.__SERVER_FILES_MANIFEST as any as let serverFilesManifest = self.__SERVER_FILES_MANIFEST as
| RequiredServerFilesManifest | RequiredServerFilesManifest
| undefined | undefined
const routerServerContext = this.getRouterServerContext(req) const routerServerContext = this.getRouterServerContext(req)
......
...@@ -260,7 +260,7 @@ export async function adapter( ...@@ -260,7 +260,7 @@ export async function adapter(
// leverage the shared instance if not we need // leverage the shared instance if not we need
// to create a fresh cache instance each time // to create a fresh cache instance each time
!(globalThis as any).__incrementalCacheShared && !(globalThis as any).__incrementalCacheShared &&
(params as any).IncrementalCache params.IncrementalCache
) { ) {
;(globalThis as any).__incrementalCache = new ( ;(globalThis as any).__incrementalCache = new (
params as { params as {
......
...@@ -237,16 +237,16 @@ describe('HeadersAdapter', () => { ...@@ -237,16 +237,16 @@ describe('HeadersAdapter', () => {
expect(sealed.get('x-custom-header')).toBe('custom') expect(sealed.get('x-custom-header')).toBe('custom')
// These methods are not available on the sealed instance // These methods are not available on the sealed instance
expect(() => expect(() => sealed.append('x-custom-header', 'custom2')).toThrow(
(sealed as any).append('x-custom-header', 'custom2')
).toThrow(ReadonlyHeadersError)
expect(() =>
(sealed as any).append('x-custom-header', 'custom2')
).toThrow(ReadonlyHeadersError)
expect(() => (sealed as any).delete('x-custom-header')).toThrow(
ReadonlyHeadersError ReadonlyHeadersError
) )
expect(() => (sealed as any).set('x-custom-header', 'custom2')).toThrow( expect(() => sealed.append('x-custom-header', 'custom2')).toThrow(
ReadonlyHeadersError
)
expect(() => sealed.delete('x-custom-header')).toThrow(
ReadonlyHeadersError
)
expect(() => sealed.set('x-custom-header', 'custom2')).toThrow(
ReadonlyHeadersError ReadonlyHeadersError
) )
...@@ -264,13 +264,13 @@ describe('HeadersAdapter', () => { ...@@ -264,13 +264,13 @@ describe('HeadersAdapter', () => {
expect(sealed).toBeInstanceOf(Headers) expect(sealed).toBeInstanceOf(Headers)
// These methods are not available on the sealed instance // These methods are not available on the sealed instance
expect(() => expect(() => sealed.append('x-custom-header', 'custom2')).toThrow(
(sealed as any).append('x-custom-header', 'custom2') ReadonlyHeadersError
).toThrow(ReadonlyHeadersError) )
expect(() => (sealed as any).delete('x-custom-header')).toThrow( expect(() => sealed.delete('x-custom-header')).toThrow(
ReadonlyHeadersError ReadonlyHeadersError
) )
expect(() => (sealed as any).set('x-custom-header', 'custom2')).toThrow( expect(() => sealed.set('x-custom-header', 'custom2')).toThrow(
ReadonlyHeadersError ReadonlyHeadersError
) )
...@@ -291,13 +291,13 @@ describe('HeadersAdapter', () => { ...@@ -291,13 +291,13 @@ describe('HeadersAdapter', () => {
expect(sealed).toBeInstanceOf(Headers) expect(sealed).toBeInstanceOf(Headers)
// These methods are not available on the sealed instance // These methods are not available on the sealed instance
expect(() => expect(() => sealed.append('x-custom-header', 'custom2')).toThrow(
(sealed as any).append('x-custom-header', 'custom2') ReadonlyHeadersError
).toThrow(ReadonlyHeadersError) )
expect(() => (sealed as any).delete('x-custom-header')).toThrow( expect(() => sealed.delete('x-custom-header')).toThrow(
ReadonlyHeadersError ReadonlyHeadersError
) )
expect(() => (sealed as any).set('x-custom-header', 'custom2')).toThrow( expect(() => sealed.set('x-custom-header', 'custom2')).toThrow(
ReadonlyHeadersError ReadonlyHeadersError
) )
...@@ -427,9 +427,7 @@ describe('HeadersAdapter', () => { ...@@ -427,9 +427,7 @@ describe('HeadersAdapter', () => {
expect(headers.get('rsc')).toBe('1') expect(headers.get('rsc')).toBe('1')
expect(headers.get('x-nextjs-request-id')).toBe('req-1') expect(headers.get('x-nextjs-request-id')).toBe('req-1')
expect(() => (sealed as any).delete('rsc')).toThrow( expect(() => sealed.delete('rsc')).toThrow(ReadonlyHeadersError)
ReadonlyHeadersError
)
expect(headers.get('rsc')).toBe('1') expect(headers.get('rsc')).toBe('1')
}) })
......
...@@ -18,12 +18,8 @@ describe('RequestCookiesAdapter', () => { ...@@ -18,12 +18,8 @@ describe('RequestCookiesAdapter', () => {
expect(sealed.get('bar')).toEqual({ name: 'bar', value: 'foo' }) expect(sealed.get('bar')).toEqual({ name: 'bar', value: 'foo' })
// These methods are not available on the sealed instance // These methods are not available on the sealed instance
expect(() => (sealed as any).set('foo', 'bar2')).toThrow( expect(() => sealed.set('foo', 'bar2')).toThrow(ReadonlyRequestCookiesError)
ReadonlyRequestCookiesError expect(() => sealed.delete('foo')).toThrow(ReadonlyRequestCookiesError)
)
expect(() => (sealed as any).delete('foo')).toThrow(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).clear()).toThrow(ReadonlyRequestCookiesError) expect(() => (sealed as any).clear()).toThrow(ReadonlyRequestCookiesError)
// Ensure nothing was actually changed. // Ensure nothing was actually changed.
...@@ -41,12 +37,8 @@ describe('RequestCookiesAdapter', () => { ...@@ -41,12 +37,8 @@ describe('RequestCookiesAdapter', () => {
expect(sealed.get('bar')).toEqual(undefined) expect(sealed.get('bar')).toEqual(undefined)
// These methods are not available on the sealed instance // These methods are not available on the sealed instance
expect(() => (sealed as any).set('foo', 'bar2')).toThrow( expect(() => sealed.set('foo', 'bar2')).toThrow(ReadonlyRequestCookiesError)
ReadonlyRequestCookiesError expect(() => sealed.delete('foo')).toThrow(ReadonlyRequestCookiesError)
)
expect(() => (sealed as any).delete('foo')).toThrow(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).clear()).toThrow(ReadonlyRequestCookiesError) expect(() => (sealed as any).clear()).toThrow(ReadonlyRequestCookiesError)
// Ensure nothing was actually changed. // Ensure nothing was actually changed.
......
...@@ -109,7 +109,7 @@ export const GlobalLayoutRouterContext = React.createContext<{ ...@@ -109,7 +109,7 @@ export const GlobalLayoutRouterContext = React.createContext<{
previousNextUrl: string | null previousNextUrl: string | null
}>(null as any) }>(null as any)
export const TemplateContext = React.createContext<React.ReactNode>(null as any) export const TemplateContext = React.createContext<React.ReactNode>(null)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
AppRouterContext.displayName = 'AppRouterContext' AppRouterContext.displayName = 'AppRouterContext'
......
...@@ -15,7 +15,7 @@ const defaultLoader = Reflect.get(defaultLoaderModule, 'default') ...@@ -15,7 +15,7 @@ const defaultLoader = Reflect.get(defaultLoaderModule, 'default')
// The bundler replaces this with fixed options. Public getImageProps has no // The bundler replaces this with fixed options. Public getImageProps has no
// context, so prepare those options once when the module is loaded. // context, so prepare those options once when the module is loaded.
const imageConfig = prepareImageConfig( const imageConfig = prepareImageConfig(
process.env.__NEXT_IMAGE_OPTS as any as ImageConfigForRendering | undefined process.env.__NEXT_IMAGE_OPTS as ImageConfigForRendering | undefined
) )
/** /**
......
...@@ -94,7 +94,7 @@ function createLoadableComponent(loadFn: any, options: any) { ...@@ -94,7 +94,7 @@ function createLoadableComponent(loadFn: any, options: any) {
if (!initialized && typeof window !== 'undefined') { if (!initialized && typeof window !== 'undefined') {
// require.resolveWeak check is needed for environments that don't have it available like Jest // require.resolveWeak check is needed for environments that don't have it available like Jest
const moduleIds = const moduleIds =
opts.webpack && typeof (require as any).resolveWeak === 'function' opts.webpack && typeof require.resolveWeak === 'function'
? opts.webpack() ? opts.webpack()
: opts.modules : opts.modules
if (moduleIds) { if (moduleIds) {
......
...@@ -1138,7 +1138,7 @@ export default class Router implements BaseRouter { ...@@ -1138,7 +1138,7 @@ export default class Router implements BaseRouter {
;({ ;({
__routerFilterStatic: staticFilterData, __routerFilterStatic: staticFilterData,
__routerFilterDynamic: dynamicFilterData, __routerFilterDynamic: dynamicFilterData,
} = (await getClientBuildManifest()) as any as { } = (await getClientBuildManifest()) as {
__routerFilterStatic?: Filter __routerFilterStatic?: Filter
__routerFilterDynamic?: Filter __routerFilterDynamic?: Filter
}) })
......
...@@ -121,7 +121,7 @@ export function safeRegexpToFunction< ...@@ -121,7 +121,7 @@ export function safeRegexpToFunction<
// Clean parameters before returning // Clean parameters before returning
return { return {
...result, ...result,
params: stripParameterSeparators(result.params as any) as T, params: stripParameterSeparators(result.params) as T,
} }
} }
} }
......
...@@ -11,7 +11,7 @@ export type ServerInsertedHTMLHook = (callbacks: () => React.ReactNode) => void ...@@ -11,7 +11,7 @@ export type ServerInsertedHTMLHook = (callbacks: () => React.ReactNode) => void
// //
// More info: https://github.com/vercel/next.js/pull/40686 // More info: https://github.com/vercel/next.js/pull/40686
export const ServerInsertedHTMLContext = export const ServerInsertedHTMLContext =
React.createContext<ServerInsertedHTMLHook | null>(null as any) React.createContext<ServerInsertedHTMLHook | null>(null)
export function useServerInsertedHTML(callback: () => React.ReactNode): void { export function useServerInsertedHTML(callback: () => React.ReactNode): void {
const addInsertedServerHTMLCallback = useContext(ServerInsertedHTMLContext) const addInsertedServerHTMLCallback = useContext(ServerInsertedHTMLContext)
......
...@@ -36,7 +36,7 @@ export function backgroundLogCompilationEvents( ...@@ -36,7 +36,7 @@ export function backgroundLogCompilationEvents(
// Close the iterator as soon as the signal fires so the for-await loop // Close the iterator as soon as the signal fires so the for-await loop
// exits without waiting for the next compilation event. // exits without waiting for the next compilation event.
signal?.addEventListener('abort', () => iterator.return?.(undefined as any), { signal?.addEventListener('abort', () => iterator.return?.(undefined), {
once: true, once: true,
}) })
......
...@@ -450,7 +450,7 @@ export class TurbopackManifestLoader { ...@@ -450,7 +450,7 @@ export class TurbopackManifestLoader {
sortedPageKeys: string[] sortedPageKeys: string[]
): ClientBuildManifest { ): ClientBuildManifest {
const manifest = { const manifest = {
__rewrites: rewrites as any, __rewrites: rewrites,
sortedPages: sortedPageKeys, sortedPages: sortedPageKeys,
} }
for (const m of manifests) { for (const m of manifests) {
......
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