Unverified Commit 9822f78f authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Resolve metadata fields (#45237)

## Feature

- [x] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [x]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
parent f879e093
......@@ -2,17 +2,18 @@ import type { ResolvedMetadata } from '../types/metadata-interface'
import React from 'react'
export function ResolvedAlternatesMetadata({
metadata,
export function AlternatesMetadata({
alternates,
}: {
metadata: ResolvedMetadata
alternates: ResolvedMetadata['alternates']
}) {
if (!alternates) return null
return (
<>
{metadata.alternates.canonical ? (
<link rel="canonical" href={metadata.alternates.canonical.toString()} />
{alternates.canonical ? (
<link rel="canonical" href={alternates.canonical.toString()} />
) : null}
{Object.entries(metadata.alternates.languages).map(([locale, url]) =>
{Object.entries(alternates.languages).map(([locale, url]) =>
url ? (
<link
key={locale}
......@@ -22,8 +23,8 @@ export function ResolvedAlternatesMetadata({
/>
) : null
)}
{metadata.alternates.media
? Object.entries(metadata.alternates.media).map(([media, url]) =>
{alternates.media
? Object.entries(alternates.media).map(([media, url]) =>
url ? (
<link
key={media}
......@@ -34,8 +35,8 @@ export function ResolvedAlternatesMetadata({
) : null
)
: null}
{metadata.alternates.types
? Object.entries(metadata.alternates.types).map(([type, url]) =>
{alternates.types
? Object.entries(alternates.types).map(([type, url]) =>
url ? (
<link
key={type}
......
......@@ -3,11 +3,7 @@ import type { ResolvedMetadata } from '../types/metadata-interface'
import React from 'react'
import { Meta } from './meta'
export function ResolvedBasicMetadata({
metadata,
}: {
metadata: ResolvedMetadata
}) {
export function BasicMetadata({ metadata }: { metadata: ResolvedMetadata }) {
return (
<>
<meta charSet="utf-8" />
......@@ -25,7 +21,8 @@ export function ResolvedBasicMetadata({
<Meta name="viewport" content={metadata.viewport} />
<Meta name="creator" content={metadata.creator} />
<Meta name="publisher" content={metadata.publisher} />
<Meta name="robots" content={metadata.robots} />
<Meta name="robots" content={metadata.robots?.basic} />
<Meta name="googlebot" content={metadata.robots?.googleBot} />
<Meta name="abstract" content={metadata.abstract} />
{metadata.archives
? metadata.archives.map((archive) => (
......@@ -44,13 +41,84 @@ export function ResolvedBasicMetadata({
: null}
<Meta name="category" content={metadata.category} />
<Meta name="classification" content={metadata.classification} />
{Object.entries(metadata.other).map(([name, content]) => (
<Meta
key={name}
name={name}
content={Array.isArray(content) ? content.join(',') : content}
{metadata.other
? Object.entries(metadata.other).map(([name, content]) => (
<Meta
key={name}
name={name}
content={Array.isArray(content) ? content.join(',') : content}
/>
))
: null}
</>
)
}
export function ItunesMeta({ itunes }: { itunes: ResolvedMetadata['itunes'] }) {
if (!itunes) return null
const { appId, appArgument } = itunes
let content = `app-id=${appId}`
if (appArgument) {
content += `, app-argument=${appArgument}`
}
return <meta name="apple-itunes-app" content={content} />
}
const formatDetectionKeys = [
'telephone',
'date',
'address',
'email',
'url',
] as const
export function FormatDetectionMeta({
formatDetection,
}: {
formatDetection: ResolvedMetadata['formatDetection']
}) {
if (!formatDetection) return null
let content = ''
for (const key of formatDetectionKeys) {
if (formatDetection[key]) {
if (content) content += ', '
content += `${key}=no`
}
}
return <meta name="format-detection" content={content} />
}
export function AppleWebAppMeta({
appleWebApp,
}: {
appleWebApp: ResolvedMetadata['appleWebApp']
}) {
if (!appleWebApp) return null
const { capable, title, startupImage, statusBarStyle } = appleWebApp
return (
<>
{capable ? (
<meta name="apple-mobile-web-app-capable" content="yes" />
) : null}
{title ? (
<meta name="apple-mobile-web-app-title" content={title} />
) : null}
{startupImage
? startupImage.map((image, index) => (
<link
key={index}
href={image.url}
media={image.media}
rel="apple-touch-startup-image"
/>
))
: null}
{statusBarStyle ? (
<meta
name="apple-mobile-web-app-status-bar-style"
content={statusBarStyle}
/>
))}
) : null}
</>
)
}
......@@ -22,11 +22,7 @@ function IconLink({ rel, icon }: { rel?: string; icon: Icon }) {
}
}
export function ResolvedIconsMetadata({
icons,
}: {
icons: ResolvedMetadata['icons']
}) {
export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) {
if (!icons) return null
const shortcutList = icons.shortcut
......
......@@ -20,6 +20,43 @@ export function Meta({
return null
}
type ExtendMetaContent = Record<
string,
undefined | string | URL | number | boolean | null | undefined
>
type MultiMetaContent =
| (ExtendMetaContent | string | URL | number)[]
| null
| undefined
export function ExtendMeta({
content,
namePrefix,
propertyPrefix,
}: {
content?: ExtendMetaContent
namePrefix?: string
propertyPrefix?: string
}) {
const keyPrefix = namePrefix || propertyPrefix
if (!content) return null
return (
<React.Fragment>
{Object.entries(content).map(([k, v], index) => {
return typeof v === 'undefined' ? null : (
<Meta
key={keyPrefix + ':' + k + '_' + index}
{...(propertyPrefix
? { property: propertyPrefix + ':' + k }
: { name: namePrefix + ':' + k })}
content={typeof v === 'string' ? v : v?.toString()}
/>
)
})}
</React.Fragment>
)
}
export function MultiMeta({
propertyPrefix,
namePrefix,
......@@ -27,15 +64,7 @@ export function MultiMeta({
}: {
propertyPrefix?: string
namePrefix?: string
contents:
| (
| Record<string, undefined | string | URL | number>
| string
| URL
| number
)[]
| null
| undefined
contents?: MultiMetaContent | null
}) {
if (typeof contents === 'undefined' || contents === null) {
return null
......@@ -61,19 +90,11 @@ export function MultiMeta({
)
} else {
return (
<React.Fragment key={keyPrefix + '_' + index}>
{Object.entries(content).map(([k, v]) => {
return typeof v === 'undefined' ? null : (
<Meta
key={keyPrefix + ':' + k + '_' + index}
{...(propertyPrefix
? { property: propertyPrefix + ':' + k }
: { name: namePrefix + ':' + k })}
content={typeof v === 'string' ? v : v.toString()}
/>
)
})}
</React.Fragment>
<ExtendMeta
namePrefix={namePrefix}
propertyPrefix={propertyPrefix}
content={content}
/>
)
}
})}
......
import type { ResolvedMetadata } from '../types/metadata-interface'
import React from 'react'
import { Meta, MultiMeta } from './meta'
import { ExtendMeta, Meta, MultiMeta } from './meta'
import { TwitterAppDescriptor } from '../types/twitter-types'
export function ResolvedOpenGraphMetadata({
export function OpenGraphMetadata({
openGraph,
}: {
openGraph: ResolvedMetadata['openGraph']
......@@ -221,3 +222,97 @@ export function ResolvedOpenGraphMetadata({
</>
)
}
function TwitterAppItem({
app,
type,
}: {
app: TwitterAppDescriptor
type: 'iphone' | 'ipad' | 'googleplay'
}) {
return (
<>
<Meta name={`twitter:app:name:${type}`} content={app.name} />
<ExtendMeta namePrefix="twitter:app:id" content={app.id} />
<ExtendMeta namePrefix="twitter:app:url" content={app.url} />
</>
)
}
export function TwitterMetadata({
twitter,
}: {
twitter: ResolvedMetadata['twitter']
}) {
if (!twitter) return null
const { card } = twitter
return (
<>
<Meta name="twitter:card" content={card} />
<Meta name="twitter:site" content={twitter.site} />
<Meta name="twitter:site:id" content={twitter.siteId} />
<Meta name="twitter:creator" content={twitter.creator} />
<Meta name="twitter:creator:id" content={twitter.creatorId} />
<Meta name="twitter:title" content={twitter.title?.absolute} />
<Meta name="twitter:description" content={twitter.description} />
{twitter.images
? twitter.images.map((image) => (
<>
<Meta name="twitter:image" content={image.url} />
<Meta name="twitter:image:alt" content={image.alt} />
</>
))
: null}
{card === 'player'
? twitter.players.map((player) => (
<>
<Meta
name="twitter:player"
content={player.playerUrl.toString()}
/>
<Meta
name="twitter:player:stream"
content={player.streamUrl.toString()}
/>
<Meta name="twitter:player:width" content={player.width} />
<Meta name="twitter:player:height" content={player.height} />
</>
))
: null}
{card === 'app' ? (
<>
<TwitterAppItem app={twitter.app} type="iphone" />
<TwitterAppItem app={twitter.app} type="ipad" />
<TwitterAppItem app={twitter.app} type="googleplay" />
</>
) : null}
</>
)
}
export function AppLinksMeta({
appLinks,
}: {
appLinks: ResolvedMetadata['appLinks']
}) {
if (!appLinks) return null
return (
<>
<MultiMeta propertyPrefix="al:ios" contents={appLinks.ios} />
<MultiMeta propertyPrefix="al:iphone" contents={appLinks.iphone} />
<MultiMeta propertyPrefix="al:ipad" contents={appLinks.ipad} />
<MultiMeta propertyPrefix="al:android" contents={appLinks.android} />
<MultiMeta
propertyPrefix="al:windows_phone"
contents={appLinks.windows_phone}
/>
<MultiMeta propertyPrefix="al:windows" contents={appLinks.windows} />
<MultiMeta
propertyPrefix="al:windows_universal"
contents={appLinks.windows_universal}
/>
<MultiMeta propertyPrefix="al:web" contents={appLinks.web} />
</>
)
}
export function resolveAsArrayOrUndefined<T = any>(
value: T | T[] | undefined | null
): undefined | T[] {
export function resolveAsArrayOrUndefined<
T extends unknown | readonly unknown[]
>(value: T | T[] | undefined | null): undefined | T[] {
if (typeof value === 'undefined' || value === null) {
return undefined
}
......
import type { ResolvedMetadata } from './types/metadata-interface'
import React from 'react'
import { ResolvedBasicMetadata } from './generate/basic'
import { ResolvedAlternatesMetadata } from './generate/alternate'
import { ResolvedOpenGraphMetadata } from './generate/opengraph'
import {
AppleWebAppMeta,
FormatDetectionMeta,
ItunesMeta,
BasicMetadata,
} from './generate/basic'
import { AlternatesMetadata } from './generate/alternate'
import {
OpenGraphMetadata,
TwitterMetadata,
AppLinksMeta,
} from './generate/opengraph'
import { resolveMetadata } from './resolve-metadata'
import { ResolvedIconsMetadata } from './generate/icons'
import { IconsMetadata } from './generate/icons'
// Generate the actual React elements from the resolved metadata.
export async function Metadata({ metadata }: { metadata: any }) {
......@@ -14,10 +23,15 @@ export async function Metadata({ metadata }: { metadata: any }) {
const resolved: ResolvedMetadata = await resolveMetadata(metadata)
return (
<>
<ResolvedBasicMetadata metadata={resolved} />
<ResolvedAlternatesMetadata metadata={resolved} />
<ResolvedOpenGraphMetadata openGraph={resolved.openGraph} />
<ResolvedIconsMetadata icons={resolved.icons} />
<BasicMetadata metadata={resolved} />
<AlternatesMetadata alternates={resolved.alternates} />
<ItunesMeta itunes={resolved.itunes} />
<FormatDetectionMeta formatDetection={resolved.formatDetection} />
<AppleWebAppMeta appleWebApp={resolved.appleWebApp} />
<OpenGraphMetadata openGraph={resolved.openGraph} />
<TwitterMetadata twitter={resolved.twitter} />
<AppLinksMeta appLinks={resolved.appLinks} />
<IconsMetadata icons={resolved.icons} />
</>
)
}
......@@ -16,6 +16,10 @@ import { resolveOpenGraph } from './resolve-opengraph'
import { mergeTitle } from './resolve-title'
import { resolveAsArrayOrUndefined } from './generate/utils'
type FieldResolver<Key extends keyof Metadata> = (
T: Metadata[Key]
) => ResolvedMetadata[Key]
const viewPortKeys = {
width: 'width',
height: 'height',
......@@ -54,9 +58,7 @@ type Item =
path?: string
}
function resolveViewport(
viewport: Metadata['viewport']
): ResolvedMetadata['viewport'] {
const resolveViewport: FieldResolver<'viewport'> = (viewport) => {
let resolved: ResolvedMetadata['viewport'] = null
if (typeof viewport === 'string') {
......@@ -74,19 +76,44 @@ function resolveViewport(
return resolved
}
function isUrlIcon(icon: any): icon is string | URL {
const resolveVerification: FieldResolver<'verification'> = (verification) => {
const google = resolveAsArrayOrUndefined(verification?.google)
const yahoo = resolveAsArrayOrUndefined(verification?.yahoo)
let other: Record<string, (string | number)[]> | undefined
if (verification?.other) {
other = {}
for (const key in verification.other) {
const value = resolveAsArrayOrUndefined(verification.other[key])
if (value) other[key] = value
}
}
return {
google,
yahoo,
other,
}
}
function isStringOrURL(icon: any): icon is string | URL {
return typeof icon === 'string' || icon instanceof URL
}
function resolveIcon(icon: Icon): IconDescriptor {
if (isUrlIcon(icon)) return { url: icon }
if (isStringOrURL(icon)) return { url: icon }
else if (Array.isArray(icon)) return icon
return icon
}
const IconKeys = ['icon', 'shortcut', 'apple', 'other'] as (keyof Icons)[]
const TwitterBasicInfoKeys = [
'site',
'siteId',
'creator',
'creatorId',
'description',
] as const
function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] {
const resolveIcons: FieldResolver<'icons'> = (icons) => {
if (!icons) {
return null
}
......@@ -94,7 +121,7 @@ function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] {
const resolved: ResolvedMetadata['icons'] = {}
if (Array.isArray(icons)) {
resolved.icon = icons.map(resolveIcon).filter(Boolean)
} else if (isUrlIcon(icons)) {
} else if (isStringOrURL(icons)) {
resolved.icon = [resolveIcon(icons)]
} else {
for (const key of IconKeys) {
......@@ -105,6 +132,107 @@ function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] {
return resolved
}
const resolveAppleWebApp: FieldResolver<'appleWebApp'> = (appWebApp) => {
if (!appWebApp) return null
if (appWebApp === true) {
return {
capable: true,
}
}
const startupImages = resolveAsArrayOrUndefined(appWebApp.startupImage)?.map(
(item) => (typeof item === 'string' ? { url: item } : item)
)
return {
capable: 'capable' in appWebApp ? !!appWebApp.capable : true,
title: appWebApp.title || null,
startupImage: startupImages || null,
statusBarStyle: appWebApp.statusBarStyle || 'default',
}
}
const resolveTwitter: FieldResolver<'twitter'> = (twitter) => {
if (!twitter) return null
const resolved = {
title: twitter.title,
} as ResolvedTwitterMetadata
for (const infoKey of TwitterBasicInfoKeys) {
resolved[infoKey] = twitter[infoKey] || null
}
resolved.images = resolveAsArrayOrUndefined(twitter.images)?.map((item) => {
if (isStringOrURL(item))
return {
url: item.toString(),
}
else {
return {
url: item.url.toString(),
alt: item.alt,
}
}
})
if ('card' in twitter) {
resolved.card = twitter.card
switch (twitter.card) {
case 'player': {
// @ts-ignore
resolved.players = resolveAsArrayOrUndefined(twitter.players) || []
break
}
case 'app': {
// @ts-ignore
resolved.app = twitter.app || {}
break
}
default:
break
}
} else {
resolved.card = 'summary'
}
return resolved
}
const resolveAppLinks: FieldResolver<'appLinks'> = (appLinks) => {
if (!appLinks) return null
for (const key in appLinks) {
// @ts-ignore // TODO: type infer
appLinks[key] = resolveAsArrayOrUndefined(appLinks[key])
}
return appLinks as ResolvedMetadata['appLinks']
}
const resolveRobotsValue: (robots: Metadata['robots']) => string | null = (
robots
) => {
if (!robots) return null
if (typeof robots === 'string') return robots
const values = []
if (robots.index) values.push('index')
else if (typeof robots.index === 'boolean') values.push('noindex')
if (robots.follow) values.push('follow')
else if (typeof robots.follow === 'boolean') values.push('nofollow')
if (robots.noarchive) values.push('noarchive')
if (robots.nosnippet) values.push('nosnippet')
if (robots.noimageindex) values.push('noimageindex')
if (robots.nocache) values.push('nocache')
return values.join(', ')
}
const resolveRobots: FieldResolver<'robots'> = (robots) => {
if (!robots) return null
return {
basic: resolveRobotsValue(robots),
googleBot:
typeof robots !== 'string' ? resolveRobotsValue(robots.googleBot) : null,
}
}
// Merge the source metadata into the resolved target metadata.
function merge(
target: ResolvedMetadata,
......@@ -119,10 +247,6 @@ function merge(
const key = key_ as keyof Metadata
switch (key) {
case 'other': {
Object.assign(target.other, source.other)
break
}
case 'title': {
if (source.title) {
target.title = source.title as AbsoluteTemplateString
......@@ -142,14 +266,15 @@ function merge(
break
}
case 'twitter': {
if (source.twitter) {
target.twitter = source.twitter as ResolvedTwitterMetadata
target.twitter = resolveTwitter(source.twitter)
if (target.twitter) {
mergeTitle(target.twitter, templateStrings.twitter)
} else {
target.twitter = null
}
break
}
case 'verification':
target.verification = resolveVerification(source.verification)
break
case 'viewport': {
target.viewport = resolveViewport(source.viewport)
break
......@@ -158,12 +283,46 @@ function merge(
target.icons = resolveIcons(source.icons)
break
}
default: {
// TODO: Make sure the type is correct.
case 'appleWebApp':
target.appleWebApp = resolveAppleWebApp(source.appleWebApp)
break
case 'appLinks':
target.appLinks = resolveAppLinks(source.appLinks)
break
case 'robots': {
target.robots = resolveRobots(source.robots)
break
}
case 'archives':
case 'assets':
case 'bookmarks':
case 'keywords':
case 'authors': {
// FIXME: type inferring
// @ts-ignore
target[key] = source[key]
target[key] = resolveAsArrayOrUndefined(source[key]) || null
break
}
// directly assign fields that fallback to null
case 'applicationName':
case 'description':
case 'generator':
case 'themeColor':
case 'creator':
case 'publisher':
case 'category':
case 'classification':
case 'referrer':
case 'colorScheme':
case 'itunes':
case 'alternates':
case 'formatDetection':
case 'other':
// @ts-ignore TODO: support inferring
target[key] = source[key] || null
break
default:
break
}
}
}
......
......@@ -12,6 +12,16 @@ export type AppLinks = {
windows_universal?: AppLinksWindows | Array<AppLinksWindows>
web?: AppLinksWeb | Array<AppLinksWeb>
}
export type ResolvedAppLinks = {
ios?: Array<AppLinksApple>
iphone?: Array<AppLinksApple>
ipad?: Array<AppLinksApple>
android?: Array<AppLinksAndroid>
windows_phone?: Array<AppLinksWindows>
windows?: Array<AppLinksWindows>
windows_universal?: Array<AppLinksWindows>
web?: Array<AppLinksWeb>
}
export type AppLinksApple = {
url: string | URL
app_store_id?: string | number
......@@ -68,6 +78,13 @@ export type AppleImageDescriptor = {
media?: string
}
export type ResolvedAppleWebApp = {
capable: boolean
title?: string | null
startupImage?: AppleImageDescriptor[] | null
statusBarStyle?: 'default' | 'black' | 'black-translucent'
}
// Format Detection
// This is a poorly specified metadata export type that is supposed to
// control whether the device attempts to conver text that matches
......
......@@ -7,6 +7,8 @@ import type {
AppLinks,
FormatDetection,
ItunesApp,
ResolvedAppleWebApp,
ResolvedAppLinks,
Viewport,
} from './extra-types'
import type {
......@@ -18,7 +20,9 @@ import type {
IconURL,
ReferrerEnum,
ResolvedIcons,
ResolvedVerification,
Robots,
ResolvedRobots,
TemplateString,
Verification,
} from './metadata-types'
......@@ -38,7 +42,7 @@ export interface Metadata {
// Standard metadata names
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name
applicationName?: null | string | Array<string>
applicationName?: null | string
authors?: null | Author | Array<Author>
generator?: null | string
// if you provide an array it will be flattened into a single tag with comma separation
......@@ -54,7 +58,7 @@ export interface Metadata {
robots?: null | string | Robots
// The canonical and alternate URLs for this location
alternates: AlternateURLs
alternates?: null | AlternateURLs
// Defaults to rel="icon" but the Icons type can be used
// to get more specific about rel types
......@@ -140,10 +144,10 @@ export interface ResolvedMetadata {
publisher: null | string
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#other_metadata_names
robots: null | string
robots: null | ResolvedRobots
// The canonical and alternate URLs for this location
alternates: ResolvedAlternateURLs
alternates: null | ResolvedAlternateURLs
// Defaults to rel="icon" but the Icons type can be used
// to get more specific about rel types
......@@ -154,11 +158,11 @@ export interface ResolvedMetadata {
twitter: null | ResolvedTwitterMetadata
// common verification tokens
verification: Verification
verification: null | ResolvedVerification
// Apple web app metadata
// https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
appleWebApp: null | AppleWebApp
appleWebApp: null | ResolvedAppleWebApp
// Should devices try to interpret various formats and make actionable links
// out of them? The canonical example is telephone numbers on mobile that can
......@@ -175,7 +179,7 @@ export interface ResolvedMetadata {
abstract: null | string
// Facebook AppLinks
appLinks: null | AppLinks
appLinks: null | ResolvedAppLinks
// link rel properties
archives: null | Array<string>
......@@ -187,7 +191,7 @@ export interface ResolvedMetadata {
classification: null | string
// Arbitrary name/value pairs
other: {
other: null | {
[name: string]: string | number | Array<string | number>
}
......
......@@ -45,7 +45,7 @@ export type ColorSchemeEnum =
| 'dark light'
| 'only light'
export type Robots = {
type RobotsInfo = {
// all and none will be inferred from index/follow boolean options
index?: boolean
follow?: boolean
......@@ -59,9 +59,15 @@ export type Robots = {
nosnippet?: boolean
noimageindex?: boolean
nocache?: boolean
}
export type Robots = RobotsInfo & {
// if you want to specify an alternate robots just for google
googleBot?: string | Robots
googleBot?: string | RobotsInfo
}
export type ResolvedRobots = {
basic: string | null
googleBot: string | null
}
export type IconURL = string | URL
......@@ -93,6 +99,14 @@ export type Verification = {
}
}
export type ResolvedVerification = {
google?: null | (string | number)[]
yahoo?: null | (string | number)[]
other?: {
[name: string]: (string | number)[]
}
}
export type ResolvedIcons = {
icon?: IconDescriptor[]
shortcut?: IconDescriptor[]
......
// Reference: https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/markup
import type { AbsoluteTemplateString, TemplateString } from './metadata-types'
export type Twitter =
......@@ -13,8 +15,8 @@ type TwitterMetadata = {
siteId?: string // id for account associated to the site itself
creator?: string // username for the account associated to the creator of the content on the site
creatorId?: string // id for the account associated to the creator of the content on the site
title?: string | TemplateString
description?: string
title?: string | TemplateString
images?: TwitterImage | Array<TwitterImage>
}
type TwitterSummary = TwitterMetadata & {
......@@ -31,7 +33,7 @@ type TwitterApp = TwitterMetadata & {
card: 'app'
app: TwitterAppDescriptor
}
type TwitterAppDescriptor = {
export type TwitterAppDescriptor = {
id: {
iphone?: string | number
ipad?: string | number
......@@ -42,14 +44,14 @@ type TwitterAppDescriptor = {
ipad?: string | URL
googleplay?: string | URL
}
country?: string
name?: string
}
type TwitterImage = string | TwitterImageDescriptor | URL
type TwitterImageDescriptor = {
url: string | URL
secureUrl?: string | URL
alt?: string
secureUrl?: string | URL
type?: string
width?: string | number
height?: string | number
......@@ -61,6 +63,26 @@ type TwitterPlayerDescriptor = {
height: number
}
export type ResolvedTwitterMetadata = Omit<TwitterMetadata, 'title'> & {
title: AbsoluteTemplateString | null
type ResolvedTwitterImage = {
url: string
alt?: string
}
type ResolvedTwitterSummary = {
site: string | null
siteId: string | null
creator: string | null
creatorId: string | null
description: string | null
title: AbsoluteTemplateString
images?: Array<ResolvedTwitterImage>
}
type ResolvedTwitterPlayer = ResolvedTwitterSummary & {
players: Array<TwitterPlayerDescriptor>
}
type ResolvedTwitterApp = ResolvedTwitterSummary & { app: TwitterAppDescriptor }
export type ResolvedTwitterMetadata =
| ({ card: 'summary' } & ResolvedTwitterSummary)
| ({ card: 'summary_large_image' } & ResolvedTwitterSummary)
| ({ card: 'player' } & ResolvedTwitterPlayer)
| ({ card: 'app' } & ResolvedTwitterApp)
......@@ -6,6 +6,7 @@ import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-ma
// Import builtin react directly to avoid require cache conflicts
import React, { use } from 'next/dist/compiled/react'
import { NotFound as DefaultNotFound } from '../client/components/error'
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
// this needs to be required lazily so that `next-server` can set
// the env before we require
......@@ -45,9 +46,9 @@ import {
RSC,
} from '../client/components/app-router-headers'
import type { StaticGenerationAsyncStorage } from '../client/components/static-generation-async-storage'
import type { RequestAsyncStorage } from '../client/components/request-async-storage'
import { formatServerError } from '../lib/format-server-error'
import { Metadata } from '../lib/metadata/metadata'
import type { RequestAsyncStorage } from '../client/components/request-async-storage'
import { runWithRequestAsyncStorage } from './run-with-request-async-storage'
import { runWithStaticGenerationAsyncStorage } from './run-with-static-generation-async-storage'
......@@ -977,6 +978,8 @@ export async function renderToHTMLOrFlight(
* The metadata items array created in next-app-loader with all relevant information
* that we need to resolve the final metadata.
*/
const requestId = nanoid(12)
const metadataItems = ComponentMod.metadata
stripInternalQueries(query)
......@@ -1708,8 +1711,9 @@ export async function renderToHTMLOrFlight(
isFirst: true,
rscPayloadHead: (
<>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */}
<Metadata metadata={metadataItems} />
<Metadata key={requestId} metadata={metadataItems} />
{rscPayloadHead}
</>
),
......@@ -1807,8 +1811,9 @@ export async function renderToHTMLOrFlight(
initialTree={initialTree}
initialHead={
<>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */}
<Metadata metadata={metadataItems} />
<Metadata key={requestId} metadata={metadataItems} />
{initialHead}
</>
}
......
export default function Page() {
return <p>hello</p>
return 'hello'
}
export const metadata = {
......
export default function Page() {
return 'app links'
}
export const metadata = {
appLinks: {
ios: {
url: 'https://example.com/ios',
app_store_id: 'app_store_id',
},
android: {
package: 'com.example.android/package',
app_name: 'app_name_android',
},
web: {
should_fallback: true,
},
},
}
export default function page() {
return 'apple'
}
export const metadata = {
itunes: {
appId: 'myAppStoreID',
appArgument: 'myAppArgument',
},
appleWebApp: {
title: 'Apple Web App',
statusBarStyle: 'black-translucent',
startupImage: [
'/assets/startup/apple-touch-startup-image-768x1004.png',
{
url: '/assets/startup/apple-touch-startup-image-1536x2008.png',
media: '(device-width: 768px) and (device-height: 1024px)',
},
],
},
}
......@@ -22,4 +22,9 @@ export const metadata = {
creator: 'shu',
publisher: 'vercel',
robots: 'index, follow',
formatDetection: {
email: 'no',
address: 'no',
telephone: 'no',
},
}
export default function Page() {
return <p>hello</p>
return 'opengraph-article'
}
export const metadata = {
......
export default function Page() {
return <p>hello</p>
return 'opengraph'
}
export const metadata = {
......
import React from 'react'
import Link from 'next/link'
export default function Page() {
......
export default function page() {
return 'robots'
}
export const metadata = {
robots: {
index: false,
follow: true,
nocache: true,
googleBot: {
index: true,
follow: false,
noimageindex: true,
},
},
}
export default function Page() {
return <p>hello</p>
return 'extra'
}
export const metadata = {
......
export default function Page() {
return <p>hello</p>
return 'title template'
}
export const metadata = {
......
import React from 'react'
import Link from 'next/link'
export default function Page() {
......
export default function page() {
return 'twitter app'
}
export const metadata = {
twitter: {
card: 'app',
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: [
'https://twitter.com/image-100x100.png',
'https://twitter.com/image-200x200.png',
],
app: {
name: 'twitter_app',
id: {
iphone: 'twitter_app://iphone',
ipad: 'twitter_app://ipad',
googleplay: 'twitter_app://googleplay',
},
url: {
iphone: 'https://iphone_url',
ipad: 'https://ipad_url',
},
},
},
}
export default function page() {
return 'twitter summary_large_image'
}
export const metadata = {
twitter: {
card: 'summary_large_image',
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: {
url: 'https://twitter.com/image.png',
alt: 'image-alt',
},
},
}
export default function page() {
return 'twitter summary'
}
export const metadata = {
twitter: {
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: 'https://twitter.com/image.png',
},
}
export default function page() {
return 'twitter player'
}
export const metadata = {
twitter: {
card: 'player',
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: 'https://twitter.com/image.png',
players: {
playerUrl: 'https://twitter.com/player',
streamUrl: 'https://twitter.com/stream',
width: 100,
height: 100,
},
},
}
export default function Page() {
return <p>viewport</p>
return 'viewport'
}
export const metadata = {
......
This diff is collapsed.
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