Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dynamic routes for social images and icons #47425

Merged
merged 4 commits into from Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -95,7 +95,7 @@
"@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.1",
"@vercel/fetch": "6.1.1",
"@vercel/og": "0.0.20",
"@vercel/og": "0.4.1",
"@webassemblyjs/ast": "1.11.1",
"@webassemblyjs/floating-point-hex-parser": "1.11.1",
"@webassemblyjs/helper-api-error": "1.11.1",
Expand Down
48 changes: 37 additions & 11 deletions packages/next/src/build/webpack/loaders/metadata/discover.ts
Expand Up @@ -80,11 +80,13 @@ export async function createStaticMetadataFromRoute(
resolvePath,
isRootLayer,
loaderContext,
pageExtensions,
}: {
route: string
resolvePath: (pathname: string) => Promise<string>
isRootLayer: boolean
loaderContext: webpack.LoaderContext<any>
pageExtensions: string[]
}
) {
let hasStaticMetadataFiles = false
Expand All @@ -106,22 +108,46 @@ export async function createStaticMetadataFromRoute(
const resolvedMetadataFiles = await enumMetadataFiles(
resolvedDir,
STATIC_METADATA_IMAGES[type].filename,
STATIC_METADATA_IMAGES[type].extensions,
pageExtensions.concat(STATIC_METADATA_IMAGES[type].extensions),
opts
)
resolvedMetadataFiles
.sort((a, b) => a.localeCompare(b))
.forEach((filepath) => {
const imageModule = `() => import(/* webpackMode: "eager" */ ${JSON.stringify(
`next-metadata-image-loader?${stringify({
route,
numericSizes:
type === 'twitter' || type === 'opengraph' ? '1' : undefined,
type,
})}!` +
filepath +
METADATA_RESOURCE_QUERY
)})`
const [filename, ext] = path.basename(filepath).split('.')
const isDynamicResource = pageExtensions.includes(ext)

// imageModule type: () => Promise<ImageMetaInfo>
const imageModule = isDynamicResource
? `(async () => {
let { alt, size, contentType } = await import(/* webpackMode: "lazy" */ ${JSON.stringify(
filepath
)})

const props = {
alt,
type: contentType,
url: ${JSON.stringify(route + '/' + filename)},
}
if (size) {
${
type === 'twitter' || type === 'opengraph'
? 'props.width = size.width; props.height = size.height;'
: 'props.sizes = size.width + "x" + size.height;'
}
}
return props
})`
: `() => import(/* webpackMode: "eager" */ ${JSON.stringify(
`next-metadata-image-loader?${stringify({
route,
numericSizes:
type === 'twitter' || type === 'opengraph' ? '1' : undefined,
type,
})}!` +
filepath +
METADATA_RESOURCE_QUERY
)})`

hasStaticMetadataFiles = true
if (type === 'favicon') {
Expand Down
4 changes: 4 additions & 0 deletions packages/next/src/build/webpack/loaders/next-app-loader.ts
Expand Up @@ -111,6 +111,7 @@ async function createTreeCodeFromPath(
resolvePath,
resolveParallelSegments,
loaderContext,
pageExtensions,
}: {
resolver: (
pathname: string,
Expand All @@ -121,6 +122,7 @@ async function createTreeCodeFromPath(
pathname: string
) => [key: string, segment: string | string[]][]
loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: string[]
}
) {
const splittedPath = pagePath.split(/[\\/]/)
Expand Down Expand Up @@ -161,6 +163,7 @@ async function createTreeCodeFromPath(
resolvePath,
isRootLayer,
loaderContext,
pageExtensions,
})
}
} catch (err: any) {
Expand Down Expand Up @@ -380,6 +383,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
resolvePath: (pathname: string) => resolve(this.rootContext, pathname),
resolveParallelSegments,
loaderContext: this,
pageExtensions,
})

if (!rootLayout) {
Expand Down
Expand Up @@ -42,7 +42,6 @@ const filePath = fileURLToPath(resourceUrl).replace(${JSON.stringify(
)}, '')
const buffer = fs.readFileSync(filePath)


export function GET() {
return new NextResponse(buffer, {
headers: {
Expand All @@ -56,7 +55,7 @@ export const dynamic = 'force-static'
`
}

function getDynamicRouteCode(resourcePath: string) {
function getDynamicTextRouteCode(resourcePath: string) {
return `\
import { NextResponse } from 'next/server'
import handler from ${JSON.stringify(resourcePath)}
Expand All @@ -79,6 +78,19 @@ export async function GET() {
`
}

function getDynamicImageRouteCode(resourcePath: string) {
return `\
import { NextResponse } from 'next/server'
import handler from ${JSON.stringify(resourcePath)}

export async function GET(req, ctx) {
const res = await handler({ params: ctx.params })
res.headers.set('Cache-Control', 'public, max-age=0, must-revalidate')
return res
}
`
}

// `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
Expand All @@ -87,12 +99,23 @@ const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLo
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)
const { name: fileBaseName, ext } = getFilenameAndExtension(resourcePath)
const isDynamic = pageExtensions.includes(ext)

let code = ''
if (isDynamic) {
if (
fileBaseName === 'sitemap' ||
fileBaseName === 'robots' ||
fileBaseName === 'manifest'
) {
code = getDynamicTextRouteCode(resourcePath)
} else {
code = getDynamicImageRouteCode(resourcePath)
}
} else {
code = getStaticRouteCode(resourcePath)
}

return code
}
Expand Down
Expand Up @@ -668,7 +668,7 @@ function getExtractMetadata(params: {
const resource = module.resource
const hasOGImageGeneration =
resource &&
/[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index.js$/.test(
/[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index\.(edge|node)\.js$/.test(
resource
)

Expand Down
19 changes: 13 additions & 6 deletions packages/next/src/lib/metadata/is-metadata-route.ts
Expand Up @@ -48,7 +48,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.icon.extensions
pageExtensions.concat(STATIC_METADATA_IMAGES.icon.extensions)
)}`
: ''
}`
Expand All @@ -57,7 +57,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.apple.extensions
pageExtensions.concat(STATIC_METADATA_IMAGES.apple.extensions)
)}`
: ''
}`
Expand All @@ -66,7 +66,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.opengraph.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.opengraph.extensions
pageExtensions.concat(STATIC_METADATA_IMAGES.opengraph.extensions)
)}`
: ''
}`
Expand All @@ -75,7 +75,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${
withExtension
? `\\.${getExtensionRegexString(
STATIC_METADATA_IMAGES.twitter.extensions
pageExtensions.concat(STATIC_METADATA_IMAGES.twitter.extensions)
)}`
: ''
}`
Expand All @@ -85,9 +85,16 @@ export function isMetadataRouteFile(
return metadataRouteFilesRegex.some((r) => r.test(appDirRelativePath))
}

/*
* Remove the 'app' prefix or '/route' suffix, only check the route name since they're only allowed in root app directory
* e.g.
* /app/robots -> /robots
* app/robots -> /robots
* /robots -> /robots
*/
export function isMetadataRoute(route: string): boolean {
// 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$/, '')
let page = route.replace(/^\/?app\//, '').replace(/\/route$/, '')
if (page[0] !== '/') page = '/' + page

return (
!page.endsWith('/page') &&
Expand Down
15 changes: 9 additions & 6 deletions packages/next/src/lib/metadata/resolve-metadata.ts
Expand Up @@ -45,9 +45,13 @@ function mergeStaticMetadata(
if (!staticFilesMetadata) return
const { icon, apple, opengraph, twitter } = staticFilesMetadata
if (icon || apple) {
if (!metadata.icons) metadata.icons = { icon: [], apple: [] }
if (icon) metadata.icons.icon.push(...icon)
if (apple) metadata.icons.apple.push(...apple)
// if (!metadata.icons)
metadata.icons = {
icon: icon || [],
apple: apple || [],
}
// if (icon) metadata.icons.icon.push(...icon)
// if (apple) metadata.icons.apple.push(...apple)
}
if (twitter) {
const resolvedTwitter = resolveTwitter(
Expand Down Expand Up @@ -215,9 +219,8 @@ async function collectStaticImagesFiles(
if (!metadata?.[type]) return undefined

const iconPromises = metadata[type as 'icon' | 'apple'].map(
// TODO-APP: share the typing between next-metadata-image-loader and here
async (iconResolver: any) =>
interopDefault(await iconResolver()) as MetadataImageModule
async (iconResolver: () => Promise<MetadataImageModule>) =>
interopDefault(await iconResolver())
)
return iconPromises?.length > 0 ? await Promise.all(iconPromises) : undefined
}
Expand Down
52 changes: 29 additions & 23 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.