Unverified Commit 4f5df6a8 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

refactor: make locales array immutable (#74037)

To improve memory efficiency, this marks all the locale arrays as
readonly. This ensures that there's no undefined behaviour from
accidentally mutating the array, and allows us to use the locales array
as a stable reference for a future optimization PR.
parent d5fc05b3
...@@ -377,13 +377,13 @@ export type RoutesManifest = { ...@@ -377,13 +377,13 @@ export type RoutesManifest = {
dynamicRoutes: Array<ManifestRoute> dynamicRoutes: Array<ManifestRoute>
dataRoutes: Array<ManifestDataRoute> dataRoutes: Array<ManifestDataRoute>
i18n?: { i18n?: {
domains?: Array<{ domains?: ReadonlyArray<{
http?: true http?: true
domain: string domain: string
locales?: string[] locales?: readonly string[]
defaultLocale: string defaultLocale: string
}> }>
locales: string[] locales: readonly string[]
defaultLocale: string defaultLocale: string
localeDetection?: false localeDetection?: false
} }
...@@ -473,7 +473,11 @@ async function writeClientSsgManifest( ...@@ -473,7 +473,11 @@ async function writeClientSsgManifest(
buildId, buildId,
distDir, distDir,
locales, locales,
}: { buildId: string; distDir: string; locales: string[] } }: {
buildId: string
distDir: string
locales: readonly string[] | undefined
}
) { ) {
const ssgPages = new Set<string>( const ssgPages = new Set<string>(
[ [
...@@ -3622,7 +3626,7 @@ export default async function build( ...@@ -3622,7 +3626,7 @@ export default async function build(
await writeClientSsgManifest(prerenderManifest, { await writeClientSsgManifest(prerenderManifest, {
distDir, distDir,
buildId, buildId,
locales: config.i18n?.locales || [], locales: config.i18n?.locales,
}) })
} else { } else {
await writePrerenderManifest(distDir, { await writePrerenderManifest(distDir, {
......
...@@ -19,7 +19,7 @@ export async function buildPagesStaticPaths({ ...@@ -19,7 +19,7 @@ export async function buildPagesStaticPaths({
page: string page: string
getStaticPaths: GetStaticPaths getStaticPaths: GetStaticPaths
configFileName: string configFileName: string
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
}): Promise<StaticPathsResult> { }): Promise<StaticPathsResult> {
const prerenderedRoutes: PrerenderedRoute[] = [] const prerenderedRoutes: PrerenderedRoute[] = []
...@@ -28,7 +28,13 @@ export async function buildPagesStaticPaths({ ...@@ -28,7 +28,13 @@ export async function buildPagesStaticPaths({
// Get the default list of allowed params. // Get the default list of allowed params.
const routeParameterKeys = Object.keys(_routeMatcher(page)) const routeParameterKeys = Object.keys(_routeMatcher(page))
const staticPathsResult = await getStaticPaths({ locales, defaultLocale }) const staticPathsResult = await getStaticPaths({
// We create a copy here to avoid having the types of `getStaticPaths`
// change. This ensures that users can't mutate this array and have it
// poison the reference.
locales: [...(locales ?? [])],
defaultLocale,
})
const expectedReturnVal = const expectedReturnVal =
`Expected: { paths: [], fallback: boolean }\n` + `Expected: { paths: [], fallback: boolean }\n` +
......
...@@ -981,7 +981,7 @@ export async function isPageStatic({ ...@@ -981,7 +981,7 @@ export async function isPageStatic({
configFileName: string configFileName: string
runtimeEnvConfig: any runtimeEnvConfig: any
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
parentId?: any parentId?: any
edgeInfo?: any edgeInfo?: any
......
...@@ -8,8 +8,8 @@ const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || '' ...@@ -8,8 +8,8 @@ const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''
export function getDomainLocale( export function getDomainLocale(
path: string, path: string,
locale?: string | false, locale?: string | false,
locales?: string[], locales?: readonly string[],
domainLocales?: DomainLocale[] domainLocales?: readonly DomainLocale[]
) { ) {
if (process.env.__NEXT_I18N_SUPPORT) { if (process.env.__NEXT_I18N_SUPPORT) {
const normalizeLocalePath: typeof NormalizeFn = const normalizeLocalePath: typeof NormalizeFn =
......
...@@ -12,7 +12,7 @@ interface Options { ...@@ -12,7 +12,7 @@ interface Options {
function parse( function parse(
raw: string, raw: string,
preferences: string[] | undefined, preferences: readonly string[] | undefined,
options: Options options: Options
) { ) {
const lowers = new Map<string, { orig: string; pos: number }>() const lowers = new Map<string, { orig: string; pos: number }>()
...@@ -127,7 +127,7 @@ function parse( ...@@ -127,7 +127,7 @@ function parse(
return preferred return preferred
} }
export function acceptLanguage(header = '', preferences?: string[]) { export function acceptLanguage(header = '', preferences?: readonly string[]) {
return ( return (
parse(header, preferences, { parse(header, preferences, {
type: 'accept-language', type: 'accept-language',
......
...@@ -1437,7 +1437,7 @@ export default abstract class Server< ...@@ -1437,7 +1437,7 @@ export default abstract class Server<
} }
const normalizeResult = normalizeLocalePath( const normalizeResult = normalizeLocalePath(
removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''), removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''),
this.nextConfig.i18n?.locales || [] this.nextConfig.i18n?.locales
) )
if (normalizeResult.detectedLocale) { if (normalizeResult.detectedLocale) {
......
...@@ -23,20 +23,20 @@ export type NextConfigComplete = Required<NextConfig> & { ...@@ -23,20 +23,20 @@ export type NextConfigComplete = Required<NextConfig> & {
configFileName: string configFileName: string
} }
export type I18NDomains = DomainLocale[] export type I18NDomains = readonly DomainLocale[]
export interface I18NConfig { export interface I18NConfig {
defaultLocale: string defaultLocale: string
domains?: I18NDomains domains?: I18NDomains
localeDetection?: false localeDetection?: false
locales: string[] locales: readonly string[]
} }
export interface DomainLocale { export interface DomainLocale {
defaultLocale: string defaultLocale: string
domain: string domain: string
http?: true http?: true
locales?: string[] locales?: readonly string[]
} }
export interface ESLintConfig { export interface ESLintConfig {
......
...@@ -55,7 +55,7 @@ export async function loadStaticPaths({ ...@@ -55,7 +55,7 @@ export async function loadStaticPaths({
pathname: string pathname: string
config: RuntimeConfig config: RuntimeConfig
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
isAppPath: boolean isAppPath: boolean
page: string page: string
......
...@@ -142,9 +142,9 @@ class ServerRouter implements NextRouter { ...@@ -142,9 +142,9 @@ class ServerRouter implements NextRouter {
isFallback: boolean isFallback: boolean
locale?: string locale?: string
isReady: boolean isReady: boolean
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: readonly DomainLocale[]
isPreview: boolean isPreview: boolean
isLocaleDomain: boolean isLocaleDomain: boolean
...@@ -156,9 +156,9 @@ class ServerRouter implements NextRouter { ...@@ -156,9 +156,9 @@ class ServerRouter implements NextRouter {
isReady: boolean, isReady: boolean,
basePath: string, basePath: string,
locale?: string, locale?: string,
locales?: string[], locales?: readonly string[],
defaultLocale?: string, defaultLocale?: string,
domainLocales?: DomainLocale[], domainLocales?: readonly DomainLocale[],
isPreview?: boolean, isPreview?: boolean,
isLocaleDomain?: boolean isLocaleDomain?: boolean
) { ) {
...@@ -261,9 +261,9 @@ export type RenderOptsPartial = { ...@@ -261,9 +261,9 @@ export type RenderOptsPartial = {
nextFontManifest?: DeepReadonly<NextFontManifest> nextFontManifest?: DeepReadonly<NextFontManifest>
distDir?: string distDir?: string
locale?: string locale?: string
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: readonly DomainLocale[]
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
supportsDynamicResponse: boolean supportsDynamicResponse: boolean
isBot?: boolean isBot?: boolean
...@@ -848,7 +848,7 @@ export async function renderToHTMLImpl( ...@@ -848,7 +848,7 @@ export async function renderToHTMLImpl(
...(isPreview ...(isPreview
? { draftMode: true, preview: true, previewData: previewData } ? { draftMode: true, preview: true, previewData: previewData }
: undefined), : undefined),
locales: renderOpts.locales, locales: [...(renderOpts.locales ?? [])],
locale: renderOpts.locale, locale: renderOpts.locale,
defaultLocale: renderOpts.defaultLocale, defaultLocale: renderOpts.defaultLocale,
revalidateReason: renderOpts.isOnDemandRevalidate revalidateReason: renderOpts.isOnDemandRevalidate
...@@ -1071,7 +1071,10 @@ export async function renderToHTMLImpl( ...@@ -1071,7 +1071,10 @@ export async function renderToHTMLImpl(
...(previewData !== false ...(previewData !== false
? { draftMode: true, preview: true, previewData: previewData } ? { draftMode: true, preview: true, previewData: previewData }
: undefined), : undefined),
locales: renderOpts.locales, // We create a copy here to avoid having the types of
// `getServerSideProps` change. This ensures that users can't
// mutate this array and have it poison the reference.
locales: [...(renderOpts.locales ?? [])],
locale: renderOpts.locale, locale: renderOpts.locale,
defaultLocale: renderOpts.defaultLocale, defaultLocale: renderOpts.defaultLocale,
}) })
......
...@@ -19,7 +19,7 @@ const pagePathCache = !isDev ? new LRUCache<string | null>(1000) : null ...@@ -19,7 +19,7 @@ const pagePathCache = !isDev ? new LRUCache<string | null>(1000) : null
export function getMaybePagePath( export function getMaybePagePath(
page: string, page: string,
distDir: string, distDir: string,
locales: string[] | undefined, locales: readonly string[] | undefined,
isAppPath: boolean isAppPath: boolean
): string | null { ): string | null {
const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}` const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}`
......
import type { DomainLocale } from '../../../server/config-shared' import type { DomainLocale } from '../../../server/config-shared'
export function detectDomainLocale( export function detectDomainLocale(
domainItems?: DomainLocale[], domainItems?: readonly DomainLocale[],
hostname?: string, hostname?: string,
detectedLocale?: string detectedLocale?: string
) { ) {
......
...@@ -14,7 +14,7 @@ export interface PathLocale { ...@@ -14,7 +14,7 @@ export interface PathLocale {
*/ */
export function normalizeLocalePath( export function normalizeLocalePath(
pathname: string, pathname: string,
locales?: string[] locales?: readonly string[]
): PathLocale { ): PathLocale {
let detectedLocale: string | undefined let detectedLocale: string | undefined
// first item will be empty string from splitting at first char // first item will be empty string from splitting at first char
......
...@@ -348,9 +348,9 @@ export type BaseRouter = { ...@@ -348,9 +348,9 @@ export type BaseRouter = {
asPath: string asPath: string
basePath: string basePath: string
locale?: string | undefined locale?: string | undefined
locales?: string[] | undefined locales?: readonly string[] | undefined
defaultLocale?: string | undefined defaultLocale?: string | undefined
domainLocales?: DomainLocale[] | undefined domainLocales?: readonly DomainLocale[] | undefined
isLocaleDomain: boolean isLocaleDomain: boolean
} }
...@@ -681,9 +681,9 @@ export default class Router implements BaseRouter { ...@@ -681,9 +681,9 @@ export default class Router implements BaseRouter {
isSsr: boolean isSsr: boolean
_inFlightRoute?: string | undefined _inFlightRoute?: string | undefined
_shallow?: boolean | undefined _shallow?: boolean | undefined
locales?: string[] | undefined locales?: readonly string[] | undefined
defaultLocale?: string | undefined defaultLocale?: string | undefined
domainLocales?: DomainLocale[] | undefined domainLocales?: readonly DomainLocale[] | undefined
isReady: boolean isReady: boolean
isLocaleDomain: boolean isLocaleDomain: boolean
isFirstPopStateEvent = true isFirstPopStateEvent = true
...@@ -735,9 +735,9 @@ export default class Router implements BaseRouter { ...@@ -735,9 +735,9 @@ export default class Router implements BaseRouter {
err?: Error err?: Error
isFallback: boolean isFallback: boolean
locale?: string locale?: string
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: readonly DomainLocale[]
isPreview?: boolean isPreview?: boolean
} }
) { ) {
......
...@@ -39,7 +39,7 @@ interface Options { ...@@ -39,7 +39,7 @@ interface Options {
*/ */
nextConfig?: { nextConfig?: {
basePath?: string basePath?: string
i18n?: { locales?: string[] } | null i18n?: { locales?: readonly string[] } | null
trailingSlash?: boolean trailingSlash?: boolean
} }
......
...@@ -17,7 +17,7 @@ export default function resolveRewrites( ...@@ -17,7 +17,7 @@ export default function resolveRewrites(
}, },
query: ParsedUrlQuery, query: ParsedUrlQuery,
resolveHref: (path: string) => string, resolveHref: (path: string) => string,
locales?: string[] locales?: readonly string[]
): { ): {
matchedPage: boolean matchedPage: boolean
parsedAs: ParsedRelativeUrl parsedAs: ParsedRelativeUrl
......
...@@ -107,9 +107,9 @@ export type NEXT_DATA = { ...@@ -107,9 +107,9 @@ export type NEXT_DATA = {
gip?: boolean gip?: boolean
appGip?: boolean appGip?: boolean
locale?: string locale?: string
locales?: string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: readonly DomainLocale[]
scriptLoader?: any[] scriptLoader?: any[]
isPreview?: boolean isPreview?: boolean
notFoundSrcPage?: string notFoundSrcPage?: string
...@@ -150,7 +150,7 @@ export interface NextPageContext { ...@@ -150,7 +150,7 @@ export interface NextPageContext {
/** /**
* All configured locales * All configured locales
*/ */
locales?: string[] locales?: readonly string[]
/** /**
* The configured default locale * The configured default locale
*/ */
......
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