Unverified Commit 694e7f9e authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Generate metadata images generation with app routes (#47225)

Generated metadata icons through api routes instead of using webpack
emitting file. Each metadata image file will go through
`next-metadata-image-loader` to get the image basic info, and then it
will go through `next-metadata-route-loader` to be converted as a
routes.

Related to NEXT-264
Closes NEXT-810
parent 7a104a67
import type webpack from 'webpack'
import type { AppLoaderOptions } from '../next-app-loader'
import type {
CollectingMetadata,
PossibleImageFileNameConvention,
......@@ -11,7 +10,7 @@ const METADATA_TYPE = 'metadata'
export const METADATA_RESOURCE_QUERY = '?__next_metadata'
const staticAssetIconsImage = {
export const STATIC_METADATA_IMAGES = {
icon: {
filename: 'icon',
extensions: ['ico', 'jpg', 'jpeg', 'png', 'svg'],
......@@ -74,18 +73,18 @@ async function enumMetadataFiles(
return collectedFiles
}
export async function discoverStaticMetadataFiles(
export async function createStaticMetadataFromRoute(
resolvedDir: string,
{
route,
resolvePath,
isRootLayer,
loaderContext,
loaderOptions,
}: {
route: string
resolvePath: (pathname: string) => Promise<string>
isRootLayer: boolean
loaderContext: webpack.LoaderContext<any>
loaderOptions: AppLoaderOptions
}
) {
let hasStaticMetadataFiles = false
......@@ -101,18 +100,13 @@ export async function discoverStaticMetadataFiles(
loaderContext,
}
const metadataImageLoaderOptions = {
isDev: loaderOptions.isDev,
assetPrefix: loaderOptions.assetPrefix,
}
async function collectIconModuleIfExists(
type: PossibleImageFileNameConvention
) {
const resolvedMetadataFiles = await enumMetadataFiles(
resolvedDir,
staticAssetIconsImage[type].filename,
staticAssetIconsImage[type].extensions,
STATIC_METADATA_IMAGES[type].filename,
STATIC_METADATA_IMAGES[type].extensions,
opts
)
resolvedMetadataFiles
......@@ -120,7 +114,7 @@ export async function discoverStaticMetadataFiles(
.forEach((filepath) => {
const imageModule = `() => import(/* webpackMode: "eager" */ ${JSON.stringify(
`next-metadata-image-loader?${stringify({
...metadataImageLoaderOptions,
route,
numericSizes:
type === 'twitter' || type === 'opengraph' ? '1' : undefined,
type,
......@@ -149,8 +143,8 @@ export async function discoverStaticMetadataFiles(
return hasStaticMetadataFiles ? staticImagesMetadata : null
}
export function buildMetadata(
metadata: Awaited<ReturnType<typeof discoverStaticMetadataFiles>>
export function createMetadataExportsCode(
metadata: Awaited<ReturnType<typeof createStaticMetadataFromRoute>>
) {
return metadata
? `${METADATA_TYPE}: {
......
......@@ -62,12 +62,12 @@ export function resolveSitemap(data: SitemapFile): string {
export function resolveRouteData(
data: RobotsFile | SitemapFile,
baseName: 'robots' | 'sitemap'
fileType: 'robots' | 'sitemap'
): string {
if (baseName === 'robots') {
if (fileType === 'robots') {
return resolveRobots(data as RobotsFile)
}
if (baseName === 'sitemap') {
if (fileType === 'sitemap') {
return resolveSitemap(data as SitemapFile)
}
return ''
......
......@@ -3,6 +3,7 @@ import type { ValueOf } from '../../../shared/lib/constants'
import type { ModuleReference, CollectedMetadata } from './metadata/types'
import path from 'path'
import { stringify } from 'querystring'
import chalk from 'next/dist/compiled/chalk'
import { NODE_RESOLVE_OPTIONS } from '../../webpack-config'
import { getModuleBuildInfo } from './get-module-build-info'
......@@ -10,8 +11,8 @@ import { verifyRootLayout } from '../../../lib/verifyRootLayout'
import * as Log from '../../../build/output/log'
import { APP_DIR_ALIAS } from '../../../lib/constants'
import {
buildMetadata,
discoverStaticMetadataFiles,
createMetadataExportsCode,
createStaticMetadataFromRoute,
METADATA_RESOURCE_QUERY,
} from './metadata/discover'
import { isAppRouteRoute } from '../../../lib/is-app-route-route'
......@@ -61,20 +62,23 @@ async function createAppRouteCode({
name,
pagePath,
resolver,
pageExtensions,
}: {
name: string
pagePath: string
resolver: PathResolver
pageExtensions: string[]
}): Promise<string> {
// routePath is the path to the route handler file,
// but could be aliased e.g. private-next-app-dir/favicon.ico
const routePath = pagePath.replace(/[\\/]/, '/')
// This, when used with the resolver will give us the pathname to the built
// route handler file.
let resolvedPagePath = (await resolver(routePath))!
if (isMetadataRoute(name)) {
resolvedPagePath = `next-metadata-route-loader!${
resolvedPagePath + METADATA_RESOURCE_QUERY
}`
resolvedPagePath = `next-metadata-route-loader?${stringify({
pageExtensions,
})}!${resolvedPagePath + METADATA_RESOURCE_QUERY}`
}
// TODO: verify if other methods need to be injected
......@@ -105,7 +109,6 @@ async function createTreeCodeFromPath(
resolvePath,
resolveParallelSegments,
loaderContext,
loaderOptions,
}: {
resolver: (
pathname: string,
......@@ -116,7 +119,6 @@ async function createTreeCodeFromPath(
pathname: string
) => [key: string, segment: string | string[]][]
loaderContext: webpack.LoaderContext<AppLoaderOptions>
loaderOptions: AppLoaderOptions
}
) {
const splittedPath = pagePath.split(/[\\/]/)
......@@ -145,17 +147,18 @@ async function createTreeCodeFromPath(
parallelSegments.push(...resolveParallelSegments(segmentPath))
}
let metadata: Awaited<ReturnType<typeof discoverStaticMetadataFiles>> = null
let metadata: Awaited<ReturnType<typeof createStaticMetadataFromRoute>> =
null
try {
const routerDirPath = `${appDirPrefix}${segmentPath}`
const resolvedRouteDir = await resolver(routerDirPath, true)
if (resolvedRouteDir) {
metadata = await discoverStaticMetadataFiles(resolvedRouteDir, {
metadata = await createStaticMetadataFromRoute(resolvedRouteDir, {
route: segmentPath,
resolvePath,
isRootLayer,
loaderContext,
loaderOptions,
})
}
} catch (err: any) {
......@@ -178,7 +181,7 @@ async function createTreeCodeFromPath(
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
resolvedPagePath
)}), ${JSON.stringify(resolvedPagePath)}],
${buildMetadata(metadata)}
${createMetadataExportsCode(metadata)}
}]`
continue
}
......@@ -238,7 +241,7 @@ async function createTreeCodeFromPath(
)}), ${JSON.stringify(filePath)}],`
})
.join('\n')}
${definedFilePaths.length ? buildMetadata(metadata) : ''}
${definedFilePaths.length ? createMetadataExportsCode(metadata) : ''}
}
]`
}
......@@ -285,8 +288,9 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
} = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module)
const page = name.replace(/^app/, '')
buildInfo.route = {
page: name.replace(/^app/, ''),
page,
absolutePagePath: createAbsolutePath(appDir, pagePath),
}
......@@ -355,7 +359,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
}
if (isAppRouteRoute(name)) {
return createAppRouteCode({ name, pagePath, resolver })
return createAppRouteCode({ name, pagePath, resolver, pageExtensions })
}
const {
......@@ -368,7 +372,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
resolvePath: (pathname: string) => resolve(this.rootContext, pathname),
resolveParallelSegments,
loaderContext: this,
loaderOptions: loaderOptions,
})
if (!rootLayout) {
......
......@@ -4,38 +4,34 @@ import type {
} from './metadata/types'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import { getImageSize } from '../../../server/image-optimizer'
import { imageExtMimeTypeMap } from '../../../lib/mime-type'
interface Options {
isDev: boolean
assetPrefix: string
route: string
numericSizes: boolean
type: PossibleImageFileNameConvention
}
const mimeTypeMap = {
jpeg: 'image/jpeg',
png: 'image/png',
ico: 'image/x-icon',
svg: 'image/svg+xml',
}
async function nextMetadataImageLoader(this: any, content: Buffer) {
const options: Options = this.getOptions()
const { assetPrefix, isDev, numericSizes, type } = options
const { type, route, numericSizes } = options
const context = this.rootContext
const opts = { context, content }
// favicon is the special case, always generate '/favicon.ico'
const isFavIcon = type === 'favicon'
// e.g. icon.png -> server/static/media/metadata/icon.399de3b9.png
const interpolatedName = loaderUtils.interpolateName(
this,
(isFavIcon ? '' : '/static/media/metadata/') + '[name].[ext]',
'[name].[ext]',
opts
)
const outputPath = isFavIcon
? '/' + interpolatedName
: assetPrefix + '/_next' + interpolatedName
// No hash query for favicon.ico
const contentHash =
type === 'favicon'
? ''
: loaderUtils.interpolateName(this, '[contenthash]', opts)
const outputPath =
route + '/' + interpolatedName + (contentHash ? `?${contentHash}` : '')
let extension = loaderUtils.interpolateName(this, '[ext]', opts)
if (extension === 'jpg') {
......@@ -52,8 +48,8 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const imageData: MetadataImageModule = {
url: outputPath,
...(extension in mimeTypeMap && {
type: mimeTypeMap[extension as keyof typeof mimeTypeMap],
...(extension in imageExtMimeTypeMap && {
type: imageExtMimeTypeMap[extension as keyof typeof imageExtMimeTypeMap],
}),
...(numericSizes
? { width: imageSize.width as number, height: imageSize.height as number }
......@@ -67,11 +63,6 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const stringifiedData = JSON.stringify(imageData)
// TODO-METADATA: Move image generation to static app routes
if (!isFavIcon) {
this.emitFile(`../${isDev ? '' : '../'}${interpolatedName}`, content, null)
}
return `export default ${stringifiedData};`
}
......
import type webpack from 'webpack'
import path from 'path'
import { isStaticMetadataRoute } from '../../../lib/metadata/is-metadata-route'
import { METADATA_RESOURCE_QUERY } from './metadata/discover'
import { imageExtMimeTypeMap } from '../../../lib/mime-type'
type MetadataRouteLoaderOptions = {
pageExtensions: string[]
}
function getFilenameAndExtension(resourcePath: string) {
const filename = path.basename(resourcePath)
......@@ -10,10 +14,16 @@ function getFilenameAndExtension(resourcePath: string) {
}
function getContentType(resourcePath: string) {
const { name, ext } = getFilenameAndExtension(resourcePath)
let { name, ext } = getFilenameAndExtension(resourcePath)
if (ext === 'jpg') ext = 'jpeg'
if (name === 'favicon' && ext === 'ico') return 'image/x-icon'
if (name === 'sitemap') return 'application/xml'
if (name === 'robots') return 'text/plain'
if (ext === 'png' || ext === 'jpeg' || ext === 'ico' || ext === 'svg') {
return imageExtMimeTypeMap[ext]
}
return 'text/plain'
}
......@@ -24,11 +34,13 @@ import fs from 'fs'
import { fileURLToPath } from 'url'
import { NextResponse } from 'next/server'
const resourceUrl = fileURLToPath(import.meta.url).replace(${JSON.stringify(
const contentType = ${JSON.stringify(getContentType(resourcePath))}
const resourceUrl = new URL(import.meta.url)
const filePath = fileURLToPath(resourceUrl).replace(${JSON.stringify(
METADATA_RESOURCE_QUERY
)}, '')
const buffer = fs.readFileSync(resourceUrl)
const contentType = ${JSON.stringify(getContentType(resourcePath))}
const buffer = fs.readFileSync(filePath)
export function GET() {
return new NextResponse(buffer, {
......@@ -50,11 +62,11 @@ import handler from ${JSON.stringify(resourcePath)}
import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data'
const contentType = ${JSON.stringify(getContentType(resourcePath))}
const name = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)}
const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)}
export async function GET() {
const data = await handler()
const content = resolveRouteData(data, name)
const content = resolveRouteData(data, fileType)
return new NextResponse(content, {
headers: {
......@@ -69,14 +81,19 @@ export async function GET() {
// `import.meta.url` is the resource name of the current module.
// When it's static route, it could be favicon.ico, sitemap.xml, robots.txt etc.
// TODO-METADATA: improve the cache control strategy
const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction = function () {
const { resourcePath } = this
const isStatic = isStaticMetadataRoute(resourcePath)
const code = isStatic
? getStaticRouteCode(resourcePath)
: getDynamicRouteCode(resourcePath)
return code
}
const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> =
function () {
const { resourcePath } = this
const { pageExtensions } = this.getOptions()
const ext = path.extname(resourcePath).slice(1)
const isStatic = !pageExtensions.includes(ext)
const code = isStatic
? getStaticRouteCode(resourcePath)
: getDynamicRouteCode(resourcePath)
return code
}
export default nextMetadataRouterLoader
......@@ -2,7 +2,7 @@ import { createHash } from 'crypto'
import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif']
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif', 'ico', 'svg']
const imageRegex = new RegExp(`\\.(${imageExtensions.join('|')})$`)
export function isClientComponentModule(mod: {
......
import { isMetadataRoute, isStaticMetadataRoute } from './is-metadata-route'
import { isMetadataRoute } from './is-metadata-route'
/**
* Map metadata page key to the corresponding route
*
* static file page key: app/robots.txt -> /robots.xml -> /robots.txt/route
* dynamic route page key: app/robots.tsx -> /robots -> /robots.txt/route
* static file page key: /app/robots.txt -> /robots.xml -> /robots.txt/route
* dynamic route page key: /app/robots.tsx -> /robots -> /robots.txt/route
*
* @param page
* @returns
......@@ -12,16 +12,13 @@ import { isMetadataRoute, isStaticMetadataRoute } from './is-metadata-route'
export function normalizeMetadataRoute(page: string) {
let route = page
if (isMetadataRoute(page)) {
if (!isStaticMetadataRoute(route)) {
if (route === '/sitemap') {
route += '.xml'
}
if (route === '/robots') {
route += '.txt'
}
if (route === '/favicon') {
route += '.ico'
}
// TODO-METADATA: add dynamic routes for metadata images.
// Better to move the extension appending to early phase.
if (route === '/sitemap') {
route += '.xml'
}
if (route === '/robots') {
route += '.txt'
}
route = `${route}/route`
}
......
import path from 'path'
const regexMetadataRoutes = [
/^robots(\.txt)?/,
/^sitemap(\.xml)?/,
/^favicon(\.ico)?/,
]
const staticRegexMetadataRoutes = [
/^robots\.txt/,
/^sitemap\.xml/,
/^favicon\.ico/,
]
import { STATIC_METADATA_IMAGES } from '../../build/webpack/loaders/metadata/discover'
// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc.
// TODO-METADATA: support more metadata routes with more extensions
const defaultExtensions = ['js', 'jsx', 'ts', 'tsx']
const getExtensionRegexString = (extensions: string[]) =>
`(?:${extensions.join('|')})`
// When you only pass the file extension as `[]`, it will only match the static convention files
// e.g. /robots.txt, /sitemap.xml, /favicon.ico
// When you pass the file extension as `['js', 'jsx', 'ts', 'tsx']`, it will also match the dynamic convention files
// e.g. /robots.js, /sitemap.tsx, /favicon.jsx
// When `withExtension` is false, it will match the static convention files without the extension, by default it's true
// e.g. /robots, /sitemap, /favicon, use to match dynamic API routes like app/robots.ts
export function isMetadataRouteFile(
appDirRelativePath: string,
pageExtensions: string[],
withExtension: boolean
) {
const metadataRouteFilesRegex = [
new RegExp(
`^[\\\\/]robots${
withExtension
? `\\.${getExtensionRegexString(pageExtensions.concat('txt'))}`
: ''
}`
),
new RegExp(
`^[\\\\/]sitemap${
withExtension
? `\\.${getExtensionRegexString(pageExtensions.concat('xml'))}`
: ''
}`
),
new RegExp(`^[\\\\/]favicon\\.ico$`),
// TODO-METADATA: add dynamic routes for metadata images
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.icon.extensions
)}`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.apple.extensions
)}`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.opengraph.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.opengraph.extensions
)}`
: ''
}`
),
new RegExp(
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.twitter.extensions
)}`
: ''
}`
),
]
return metadataRouteFilesRegex.some((r) => r.test(appDirRelativePath))
}
export function isMetadataRoute(route: string): boolean {
// Remove the 'app/' or '/' prefix, only check the route name since they're only allowed in root app directory
const baseName = route
.replace(/^app\//, '')
.replace(/^\//, '')
.replace(/\/route$/, '')
// Remove the 'app' prefix or '/route' suffix, only check the route name since they're only allowed in root app directory
const page = route.replace(/^\/?app/, '').replace(/\/route$/, '')
return (
!baseName.endsWith('/page') &&
regexMetadataRoutes.some((r) => r.test(baseName))
!page.endsWith('/page') &&
isMetadataRouteFile(page, defaultExtensions, false)
)
}
// Only match the static metadata files
// TODO-METADATA: support static metadata files under nested routes folders
export function isStaticMetadataRoute(resourcePath: string) {
const filename = path.basename(resourcePath)
return staticRegexMetadataRoutes.some((r) => r.test(filename))
}
/**
* Map of images extensions to MIME types
*/
export const imageExtMimeTypeMap = {
jpeg: 'image/jpeg',
png: 'image/png',
ico: 'image/x-icon',
svg: 'image/svg+xml',
} as const
......@@ -8,9 +8,9 @@ import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'
import { PrefixingNormalizer } from '../../normalizers/prefixing-normalizer'
import { RouteKind } from '../../route-kind'
import { FileCacheRouteMatcherProvider } from './file-cache-route-matcher-provider'
import { isAppRouteRoute } from '../../../../lib/is-app-route-route'
export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvider<AppRouteRouteMatcher> {
private readonly expression: RegExp
private readonly normalizers: {
page: Normalizer
pathname: Normalizer
......@@ -24,18 +24,6 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
) {
super(appDir, reader)
// Match any route file that ends with `/route.${extension}` under the app directory.
// Match top level robots file that ends with `/robots.${extension}` under the app directory.
this.expression = new RegExp(
`[/\\\\]route\\.(?:${extensions.join(
'|'
)})$|[/\\\\]robots\\.(?:${extensions
.concat('txt')
.join('|')})?$|[/\\\\]sitemap\\.(?:${extensions
.concat('xml')
.join('|')})?$|[/\\\\]favicon\\.ico$`
)
const pageNormalizer = new AbsoluteFilenameNormalizer(appDir, extensions)
this.normalizers = {
......@@ -59,10 +47,11 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
): Promise<ReadonlyArray<AppRouteRouteMatcher>> {
const matchers: Array<AppRouteRouteMatcher> = []
for (const filename of files) {
const page = this.normalizers.page.normalize(filename)
// If the file isn't a match for this matcher, then skip it.
if (!this.expression.test(filename)) continue
if (!isAppRouteRoute(page)) continue
const page = this.normalizers.page.normalize(filename)
const pathname = this.normalizers.pathname.normalize(filename)
const bundlePath = this.normalizers.bundlePath.normalize(filename)
......
......@@ -5,6 +5,7 @@ import { join, sep, normalize } from 'path'
import { promises } from 'fs'
import { warn } from '../../build/output/log'
import chalk from '../../lib/chalk'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
async function isTrueCasePagePath(pagePath: string, pagesDir: string) {
const pageSegments = normalize(pagePath).split(sep).filter(Boolean)
......@@ -79,10 +80,8 @@ export function createValidFileMatcher(
pageExtensions: string[],
appDirPath: string | undefined
) {
const getExtensionRegexString = (
extensions: string[],
...extraExtensions: string[]
) => `(?:${extensions.concat(extraExtensions).join('|')})`
const getExtensionRegexString = (extensions: string[]) =>
`(?:${extensions.join('|')})`
const validExtensionFileRegex = new RegExp(
'\\.' + getExtensionRegexString(pageExtensions) + '$'
......@@ -95,40 +94,37 @@ export function createValidFileMatcher(
/** TODO-METADATA: support other metadata routes
* regex for:
*
* /robots.txt|((j|t)sx?)
* /sitemap.xml|((j|t)sx?)
* /favicon.ico
* /robots.txt|<ext>
* /sitemap.xml|<ext>
* /favicon.ico
* <route>/icon.png|jpg|<ext>
* <route>/apple-touch-icon.png|jpg|<ext>
*
*/
const metadataRoutesRelativePathRegex = new RegExp(
`^[\\\\/]((robots\\.${getExtensionRegexString(pageExtensions, 'txt')})` +
'|' +
`(sitemap\\.${getExtensionRegexString(pageExtensions, 'xml')})` +
'|' +
`(favicon\\.ico))$`
)
function isMetadataRouteFile(filePath: string) {
if (!appDirPath) return false
const relativePath = filePath.replace(appDirPath, '')
return metadataRoutesRelativePathRegex.test(relativePath)
/**
* Match the file if it's a metadata route file, static: if the file is a static metadata file
*
*/
function isMetadataFile(filePath: string) {
const appDirRelativePath = filePath.replace(appDirPath || '', '')
return isMetadataRouteFile(appDirRelativePath, pageExtensions, true)
}
// Determine if the file is leaf node page file or route file under layouts,
// 'page.<extension>' | 'route.<extension>'
function isAppRouterPage(filePath: string) {
return leafOnlyPageFileRegex.test(filePath) || isMetadataRouteFile(filePath)
return leafOnlyPageFileRegex.test(filePath) || isMetadataFile(filePath)
}
function isPageFile(filePath: string) {
return (
validExtensionFileRegex.test(filePath) || isMetadataRouteFile(filePath)
)
return validExtensionFileRegex.test(filePath) || isMetadataFile(filePath)
}
return {
isPageFile,
isAppRouterPage,
isMetadataRouteFile,
isMetadataFile,
}
}
......@@ -7,7 +7,7 @@ createNextDescribe(
'app dir - metadata',
{
files: __dirname,
// skipDeployment: true,
skipDeployment: false,
},
({ next, isNextDev, isNextStart }) => {
const getTitle = (browser: BrowserInterface) =>
......@@ -16,7 +16,7 @@ createNextDescribe(
async function checkMeta(
browser: BrowserInterface,
queryValue: string,
expected: string | string[],
expected: string | string[] | undefined | null,
queryKey: string = 'property',
tag: string = 'meta',
domAttributeField: string = 'content'
......@@ -45,7 +45,7 @@ createNextDescribe(
return async (
tag: string,
query: string,
expectedObject: Record<string, string>
expectedObject: Record<string, string | null | undefined>
) => {
const props = await browser.eval(`
const el = document.querySelector('${tag}[${query}]');
......@@ -118,7 +118,7 @@ createNextDescribe(
tag: string,
queryKey: string,
domAttributeField: string,
expected: Record<string, string | string[]>
expected: Record<string, string | string[] | undefined | null>
) => {
await Promise.all(
Object.keys(expected).map(async (key) => {
......@@ -427,8 +427,8 @@ createNextDescribe(
it('should pick up opengraph-image and twitter-image as static metadata files', async () => {
const $ = await next.render$('/opengraph/static')
expect($('[property="og:image"]').attr('content')).toMatch(
/https:\/\/example.com\/_next\/static\/media\/metadata\/opengraph-image.png/
expect($('[property="og:image"]').attr('content')).toBe(
'https://example.com/opengraph/static/opengraph-image.png?b76e8f0282c93c8e'
)
expect($('[property="og:image:type"]').attr('content')).toBe(
'image/png'
......@@ -436,8 +436,8 @@ createNextDescribe(
expect($('[property="og:image:width"]').attr('content')).toBe('114')
expect($('[property="og:image:height"]').attr('content')).toBe('114')
expect($('[name="twitter:image"]').attr('content')).toMatch(
/https:\/\/example.com\/_next\/static\/media\/metadata\/twitter-image.png/
expect($('[name="twitter:image"]').attr('content')).toBe(
'https://example.com/opengraph/static/twitter-image.png?b76e8f0282c93c8e'
)
expect($('[name="twitter:card"]').attr('content')).toBe(
'summary_large_image'
......@@ -514,12 +514,12 @@ createNextDescribe(
const $appleIcon = $('head > link[rel="apple-touch-icon"]')
expect($icon.attr('href')).toMatch(
/\/_next\/static\/media\/metadata\/icon1\.png/
/\/icons\/static\/nested\/icon1\.png\?399de3b94b888afc/
)
expect($icon.attr('sizes')).toBe('32x32')
expect($icon.attr('type')).toBe('image/png')
expect($appleIcon.attr('href')).toMatch(
/\/_next\/static\/media\/metadata\/apple-icon\.png/
/\/icons\/static\/nested\/apple-icon\.png\?b76e8f0282c93c8e/
)
expect($appleIcon.attr('type')).toBe('image/png')
expect($appleIcon.attr('sizes')).toMatch('114x114')
......@@ -529,13 +529,14 @@ createNextDescribe(
const $ = await next.render$('/icons/static')
const $icon = $('head > link[rel="icon"][type!="image/x-icon"]')
const $appleIcon = $('head > link[rel="apple-touch-icon"]')
expect($icon.attr('href')).toMatch(
/\/_next\/static\/media\/metadata\/icon\.png/
/\/icons\/static\/icon\.png\?b76e8f0282c93c8e/
)
expect($icon.attr('sizes')).toBe('114x114')
// No apple icon if it's not provided
const $appleIcon = $('head > link[rel="apple-touch-icon"]')
expect($appleIcon.length).toBe(0)
})
......@@ -550,7 +551,7 @@ createNextDescribe(
const $ = await next.render$('/icons/static')
const $icon = $('head > link[rel="icon"][type!="image/x-icon"]')
return $icon.attr('href')
}, /\/_next\/static\/media\/metadata\/icon2\.png/)
}, /\/icons\/static\/icon2\.png\?b76e8f0282c93c8e/)
await next.renameFile(
'app/icons/static/icon2.png',
......@@ -639,6 +640,33 @@ createNextDescribe(
})
describe('static routes', () => {
it('should have /favicon.ico as route', async () => {
const res = await next.fetch('/favicon.ico')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/x-icon')
expect(res.headers.get('cache-control')).toBe(
'public, max-age=0, must-revalidate'
)
})
it('should have icons as route', async () => {
const resIcon = await next.fetch('/icons/static/icon.png')
const resAppleIcon = await next.fetch(
'/icons/static/nested/apple-icon.png'
)
expect(resAppleIcon.status).toBe(200)
expect(resAppleIcon.headers.get('content-type')).toBe('image/png')
expect(resAppleIcon.headers.get('cache-control')).toBe(
'public, max-age=0, must-revalidate'
)
expect(resIcon.status).toBe(200)
expect(resIcon.headers.get('content-type')).toBe('image/png')
expect(resIcon.headers.get('cache-control')).toBe(
'public, max-age=0, must-revalidate'
)
})
it('should support root dir robots.txt', async () => {
const res = await next.fetch('/robots.txt')
expect(res.headers.get('content-type')).toBe('text/plain')
......
......@@ -74,17 +74,15 @@ describe('createPageFileMatcher', () => {
const pageExtensions = ['tsx', 'ts', 'jsx', 'js']
const fileMatcher = createValidFileMatcher(pageExtensions, 'app')
it('should determine top level metadata routes', () => {
expect(fileMatcher.isMetadataRouteFile('app/route.js')).toBe(false)
expect(fileMatcher.isMetadataRouteFile('app/page.js')).toBe(false)
expect(fileMatcher.isMetadataRouteFile('pages/index.js')).toBe(false)
expect(fileMatcher.isMetadataFile('app/route.js')).toBe(false)
expect(fileMatcher.isMetadataFile('app/page.js')).toBe(false)
expect(fileMatcher.isMetadataFile('pages/index.js')).toBe(false)
expect(fileMatcher.isMetadataRouteFile('app/robots.txt')).toBe(true)
expect(fileMatcher.isMetadataRouteFile('app/path/robots.txt')).toBe(false)
expect(fileMatcher.isMetadataFile('app/robots.txt')).toBe(true)
expect(fileMatcher.isMetadataFile('app/path/robots.txt')).toBe(false)
expect(fileMatcher.isMetadataRouteFile('app/sitemap.xml')).toBe(true)
expect(fileMatcher.isMetadataRouteFile('app/path/sitemap.xml')).toBe(
false
)
expect(fileMatcher.isMetadataFile('app/sitemap.xml')).toBe(true)
expect(fileMatcher.isMetadataFile('app/path/sitemap.xml')).toBe(false)
})
})
})
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