Commit 36c289ca authored by Janka Uryga's avatar Janka Uryga

do not await params for static metadata images

parent 9941188a
...@@ -230,7 +230,7 @@ impl AppPageLoaderTreeBuilder { ...@@ -230,7 +230,7 @@ impl AppPageLoaderTreeBuilder {
let identifier = magic_identifier::mangle(&format!("{name} #{i}")); let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let inner_module_id = format!("METADATA_{i}"); let inner_module_id = format!("METADATA_{i}");
let helper_import = rcstr!( let helper_import = rcstr!(
"import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'" "import { fillStaticMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'"
); );
if !self.base.imports.contains(&helper_import) { if !self.base.imports.contains(&helper_import) {
...@@ -310,7 +310,7 @@ impl AppPageLoaderTreeBuilder { ...@@ -310,7 +310,7 @@ impl AppPageLoaderTreeBuilder {
let metadata_route = &*get_metadata_route_name(item.clone().into()).await?; let metadata_route = &*get_metadata_route_name(item.clone().into()).await?;
writeln!( writeln!(
self.loader_tree_code, self.loader_tree_code,
"{s} url: fillMetadataSegment({}, await props.params, {}, true) + \ "{s} url: fillStaticMetadataSegment({}, {}) + \
`?${{mod.src.split(\"/\").splice(-1)[0]}}`,", `?${{mod.src.split(\"/\").splice(-1)[0]}}`,",
StringifyJs(&pathname_prefix), StringifyJs(&pathname_prefix),
StringifyJs(metadata_route), StringifyJs(metadata_route),
......
...@@ -52,13 +52,13 @@ async fn dynamic_image_metadata_with_generator_source( ...@@ -52,13 +52,13 @@ async fn dynamic_image_metadata_with_generator_source(
let code = formatdoc! { let code = formatdoc! {
r#" r#"
import {{ {exported_fields_excluding_default} }} from {resource_path} import {{ {exported_fields_excluding_default} }} from {resource_path}
import {{ fillMetadataSegment }} from 'next/dist/lib/metadata/get-metadata-route' import {{ fillDynamicMetadataSegment }} from 'next/dist/lib/metadata/get-metadata-route'
const imageModule = {{ {exported_fields_excluding_default} }} const imageModule = {{ {exported_fields_excluding_default} }}
export default async function (props) {{ export default async function (props) {{
const {{ __metadata_id__: _, ...params }} = await props.params const {{ __metadata_id__: _, ...params }} = await props.params
const imageUrl = fillMetadataSegment({pathname_prefix}, params, {page_segment}, false) const imageUrl = fillDynamicMetadataSegment({pathname_prefix}, {page_segment}, params)
const {{ generateImageMetadata }} = imageModule const {{ generateImageMetadata }} = imageModule
...@@ -127,13 +127,13 @@ async fn dynamic_image_metadata_without_generator_source( ...@@ -127,13 +127,13 @@ async fn dynamic_image_metadata_without_generator_source(
let code = formatdoc! { let code = formatdoc! {
r#" r#"
import {{ {exported_fields_excluding_default} }} from {resource_path} import {{ {exported_fields_excluding_default} }} from {resource_path}
import {{ fillMetadataSegment }} from 'next/dist/lib/metadata/get-metadata-route' import {{ fillDynamicMetadataSegment }} from 'next/dist/lib/metadata/get-metadata-route'
const imageModule = {{ {exported_fields_excluding_default} }} const imageModule = {{ {exported_fields_excluding_default} }}
export default async function (props) {{ export default async function (props) {{
const {{ __metadata_id__: _, ...params }} = await props.params const {{ __metadata_id__: _, ...params }} = await props.params
const imageUrl = fillMetadataSegment({pathname_prefix}, params, {page_segment}, false) const imageUrl = fillDynamicMetadataSegment({pathname_prefix}, {page_segment}, params)
function getImageMetadata(imageMetadata, idParam) {{ function getImageMetadata(imageMetadata, idParam) {{
const data = {{ const data = {{
......
...@@ -81,7 +81,7 @@ import type { ...@@ -81,7 +81,7 @@ import type {
import type { FunctionsConfigManifest, ManifestRoute } from './index' import type { FunctionsConfigManifest, ManifestRoute } from './index'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { parseAppRoute } from '../shared/lib/router/routes/app' import { parseAppRoute } from '../shared/lib/router/routes/app'
import { fillMetadataSegment } from '../lib/metadata/get-metadata-route' import { fillStaticMetadataSegment } from '../lib/metadata/get-metadata-route'
import { STATIC_METADATA_IMAGES } from '../lib/metadata/is-metadata-route' import { STATIC_METADATA_IMAGES } from '../lib/metadata/is-metadata-route'
// Build a set of static metadata image filenames for quick lookup // Build a set of static metadata image filenames for quick lookup
...@@ -111,10 +111,10 @@ function getTreeViewDisplayPath(pagePath: string): string { ...@@ -111,10 +111,10 @@ function getTreeViewDisplayPath(pagePath: string): string {
return pagePath return pagePath
} }
// Transform using fillMetadataSegment with isStatic=true // Transform using fillStaticMetadataSegment
const segment = pagePath.slice(0, lastSlash) const segment = pagePath.slice(0, lastSlash)
const lastSegment = filename const lastSegment = filename
return fillMetadataSegment(segment, {}, lastSegment, true) return fillStaticMetadataSegment(segment, lastSegment)
} }
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
......
...@@ -80,7 +80,7 @@ async function nextMetadataImageLoader( ...@@ -80,7 +80,7 @@ async function nextMetadataImageLoader(
// smaller. // smaller.
resourcePath + '?' + WEBPACK_RESOURCE_QUERIES.metadataImageMeta resourcePath + '?' + WEBPACK_RESOURCE_QUERIES.metadataImageMeta
)} )}
import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route' import { fillDynamicMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
const imageModule = { const imageModule = {
${exportedFieldsExcludingDefault ${exportedFieldsExcludingDefault
...@@ -89,9 +89,9 @@ async function nextMetadataImageLoader( ...@@ -89,9 +89,9 @@ async function nextMetadataImageLoader(
} }
function getImageMetadata(imageMetadata, idParam, resolvedParams) { function getImageMetadata(imageMetadata, idParam, resolvedParams) {
const imageUrl = fillMetadataSegment(${JSON.stringify( const imageUrl = fillDynamicMetadataSegment(${JSON.stringify(
pathnamePrefix pathnamePrefix
)}, resolvedParams, ${JSON.stringify(pageSegment)}, false) )}, ${JSON.stringify(pageSegment)}, resolvedParams)
const data = { const data = {
alt: imageMetadata.alt, alt: imageMetadata.alt,
type: imageMetadata.contentType || 'image/png', type: imageMetadata.contentType || 'image/png',
...@@ -169,13 +169,13 @@ async function nextMetadataImageLoader( ...@@ -169,13 +169,13 @@ async function nextMetadataImageLoader(
} }
return `\ return `\
import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route' import { fillStaticMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
export default async (props) => { export default async (props) => {
const imageData = ${JSON.stringify(imageData)} const imageData = ${JSON.stringify(imageData)}
const imageUrl = fillMetadataSegment(${JSON.stringify( const imageUrl = fillStaticMetadataSegment(${JSON.stringify(
pathnamePrefix pathnamePrefix
)}, await props.params, ${JSON.stringify(pageSegment)}, true) )}, ${JSON.stringify(pageSegment)})
return [{ return [{
...imageData, ...imageData,
......
...@@ -52,39 +52,39 @@ function getMetadataRouteSuffix(page: string) { ...@@ -52,39 +52,39 @@ function getMetadataRouteSuffix(page: string) {
* Fill the dynamic segment in the metadata route * Fill the dynamic segment in the metadata route
* *
* Example: * Example:
* fillMetadataSegment('/a/[slug]', { params: { slug: 'b' } }, 'open-graph', false) -> '/a/b/open-graph' * fillDynamicMetadataSegment('/a/[slug]', 'open-graph', { params: { slug: 'b' } }) -> '/a/b/open-graph'
* */
* When isStatic is true, all dynamic segments are filled with "-" placeholder export function fillDynamicMetadataSegment(
* since static metadata files have consistent responses regardless of params. segment: string,
* Example: lastSegment: string,
* fillMetadataSegment('/a/[slug]', {}, 'icon.png', true) -> '/a/-/icon.png' routeParams: Record<string, string | string[]>
) {
return fillMetadataSegmentImpl(segment, lastSegment, routeParams)
}
/**
* If the route has params, replace them with placeholders, because a static file can't depend on params.
* *
* fillStaticMetadataSegment('/a/[slug]', 'icon.png') -> '/a/-/icon.png'
*/ */
export function fillMetadataSegment( export function fillStaticMetadataSegment(
segment: string,
lastSegment: string
) {
return fillMetadataSegmentImpl(segment, lastSegment, {})
}
function fillMetadataSegmentImpl(
segment: string, segment: string,
params: any,
lastSegment: string, lastSegment: string,
isStatic: boolean routeParams: Record<string, string | string[]>
) { ) {
const pathname = normalizeAppPath(segment) const pathname = normalizeAppPath(segment)
const routeRegex = getNamedRouteRegex(pathname, { const routeRegex = getNamedRouteRegex(pathname, {
prefixRouteKeys: false, prefixRouteKeys: false,
}) })
// For static metadata files, fill all dynamic segments with "-" placeholder const route = interpolateDynamicPath(pathname, routeParams, routeRegex, '-')
const routeParams = isStatic
? Object.keys(routeRegex.groups).reduce(
(acc, key) => {
const { repeat } = routeRegex.groups[key]
// Use array for catch-all segments, string for regular segments
acc[key] = repeat ? ['-'] : '-'
return acc
},
{} as Record<string, string | string[]>
)
: params
const route = interpolateDynamicPath(pathname, routeParams, routeRegex)
const { name, ext } = path.parse(lastSegment) const { name, ext } = path.parse(lastSegment)
const pagePath = path.posix.join(segment, name) const pagePath = path.posix.join(segment, name)
const suffix = getMetadataRouteSuffix(pagePath) const suffix = getMetadataRouteSuffix(pagePath)
......
...@@ -65,7 +65,7 @@ import { ...@@ -65,7 +65,7 @@ import {
isStaticMetadataFile, isStaticMetadataFile,
} from '../../../lib/metadata/is-metadata-route' } from '../../../lib/metadata/is-metadata-route'
import { import {
fillMetadataSegment, fillStaticMetadataSegment,
normalizeMetadataPageToRoute, normalizeMetadataPageToRoute,
} from '../../../lib/metadata/get-metadata-route' } from '../../../lib/metadata/get-metadata-route'
import { JsConfigPathsPlugin } from '../../../build/webpack/plugins/jsconfig-paths-plugin' import { JsConfigPathsPlugin } from '../../../build/webpack/plugins/jsconfig-paths-plugin'
...@@ -687,11 +687,9 @@ async function startWatcher( ...@@ -687,11 +687,9 @@ async function startWatcher(
if (appDir && isStaticMetadataFile(fileName.replace(appDir, ''))) { if (appDir && isStaticMetadataFile(fileName.replace(appDir, ''))) {
const segment = path.posix.dirname(pageName) const segment = path.posix.dirname(pageName)
const lastSegment = path.posix.basename(pageName) const lastSegment = path.posix.basename(pageName)
const normalizedPath = fillMetadataSegment( const normalizedPath = fillStaticMetadataSegment(
segment, segment,
{}, lastSegment
lastSegment,
true
) )
staticMetadataFiles.set(normalizedPath, fileName) staticMetadataFiles.set(normalizedPath, fileName)
} else { } else {
......
...@@ -75,7 +75,8 @@ export function normalizeCdnUrl( ...@@ -75,7 +75,8 @@ export function normalizeCdnUrl(
export function interpolateDynamicPath( export function interpolateDynamicPath(
pathname: string, pathname: string,
params: ParsedUrlQuery, params: ParsedUrlQuery,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined,
defaultParamValue?: string
) { ) {
if (!defaultRouteRegex) return pathname if (!defaultRouteRegex) return pathname
...@@ -95,7 +96,7 @@ export function interpolateDynamicPath( ...@@ -95,7 +96,7 @@ export function interpolateDynamicPath(
} else if (value) { } else if (value) {
paramValue = encodeURIComponent(value) paramValue = encodeURIComponent(value)
} else { } else {
paramValue = '' paramValue = defaultParamValue ?? ''
} }
if (paramValue || optional) { if (paramValue || optional) {
......
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