Commit cc8fd49f authored by devjiwonchoi's avatar devjiwonchoi

Revert "[Breaking] Remove AMP"

This reverts commit 3c66eb80.
parent ab15c7ff
export * from './dist/shared/lib/amp'
module.exports = require('./dist/shared/lib/amp')
/// <reference types="./types/global" />
/// <reference types="./types/compiled" />
/// <reference path="./dist/styled-jsx/types/index.d.ts" />
/// <reference path="./amp.d.ts" />
/// <reference path="./app.d.ts" />
/// <reference path="./cache.d.ts" />
/// <reference path="./config.d.ts" />
......
......@@ -47,6 +47,8 @@
"router.d.ts",
"jest.js",
"jest.d.ts",
"amp.js",
"amp.d.ts",
"og.js",
"og.d.ts",
"root-params.js",
......@@ -132,6 +134,7 @@
"sharp": "^0.34.4"
},
"devDependencies": {
"@ampproject/toolbox-optimizer": "2.8.3",
"@babel/code-frame": "7.26.2",
"@babel/core": "7.26.10",
"@babel/eslint-parser": "7.24.6",
......@@ -185,6 +188,7 @@
"@swc/types": "0.1.7",
"@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0",
"@types/amphtml-validator": "1.0.0",
"@types/babel__code-frame": "7.0.6",
"@types/babel__core": "7.20.5",
"@types/babel__generator": "7.27.0",
......@@ -222,6 +226,7 @@
"@vercel/nft": "0.27.1",
"@vercel/turbopack-ecmascript-runtime": "*",
"acorn": "8.14.0",
"amphtml-validator": "1.0.38",
"anser": "1.4.9",
"arg": "4.1.0",
"assert": "2.0.0",
......
import type { NodePath, types, PluginObj } from 'next/dist/compiled/babel/core'
export default function AmpAttributePatcher(): PluginObj {
return {
visitor: {
JSXOpeningElement(path: NodePath<types.JSXOpeningElement>) {
const openingElement = path.node
const { name, attributes } = openingElement
if (!(name && name.type === 'JSXIdentifier')) {
return
}
if (!name.name.startsWith('amp-')) {
return
}
for (const attribute of attributes) {
if (attribute.type !== 'JSXAttribute') {
continue
}
if (attribute.name.name === 'className') {
attribute.name.name = 'class'
}
}
},
},
}
}
......@@ -5,9 +5,28 @@ import type {
Visitor,
NodePath,
} from 'next/dist/compiled/babel/core'
import type { PageConfig } from '../../../types'
import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants'
const CONFIG_KEY = 'config'
// replace program path with just a variable with the drop identifier
function replaceBundle(path: any, t: typeof BabelTypes): void {
path.parentPath.replaceWith(
t.program(
[
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(STRING_LITERAL_DROP_BUNDLE),
t.stringLiteral(`${STRING_LITERAL_DROP_BUNDLE} ${Date.now()}`)
),
]),
],
[]
)
)
}
function errorMessage(state: any, details: string): string {
const pageName =
(state.filename || '').split(state.cwd || '').pop() || 'unknown'
......@@ -65,6 +84,7 @@ export default function nextPageConfig({
return
}
const config: PageConfig = {}
const declarations: BabelTypes.VariableDeclarator[] = [
...((
exportPath.node
......@@ -146,8 +166,41 @@ export default function nextPageConfig({
)
)
}
const { name } = prop.key as BabelTypes.Identifier
if (BabelTypes.isIdentifier(prop.key, { name: 'amp' })) {
if (!BabelTypes.isObjectProperty(prop)) {
throw new Error(
errorMessage(
exportState,
`Invalid property "${name}"`
)
)
}
if (
!BabelTypes.isBooleanLiteral(prop.value) &&
!BabelTypes.isStringLiteral(prop.value)
) {
throw new Error(
errorMessage(
exportState,
`Invalid value for "${name}"`
)
)
}
config.amp = prop.value.value as PageConfig['amp']
}
}
}
if (config.amp === true) {
if (!exportState.file?.opts?.caller.isDev) {
// don't replace bundle in development so HMR can track
// dependencies and trigger reload when they are changed
replaceBundle(exportPath, t)
}
exportState.bundleDropped = true
return
}
},
},
state
......
......@@ -318,6 +318,7 @@ export default (
: (require('styled-jsx/babel') as typeof import('styled-jsx/babel')),
styledJsxOptions(options['styled-jsx']),
],
require('./plugins/amp-attributes') as typeof import('./plugins/amp-attributes'),
isProduction && [
require('next/dist/compiled/babel/plugin-transform-react-remove-prop-types') as typeof import('next/dist/compiled/babel/plugin-transform-react-remove-prop-types'),
{
......
......@@ -79,12 +79,14 @@ export async function collectBuildTraces({
edgeRuntimeRoutes,
staticPages,
nextBuildSpan = new Span({ name: 'build' }),
hasSsrAmpPages,
buildTraceContext,
outputFileTracingRoot,
}: {
dir: string
distDir: string
staticPages: string[]
hasSsrAmpPages: boolean
outputFileTracingRoot: string
// pageInfos is serialized when this function runs in a worker.
edgeRuntimeRoutes: RoutesUsingEdgeRuntime
......@@ -231,6 +233,10 @@ export async function collectBuildTraces({
]
: []),
...(!hasSsrAmpPages
? ['**/next/dist/compiled/@ampproject/toolbox-optimizer/**/*']
: []),
...(isStandalone ? [] : TRACE_IGNORES),
...additionalIgnores,
]
......@@ -263,6 +269,7 @@ export async function collectBuildTraces({
// as otherwise all chunks are traced here and included for all pages
// whether they are needed or not
'**/.next/server/chunks/**',
'**/next/dist/server/optimize-amp.js',
'**/next/dist/server/post-process.js',
].filter(nonNullable)
......
......@@ -29,6 +29,7 @@ import {
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../shared/lib/constants'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
......@@ -1143,6 +1144,7 @@ export function finalizeEntrypoint({
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) {
if (isAppLayer) {
......
......@@ -1747,6 +1747,7 @@ export default async function build(
new Map()
),
staticPages: [],
hasSsrAmpPages: false,
buildTraceContext,
outputFileTracingRoot,
})
......@@ -1851,6 +1852,7 @@ export default async function build(
const ssgBlockingFallbackPages = new Set<string>()
const staticPages = new Set<string>()
const invalidPages = new Set<string>()
const hybridAmpPages = new Set<string>()
const serverPropsPages = new Set<string>()
const additionalPaths = new Map<string, PrerenderedRoute[]>()
const staticPaths = new Map<string, PrerenderedRoute[]>()
......@@ -1894,6 +1896,7 @@ export default async function build(
customAppGetInitialProps,
namedExports,
isNextImageImported,
hasSsrAmpPages,
hasNonStaticErrorPage,
} = await staticCheckSpan.traceAsyncFn(async () => {
if (isCompileMode) {
......@@ -1901,6 +1904,7 @@ export default async function build(
customAppGetInitialProps: false,
namedExports: [],
isNextImageImported: true,
hasSsrAmpPages: !!pagesDir,
hasNonStaticErrorPage: hasUserPagesRoutes,
}
}
......@@ -1971,6 +1975,8 @@ export default async function build(
// eslint-disable-next-line @typescript-eslint/no-shadow
let isNextImageImported: boolean | undefined
// eslint-disable-next-line @typescript-eslint/no-shadow
let hasSsrAmpPages = false
const middlewareManifest: MiddlewareManifest = require(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)
......@@ -2034,6 +2040,7 @@ export default async function build(
let isSSG = false
let isStatic = false
let isServerComponent = false
let isHybridAmp = false
let ssgPageRoutes: string[] | null = null
let pagePath = ''
......@@ -2278,6 +2285,18 @@ export default async function build(
workerResult.hasStaticProps = false
}
if (
workerResult.isStatic === false &&
(workerResult.isHybridAmp || workerResult.isAmpOnly)
) {
hasSsrAmpPages = true
}
if (workerResult.isHybridAmp) {
isHybridAmp = true
hybridAmpPages.add(page)
}
if (workerResult.isNextImageImported) {
isNextImageImported = true
}
......@@ -2379,6 +2398,7 @@ export default async function build(
isStatic,
isSSG,
isRoutePPREnabled,
isHybridAmp,
ssgPageRoutes,
initialCacheControl: undefined,
runtime: pageRuntime,
......@@ -2399,6 +2419,7 @@ export default async function build(
customAppGetInitialProps: await customAppGetInitialPropsPromise,
namedExports: await namedExportsPromise,
isNextImageImported,
hasSsrAmpPages,
hasNonStaticErrorPage: nonStaticErrorPage,
}
......@@ -2537,6 +2558,22 @@ export default async function build(
return serverFilesManifest
})
if (!hasSsrAmpPages) {
requiredServerFilesManifest.ignore.push(
path.relative(
dir,
path.join(
path.dirname(
require.resolve(
'next/dist/compiled/@ampproject/toolbox-optimizer'
)
),
'**/*'
)
)
)
}
const middlewareFile = rootPaths.find((p) =>
p.includes(MIDDLEWARE_FILENAME)
)
......@@ -2596,6 +2633,7 @@ export default async function build(
edgeRuntimeRoutes: collectRoutesUsingEdgeRuntime(pageInfos),
staticPages: [...staticPages],
nextBuildSpan,
hasSsrAmpPages,
buildTraceContext,
outputFileTracingRoot,
}).catch((err) => {
......@@ -3722,6 +3760,7 @@ export default async function build(
const isSsg = ssgPages.has(page)
const isStaticSsgFallback = ssgStaticFallbackPages.has(page)
const isDynamic = isDynamicRoute(page)
const hasAmp = hybridAmpPages.has(page)
const file = normalizePagePath(page)
const pageInfo = pageInfos.get(page)
......@@ -3752,6 +3791,15 @@ export default async function build(
await moveExportedPage(page, page, file, isSsg, 'html')
}
if (hasAmp && (!isSsg || (isSsg && !isDynamic))) {
const ampPage = `${file}.amp`
await moveExportedPage(page, ampPage, ampPage, isSsg, 'html')
if (isSsg) {
await moveExportedPage(page, ampPage, ampPage, isSsg, 'json')
}
}
if (isSsg) {
// For a non-dynamic SSG page, we must copy its data file
// from export, we already moved the HTML file above
......@@ -3826,6 +3874,26 @@ export default async function build(
true
)
if (hasAmp) {
const ampPage = `${pageFile}.amp`
await moveExportedPage(
page,
ampPage,
ampPage,
isSsg,
'html',
true
)
await moveExportedPage(
page,
ampPage,
ampPage,
isSsg,
'json',
true
)
}
const cacheControl = getCacheControl(route.pathname)
prerenderManifest.routes[route.pathname] = {
......
import { bold, red, yellow } from '../../lib/picocolors'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import textTable from 'next/dist/compiled/text-table'
import createStore from 'next/dist/compiled/unistore'
import formatWebpackMessages from '../../shared/lib/format-webpack-messages'
import { store as consoleStore } from './store'
......@@ -16,12 +19,79 @@ type WebpackStatus =
| { loading: true }
| ({ loading: false } & CompilerDiagnostics)
type AmpStatus = {
message: string
line: number
col: number
specUrl: string | null
code: string
}
export type AmpPageStatus = {
[page: string]: { errors: AmpStatus[]; warnings: AmpStatus[] }
}
type BuildStatusStore = {
client: WebpackStatus
server: WebpackStatus
edgeServer: WebpackStatus
trigger: string | undefined
url: string | undefined
amp: AmpPageStatus
}
export function formatAmpMessages(amp: AmpPageStatus) {
let output = bold('Amp Validation') + '\n\n'
let messages: string[][] = []
const chalkError = red('error')
function ampError(page: string, error: AmpStatus) {
messages.push([page, chalkError, error.message, error.specUrl || ''])
}
const chalkWarn = yellow('warn')
function ampWarn(page: string, warn: AmpStatus) {
messages.push([page, chalkWarn, warn.message, warn.specUrl || ''])
}
for (const page in amp) {
let { errors, warnings } = amp[page]
const devOnlyFilter = (err: AmpStatus) => err.code !== 'DEV_MODE_ONLY'
errors = errors.filter(devOnlyFilter)
warnings = warnings.filter(devOnlyFilter)
if (!(errors.length || warnings.length)) {
// Skip page with no non-dev warnings
continue
}
if (errors.length) {
ampError(page, errors[0])
for (let index = 1; index < errors.length; ++index) {
ampError('', errors[index])
}
}
if (warnings.length) {
ampWarn(errors.length ? '' : page, warnings[0])
for (let index = 1; index < warnings.length; ++index) {
ampWarn('', warnings[index])
}
}
messages.push(['', '', '', ''])
}
if (!messages.length) {
return ''
}
output += textTable(messages, {
align: ['l', 'l', 'l', 'l'],
stringLength(str: string) {
return stripAnsi(str).length
},
})
return output
}
const buildStore = createStore<BuildStatusStore>({
......@@ -38,7 +108,7 @@ let serverWasLoading = true
let edgeServerWasLoading = false
buildStore.subscribe((state) => {
const { client, server, edgeServer, trigger, url } = state
const { amp, client, server, edgeServer, trigger, url } = state
const { appUrl } = consoleStore.getState()
......@@ -109,7 +179,7 @@ buildStore.subscribe((state) => {
...(client.warnings || []),
...(server.warnings || []),
...(edgeServer.warnings || []),
]
].concat(formatAmpMessages(amp) || [])
consoleStore.setState(
{
......@@ -122,6 +192,32 @@ buildStore.subscribe((state) => {
}
})
export function ampValidation(
page: string,
errors: AmpStatus[],
warnings: AmpStatus[]
) {
const { amp } = buildStore.getState()
if (!(errors.length || warnings.length)) {
buildStore.setState({
amp: Object.keys(amp)
.filter((k) => k !== page)
.sort()
// eslint-disable-next-line no-sequences
.reduce((a, c) => ((a[c] = amp[c]), a), {} as AmpPageStatus),
})
return
}
const newAmp: AmpPageStatus = { ...amp, [page]: { errors, warnings } }
buildStore.setState({
amp: Object.keys(newAmp)
.sort()
// eslint-disable-next-line no-sequences
.reduce((a, c) => ((a[c] = newAmp[c]), a), {} as AmpPageStatus),
})
}
export function watchCompilers(
client: webpack.Compiler,
server: webpack.Compiler,
......@@ -145,6 +241,8 @@ export function watchCompilers(
})
compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: webpack.Stats) => {
buildStore.setState({ amp: {} })
const { errors, warnings } = formatWebpackMessages(
stats.toJson({
preset: 'errors-warnings',
......
import createStore from 'next/dist/compiled/unistore'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { type Span, flushAllTraces, trace } from '../../trace'
import { teardownTraceSubscriber } from '../swc'
import * as Log from './log'
......@@ -134,6 +135,19 @@ store.subscribe((state) => {
// Log compilation errors
Log.error(state.errors[0])
const cleanError = stripAnsi(state.errors[0])
if (cleanError.indexOf('SyntaxError') > -1) {
const matches = cleanError.match(/\[.*\]=/)
if (matches) {
for (const match of matches) {
const prop = (match.split(']').shift() || '').slice(1)
console.log(
`AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt`
)
}
return
}
}
startTime = 0
// Ensure traces are flushed after each compile in development mode
flushAllTraces()
......
......@@ -20,6 +20,11 @@ const PagesSegmentConfigSchema = z.object({
*/
config: z
.object({
/**
* Enables AMP for the page.
*/
amp: z.union([z.boolean(), z.literal('hybrid')]).optional(),
/**
* The runtime to use for the page.
*/
......@@ -63,6 +68,11 @@ export const PagesSegmentConfigSchemaKeys =
PagesSegmentConfigSchema.keyof().options
export type PagesSegmentConfigConfig = {
/**
* Enables AMP for the page.
*/
amp?: boolean | 'hybrid'
/**
* The maximum duration for the page render.
*/
......
......@@ -141,7 +141,9 @@ async function requestHandler(
ComponentMod: pageMod,
pageConfig: pageMod.pageConfig,
routeModule: pageMod.routeModule,
canonicalBase: nextConfig.amp.canonicalBase || '',
previewProps: prerenderManifest.preview,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer,
basePath: nextConfig.basePath,
assetPrefix: nextConfig.assetPrefix,
images: nextConfig.images,
......
import type { NextConfigComplete } from '../server/config-shared'
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr'
import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type { ServerRuntime } from '../types'
import type { PageConfig, ServerRuntime } from '../types'
import type { BuildManifest } from '../server/get-page-files'
import type {
Redirect,
......@@ -56,6 +56,7 @@ import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
import { Sema } from 'next/dist/compiled/async-sema'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getRuntimeContext } from '../server/web/sandbox'
import { isClientReference } from '../lib/client-and-server-references'
import { RouteKind } from '../server/route-kind'
import type { PageExtensions } from './page-extensions-type'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
......@@ -136,6 +137,7 @@ const filterAndSortList = (
export interface PageInfo {
originalAppPath: string | undefined
isHybridAmp?: boolean
isStatic: boolean
isSSG: boolean
/**
......@@ -180,6 +182,7 @@ export async function printTreeView(
{
pagesDir,
pageExtensions,
buildManifest,
middlewareManifest,
useStaticPages404,
}: {
......@@ -267,6 +270,9 @@ export async function printTreeView(
: '├'
const pageInfo = pageInfos.get(item)
const ampLabel = buildManifest.ampFirstPages.includes(item)
? ` ${cyan('AMP')}`
: ''
const totalDuration =
(pageInfo?.pageDuration || 0) +
(pageInfo?.ssgPageDurations?.reduce((a, b) => a + (b || 0), 0) || 0)
......@@ -303,7 +309,7 @@ export async function printTreeView(
usedSymbols.add(symbol)
messages.push([
`${border} ${symbol} ${item}${
`${border} ${symbol} ${item}${ampLabel}${
totalDuration > MIN_DURATION
? ` (${getPrettyDuration(totalDuration)})`
: ''
......@@ -543,6 +549,8 @@ export function printCustomRoutes({
type PageIsStaticResult = {
isRoutePPREnabled?: boolean
isStatic?: boolean
isAmpOnly?: boolean
isHybridAmp?: boolean
hasServerProps?: boolean
hasStaticProps?: boolean
prerenderedRoutes: PrerenderedRoute[] | undefined
......@@ -612,6 +620,8 @@ export async function isPageStatic({
return {
isStatic: true,
isRoutePPREnabled: false,
isHybridAmp: false,
isAmpOnly: false,
prerenderFallbackMode: undefined,
prerenderedRoutes: undefined,
rootParamKeys: undefined,
......@@ -646,6 +656,7 @@ export async function isPageStatic({
let prerenderFallbackMode: FallbackMode | undefined
let appConfig: AppSegmentConfig = {}
let rootParamKeys: readonly string[] | undefined
let isClientComponent: boolean = false
const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime)
if (pathIsEdgeRuntime) {
......@@ -669,6 +680,7 @@ export async function isPageStatic({
// This is not needed during require.
const buildManifest = {} as BuildManifest
isClientComponent = isClientReference(mod)
componentsResult = {
Component: mod.default,
Document: mod.Document,
......@@ -703,6 +715,8 @@ export async function isPageStatic({
if (pageType === 'app') {
const ComponentMod: AppPageModule = componentsResult.ComponentMod
isClientComponent = isClientReference(componentsResult.ComponentMod)
let segments: AppSegment[]
try {
segments = await collectSegments(
......@@ -820,6 +834,9 @@ export async function isPageStatic({
}
const isNextImageImported = (globalThis as any).__NEXT_IMAGE_IMPORTED
const config: PageConfig = isClientComponent
? {}
: componentsResult.pageConfig
let isStatic = false
if (!hasStaticProps && !hasGetInitialProps && !hasServerProps) {
......@@ -835,6 +852,8 @@ export async function isPageStatic({
return {
isStatic,
isRoutePPREnabled,
isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true,
prerenderFallbackMode,
prerenderedRoutes,
rootParamKeys,
......
......@@ -18,6 +18,7 @@ import {
} from './utils'
import type { CustomRoutes } from '../lib/load-custom-routes.js'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
......@@ -40,6 +41,7 @@ import MiddlewarePlugin, {
} from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
......@@ -709,6 +711,14 @@ export default async function getBaseWebpackConfig(
...(dev
? {
[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: reactRefreshEntry,
[CLIENT_STATIC_FILES_RUNTIME_AMP]:
`./` +
path
.relative(
dir,
path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'dev', 'amp-dev')
)
.replace(/\\/g, '/'),
}
: {}),
[CLIENT_STATIC_FILES_RUNTIME_MAIN]:
......@@ -2017,6 +2027,8 @@ export default async function getBaseWebpackConfig(
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
dev,
}),
// rspack doesn't support the parser hooks used here
!isRspack && (isClient || isEdgeServer) && new DropClientPage(),
isNodeServer &&
!dev &&
new ((
......
......@@ -10,10 +10,12 @@ import {
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
SYSTEM_ENTRYPOINTS,
} from '../../../shared/lib/constants'
import type { BuildManifest } from '../../../server/get-page-files'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { Span } from '../../../trace'
import { getCompilationSpan } from '../utils'
......@@ -144,10 +146,24 @@ export default class BuildManifestPlugin {
const assetMap: DeepMutable<BuildManifest> = {
polyfillFiles: [],
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
rootMainFiles: [],
rootMainFilesTree: {},
pages: { '/_app': [] },
ampFirstPages: [],
}
const ampFirstEntryNames = ampFirstEntryNamesMap.get(compilation)
if (ampFirstEntryNames) {
for (const entryName of ampFirstEntryNames) {
const pagePath = getRouteFromEntrypoint(entryName)
if (!pagePath) {
continue
}
assetMap.ampFirstPages.push(pagePath)
}
}
const mainFiles = new Set(
......@@ -187,6 +203,10 @@ export default class BuildManifestPlugin {
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH)
).filter((file) => !mainFiles.has(file))
assetMap.ampDevFiles = getEntrypointFiles(
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_AMP)
)
for (const entrypoint of compilation.entrypoints.values()) {
if (SYSTEM_ENTRYPOINTS.has(entrypoint.name)) continue
const pagePath = getRouteFromEntrypoint(entrypoint.name)
......
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants'
export const ampFirstEntryNamesMap: WeakMap<webpack.Compilation, string[]> =
new WeakMap()
const PLUGIN_NAME = 'DropAmpFirstPagesPlugin'
// Prevents outputting client pages when they are not needed
export class DropClientPage implements webpack.WebpackPluginInstance {
ampPages = new Set()
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation: any, { normalModuleFactory }: any) => {
// Recursively look up the issuer till it ends up at the root
function findEntryModule(mod: any): webpack.Module | null {
const queue = new Set([mod])
for (const module of queue) {
const incomingConnections =
compilation.moduleGraph.getIncomingConnections(module)
for (const incomingConnection of incomingConnections) {
if (!incomingConnection.originModule) return module
queue.add(incomingConnection.originModule)
}
}
return null
}
function handler(parser: any) {
function markAsAmpFirst() {
const entryModule = findEntryModule(parser.state.module)
if (!entryModule) {
return
}
// @ts-ignore buildInfo exists on Module
entryModule.buildInfo.NEXT_ampFirst = true
}
parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator: any) => {
if (declarator?.id?.name === STRING_LITERAL_DROP_BUNDLE) {
markAsAmpFirst()
}
})
}
normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(PLUGIN_NAME, handler)
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap(PLUGIN_NAME, handler)
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap(PLUGIN_NAME, handler)
if (!ampFirstEntryNamesMap.has(compilation)) {
ampFirstEntryNamesMap.set(compilation, [])
}
const ampFirstEntryNamesItem = ampFirstEntryNamesMap.get(
compilation
) as string[]
compilation.hooks.seal.tap(PLUGIN_NAME, () => {
for (const [name, entryData] of compilation.entries) {
for (const dependency of entryData.dependencies) {
const module = compilation.moduleGraph.getModule(dependency)
if (module?.buildInfo?.NEXT_ampFirst) {
ampFirstEntryNamesItem.push(name)
compilation.entries.delete(name)
}
}
}
})
}
)
}
}
/* globals __webpack_hash__ */
import { displayContent } from './fouc'
import initOnDemandEntries from './on-demand-entries-client'
import { addMessageListener, connectHMR } from './hot-reloader/pages/websocket'
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types'
import { reportInvalidHmrMessage } from './hot-reloader/shared'
/// <reference types="webpack/module.d.ts" />
const data = JSON.parse(
(document.getElementById('__NEXT_DATA__') as any).textContent
)
window.__NEXT_DATA__ = data
let { assetPrefix, page } = data
assetPrefix = assetPrefix || ''
let mostRecentHash: null | string = null
/* eslint-disable-next-line */
let curHash = __webpack_hash__
const hotUpdatePath =
assetPrefix + (assetPrefix.endsWith('/') ? '' : '/') + '_next/static/webpack/'
// Is there a newer version of this code available?
function isUpdateAvailable() {
// __webpack_hash__ is the hash of the current compilation.
// It's a global variable injected by Webpack.
/* eslint-disable-next-line */
return mostRecentHash !== __webpack_hash__
}
// Webpack disallows updates in other states.
function canApplyUpdates() {
return module.hot.status() === 'idle'
}
// This function reads code updates on the fly and hard
// reloads the page when it has changed.
async function tryApplyUpdates() {
if (!isUpdateAvailable() || !canApplyUpdates()) {
return
}
try {
const res = await fetch(
typeof __webpack_runtime_id__ !== 'undefined'
? // eslint-disable-next-line no-undef
`${hotUpdatePath}${curHash}.${__webpack_runtime_id__}.hot-update.json`
: `${hotUpdatePath}${curHash}.hot-update.json`
)
const jsonData = await res.json()
const curPage = page === '/' ? 'index' : page
// webpack 5 uses an array instead
const pageUpdated = (
Array.isArray(jsonData.c) ? jsonData.c : Object.keys(jsonData.c)
).some((mod: string) => {
return (
mod.indexOf(
`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`
) !== -1 ||
mod.indexOf(
`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`.replace(
/\//g,
'\\'
)
) !== -1
)
})
if (pageUpdated) {
window.location.reload()
} else {
curHash = mostRecentHash as string
}
} catch (err) {
console.error('Error occurred checking for update', err)
window.location.reload()
}
}
addMessageListener((message) => {
try {
// messages which are not related to amp-dev
if (
message.type === HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ERROR ||
message.type === HMR_MESSAGE_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE
) {
return
}
if (
message.type === HMR_MESSAGE_SENT_TO_BROWSER.SYNC ||
message.type === HMR_MESSAGE_SENT_TO_BROWSER.BUILT
) {
if (!message.hash) {
return
}
mostRecentHash = message.hash
tryApplyUpdates()
} else if (message.type === HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE) {
window.location.reload()
}
} catch (err: unknown) {
reportInvalidHmrMessage(message, err)
}
})
connectHMR({
assetPrefix,
path: '/_next/webpack-hmr',
})
displayContent()
initOnDemandEntries(data.page)
......@@ -8,7 +8,8 @@ export default async (page?: string) => {
return
}
if (page) {
// ping the initial page periodically
// in AMP the router isn't initialized on the client and
// client-transitions don't occur so ping initial page
setInterval(() => {
sendMessage(JSON.stringify({ event: 'ping', page }))
}, 2500)
......
import AmpHtmlValidator, {
type Validator,
} from 'next/dist/compiled/amphtml-validator'
const instancePromises = new Map<string | undefined, Promise<Validator>>()
/**
* `AmpHtmlValidator.getInstance` is buggy when multiple calls to getInstance occur in parallel.
* This wrapper is a workaround for that.
*
* `AmpHtmlValidator.getInstance(validatorPath)` attempts to re-use the instances across multiple calls
* by stashing existing instances in `instanceByValidatorJs`.
* However, when creating a fresh instance, it is added to `instanceByValidatorJs` before `instance.init()` is finished:
* https://github.com/ampproject/amphtml/blob/0c8eaba73ca8f5c462a642fa91901a29e6304f6e/validator/js/nodejs/index.js#L309-L313
*
* which means that, if a concurrent call to `AmpHtmlValidator.getInstance(validatorPath)` happens before the original `init()` is done,
* then we'll get back an uninitialized or partially initialized instance:
* https://github.com/ampproject/amphtml/blob/0c8eaba73ca8f5c462a642fa91901a29e6304f6e/validator/js/nodejs/index.js#L292-L294
*
* And, since `instance.init()` is the part that handles loading the webassembly code, this race results in
* the dreaded "AssertionError: Assertion failed: WebAssembly is uninitialized" error.
* As a workaround, we properly dedupe instance creation on our own.
* */
export function getAmpValidatorInstance(
validatorPath: string | undefined
): Promise<Validator> {
let promise = instancePromises.get(validatorPath)
if (!promise) {
// NOTE: if `validatorPath` is undefined, `AmpHtmlValidator` will load the code from its default URL
promise = AmpHtmlValidator.getInstance(validatorPath)
instancePromises.set(validatorPath, promise)
}
return promise
}
export function getBundledAmpValidatorFilepath() {
return require.resolve(
'next/dist/compiled/amphtml-validator/validator_wasm.js'
)
}
......@@ -19,6 +19,8 @@ import { existsSync, promises as fs } from 'fs'
import '../server/require-hook'
import { dirname, join, resolve, sep, relative } from 'path'
import { formatAmpMessages } from '../build/output/index'
import type { AmpPageStatus } from '../build/output/index'
import * as Log from '../build/output/log'
import {
RSC_SEGMENT_SUFFIX,
......@@ -364,6 +366,9 @@ async function exportAppImpl(
dev: false,
basePath: nextConfig.basePath,
trailingSlash: nextConfig.trailingSlash,
canonicalBase: nextConfig.amp?.canonicalBase || '',
ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
locales: i18n?.locales,
locale: i18n?.defaultLocale,
defaultLocale: i18n?.defaultLocale,
......@@ -556,6 +561,8 @@ async function exportAppImpl(
? outDir
: join(outDir, '_next/data', buildId)
const ampValidations: AmpPageStatus = {}
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
// Copy public directory
if (!options.buildExport && existsSync(publicDir)) {
......@@ -693,6 +700,8 @@ async function exportAppImpl(
}
}
let hadValidationError = false
const collector: ExportAppResult = {
byPath: new Map(),
byPage: new Map(),
......@@ -718,6 +727,14 @@ async function exportAppImpl(
)
}
// Capture any amp validations.
if (result.ampValidations) {
for (const validation of result.ampValidations) {
ampValidations[validation.page] = validation.result
hadValidationError ||= validation.result.errors.length > 0
}
}
if (options.buildExport) {
// Update path info by path.
const info = collector.byPath.get(path) ?? {}
......@@ -848,6 +865,10 @@ async function exportAppImpl(
subFolders && route !== '/index' ? `${sep}index` : ''
}.html`
)
const ampHtmlDest = join(
outDir,
`${route}.amp${subFolders ? `${sep}index` : ''}.html`
)
const jsonDest = isAppPath
? join(
outDir,
......@@ -866,6 +887,11 @@ async function exportAppImpl(
await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest)
if (existsSync(`${orig}.amp.html`)) {
await fs.mkdir(dirname(ampHtmlDest), { recursive: true })
await fs.copyFile(`${orig}.amp.html`, ampHtmlDest)
}
const segmentsDir = `${orig}${RSC_SEGMENTS_DIR_SUFFIX}`
if (isAppPath && existsSync(segmentsDir)) {
......@@ -899,6 +925,15 @@ async function exportAppImpl(
)
}
if (Object.keys(ampValidations).length) {
console.log(formatAmpMessages(ampValidations))
}
if (hadValidationError) {
throw new ExportError(
`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`
)
}
if (failedExportAttemptsByPage.size > 0) {
const failedPages = Array.from(failedExportAttemptsByPage.keys())
throw new ExportError(
......
......@@ -5,6 +5,7 @@ import type {
RenderOpts,
} from '../../server/render'
import type { LoadComponentsReturnType } from '../../server/load-components'
import type { AmpValidation } from '../types'
import type { NextParsedUrlQuery } from '../../server/request-meta'
import type { Params } from '../../server/request/params'
......@@ -14,14 +15,20 @@ import type {
MockedRequest,
MockedResponse,
} from '../../server/lib/mock-request'
import { isInAmpMode } from '../../shared/lib/amp-mode'
import {
HTML_CONTENT_TYPE_HEADER,
NEXT_DATA_SUFFIX,
SERVER_PROPS_EXPORT_ERROR,
} from '../../lib/constants'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { FileType, fileExists } from '../../lib/file-exists'
import { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render'
import type { MultiFileWriter } from '../../lib/multi-file-writer'
import {
getAmpValidatorInstance,
getBundledAmpValidatorFilepath,
} from '../helpers/get-amp-html-validator'
/**
* Renders & exports a page associated with the /pages directory
......@@ -35,6 +42,10 @@ export async function exportPagesPage(
params: Params | undefined,
htmlFilepath: string,
htmlFilename: string,
ampPath: string,
subFolders: boolean,
outDir: string,
ampValidatorPath: string | undefined,
pagesDataDir: string,
buildExport: boolean,
isDynamic: boolean,
......@@ -45,6 +56,19 @@ export async function exportPagesPage(
components: LoadComponentsReturnType,
fileWriter: MultiFileWriter
): Promise<ExportRouteResult | undefined> {
const ampState = {
ampFirst: components.pageConfig?.amp === true,
hasQuery: Boolean(query.amp),
hybrid: components.pageConfig?.amp === 'hybrid',
}
if (!ampValidatorPath) {
ampValidatorPath = getBundledAmpValidatorFilepath()
}
const inAmpMode = isInAmpMode(ampState)
const hybridAmp = ampState.hybrid
if (components.getServerSideProps) {
throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`)
}
......@@ -109,10 +133,109 @@ export async function exportPagesPage(
const ssgNotFound = renderResult?.metadata.isNotFound
const ampValidations: AmpValidation[] = []
const validateAmp = async (
rawAmpHtml: string,
ampPageName: string,
validatorPath: string | undefined
) => {
const validator = await getAmpValidatorInstance(validatorPath)
const result = validator.validateString(rawAmpHtml)
const errors = result.errors.filter((error) => {
if (error.severity === 'ERROR') {
// Unclear yet if these actually prevent the page from being indexed by the AMP cache.
// These are coming from React so all we can do is ignore them for now.
// <link rel="expect" blocking="render" />
// https://github.com/ampproject/amphtml/issues/40279
if (
error.code === 'DISALLOWED_ATTR' &&
error.params[0] === 'blocking' &&
error.params[1] === 'link'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MANDATORY_ATTR_MISSING' &&
error.params[0] === 'type' &&
error.params[1] === 'template'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MISSING_REQUIRED_EXTENSION' &&
error.params[0] === 'template' &&
error.params[1] === 'amp-mustache'
) {
return false
}
return true
}
return false
})
const warnings = result.errors.filter((e) => e.severity !== 'ERROR')
if (warnings.length || errors.length) {
ampValidations.push({
page: ampPageName,
result: {
errors,
warnings,
},
})
}
}
const html =
renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : ''
const metadata = renderResult?.metadata || {}
let ampRenderResult: RenderResult | undefined
if (inAmpMode && !renderOpts.ampSkipValidation) {
if (!ssgNotFound) {
await validateAmp(html, path, ampValidatorPath)
}
} else if (hybridAmp) {
const ampHtmlFilename = subFolders
? join(ampPath, 'index.html')
: `${ampPath}.html`
const ampHtmlFilepath = join(outDir, ampHtmlFilename)
const exists = await fileExists(ampHtmlFilepath, FileType.File)
if (!exists) {
try {
ampRenderResult = await lazyRenderPagesPage(
req,
res,
page,
{ ...searchAndDynamicParams, amp: '1' },
renderOpts,
sharedContext,
renderContext
)
} catch (err) {
if (!isBailoutToCSRError(err)) throw err
}
const ampHtml =
ampRenderResult && !ampRenderResult.isNull
? ampRenderResult.toUnchunkedString()
: ''
if (!renderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + '?amp=1', ampValidatorPath)
}
fileWriter.append(ampHtmlFilepath, ampHtml)
}
}
const metadata = renderResult?.metadata || ampRenderResult?.metadata || {}
if (metadata.pageData) {
const dataFile = join(
pagesDataDir,
......@@ -120,6 +243,13 @@ export async function exportPagesPage(
)
fileWriter.append(dataFile, JSON.stringify(metadata.pageData))
if (hybridAmp) {
fileWriter.append(
dataFile.replace(/\.json$/, '.amp.json'),
JSON.stringify(metadata.pageData)
)
}
}
if (!ssgNotFound) {
......@@ -128,6 +258,7 @@ export async function exportPagesPage(
}
return {
ampValidations,
cacheControl: metadata.cacheControl ?? {
revalidate: false,
expire: undefined,
......
......@@ -2,6 +2,7 @@ import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-re
import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render'
import type { LoadComponentsReturnType } from '../server/load-components'
import type { OutgoingHttpHeaders } from 'http'
import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { CacheControl } from '../server/lib/cache-control'
import type { NextEnabledDirectories } from '../server/base-server'
......@@ -13,6 +14,14 @@ import type { FetchMetrics } from '../server/base-http'
import type { RouteMetadata } from './routes/types'
import type { RenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
export interface AmpValidation {
page: string
result: {
errors: AmpHtmlValidator.ValidationError[]
warnings: AmpHtmlValidator.ValidationError[]
}
}
export type ExportPathEntry = ExportPathMap[keyof ExportPathMap] & {
path: string
}
......@@ -42,6 +51,7 @@ export interface ExportPageInput {
outDir: string
pagesDataDir: string
renderOpts: WorkerRenderOptsPartial
ampValidatorPath?: string
trailingSlash?: boolean
buildExport?: boolean
serverRuntimeConfig: { [key: string]: any }
......@@ -59,6 +69,7 @@ export interface ExportPageInput {
export type ExportRouteResult =
| {
ampValidations?: AmpValidation[]
cacheControl: CacheControl
metadata?: Partial<RouteMetadata>
ssgNotFound?: boolean
......
......@@ -81,6 +81,7 @@ async function exportPageImpl(
disableOptimizedLoading,
debugOutput = false,
enableExperimentalReact,
ampValidatorPath,
trailingSlash,
sriEnabled,
renderOpts: commonRenderOpts,
......@@ -127,6 +128,8 @@ async function exportPageImpl(
const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir
const filePath = normalizePagePath(path)
const ampPath = `${filePath}.amp`
let renderAmpPath = ampPath
let updatedPath = exportPath._ssgPath || path
let locale = exportPath._locale || commonRenderOpts.locale
......@@ -137,6 +140,10 @@ async function exportPageImpl(
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname
locale = localePathResult.detectedLocale
if (locale === commonRenderOpts.defaultLocale) {
renderAmpPath = `${normalizePagePath(updatedPath)}.amp`
}
}
}
......@@ -256,6 +263,7 @@ async function exportPageImpl(
const renderOpts: WorkerRenderOpts = {
...components,
...commonRenderOpts,
ampPath: renderAmpPath,
params,
optimizeCss,
disableOptimizedLoading,
......@@ -316,6 +324,10 @@ async function exportPageImpl(
params,
htmlFilepath,
htmlFilename,
ampPath,
subFolders,
outDir,
ampValidatorPath,
pagesDataDir,
buildExport,
isDynamic,
......@@ -401,6 +413,8 @@ export async function exportPages(
outDir,
pagesDataDir,
renderOpts,
ampValidatorPath:
nextConfig.experimental.amp?.validator || undefined,
trailingSlash: nextConfig.trailingSlash,
serverRuntimeConfig: nextConfig.serverRuntimeConfig,
subFolders: nextConfig.trailingSlash && !options.buildExport,
......
......@@ -7,6 +7,10 @@ import {
} from '../shared/lib/constants'
const unsupportedTurbopackNextConfigOptions = [
// is this supported?
// 'amp',
// 'experimental.amp',
// Left to be implemented (priority)
// 'experimental.clientRouterFilter',
// 'experimental.optimizePackageImports',
......
This diff is collapsed.
......@@ -2479,7 +2479,7 @@ async function renderToStream(
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page.
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* 3.) If `shouldWaitOnAllReady` is true, which indicates we need to
* resolve all suspenses and generate a full HTML. e.g. when it's a
......@@ -2628,7 +2628,7 @@ async function renderToStream(
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page.
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
* 3.) If `shouldWaitOnAllReady` is true, which indicates we need to
* resolve all suspenses and generate a full HTML. e.g. when it's a
* html limited bot requests, we produce the full HTML content.
......
......@@ -89,7 +89,7 @@ export function createWorkStore({
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page.
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* 3.) If the request is in draft mode, we must generate dynamic HTML.
*
......
......@@ -532,8 +532,10 @@ export default abstract class Server<
trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId,
poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '',
generateEtags,
previewProps: this.getPrerenderManifest().preview,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath,
images: this.nextConfig.images,
optimizeCss: this.nextConfig.experimental.optimizeCss,
......@@ -2269,6 +2271,10 @@ export default abstract class Server<
}
}
// Ensure that if the `amp` query parameter is falsy that we remove it from
// the query object. This ensures it won't be found by the `in` operator.
if ('amp' in query && !query.amp) delete query.amp
if (opts.supportsDynamicResponse === true) {
const ua = req.headers['user-agent'] || ''
const isBotRequest = isBot(ua)
......@@ -2283,7 +2289,7 @@ export default abstract class Server<
// be static so we can collect revalidate and populate the
// cache if there are no dynamic data requirements
opts.supportsDynamicResponse =
!isSSG && !isBotRequest && isSupportedDocument
!isSSG && !isBotRequest && !query.amp && isSupportedDocument
}
// In development, we always want to generate dynamic HTML.
......@@ -2396,6 +2402,7 @@ export default abstract class Server<
addRequestMeta(request, 'distDir', this.distDir)
addRequestMeta(request, 'query', query)
addRequestMeta(request, 'params', opts.params)
addRequestMeta(request, 'ampValidator', this.renderOpts.ampValidator)
addRequestMeta(request, 'minimalMode', this.minimalMode)
if (opts.err) {
......
......@@ -165,6 +165,11 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
z.strictObject({
allowedDevOrigins: z.array(z.string()).optional(),
amp: z
.object({
canonicalBase: z.string().optional(),
})
.optional(),
assetPrefix: z.string().optional(),
basePath: z.string().optional(),
bundlePagesRouterDependencies: z.boolean().optional(),
......@@ -296,6 +301,14 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
appNavFailHandling: z.boolean().optional(),
preloadEntriesOnStart: z.boolean().optional(),
allowedRevalidateHeaderKeys: z.array(z.string()).optional(),
amp: z
.object({
// AMP optimizer option is unknown, use z.any() here
optimizer: z.any().optional(),
skipValidation: z.boolean().optional(),
validator: z.string().optional(),
})
.optional(),
staleTimes: z
.object({
dynamic: z.number().optional(),
......
......@@ -368,6 +368,12 @@ export interface ExperimentalConfig {
nextScriptWorkers?: boolean
scrollRestoration?: boolean
externalDir?: boolean
/** @deprecated built-in amp support will be removed in Next 16 */
amp?: {
optimizer?: any
validator?: string
skipValidation?: boolean
}
disableOptimizedLoading?: boolean
/** @deprecated A no-op as of Next 16, size metrics were removed from the build output. */
......@@ -1055,6 +1061,14 @@ export interface NextConfig {
pagesBufferLength?: number
}
/**
* @deprecated built-in amp support will be removed in Next 16
* @see [`next/amp`](https://nextjs.org/docs/api-reference/next/amp)
*/
amp?: {
canonicalBase?: string
}
/**
* A unique identifier for a deployment that will be included in each request's query string or header.
*/
......@@ -1344,6 +1358,9 @@ export const defaultConfig = Object.freeze({
maxInactiveAge: 60 * 1000,
pagesBufferLength: 5,
},
amp: {
canonicalBase: '',
},
basePath: '',
sassOptions: {},
trailingSlash: false,
......@@ -1463,6 +1480,7 @@ export const defaultConfig = Object.freeze({
swcPlugins: undefined,
largePageDataBytes: 128 * 1000, // 128KB by default
disablePostcssPresetEnv: undefined,
amp: undefined,
urlImports: undefined,
typedEnv: false,
clientTraceMetadata: undefined,
......
......@@ -97,6 +97,20 @@ function checkDeprecations(
silent: boolean,
dir: string
) {
warnOptionHasBeenDeprecated(
userConfig,
'amp',
`Built-in amp support is deprecated and the \`amp\` configuration option will be removed in Next.js 16.`,
silent
)
warnOptionHasBeenDeprecated(
userConfig,
'experimental.amp',
`Built-in amp support is deprecated and the \`experimental.amp\` configuration option will be removed in Next.js 16.`,
silent
)
if (userConfig.experimental?.dynamicIO !== undefined) {
warnOptionHasBeenDeprecated(
userConfig,
......@@ -408,6 +422,10 @@ function assignDefaultsAndValidate(
if (result.assetPrefix === '') {
result.assetPrefix = result.basePath
}
if (result.amp?.canonicalBase === '') {
result.amp.canonicalBase = result.basePath
}
}
}
......@@ -1471,6 +1489,15 @@ export default async function loadConfig(
)
}
if (userConfig.amp?.canonicalBase) {
const { canonicalBase } = userConfig.amp || ({} as any)
userConfig.amp = userConfig.amp || {}
userConfig.amp.canonicalBase =
(canonicalBase?.endsWith('/')
? canonicalBase.slice(0, -1)
: canonicalBase) || ''
}
if (reactProductionProfiling) {
userConfig.reactProductionProfiling = reactProductionProfiling
}
......
......@@ -35,6 +35,7 @@ import { APP_DIR_ALIAS, WEBPACK_LAYERS } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete'
import {
BLOCKED_PAGES,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
......@@ -210,6 +211,7 @@ function erroredPages(compilation: webpack.Compilation) {
}
export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
private hasAmpEntrypoints: boolean
private hasAppRouterEntrypoints: boolean
private hasPagesRouterEntrypoints: boolean
private dir: string
......@@ -284,6 +286,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
resetFetch: () => void
}
) {
this.hasAmpEntrypoints = false
this.hasAppRouterEntrypoints = false
this.hasPagesRouterEntrypoints = false
this.buildId = buildId
......@@ -904,6 +907,15 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
})
: undefined
if (staticInfo?.type === PAGE_TYPES.PAGES) {
if (
staticInfo.config?.config?.amp === true ||
staticInfo.config?.config?.amp === 'hybrid'
) {
this.hasAmpEntrypoints = true
}
}
const isServerComponent =
isAppPath && staticInfo?.rsc !== RSC_MODULE_TYPES.client
......@@ -1141,6 +1153,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
})
)
if (!this.hasAmpEntrypoints) {
delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_AMP]
}
if (!this.hasPagesRouterEntrypoints) {
delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_MAIN]
delete entrypoints['pages/_app']
......@@ -1149,7 +1164,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
delete entrypoints['pages/_document']
}
// Remove React Refresh entrypoint chunk as `app` doesn't require it.
if (!this.hasPagesRouterEntrypoints) {
if (!this.hasAmpEntrypoints && !this.hasPagesRouterEntrypoints) {
delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]
}
if (!this.hasAppRouterEntrypoints) {
......
......@@ -25,6 +25,7 @@ import * as React from 'react'
import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker'
import { join as pathJoin } from 'path'
import { ampValidation } from '../../build/output'
import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'
import { findPagesDir } from '../../lib/find-pages-dir'
import {
......@@ -177,6 +178,62 @@ export default class DevServer extends Server {
return JSON.stringify(value.staticPaths)?.length ?? 0
}
)
this.renderOpts.ampSkipValidation =
this.nextConfig.experimental?.amp?.skipValidation ?? false
this.renderOpts.ampValidator = async (html: string, pathname: string) => {
const { getAmpValidatorInstance, getBundledAmpValidatorFilepath } =
require('../../export/helpers/get-amp-html-validator') as typeof import('../../export/helpers/get-amp-html-validator')
const validatorPath =
this.nextConfig.experimental?.amp?.validator ||
getBundledAmpValidatorFilepath()
const validator = await getAmpValidatorInstance(validatorPath)
const result = validator.validateString(html)
ampValidation(
pathname,
result.errors
.filter((error) => {
if (error.severity === 'ERROR') {
// Unclear yet if these actually prevent the page from being indexed by the AMP cache.
// These are coming from React so all we can do is ignore them for now.
// <link rel="expect" blocking="render" />
// https://github.com/ampproject/amphtml/issues/40279
if (
error.code === 'DISALLOWED_ATTR' &&
error.params[0] === 'blocking' &&
error.params[1] === 'link'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MANDATORY_ATTR_MISSING' &&
error.params[0] === 'type' &&
error.params[1] === 'template'
) {
return false
}
// <template> without type
// https://github.com/ampproject/amphtml/issues/40280
if (
error.code === 'MISSING_REQUIRED_EXTENSION' &&
error.params[0] === 'template' &&
error.params[1] === 'amp-mustache'
) {
return false
}
return true
}
return false
})
.filter((e) => this._filterAmpDevelopmentScript(html, e)),
result.errors.filter((e) => e.severity !== 'ERROR')
)
}
const { pagesDir, appDir } = findPagesDir(this.dir)
this.pagesDir = pagesDir
......@@ -702,6 +759,30 @@ export default class DevServer extends Server {
// })
}
_filterAmpDevelopmentScript(
html: string,
event: { line: number; col: number; code: string }
): boolean {
if (event.code !== 'DISALLOWED_SCRIPT_TAG') {
return true
}
const snippetChunks = html.split('\n')
let snippet
if (
!(snippet = html.split('\n')[event.line - 1]) ||
!(snippet = snippet.substring(event.col))
) {
return true
}
snippet = snippet + snippetChunks.slice(event.line).join('\n')
snippet = snippet.substring(0, snippet.indexOf('</script>'))
return !snippet.includes('data-amp-development-mode-only')
}
protected async getStaticPaths({
pathname,
urlPathname,
......
......@@ -3,6 +3,7 @@ import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
export type BuildManifest = {
devFiles: readonly string[]
ampDevFiles: readonly string[]
polyfillFiles: readonly string[]
lowPriorityFiles: readonly string[]
rootMainFiles: readonly string[]
......@@ -14,6 +15,7 @@ export type BuildManifest = {
'/_app': readonly string[]
[page: string]: readonly string[]
}
ampFirstPages: readonly string[]
}
export function getPageFiles(
......
......@@ -527,6 +527,7 @@ export function generateValidatorFile(
* Validated at build-time by parsePagesSegmentConfig.
*/
config?: {
amp?: boolean | 'hybrid' | string // necessary for JS
maxDuration?: number
runtime?: 'edge' | 'experimental-edge' | 'nodejs' | string // necessary unless config is exported as const
regions?: string[]
......
......@@ -880,6 +880,7 @@ export default class NextNodeServer extends BaseServer<
private async findPageComponentsImpl({
locale,
page,
query,
params,
isAppPath,
url: _url,
......@@ -892,6 +893,12 @@ export default class NextNodeServer extends BaseServer<
url?: string
}): Promise<FindComponentsResult | null> {
const pagePaths: string[] = [page]
if (query.amp) {
// try serving a static AMP version first
pagePaths.unshift(
(isAppPath ? normalizeAppPath(page) : normalizePagePath(page)) + '.amp'
)
}
if (locale) {
pagePaths.unshift(
......@@ -924,6 +931,12 @@ export default class NextNodeServer extends BaseServer<
return {
components,
query: {
...(!this.renderOpts.isExperimentalCompile &&
components.getStaticProps
? ({
amp: query.amp,
} as NextParsedUrlQuery)
: query),
// For appDir params is excluded.
...((isAppPath ? {} : params) || {}),
},
......
export default async function optimize(
html: string,
config: any
): Promise<string> {
let AmpOptimizer
try {
AmpOptimizer =
require('next/dist/compiled/@ampproject/toolbox-optimizer') as typeof import('next/dist/compiled/@ampproject/toolbox-optimizer')
} catch (_) {
return html
}
const optimizer = AmpOptimizer.create(config)
return optimizer.transformHtml(html, config)
}
......@@ -7,10 +7,32 @@ type PostProcessorFunction =
| ((html: string) => string)
async function postProcessHTML(
pathname: string,
content: string,
renderOpts: Pick<RenderOpts, 'optimizeCss' | 'distDir' | 'assetPrefix'>
renderOpts: Pick<
RenderOpts,
| 'ampOptimizerConfig'
| 'ampValidator'
| 'ampSkipValidation'
| 'optimizeCss'
| 'distDir'
| 'assetPrefix'
>,
{ inAmpMode, hybridAmp }: { inAmpMode: boolean; hybridAmp: boolean }
) {
const postProcessors: Array<PostProcessorFunction> = [
process.env.NEXT_RUNTIME !== 'edge' && inAmpMode && !process.env.TURBOPACK
? async (html: string) => {
const optimizeAmp = (
require('./optimize-amp') as typeof import('./optimize-amp')
).default as typeof import('./optimize-amp').default
html = await optimizeAmp!(html, renderOpts.ampOptimizerConfig)
if (!renderOpts.ampSkipValidation && renderOpts.ampValidator) {
await renderOpts.ampValidator(html, pathname)
}
return html
}
: null,
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss
? async (html: string) => {
// eslint-disable-next-line import/no-extraneous-dependencies
......@@ -31,6 +53,11 @@ async function postProcessHTML(
return await cssOptimizer.process(html)
}
: null,
inAmpMode || hybridAmp
? (html: string) => {
return html.replace(/&amp;amp=1/g, '&amp=1')
}
: null,
].filter(nonNullable)
for (const postProcessor of postProcessors) {
......
......@@ -61,6 +61,8 @@ import {
STATIC_STATUS_PAGES,
} from '../shared/lib/constants'
import { isSerializableProps } from '../lib/is-serializable-props'
import { isInAmpMode } from '../shared/lib/amp-mode'
import { AmpStateContext } from '../shared/lib/amp-context.shared-runtime'
import { defaultHead } from '../shared/lib/head'
import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime'
import Loadable from '../shared/lib/loadable.shared-runtime'
......@@ -124,7 +126,7 @@ if (process.env.NEXT_RUNTIME !== 'edge') {
).postProcessHTML
} else {
warn = console.warn.bind(console)
postProcessHTML = async (html: string) => html
postProcessHTML = async (_pathname: string, html: string) => html
}
function noRouter() {
......@@ -240,12 +242,17 @@ function renderPageTree(
}
export type RenderOptsPartial = {
canonicalBase: string
runtimeConfig?: { [key: string]: any }
assetPrefix?: string
err?: Error | null
nextExport?: boolean
dev?: boolean
ampPath?: string
ErrorDebug?: PagesDevOverlayBridgeType
ampValidator?: (html: string, pathname: string) => Promise<void>
ampSkipValidation?: boolean
ampOptimizerConfig?: { [key: string]: any }
isNextDataRequest?: boolean
params?: ParsedUrlQuery
previewProps: __ApiPreviewProps | undefined
......@@ -484,6 +491,7 @@ export async function renderToHTMLImpl(
const {
err,
dev = false,
ampPath = '',
pageConfig = {},
buildManifest,
reactLoadableManifest,
......@@ -624,6 +632,14 @@ export async function renderToHTMLImpl(
}
if (isAutoExport || isFallback) {
// remove query values except ones that will be set during export
query = {
...(query.amp
? {
amp: query.amp,
}
: {}),
}
asPath = `${pathname}${
// ensure trailing slash is present for non-dynamic auto-export pages
req.url!.endsWith('/') && pathname !== '/' && !pageIsDynamic ? '/' : ''
......@@ -713,8 +729,15 @@ export async function renderToHTMLImpl(
let scriptLoader: any = {}
const jsxStyleRegistry = createStyleRegistry()
const ampState = {
ampFirst: pageConfig.amp === true,
hasQuery: Boolean(query.amp),
hybrid: pageConfig.amp === 'hybrid',
}
let head: JSX.Element[] = defaultHead()
// Disable AMP under the web environment
const inAmpMode = process.env.NEXT_RUNTIME !== 'edge' && isInAmpMode(ampState)
let head: JSX.Element[] = defaultHead(inAmpMode)
const reactLoadableModules: string[] = []
let initialScripts: any = {}
......@@ -741,29 +764,33 @@ export async function renderToHTMLImpl(
>
<PathParamsContext.Provider value={adaptForPathParams(router)}>
<RouterContext.Provider value={router}>
<HeadManagerContext.Provider
value={{
updateHead: (state) => {
head = state
},
updateScripts: (scripts) => {
scriptLoader = scripts
},
scripts: initialScripts,
mountedInstances: new Set(),
nonce,
}}
>
<LoadableContext.Provider
value={(moduleName) => reactLoadableModules.push(moduleName)}
<AmpStateContext.Provider value={ampState}>
<HeadManagerContext.Provider
value={{
updateHead: (state) => {
head = state
},
updateScripts: (scripts) => {
scriptLoader = scripts
},
scripts: initialScripts,
mountedInstances: new Set(),
nonce,
}}
>
<StyleRegistry registry={jsxStyleRegistry}>
<ImageConfigContext.Provider value={images}>
{children}
</ImageConfigContext.Provider>
</StyleRegistry>
</LoadableContext.Provider>
</HeadManagerContext.Provider>
<LoadableContext.Provider
value={(moduleName) =>
reactLoadableModules.push(moduleName)
}
>
<StyleRegistry registry={jsxStyleRegistry}>
<ImageConfigContext.Provider value={images}>
{children}
</ImageConfigContext.Provider>
</StyleRegistry>
</LoadableContext.Provider>
</HeadManagerContext.Provider>
</AmpStateContext.Provider>
</RouterContext.Provider>
</PathParamsContext.Provider>
</PathnameContextProviderAdapter>
......@@ -1250,7 +1277,7 @@ export async function renderToHTMLImpl(
}
const Body = ({ children }: { children: JSX.Element }) => {
return <div id="__next">{children}</div>
return inAmpMode ? children : <div id="__next">{children}</div>
}
const renderDocument = async () => {
......@@ -1454,6 +1481,7 @@ export async function renderToHTMLImpl(
}
}
const hybridAmp = ampState.hybrid
const docComponentsRendered: DocumentProps['docComponentsRendered'] = {}
const {
......@@ -1498,7 +1526,14 @@ export async function renderToHTMLImpl(
buildManifest: filteredBuildManifest,
docComponentsRendered,
dangerousAsPath: router.asPath,
canonicalBase:
!renderOpts.ampPath && getRequestMeta(req, 'didStripLocale')
? `${renderOpts.canonicalBase || ''}/${renderOpts.locale}`
: renderOpts.canonicalBase,
ampPath,
inAmpMode,
isDevelopment: !!dev,
hybridAmp,
dynamicImports: Array.from(dynamicImports),
dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),
assetPrefix,
......@@ -1527,9 +1562,11 @@ export async function renderToHTMLImpl(
}
const document = (
<HtmlContext.Provider value={htmlProps}>
{documentResult.documentElement(htmlProps)}
</HtmlContext.Provider>
<AmpStateContext.Provider value={ampState}>
<HtmlContext.Provider value={htmlProps}>
{documentResult.documentElement(htmlProps)}
</HtmlContext.Provider>
</AmpStateContext.Provider>
)
const documentHTML = await getTracer().trace(
......@@ -1570,10 +1607,16 @@ export async function renderToHTMLImpl(
prefix += DOCTYPE
}
prefix += renderTargetPrefix
if (inAmpMode) {
prefix += '<!-- __NEXT_DATA__ -->'
}
const content = prefix + documentResult.contentHTML + renderTargetSuffix
const optimizedHtml = await postProcessHTML(content, renderOpts)
const optimizedHtml = await postProcessHTML(pathname, content, renderOpts, {
inAmpMode,
hybridAmp,
})
return new RenderResult(optimizedHtml, {
metadata,
......
......@@ -248,6 +248,11 @@ export interface RequestMeta {
*/
params?: ParsedUrlQuery
/**
* The AMP validator to use in development
*/
ampValidator?: (html: string, pathname: string) => Promise<void>
/**
* ErrorOverlay component to use in development for pages router
*/
......@@ -343,7 +348,10 @@ type NextQueryMetadata = {
[NEXT_RSC_UNION_QUERY]?: string
}
export type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata
export type NextParsedUrlQuery = ParsedUrlQuery &
NextQueryMetadata & {
amp?: '1'
}
export interface NextUrlWithParsedQuery extends UrlWithParsedQuery {
query: NextParsedUrlQuery
......
module.exports = (
require('../../module.compiled') as typeof import('../../module.compiled')
).vendored['contexts'].AmpContext
......@@ -3,4 +3,5 @@ export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-h
export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'
export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'
export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'
export * as AmpContext from '../../../../../shared/lib/amp-context.shared-runtime'
export * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime'
......@@ -128,6 +128,7 @@ export const getHandler = ({
const hasGetInitialProps = Boolean(
(userland.default || userland).getInitialProps
)
const isAmp = query.amp && config?.amp
let cacheKey: null | string = null
let isIsrFallback = false
let isNextDataRequest =
......@@ -142,10 +143,10 @@ export const getHandler = ({
(srcPage === '/' || resolvedPathname === '/') && locale
? ''
: resolvedPathname
}`
}${isAmp ? '.amp' : ''}`
if (is404Page || is500Page || isErrorPage) {
cacheKey = `${locale ? `/${locale}` : ''}${srcPage}`
cacheKey = `${locale ? `/${locale}` : ''}${srcPage}${isAmp ? '.amp' : ''}`
}
// ensure /index and / is normalized to one key
......@@ -219,6 +220,11 @@ export const getHandler = ({
hasStaticProps && !isExperimentalCompile
? ({
...params,
...(isAmp
? {
amp: query.amp,
}
: {}),
} as ParsedUrlQuery)
: {
...query,
......@@ -270,6 +276,8 @@ export const getHandler = ({
multiZoneDraftMode,
basePath: nextConfig.basePath,
canonicalBase: nextConfig.amp.canonicalBase || '',
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer,
disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading,
largePageDataBytes:
......@@ -326,6 +334,10 @@ export const getHandler = ({
routeModule.relativeProjectDir,
routeModule.distDir
),
ampSkipValidation:
nextConfig.experimental.amp?.skipValidation,
ampValidator: getRequestMeta(req, 'ampValidator'),
},
})
.then((renderResult): ResponseCacheEntry => {
......
module.exports = (
require('../../module.compiled') as typeof import('../../module.compiled')
).vendored['contexts'].AmpContext
......@@ -6,4 +6,5 @@ export * as HtmlContext from '../../../../../shared/lib/html-context.shared-runt
export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'
export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'
export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'
export * as AmpContext from '../../../../../shared/lib/amp-context.shared-runtime'
export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'
......@@ -6,7 +6,11 @@ import {
getTs,
removeStringQuotes,
} from '../utils'
import { NEXT_TS_ERRORS, ALLOWED_EXPORTS } from '../constant'
import {
NEXT_TS_ERRORS,
ALLOWED_EXPORTS,
LEGACY_CONFIG_EXPORT,
} from '../constant'
import type tsModule from 'typescript/lib/tsserverlibrary'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
......@@ -612,6 +616,28 @@ const config = {
})
}
}
} else if (name.text === LEGACY_CONFIG_EXPORT) {
// export const config = { ... }
// Error if using `amp: ...`
const value = declaration.initializer
if (value && ts.isObjectLiteralExpression(value)) {
for (const prop of value.properties) {
if (
ts.isPropertyAssignment(prop) &&
ts.isIdentifier(prop.name) &&
prop.name.text === 'amp'
) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_CONFIG_OPTION,
messageText: `AMP is not supported in the app directory. If you need to use AMP it will continue to be supported in the pages directory.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
}
}
}
......
......@@ -4,6 +4,17 @@ export function isBlockedPage(page: string): boolean {
return BLOCKED_PAGES.includes(page)
}
export function cleanAmpPath(pathname: string): string {
if (pathname.match(/\?amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/\?amp=(y|yes|true|1)&?/, '?')
}
if (pathname.match(/&amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/&amp=(y|yes|true|1)/, '')
}
pathname = pathname.replace(/\?$/, '')
return pathname
}
type AnyFunc<T> = (this: T, ...args: any) => any
export function debounce<T, F extends AnyFunc<T>>(
fn: F,
......
import React from 'react'
export const AmpStateContext: React.Context<any> = React.createContext({})
if (process.env.NODE_ENV !== 'production') {
AmpStateContext.displayName = 'AmpStateContext'
}
export function isInAmpMode({
ampFirst = false,
hybrid = false,
hasQuery = false,
} = {}): boolean {
return ampFirst || (hybrid && hasQuery)
}
import React from 'react'
import { AmpStateContext } from './amp-context.shared-runtime'
import { isInAmpMode } from './amp-mode'
export function useAmp(): boolean {
// Don't assign the context value to a variable to save bytes
return isInAmpMode(React.useContext(AmpStateContext))
}
......@@ -142,6 +142,8 @@ export const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = `${CLIENT_STATIC_FILES_RUNTI
export const APP_CLIENT_INTERNALS = 'app-pages-internals'
// static/runtime/react-refresh.js
export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`
// static/runtime/amp.js
export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`
// static/runtime/webpack.js
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`
// static/runtime/polyfills.js
......@@ -201,5 +203,6 @@ export const EDGE_UNSUPPORTED_NODE_APIS = [
export const SYSTEM_ENTRYPOINTS = new Set<string>([
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
])
......@@ -2,14 +2,22 @@
import React, { useContext, type JSX } from 'react'
import Effect from './side-effect'
import { AmpStateContext } from './amp-context.shared-runtime'
import { HeadManagerContext } from './head-manager-context.shared-runtime'
import { isInAmpMode } from './amp-mode'
import { warnOnce } from './utils/warn-once'
export function defaultHead(): JSX.Element[] {
type WithInAmpMode = {
inAmpMode?: boolean
}
export function defaultHead(inAmpMode = false): JSX.Element[] {
const head = [<meta charSet="utf-8" key="charset" />]
head.push(
<meta name="viewport" content="width=device-width" key="viewport" />
)
if (!inAmpMode) {
head.push(
<meta name="viewport" content="width=device-width" key="viewport" />
)
}
return head
}
......@@ -116,13 +124,15 @@ function unique() {
*
* @param headChildrenElements List of children of <Head>
*/
function reduceComponents(
headChildrenElements: Array<React.ReactElement<any>>
function reduceComponents<T extends {} & WithInAmpMode>(
headChildrenElements: Array<React.ReactElement<any>>,
props: T
) {
const { inAmpMode } = props
return headChildrenElements
.reduce(onlyReactElement, [])
.reverse()
.concat(defaultHead().reverse())
.concat(defaultHead(inAmpMode).reverse())
.filter(unique())
.reverse()
.map((c: React.ReactElement<any>, i: number) => {
......@@ -151,11 +161,13 @@ function reduceComponents(
* To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once.
*/
function Head({ children }: { children: React.ReactNode }) {
const ampState = useContext(AmpStateContext)
const headManager = useContext(HeadManagerContext)
return (
<Effect
reduceComponentsToState={reduceComponents}
headManager={headManager}
inAmpMode={isInAmpMode(ampState)}
>
{children}
</Effect>
......
......@@ -17,6 +17,9 @@ export type HtmlProps = {
NextScript?: boolean
}
buildManifest: BuildManifest
ampPath: string
inAmpMode: boolean
hybridAmp: boolean
isDevelopment: boolean
dynamicImports: string[]
/**
......@@ -25,6 +28,7 @@ export type HtmlProps = {
*/
dynamicCssManifest: Set<string>
assetPrefix?: string
canonicalBase: string
headTags: any[]
unstable_runtimeJS?: false
unstable_JsPreload?: false
......
......@@ -10,6 +10,7 @@ export type SideEffectProps = {
) => State
handleStateChange?: (state: State) => void
headManager: any
inAmpMode?: boolean
children: React.ReactNode
}
......
......@@ -373,12 +373,14 @@ export class TurbopackManifestLoader {
},
// Something in next.js depends on these to exist even for app dir rendering
devFiles: [],
ampDevFiles: [],
polyfillFiles: [],
lowPriorityFiles: [
`static/${this.buildId}/_ssgManifest.js`,
`static/${this.buildId}/_buildManifest.js`,
],
rootMainFiles: [],
ampFirstPages: [],
}
for (const m of manifests) {
Object.assign(manifest.pages, m.pages)
......
......@@ -7,6 +7,7 @@
import type { Agent as HttpAgent } from 'http'
import type { Agent as HttpsAgent } from 'https'
import type React from 'react'
import type { ParsedUrlQuery } from 'querystring'
import type { IncomingMessage, ServerResponse } from 'http'
......@@ -60,6 +61,11 @@ export type Route<RouteInferType = any> = string & {}
// Extend the React types with missing properties
declare module 'react' {
// <html amp=""> support
interface HtmlHTMLAttributes<T> extends React.HTMLAttributes<T> {
amp?: string
}
// <img fetchPriority=""> support
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- It's actually required for module augmentation to work.
interface ImgHTMLAttributes<T> {
......@@ -108,6 +114,11 @@ export type ResponseLimit = SizeLimit | boolean
* `Config` type, use it for export const config
*/
export type PageConfig = {
/**
* @deprecated built-in amp support will be removed in Next 16
* @see [`next/amp`](https://nextjs.org/docs/api-reference/next/amp)
*/
amp?: boolean | 'hybrid'
api?: {
/**
* Configures or disables body size limit warning. Can take a number or
......
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