Unverified Commit e601a3b5 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Support manifest.json static and dynamic route (#47240)

* Add `manifest.webmanifest` and `manifest.(j|t)xs?` support for
manifest.json route
* Add `Manifest` type for it for autocomplete purpose.

Remove the exports for `SitemapFile` and `RobotsFile` globally, will
discuss how to re-export them with better naming later

Small fix for `Robots` typing, should allow `string | string[]` for user
agent of single Robots

Closes NEXT-839

---------
parent 990f62ac
...@@ -31,13 +31,13 @@ export const STATIC_METADATA_IMAGES = { ...@@ -31,13 +31,13 @@ export const STATIC_METADATA_IMAGES = {
filename: 'twitter-image', filename: 'twitter-image',
extensions: ['jpg', 'jpeg', 'png', 'gif'], extensions: ['jpg', 'jpeg', 'png', 'gif'],
}, },
} } as const
// Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.) // Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.)
async function enumMetadataFiles( async function enumMetadataFiles(
dir: string, dir: string,
filename: string, filename: string,
extensions: string[], extensions: readonly string[],
{ {
resolvePath, resolvePath,
loaderContext, loaderContext,
......
import type { RobotsFile } from '../../../../lib/metadata/types/metadata-interface' import type { Robots } from '../../../../lib/metadata/types/metadata-interface'
import { resolveRobots, resolveSitemap } from './resolve-route-data' import { resolveRobots, resolveSitemap } from './resolve-route-data'
describe('resolveRouteData', () => { describe('resolveRouteData', () => {
...@@ -30,7 +30,7 @@ describe('resolveRouteData', () => { ...@@ -30,7 +30,7 @@ describe('resolveRouteData', () => {
}) })
it('should error with ts when specify both wildcard userAgent and specific userAgent', () => { it('should error with ts when specify both wildcard userAgent and specific userAgent', () => {
const data1: RobotsFile = { const data1: Robots = {
rules: [ rules: [
// @ts-expect-error userAgent is required for Array<Robots> // @ts-expect-error userAgent is required for Array<Robots>
{ {
...@@ -43,15 +43,14 @@ describe('resolveRouteData', () => { ...@@ -43,15 +43,14 @@ describe('resolveRouteData', () => {
], ],
} }
const data2: RobotsFile = { const data2: Robots = {
rules: { rules: {
// @ts-expect-error When apply only 1 rule, only '*' or undefined is allowed // Can skip userAgent for single Robots
userAgent: 'Somebot',
allow: '/', allow: '/',
}, },
} }
const data3: RobotsFile = { const data3: Robots = {
rules: { allow: '/' }, rules: { allow: '/' },
} }
......
import type { import type {
RobotsFile, Robots,
SitemapFile, Sitemap,
} from '../../../../lib/metadata/types/metadata-interface' } from '../../../../lib/metadata/types/metadata-interface'
import type { Manifest } from '../../../../lib/metadata/types/manifest-types'
import { resolveAsArrayOrUndefined } from '../../../../lib/metadata/generate/utils' import { resolveAsArrayOrUndefined } from '../../../../lib/metadata/generate/utils'
// convert robots data to txt string // convert robots data to txt string
export function resolveRobots(data: RobotsFile): string { export function resolveRobots(data: Robots): string {
let content = '' let content = ''
const rules = Array.isArray(data.rules) ? data.rules : [data.rules] const rules = Array.isArray(data.rules) ? data.rules : [data.rules]
for (const rule of rules) { for (const rule of rules) {
...@@ -40,7 +41,7 @@ export function resolveRobots(data: RobotsFile): string { ...@@ -40,7 +41,7 @@ export function resolveRobots(data: RobotsFile): string {
// TODO-METADATA: support multi sitemap files // TODO-METADATA: support multi sitemap files
// convert sitemap data to xml string // convert sitemap data to xml string
export function resolveSitemap(data: SitemapFile): string { export function resolveSitemap(data: Sitemap): string {
let content = '' let content = ''
content += '<?xml version="1.0" encoding="UTF-8"?>\n' content += '<?xml version="1.0" encoding="UTF-8"?>\n'
content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
...@@ -60,15 +61,22 @@ export function resolveSitemap(data: SitemapFile): string { ...@@ -60,15 +61,22 @@ export function resolveSitemap(data: SitemapFile): string {
return content return content
} }
export function resolveManifest(data: Manifest): string {
return JSON.stringify(data)
}
export function resolveRouteData( export function resolveRouteData(
data: RobotsFile | SitemapFile, data: Robots | Sitemap | Manifest,
fileType: 'robots' | 'sitemap' fileType: 'robots' | 'sitemap' | 'manifest'
): string { ): string {
if (fileType === 'robots') { if (fileType === 'robots') {
return resolveRobots(data as RobotsFile) return resolveRobots(data as Robots)
} }
if (fileType === 'sitemap') { if (fileType === 'sitemap') {
return resolveSitemap(data as SitemapFile) return resolveSitemap(data as Sitemap)
}
if (fileType === 'manifest') {
return resolveManifest(data as Manifest)
} }
return '' return ''
} }
...@@ -20,6 +20,7 @@ function getContentType(resourcePath: string) { ...@@ -20,6 +20,7 @@ function getContentType(resourcePath: string) {
if (name === 'favicon' && ext === 'ico') return 'image/x-icon' if (name === 'favicon' && ext === 'ico') return 'image/x-icon'
if (name === 'sitemap') return 'application/xml' if (name === 'sitemap') return 'application/xml'
if (name === 'robots') return 'text/plain' if (name === 'robots') return 'text/plain'
if (name === 'manifest') return 'application/manifest+json'
if (ext === 'png' || ext === 'jpeg' || ext === 'ico' || ext === 'svg') { if (ext === 'png' || ext === 'jpeg' || ext === 'ico' || ext === 'svg') {
return imageExtMimeTypeMap[ext] return imageExtMimeTypeMap[ext]
......
...@@ -20,6 +20,9 @@ export function normalizeMetadataRoute(page: string) { ...@@ -20,6 +20,9 @@ export function normalizeMetadataRoute(page: string) {
if (route === '/robots') { if (route === '/robots') {
route += '.txt' route += '.txt'
} }
if (route === '/manifest') {
route += '.webmanifest'
}
route = `${route}/route` route = `${route}/route`
} }
return route return route
......
...@@ -4,15 +4,15 @@ import { STATIC_METADATA_IMAGES } from '../../build/webpack/loaders/metadata/dis ...@@ -4,15 +4,15 @@ import { STATIC_METADATA_IMAGES } from '../../build/webpack/loaders/metadata/dis
// TODO-METADATA: support more metadata routes with more extensions // TODO-METADATA: support more metadata routes with more extensions
const defaultExtensions = ['js', 'jsx', 'ts', 'tsx'] const defaultExtensions = ['js', 'jsx', 'ts', 'tsx']
const getExtensionRegexString = (extensions: string[]) => const getExtensionRegexString = (extensions: readonly string[]) =>
`(?:${extensions.join('|')})` `(?:${extensions.join('|')})`
// When you only pass the file extension as `[]`, it will only match the static convention files // When you only pass the file extension as `[]`, it will only match the static convention files
// e.g. /robots.txt, /sitemap.xml, /favicon.ico // e.g. /robots.txt, /sitemap.xml, /favicon.ico, /manifest.json
// When you pass the file extension as `['js', 'jsx', 'ts', 'tsx']`, it will also match the dynamic convention files // 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 // e.g. /robots.js, /sitemap.tsx, /favicon.jsx, /manifest.ts
// When `withExtension` is false, it will match the static convention files without the extension, by default it's true // 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 // e.g. /robots, /sitemap, /favicon, /manifest, use to match dynamic API routes like app/robots.ts
export function isMetadataRouteFile( export function isMetadataRouteFile(
appDirRelativePath: string, appDirRelativePath: string,
pageExtensions: string[], pageExtensions: string[],
...@@ -33,6 +33,15 @@ export function isMetadataRouteFile( ...@@ -33,6 +33,15 @@ export function isMetadataRouteFile(
: '' : ''
}` }`
), ),
new RegExp(
`^[\\\\/]manifest${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat('webmanifest', 'json')
)}`
: ''
}`
),
new RegExp(`^[\\\\/]favicon\\.ico$`), new RegExp(`^[\\\\/]favicon\\.ico$`),
// TODO-METADATA: add dynamic routes for metadata images // TODO-METADATA: add dynamic routes for metadata images
new RegExp( new RegExp(
......
export type Manifest = {
background_color?: string
categories?: string[]
description?: string
display?: 'fullscreen' | 'standalone' | 'minimal-ui' | 'browser'
display_override?: string[]
icons?: {
src: string
type?: string
sizes?: string
purpose?: 'any' | 'maskable' | 'monochrome' | 'badge'
}[]
id?: string
launch_handler?: {
platform?: 'windows' | 'macos' | 'linux'
url?: string
}
name?: string
orientation?:
| 'any'
| 'natural'
| 'landscape'
| 'portrait'
| 'portrait-primary'
| 'portrait-secondary'
| 'landscape-primary'
| 'landscape-secondary'
prefer_related_applications?: boolean
protocol_handlers?: {
protocol: string
url: string
title?: string
}[]
related_applications?: {
platform: string
url: string
id?: string
}[]
scope?: string
screenshots?: {
src: string
type?: string
sizes?: string
}[]
serviceworker?: {
src?: string
scope?: string
type?: string
update_via_cache?: 'import' | 'none' | 'all'
}
share_target?: {
action?: string
method?: 'get' | 'post'
enctype?:
| 'application/x-www-form-urlencoded'
| 'multipart/form-data'
| 'text/plain'
params?: {
name: string
value: string
required?: boolean
}[]
url?: string
title?: string
text?: string
files?: {
accept?: string[]
name?: string
}[]
}
short_name?: string
shortcuts?: {
name: string
short_name?: string
description?: string
url: string
icons?: {
src: string
type?: string
sizes?: string
purpose?: 'any' | 'maskable' | 'monochrome' | 'badge'
}[]
}[]
start_url?: string
theme_color?: string
}
...@@ -538,7 +538,7 @@ type RobotsFile = { ...@@ -538,7 +538,7 @@ type RobotsFile = {
// Apply rules for all // Apply rules for all
rules: rules:
| { | {
userAgent?: undefined | '*' userAgent?: string | string[]
allow?: string | string[] allow?: string | string[]
disallow?: string | string[] disallow?: string | string[]
crawlDelay?: number crawlDelay?: number
...@@ -554,10 +554,10 @@ type RobotsFile = { ...@@ -554,10 +554,10 @@ type RobotsFile = {
host?: string host?: string
} }
type SitemapFile = Array<{ type Sitemap = Array<{
url: string url: string
lastModified?: string | Date lastModified?: string | Date
}> }>
export type ResolvingMetadata = Promise<ResolvedMetadata> export type ResolvingMetadata = Promise<ResolvedMetadata>
export { Metadata, ResolvedMetadata, RobotsFile, SitemapFile } export { Metadata, ResolvedMetadata, RobotsFile as Robots, Sitemap }
...@@ -97,6 +97,7 @@ export function createValidFileMatcher( ...@@ -97,6 +97,7 @@ export function createValidFileMatcher(
* /robots.txt|<ext> * /robots.txt|<ext>
* /sitemap.xml|<ext> * /sitemap.xml|<ext>
* /favicon.ico * /favicon.ico
* /manifest.json|<ext>
* <route>/icon.png|jpg|<ext> * <route>/icon.png|jpg|<ext>
* <route>/apple-touch-icon.png|jpg|<ext> * <route>/apple-touch-icon.png|jpg|<ext>
* *
......
...@@ -28,11 +28,8 @@ export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined ...@@ -28,11 +28,8 @@ export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined
// @ts-ignore This path is generated at build time and conflicts otherwise // @ts-ignore This path is generated at build time and conflicts otherwise
export { NextConfig } from '../dist/server/config' export { NextConfig } from '../dist/server/config'
export type { // @ts-ignore This path is generated at build time and conflicts otherwise
Metadata, export type { Metadata } from '../dist/lib/metadata/types/metadata-interface'
RobotsFile,
SitemapFile, // @ts-ignore This path is generated at build time and conflicts otherwise
} from '../dist/lib/metadata/types/metadata-interface'
// Extend the React types with missing properties // Extend the React types with missing properties
declare module 'react' { declare module 'react' {
......
export default function manifest() {
return {
name: 'Next.js App',
short_name: 'Next.js App',
description: 'Next.js App',
start_url: '/',
display: 'standalone',
background_color: '#fff',
theme_color: '#fff',
icons: [
{
src: '/favicon.ico',
sizes: 'any',
type: 'image/x-icon',
},
],
}
}
import type { RobotsFile } from 'next' export default function robots() {
export default function robots(): RobotsFile {
return { return {
rules: [ rules: [
{ {
......
import type { SitemapFile } from 'next' export default function sitemap() {
export default function sitemap(): SitemapFile {
return [ return [
{ {
url: 'https://example.com', url: 'https://example.com',
......
...@@ -56,6 +56,35 @@ createNextDescribe( ...@@ -56,6 +56,35 @@ createNextDescribe(
" "
`) `)
}) })
it('should handle manifest.[ext] dynamic routes', async () => {
const res = await next.fetch('/manifest.webmanifest')
const json = await res.json()
expect(res.headers.get('content-type')).toBe(
'application/manifest+json'
)
expect(res.headers.get('cache-control')).toBe(
'public, max-age=0, must-revalidate'
)
expect(json).toMatchObject({
name: 'Next.js App',
short_name: 'Next.js App',
description: 'Next.js App',
start_url: '/',
display: 'standalone',
background_color: '#fff',
theme_color: '#fff',
icons: [
{
src: '/favicon.ico',
sizes: 'any',
type: 'image/x-icon',
},
],
})
})
}) })
} }
) )
...@@ -25,7 +25,7 @@ export const metadata: Metadata = { ...@@ -25,7 +25,7 @@ export const metadata: Metadata = {
authors: [{ name: 'huozhi' }, { name: 'tree', url: 'https://tree.com' }], authors: [{ name: 'huozhi' }, { name: 'tree', url: 'https://tree.com' }],
themeColor: { color: 'cyan', media: '(prefers-color-scheme: dark)' }, themeColor: { color: 'cyan', media: '(prefers-color-scheme: dark)' },
colorScheme: 'dark', colorScheme: 'dark',
manifest: 'https://github.com/manifest.json', manifest: 'https://www.google.com/manifest',
viewport: { viewport: {
width: 'device-width', width: 'device-width',
initialScale: 1, initialScale: 1,
......
{
"name": "Next.js Static Manifest",
"short_name": "Next.js App",
"description": "Next.js App",
"start_url": "/",
"display": "standalone",
"background_color": "#fff",
"theme_color": "#fff"
}
...@@ -210,7 +210,7 @@ createNextDescribe( ...@@ -210,7 +210,7 @@ createNextDescribe(
}) })
await matchMultiDom('link', 'rel', 'href', { await matchMultiDom('link', 'rel', 'href', {
manifest: 'https://github.com/manifest.json', manifest: 'https://www.google.com/manifest',
author: 'https://tree.com', author: 'https://tree.com',
preconnect: '/preconnect-url', preconnect: '/preconnect-url',
preload: '/preload-url', preload: '/preload-url',
...@@ -687,6 +687,23 @@ createNextDescribe( ...@@ -687,6 +687,23 @@ createNextDescribe(
expect(invalidSitemapResponse.status).toBe(404) expect(invalidSitemapResponse.status).toBe(404)
}) })
it('should support static manifest.webmanifest', async () => {
const res = await next.fetch('/manifest.webmanifest')
expect(res.headers.get('content-type')).toBe(
'application/manifest+json'
)
const manifest = await res.json()
expect(manifest).toMatchObject({
name: 'Next.js Static Manifest',
short_name: 'Next.js App',
description: 'Next.js App',
start_url: '/',
display: 'standalone',
background_color: '#fff',
theme_color: '#fff',
})
})
if (isNextStart) { if (isNextStart) {
it('should build favicon.ico as a custom route', async () => { it('should build favicon.ico as a custom route', async () => {
const appPathsManifest = JSON.parse( const appPathsManifest = JSON.parse(
......
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