Skip to content

Commit

Permalink
Revert "Support dynamic routes for social images and icons (#47372)"
Browse files Browse the repository at this point in the history
This reverts commit bbd79ac.
  • Loading branch information
styfle committed Mar 22, 2023
1 parent 1a85bb7 commit 26c84ef
Show file tree
Hide file tree
Showing 16 changed files with 57 additions and 351 deletions.
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.4.0",
"@vercel/og": "0.0.20",
"@webassemblyjs/ast": "1.11.1",
"@webassemblyjs/floating-point-hex-parser": "1.11.1",
"@webassemblyjs/helper-api-error": "1.11.1",
Expand Down
48 changes: 11 additions & 37 deletions packages/next/src/build/webpack/loaders/metadata/discover.ts
Expand Up @@ -80,13 +80,11 @@ 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 @@ -108,46 +106,22 @@ export async function createStaticMetadataFromRoute(
const resolvedMetadataFiles = await enumMetadataFiles(
resolvedDir,
STATIC_METADATA_IMAGES[type].filename,
pageExtensions.concat(STATIC_METADATA_IMAGES[type].extensions),
STATIC_METADATA_IMAGES[type].extensions,
opts
)
resolvedMetadataFiles
.sort((a, b) => a.localeCompare(b))
.forEach((filepath) => {
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
)})`
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
)})`

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

if (!rootLayout) {
Expand Down
Expand Up @@ -42,6 +42,7 @@ const filePath = fileURLToPath(resourceUrl).replace(${JSON.stringify(
)}, '')
const buffer = fs.readFileSync(filePath)
export function GET() {
return new NextResponse(buffer, {
headers: {
Expand All @@ -55,7 +56,7 @@ export const dynamic = 'force-static'
`
}

function getDynamicTextRouteCode(resourcePath: string) {
function getDynamicRouteCode(resourcePath: string) {
return `\
import { NextResponse } from 'next/server'
import handler from ${JSON.stringify(resourcePath)}
Expand All @@ -78,19 +79,6 @@ 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 @@ -99,23 +87,12 @@ const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLo
const { resourcePath } = this
const { pageExtensions } = this.getOptions()

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)
}
const ext = path.extname(resourcePath).slice(1)
const isStatic = !pageExtensions.includes(ext)

const code = isStatic
? getStaticRouteCode(resourcePath)
: getDynamicRouteCode(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\.(edge|node)\.js$/.test(
/[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index.js$/.test(
resource
)

Expand Down
19 changes: 6 additions & 13 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(
pageExtensions.concat(STATIC_METADATA_IMAGES.icon.extensions)
STATIC_METADATA_IMAGES.icon.extensions
)}`
: ''
}`
Expand All @@ -57,7 +57,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.apple.extensions)
STATIC_METADATA_IMAGES.apple.extensions
)}`
: ''
}`
Expand All @@ -66,7 +66,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.opengraph.filename}${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.opengraph.extensions)
STATIC_METADATA_IMAGES.opengraph.extensions
)}`
: ''
}`
Expand All @@ -75,7 +75,7 @@ export function isMetadataRouteFile(
`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${
withExtension
? `\\.${getExtensionRegexString(
pageExtensions.concat(STATIC_METADATA_IMAGES.twitter.extensions)
STATIC_METADATA_IMAGES.twitter.extensions
)}`
: ''
}`
Expand All @@ -85,16 +85,9 @@ 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 {
let page = route.replace(/^\/?app\//, '').replace(/\/route$/, '')
if (page[0] !== '/') page = '/' + page
// 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 (
!page.endsWith('/page') &&
Expand Down
15 changes: 6 additions & 9 deletions packages/next/src/lib/metadata/resolve-metadata.ts
Expand Up @@ -45,13 +45,9 @@ function mergeStaticMetadata(
if (!staticFilesMetadata) return
const { icon, apple, opengraph, twitter } = staticFilesMetadata
if (icon || 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 (!metadata.icons) metadata.icons = { icon: [], apple: [] }
if (icon) metadata.icons.icon.push(...icon)
if (apple) metadata.icons.apple.push(...apple)
}
if (twitter) {
const resolvedTwitter = resolveTwitter(
Expand Down Expand Up @@ -219,8 +215,9 @@ async function collectStaticImagesFiles(
if (!metadata?.[type]) return undefined

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

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

0 comments on commit 26c84ef

Please sign in to comment.