@farm.js/plugin 0.1.69 → 0.1.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,11 @@ import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER, FARM_RSC_NATIVE_STYLESHEETS_PLACEHOLDER, } from "../mobile-client.js";
5
5
  const require_ = createRequire(import.meta.url);
6
+ /**
7
+ * The import query the entry globs static `opengraph-image`/`twitter-image` files with. The
8
+ * plugin's loader answers it with the file's info and bytes (index.ts).
9
+ */
10
+ export const FARM_METADATA_IMAGE_QUERY = "?farm-metadata-image";
6
11
  /** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
7
12
  function generateMCPPluginSource() {
8
13
  const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
@@ -43,6 +48,8 @@ import {
43
48
  getFarmLocaleVaryHeaders,
44
49
  localizeFarmHref,
45
50
  localizeFarmPathname,
51
+ renderFarmLocaleAlternateLinks,
52
+ resolveFarmWebRequestOrigin as resolveFarmI18nRequestOrigin,
46
53
  } from '@farm.js/core/internal/production-runtime';
47
54
  ${catalogs}
48
55
  // createTranslator(locale) and runWithLocale() outside a request.
@@ -53,8 +60,8 @@ _setDefaultFarmI18nRuntime(farmI18nRuntime);
53
60
  * visitor's cookie or Accept-Language picks is redirected to it (307), and a payload request to
54
61
  * that page's payload; a response that depends on those signals varies on them and stays out of
55
62
  * shared caches. API routes keep their URLs, as in core, and so does the image optimizer, which
56
- * this server answers only at its path. llms.txt and sitemap.xml answer at their localized URLs
57
- * too (they match the route path), so they redirect as in core.
63
+ * this server answers only at its path. Core's resolver answers site-level agent files
64
+ * (llms.txt, sitemap.xml, robots.txt) where they are asked for, without a redirect, as in core.
58
65
  */
59
66
  async function runFarmLocalizedRequest(request, payloadRequested, render) {
60
67
  const { pathname } = new URL(request.url);
@@ -95,6 +102,43 @@ function localizeFarmRedirectUrl(url) {
95
102
  : url;
96
103
  }
97
104
 
105
+ /**
106
+ * The page's \`<link rel="alternate" hreflang>\` tags, as core's servers render them: its URL in each
107
+ * locale and x-default, absolute on the route's metadataBase, else on the request's origin (under
108
+ * server.trustProxy). A prerendered page, which no visitor's request drives, uses metadataBase
109
+ * only, as core's background regeneration does.
110
+ */
111
+ function renderFarmI18nAlternateLinks(request, pathname, metadata) {
112
+ const snapshot = getFarmI18nClientSnapshot();
113
+ if (!snapshot) return '';
114
+ return renderFarmLocaleAlternateLinks(pathname, snapshot, {
115
+ metadataBase: metadata.metadataBase,
116
+ origin: isFarmPrerenderRequest(request)
117
+ ? undefined
118
+ : resolveFarmI18nRequestOrigin(request, { trustProxy: ${JSON.stringify(ctx.server?.trustProxy === true)} }),
119
+ });
120
+ }
121
+
122
+ /**
123
+ * A root layout that renders \`<html>\` gets the request's \`lang\` and \`dir\` on it, replacing its
124
+ * own, as core's servers set them on any document. They go on the element the layout returns, so
125
+ * the browser hydrates the attributes the HTML has. FarmLocaleDocument renders a synchronous
126
+ * layout in its place, within the render, as React would.
127
+ */
128
+ function FarmLocaleDocument({ Layout, layoutProps }) {
129
+ const element = Layout(layoutProps);
130
+ return element && typeof element.then === 'function'
131
+ ? element.then(withFarmDocumentLocale)
132
+ : withFarmDocumentLocale(element);
133
+ }
134
+
135
+ function withFarmDocumentLocale(element) {
136
+ const snapshot = getFarmI18nClientSnapshot();
137
+ return snapshot && React.isValidElement(element) && element.type === 'html'
138
+ ? React.cloneElement(element, { lang: snapshot.locale, dir: snapshot.direction })
139
+ : element;
140
+ }
141
+
98
142
  function applyFarmI18nResponse(response, resolution) {
99
143
  const varyHeaders = getFarmLocaleVaryHeaders(farmRouteI18n, resolution);
100
144
  if (!resolution.persist && varyHeaders.length === 0) return response;
@@ -112,6 +156,106 @@ function applyFarmI18nResponse(response, resolution) {
112
156
  }
113
157
  `;
114
158
  }
159
+ /**
160
+ * The config `redirects()`, `rewrites()` and `headers()` in the production server, with core's
161
+ * matchers: sources match the path below the basePath and locale, a redirect keeps the query and
162
+ * an internal destination stays below the basePath (in the request's locale under i18n), and a
163
+ * rewrite keeps the query when its destination names none. A payload request ('<page>.rsc')
164
+ * matches as its page and is sent to the destination's payload. Development gets only the check
165
+ * for a local route, which its dev server asks before a rewrite.
166
+ */
167
+ export function generateConfigRoutesRuntime(ctx, configRoutes, localRouteCheck) {
168
+ if (!configRoutes && !localRouteCheck)
169
+ return "";
170
+ const llms = ctx.llmsTxt?.enabled === true;
171
+ const localRoute = localRouteCheck
172
+ ? `
173
+ // Whether this server answers the URL itself: a page, an API route, the image optimizer, a
174
+ // metadata route file or image, or a generated agent file. A config rewrite applies only when
175
+ // none does, as in core's servers.
176
+ function farmHasLocalRequestRoute(url) {
177
+ const pathname = url.pathname;
178
+ if (matchRoute(pathname)) return true;
179
+ if (matchAPIRouteAtBasePath(apiRouteMap, pathname, farmApiBasePath)) return true;
180
+ if (farmImageHandler && pathname === farmImagePath) return true;
181
+ const routePathname = getFarmRoutePathname(pathname.replace(/\\/+$/, '') || '/');${ctx.appMetadataRoutes === true
182
+ ? `
183
+ if (matchFarmAppMetadataRoute(routePathname)) return true;`
184
+ : ""}${ctx.metadataImages?.static || ctx.metadataImages?.generated
185
+ ? `
186
+ if (matchFarmMetadataImageRequest(routePathname)) return true;`
187
+ : ""}${llms
188
+ ? `
189
+ if (routePathname === '/llms.txt' || (farmLlmsTxtConfig.full && routePathname === '/llms-full.txt')) return true;`
190
+ : ""}${ctx.sitemap?.enabled
191
+ ? `
192
+ if (routePathname === '/sitemap.xml') return true;`
193
+ : ""}${ctx.crawlers?.enabled === true
194
+ ? `
195
+ if (routePathname === '/robots.txt') return true;`
196
+ : ""}
197
+ return false;
198
+ }
199
+ ${ctx.development === true
200
+ ? `// farm dev applies config rewrites ahead of this entry, and asks it first.
201
+ export function __farmHasLocalRequestRoute(href) {
202
+ return farmHasLocalRequestRoute(new URL(href));
203
+ }
204
+ `
205
+ : ""}`
206
+ : "";
207
+ if (!configRoutes)
208
+ return localRoute;
209
+ return `
210
+ import {
211
+ applyConfigResponseHeaders,
212
+ createConfigHeadersMatcher,
213
+ createConfigRedirectMatcher,
214
+ createConfigRewriteMatcher,
215
+ fetchFarmExternalRewrite,
216
+ } from '@farm.js/core/internal/production-runtime';
217
+
218
+ // The config redirects(), rewrites() and headers(), resolved by the build as core resolves them.
219
+ const farmConfigRouteOptions = { i18n: farmRouteI18n, basePath: ${JSON.stringify(ctx.basePath)} };
220
+ const matchFarmConfigRedirect = createConfigRedirectMatcher(${JSON.stringify(configRoutes.redirects)}, farmConfigRouteOptions);
221
+ const matchFarmConfigRewrite = createConfigRewriteMatcher(${JSON.stringify(configRoutes.rewrites)}, farmConfigRouteOptions);
222
+ const matchFarmConfigHeaders = createConfigHeadersMatcher(${JSON.stringify(configRoutes.headers)}, farmConfigRouteOptions);
223
+ ${localRoute}
224
+ /**
225
+ * A config redirect's response, the Request a config rewrite replaces this one with (a payload
226
+ * request's stays one), the proxied response of a rewrite to another origin, or null.
227
+ */
228
+ async function resolveFarmConfigRoute(request, payloadRequested) {
229
+ const url = new URL(request.url);
230
+ const redirect = matchFarmConfigRedirect(url);
231
+ if (redirect) {
232
+ let location = redirect.destination;
233
+ if (payloadRequested) {
234
+ const target = new URL(location, url);
235
+ if (target.origin === url.origin) location = farmPayloadPath(target.pathname) + target.search;
236
+ }
237
+ return new Response('Redirecting to ' + location, {
238
+ status: redirect.statusCode,
239
+ headers: { Location: location },
240
+ });
241
+ }
242
+ const destination = matchFarmConfigRewrite(url);
243
+ if (!destination${localRouteCheck ? " || farmHasLocalRequestRoute(url)" : ""}) return null;
244
+ const rewritten = new Request(destination, request);
245
+ if (destination.origin !== url.origin) return fetchFarmExternalRewrite(rewritten);
246
+ if (payloadRequested) farmPayloadRequests.add(rewritten);
247
+ return rewritten;
248
+ }
249
+
250
+ // A prerendered page is a file the platform serves without this server, so a page a config
251
+ // redirect or rewrite may answer, or that config headers apply to, stays server-rendered.
252
+ function farmConfigRouteMayHandlePath(pathname) {
253
+ const url = new URL(pathname, 'http://farm.invalid');
254
+ return Boolean(matchFarmConfigRedirect(url) || matchFarmConfigRewrite(url)) ||
255
+ matchFarmConfigHeaders(url).length > 0;
256
+ }
257
+ `;
258
+ }
115
259
  /**
116
260
  * Generates the terminal middleware-result handling shared by the RSC entry
117
261
  * and its executable contract tests.
@@ -147,6 +291,15 @@ export function generateRscEntry(ctx) {
147
291
  const hasBasePath = !["", "/"].includes(ctx.basePath.trim());
148
292
  const i18n = ctx.i18n?.enabled === true ? ctx.i18n : undefined;
149
293
  const routesBelowPrefix = hasBasePath || i18n !== undefined;
294
+ // The config redirects(), rewrites() and headers(). This server applies them in production; in
295
+ // development the dev server does, ahead of Vite and the API routes, as core's dev server does.
296
+ const configRoutes = ctx.development === true ? undefined : ctx.configRoutes;
297
+ const configHeaders = (configRoutes?.headers.length ?? 0) > 0;
298
+ // A static or revalidating page gets core's shared Cache-Control in production. farm dev keeps
299
+ // pages out of shared caches, as core's dev server never sends an s-maxage.
300
+ const sharedPageCache = ctx.development !== true;
301
+ const pageCacheArg = sharedPageCache ? ", farmPageCacheControl" : "";
302
+ const localRouteCheck = (ctx.configRoutes?.rewrites.length ?? 0) > 0;
150
303
  // Build the glob pattern for discovering routes (Farm convention: src/app when routesDir unset)
151
304
  const appSegment = ctx.routesDir === undefined ? "app" : ctx.routesDir.trim();
152
305
  const glob = appSegment ? `/${ctx.srcDir}/${appSegment}` : `/${ctx.srcDir}`;
@@ -195,7 +348,6 @@ import {
195
348
  }
196
349
  code += `} from '@vitejs/plugin-rsc/rsc';
197
350
  import {
198
- createFarmDeploymentCookie,
199
351
  createFarmDeploymentMismatchResponse,
200
352
  getFarmDeploymentMismatch,
201
353
  } from '@farm.js/core/deployment';
@@ -205,7 +357,7 @@ import {
205
357
  applyProductionMiddlewareHeaders,
206
358
  createProductionMiddlewareRunner,
207
359
  } from '@farm.js/core/middleware';
208
- import { _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
360
+ import { _withFarmDeploymentCookie, _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
209
361
  ${ctx.mobileClient === "entry" ? "import { _applyFarmMobileShellClient, createFarmNativeTreeResponse, resolveFarmWebRequestOrigin } from '@farm.js/core/internal/production-runtime';\n" : ctx.mobileClient === "inline" ? "import { createFarmNativeTreeResponse, resolveFarmWebRequestOrigin } from '@farm.js/core/internal/production-runtime';\n" : ""}import {
210
362
  getAllowedAPIRouteMethods,
211
363
  invokeAPIRouteEndpoint,
@@ -231,7 +383,14 @@ import {
231
383
  renderMetadataHead,
232
384
  resolveMetadataTitle,
233
385
  } from '@farm.js/core/internal/production-runtime';
234
-
386
+ ${sharedPageCache
387
+ ? `import {
388
+ _getRequestReadCount,
389
+ _hasPrivateFarmRequestHeaders,
390
+ resolveRouteSharedCacheControl,
391
+ } from '@farm.js/core/internal/production-runtime';
392
+ ${i18n ? "import { getLocaleSource } from '@farm.js/core/i18n/server';\n" : ""}`
393
+ : ""}
235
394
  import {
236
395
  FARM_MARKDOWN_CONTENT_TYPE,
237
396
  applyMarkdownNegotiationHeaders,
@@ -301,18 +460,48 @@ function getFarmRoutePathname(pathname) {
301
460
  : stripFarmBasePath(pathname, farmRouteI18n.basePath);
302
461
  }
303
462
  ${i18n ? generateI18nRuntime(ctx, i18n) : ""}`;
463
+ // sitemap.ts, robots.ts, llms.ts and llms-full.ts route files, served as core serves them. An
464
+ // llms.ts receives the pages and defaults the generated llms.txt would list.
465
+ const servesAppMetadataRoutes = ctx.appMetadataRoutes === true;
466
+ const buildsLlmsTxt = ctx.llmsTxt?.enabled === true || servesAppMetadataRoutes;
304
467
  // The generated agent files list the app's static pages.
305
- const listsAgentPages = ctx.llmsTxt?.enabled === true || ctx.sitemap?.enabled === true;
468
+ const listsAgentPages = ctx.llmsTxt?.enabled === true || ctx.sitemap?.enabled === true || servesAppMetadataRoutes;
469
+ // agent.crawlers: a generated robots.txt, as core serves it.
470
+ const servesAgentRobots = ctx.crawlers?.enabled === true;
471
+ // opengraph-image and twitter-image files: static images and generated modules, served and
472
+ // added to the page head as core does.
473
+ const staticMetadataImages = ctx.metadataImages?.static === true;
474
+ const generatedMetadataImages = ctx.metadataImages?.generated === true;
475
+ const servesMetadataImages = staticMetadataImages || generatedMetadataImages;
476
+ if (servesMetadataImages) {
477
+ code += `import { addMetadataImageReference, matchesFarmIfNoneMatch } from '@farm.js/core/internal/production-runtime';
478
+ `;
479
+ }
480
+ if (generatedMetadataImages) {
481
+ // Loads @vercel/og only when a generated image renders, as in core's servers.
482
+ code += `import { createFarmSearchParams } from '@farm.js/core/internal/production-runtime';
483
+ import { createFarmMetadataImageResponse } from '@farm.js/core/internal/metadata-image-runtime';
484
+ `;
485
+ }
486
+ if (listsAgentPages || servesAgentRobots) {
487
+ code += `import { createFarmMetadataRouteResponse } from '@farm.js/core/internal/production-runtime';
488
+ `;
489
+ }
490
+ if (servesAgentRobots) {
491
+ code += `import { createFarmAgentRobots } from '@farm.js/core/internal/production-runtime';
492
+
493
+ const farmAgentCrawlers = ${JSON.stringify(ctx.crawlers)};
494
+ `;
495
+ }
306
496
  if (listsAgentPages) {
307
497
  code += `import {
308
- createFarmMetadataRouteResponse,
309
498
  farmPathGuardCoversPage,
310
499
  isFarmPageNoIndex,
311
500
  resolveFarmAgentOrigin,
312
501
  } from '@farm.js/core/internal/production-runtime';
313
502
  `;
314
503
  }
315
- if (ctx.llmsTxt?.enabled) {
504
+ if (buildsLlmsTxt) {
316
505
  code += `import {
317
506
  collectFarmLlmsTxtPages,
318
507
  createFarmDefaultLlmsTxt,
@@ -322,7 +511,7 @@ ${i18n ? generateI18nRuntime(ctx, i18n) : ""}`;
322
511
  } from '@farm.js/core/internal/production-runtime';
323
512
  import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
324
513
 
325
- const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
514
+ const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt ?? { enabled: false, include: [], exclude: [], full: false })};
326
515
  const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
327
516
  `;
328
517
  }
@@ -404,19 +593,28 @@ function debug(...args) {
404
593
  ${debugLog}
405
594
  }
406
595
 
407
- function applyActionResponseHeaders(headers, request) {
596
+ /**
597
+ * Store the deployment ID in the deployment cookie on a page document a browser loads, so a form
598
+ * posted from it before JavaScript runs names its deployment. Core's _withFarmDeploymentCookie
599
+ * decides, as on its production server: only a GET page response that names this deployment and
600
+ * stays out of shared caches carries it, and a request naming another deployment keeps its cookie.
601
+ * A Flight payload is fetched by the client router, which names its deployment in a header, so it
602
+ * never carries the cookie.
603
+ */
604
+ function withFarmDeploymentCookie(request, response) {
605
+ if ((request.headers.get('accept') || '').includes('text/x-component')) return response;
606
+ return _withFarmDeploymentCookie(request, response, farmDeploymentId, ${JSON.stringify(ctx.basePath)});
607
+ }
608
+
609
+ function applyActionResponseHeaders(headers, request, pageCacheControl) {
408
610
  // The same page URL serves HTML or Flight depending on Accept.
409
611
  const vary = (headers.get('vary') || '').split(',').map(value => value.trim().toLowerCase());
410
612
  if (!vary.includes('*') && !vary.includes('accept')) headers.append('vary', 'Accept');
613
+ // handler() sets the deployment cookie once the response's cache policy is final.
411
614
  headers.set('x-farm-deployment-id', farmDeploymentId);
412
- const accept = request.headers.get('accept') || '';
413
- if (request.method === 'GET' && !accept.includes('text/x-component')) {
414
- headers.append('set-cookie', createFarmDeploymentCookie(
415
- farmDeploymentId,
416
- ${JSON.stringify(ctx.basePath)},
417
- new URL(request.url).protocol === 'https:',
418
- ));
419
- }
615
+ // A static or revalidating page's own policy (getFarmPageCacheControl) wins over a Cache-Control
616
+ // middleware set, as a page's own headers do in core's server.
617
+ if (pageCacheControl) headers.set('cache-control', pageCacheControl);
420
618
  if (${ctx.actionsEnabled ? "true" : "false"} && request.method === 'POST') {
421
619
  headers.set('cache-control', 'no-store');
422
620
  headers.set('x-content-type-options', 'nosniff');
@@ -440,7 +638,15 @@ const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.so
440
638
  : [
441
639
  `${root.sourceGlob}/{farm.route,farm.routes,routes}.{tsx,jsx,ts,js}`,
442
640
  `${root.glob}/{farm.route,farm.routes,routes}.{tsx,jsx,ts,js}`,
443
- ])}, { eager: true });`)
641
+ ])}, { eager: true });${servesAppMetadataRoutes
642
+ ? `\nconst appMetadataRoutes${index} = ${uiRouteGlob(`${root.glob}/**/{sitemap,robots,manifest,llms,llms-full}.{ts,js}`)};`
643
+ : ""}${generatedMetadataImages
644
+ ? `\nconst metadataImageModules${index} = ${uiRouteGlob(`${root.glob}/**/{opengraph-image,twitter-image}.{tsx,jsx,ts,js}`)};`
645
+ : ""}${staticMetadataImages
646
+ ? // Each file's dimensions, alt text, hash and bytes, read by the plugin's loader as core's
647
+ // router reads them (and inlined by a build, as core's build inlines them).
648
+ `\nconst metadataImageFiles${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/{opengraph-image,twitter-image}.{png,jpg,jpeg,gif,webp}`)}, { query: ${JSON.stringify(FARM_METADATA_IMAGE_QUERY)}, import: 'default', eager: true });`
649
+ : ""}`)
444
650
  .join("\n")}
445
651
 
446
652
  function mergeRouteModules(sources) {
@@ -860,7 +1066,37 @@ function matchFarmPagePath(normalized) {
860
1066
  // Each page's parsed rendering directive and whether its source reads request state, baked by
861
1067
  // the build because module exports cannot tell.
862
1068
  const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives ?? {})};
863
-
1069
+ ${sharedPageCache
1070
+ ? `
1071
+ /**
1072
+ * The Cache-Control of a page a shared cache may store (\`revalidate\`, or a static page this server
1073
+ * renders), as core's production server decides it: core's policy for the route, or
1074
+ * \`private, no-store\` when this render is one visitor's (a cookie other than the deployment
1075
+ * cookie, \`Authorization\`, middleware request data, or a request read since \`readsBefore\`).
1076
+ * Null for any other page, which keeps the default. Decided before the page streams, so its HTML
1077
+ * and its Flight payload get the same policy; middleware that let the request through makes it
1078
+ * private afterwards, as in core.
1079
+ */
1080
+ function getFarmPageCacheControl(request, matched, readsBefore, middlewareData, middlewareContext) {
1081
+ const shared = resolveRouteSharedCacheControl(
1082
+ mergeRouteRenderingDirectiveConfig(farmPageRenderingDirectives[matched.pattern], matched.module),
1083
+ );
1084
+ if (!shared) return null;
1085
+ const method = request.method.toUpperCase();
1086
+ const perRequest =
1087
+ (method !== 'GET' && method !== 'HEAD') ||
1088
+ _hasPrivateFarmRequestHeaders(request${i18n
1089
+ ? `, getLocaleSource() === 'url'
1090
+ ? { name: farmRouteI18n.cookie.name, locales: farmRouteI18n.locales }
1091
+ : undefined`
1092
+ : ""}) ||
1093
+ middlewareData.size > 0 ||
1094
+ middlewareContext.size > 0 ||
1095
+ _getRequestReadCount(request) !== readsBefore;
1096
+ return perRequest ? 'private, no-store' : shared;
1097
+ }
1098
+ `
1099
+ : ""}
864
1100
  /**
865
1101
  * The URL paths the build prerenders, by core's SSG rules: a page asks to be static
866
1102
  * (dynamic = "force-static", generateStaticParams, "use ssg"), does not read request
@@ -935,7 +1171,7 @@ async function collectFarmStaticPages() {
935
1171
  : "paths.add(pagePath);"}
936
1172
  }
937
1173
  }
938
- return [...paths];
1174
+ return [...paths]${configRoutes ? ".filter((path) => !farmConfigRouteMayHandlePath(path))" : ""};
939
1175
  }
940
1176
  ${i18n
941
1177
  ? `/**
@@ -1052,11 +1288,15 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
1052
1288
  */
1053
1289
  async function handleFarmRequest(request, context) {
1054
1290
  const farmCacheGuard = { guarded: false };
1055
- const response = await resolveFarmRequest(farmCacheGuard, request, context);
1291
+ const response = await resolveFarmRequest(farmCacheGuard, request, context);${configHeaders
1292
+ ? `
1293
+ // Tells handler(), whose config headers() must not make this response shareable again.
1294
+ if (farmCacheGuard.guarded) context?.onGuardedResponse?.();`
1295
+ : ""}
1056
1296
  return farmCacheGuard.guarded ? _withFarmGuardedResponseCache(response) : response;
1057
1297
  }
1058
1298
 
1059
- async function resolveFarmRequest(farmCacheGuard, request, context) {
1299
+ async function resolveFarmRequest(farmCacheGuard, request, context${configRoutes ? ", farmConfigRewritten = false" : ""}) {
1060
1300
  let url = new URL(request.url);
1061
1301
  const isFarmPayloadRequest = farmPayloadRequests.has(request);
1062
1302
  let matchedPage = null;
@@ -1065,7 +1305,22 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1065
1305
  let errorHeaders = new Headers();
1066
1306
  try {
1067
1307
  debug('Handling request:', request.method, url.pathname);
1068
-
1308
+ ${configRoutes
1309
+ ? `
1310
+ // Config redirects() answer before any route or middleware, and a config rewrite applies when
1311
+ // no route of this server answers the URL, once: its destination runs through middleware and
1312
+ // routing again, as in core's servers.
1313
+ if (!farmConfigRewritten) {
1314
+ const configRoute = await resolveFarmConfigRoute(request, isFarmPayloadRequest);
1315
+ if (configRoute instanceof Response) return configRoute;
1316
+ if (configRoute) {
1317
+ return await _runWithCurrentRequest(configRoute, () =>
1318
+ resolveFarmRequest(farmCacheGuard, configRoute, context, true)
1319
+ );
1320
+ }
1321
+ }
1322
+ `
1323
+ : ""}
1069
1324
  const deploymentMismatch = getFarmDeploymentMismatch(request, farmDeploymentId);
1070
1325
  if (deploymentMismatch) {
1071
1326
  return createFarmDeploymentMismatchResponse(deploymentMismatch);
@@ -1131,7 +1386,18 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1131
1386
  if (apiResponse) {
1132
1387
  return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
1133
1388
  }
1134
- ${ctx.llmsTxt?.enabled
1389
+ ${servesMetadataImages
1390
+ ? `// opengraph-image and twitter-image: answered after middleware, as in core's servers.
1391
+ const metadataImageResponse = await handleFarmMetadataImageRequest(request);
1392
+ if (metadataImageResponse) return applyProductionMiddlewareHeaders(metadataImageResponse, middlewareHeaders);
1393
+ `
1394
+ : ""}${servesAppMetadataRoutes
1395
+ ? `// sitemap.ts, robots.ts, manifest.ts, llms.ts and llms-full.ts: answered after middleware, as
1396
+ // in core's servers, and before the generated files they replace.
1397
+ const appMetadataResponse = await handleFarmAppMetadataRoute(request, context);
1398
+ if (appMetadataResponse) return applyProductionMiddlewareHeaders(appMetadataResponse, middlewareHeaders);
1399
+ `
1400
+ : ""}${ctx.llmsTxt?.enabled
1135
1401
  ? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
1136
1402
  const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
1137
1403
  if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
@@ -1141,6 +1407,12 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1141
1407
  if (getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/') === '/sitemap.xml') {
1142
1408
  return applyProductionMiddlewareHeaders(createFarmAgentSitemapResponse(request), middlewareHeaders);
1143
1409
  }
1410
+ `
1411
+ : ""}${servesAgentRobots
1412
+ ? `// agent.crawlers: answered after middleware, as in core's servers.
1413
+ if (getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/') === '/robots.txt') {
1414
+ return applyProductionMiddlewareHeaders(createFarmAgentRobotsResponse(request), middlewareHeaders);
1415
+ }
1144
1416
  `
1145
1417
  : ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
1146
1418
  return applyProductionMiddlewareHeaders(new Response(
@@ -1304,6 +1576,10 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1304
1576
  }
1305
1577
  `;
1306
1578
  }
1579
+ // The nearest manifest.ts and metadata images join the route's metadata, as in core's servers.
1580
+ const routeMetadata = servesAppMetadataRoutes || servesMetadataImages
1581
+ ? "addFarmMetadataFileReferences(await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps), url.pathname)"
1582
+ : "await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps)";
1307
1583
  // Route matching and rendering
1308
1584
  code += `
1309
1585
  // Match the URL to a page component
@@ -1342,21 +1618,27 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1342
1618
  // every non-RSC environment produces (see core's search-params.ts).
1343
1619
  const searchParams = searchParamsToObject(url.searchParams);
1344
1620
 
1345
- // Page props passed to components (includes middleware shared data)
1621
+ ${sharedPageCache
1622
+ ? `// A request read from here on (metadata, the page, its layouts) makes the render one visitor's,
1623
+ // as in core's server; reads in middleware do not count.
1624
+ const farmReadsBeforeRender = _getRequestReadCount(request);
1625
+ `
1626
+ : ""}// Page props passed to components (includes middleware shared data)
1346
1627
  const pageProps = { params, searchParams, middlewareData };
1347
1628
  ${ctx.markdown?.enabled
1348
1629
  ? `// The head advertises the page's Markdown mirror as the Link header does, as in core's servers.
1349
1630
  const metadata = addMetadataMarkdownAlternate(
1350
- await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps),
1631
+ ${routeMetadata},
1351
1632
  getFarmMarkdownAlternatePath(farmMarkdownConfig, url.pathname, { routePathname: getFarmRoutePathname }),
1352
1633
  );`
1353
- : "const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);"}
1634
+ : `const metadata = ${routeMetadata};`}
1354
1635
  const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
1355
- // Injected into <head> by the SSR entry; React renders only the charset.
1636
+ // Injected into <head> by the SSR entry (React renders only the charset), and swapped in by the
1637
+ // browser entry on client navigation.
1356
1638
  const metadataHead =
1357
1639
  (renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
1358
1640
  renderedHead.viewport +
1359
- renderedHead.tags;
1641
+ renderedHead.tags${i18n ? " + renderFarmI18nAlternateLinks(request, url.pathname, metadata)" : ""};
1360
1642
  const metadataTitle = resolveMetadataTitle(metadata.title);
1361
1643
 
1362
1644
  debug('Rendering page:', pattern, 'with props:', pageProps);
@@ -1403,9 +1685,20 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1403
1685
  const Layout = LayoutModules[index].default;
1404
1686
  const layoutProps = { params: pageProps.params, children: layoutContent };
1405
1687
  if (Layout.constructor.name === 'AsyncFunction') {
1406
- layoutContent = await Layout(layoutProps);
1688
+ layoutContent = await Layout(layoutProps);${i18n
1689
+ ? `
1690
+ if (index === 0 && farmDocumentLayoutModules.has(LayoutModules[0])) {
1691
+ layoutContent = withFarmDocumentLocale(layoutContent);
1692
+ }`
1693
+ : ""}
1407
1694
  } else {
1408
- layoutContent = h(Layout, layoutProps);
1695
+ layoutContent = ${i18n
1696
+ ? `index === 0 &&
1697
+ farmDocumentLayoutModules.has(LayoutModules[0]) &&
1698
+ Layout.$$typeof !== Symbol.for('react.client.reference')
1699
+ ? h(FarmLocaleDocument, { Layout, layoutProps })
1700
+ : `
1701
+ : ""}h(Layout, layoutProps);
1409
1702
  }
1410
1703
  }
1411
1704
 
@@ -1441,10 +1734,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1441
1734
  ),
1442
1735
  rootContent: rootInner,
1443
1736
  metadataHead,
1444
- metadata: {
1445
- title: metadataTitle,
1446
- description: typeof metadata.description === 'string' ? metadata.description : undefined,
1447
- },
1737
+ metadata: { title: metadataTitle },
1448
1738
  ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1449
1739
  // Include action results in payload if actions are enabled
1450
1740
  if (ctx.actionsEnabled) {
@@ -1457,7 +1747,16 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1457
1747
  // Check if this is a client-side navigation request
1458
1748
  // Client sends Accept: text/x-component header for RSC requests
1459
1749
  const acceptHeader = request.headers.get('accept') || '';
1460
-
1750
+ ${sharedPageCache
1751
+ ? `const farmPageCacheControl = getFarmPageCacheControl(
1752
+ request,
1753
+ matched,
1754
+ farmReadsBeforeRender,
1755
+ middlewareResult.data,
1756
+ middlewareContext,
1757
+ );
1758
+ `
1759
+ : ""}
1461
1760
  if (renderToReadableStream) {
1462
1761
  // Full RSC mode with streaming
1463
1762
  debug('Using RSC streaming mode');
@@ -1469,7 +1768,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1469
1768
  // Merge middleware headers with response headers
1470
1769
  const responseHeaders = new Headers(middlewareHeaders);
1471
1770
  responseHeaders.set('content-type', 'text/x-component');
1472
- applyActionResponseHeaders(responseHeaders, request);
1771
+ applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
1473
1772
  return new Response(rscStream, { headers: responseHeaders });
1474
1773
  }
1475
1774
 
@@ -1489,7 +1788,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1489
1788
  // Merge middleware headers with response headers
1490
1789
  const responseHeaders = new Headers(middlewareHeaders);
1491
1790
  responseHeaders.set('content-type', 'text/html');
1492
- applyActionResponseHeaders(responseHeaders, request);
1791
+ applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
1493
1792
  return new Response(html, { headers: responseHeaders });
1494
1793
  }
1495
1794
  }
@@ -1515,7 +1814,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1515
1814
  // Merge middleware headers with response headers
1516
1815
  const responseHeaders = new Headers(middlewareHeaders);
1517
1816
  responseHeaders.set('content-type', 'text/html');
1518
- applyActionResponseHeaders(responseHeaders, request);
1817
+ applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
1519
1818
  return new Response(html, { headers: responseHeaders });
1520
1819
  })
1521
1820
  )
@@ -1611,7 +1910,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1611
1910
  }
1612
1911
  }
1613
1912
 
1614
- ${ctx.llmsTxt?.enabled
1913
+ ${buildsLlmsTxt
1615
1914
  ? `/**
1616
1915
  * agent.llmsTxt, built the same way as core's production server: /llms.txt
1617
1916
  * lists the app's static pages and links to their Markdown mirrors, and
@@ -1631,12 +1930,15 @@ function createFarmLlmsTxtContext(request, context, full) {
1631
1930
  basePath: ${JSON.stringify(ctx.basePath)},
1632
1931
  markdown: farmMarkdownConfig,
1633
1932
  include: farmLlmsTxtConfig.include,
1634
- exclude: farmLlmsTxtConfig.exclude,
1933
+ exclude: farmLlmsTxtConfig.exclude,${ctx.trailingSlash ? "\n // A page without a mirror is linked at the URL it answers at ('/console/about/').\n trailingSlash: true," : ""}
1934
+ // With i18n, in the default locale's URL ('/en/about.md' under routing "prefix-always").
1935
+ i18n: farmRouteI18n,
1635
1936
  },
1636
1937
  );
1637
1938
  const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
1638
1939
  return {
1639
1940
  origin,
1941
+ pages,
1640
1942
  defaults: createFarmDefaultLlmsTxt({
1641
1943
  origin,
1642
1944
  pages,
@@ -1765,7 +2067,8 @@ function createFarmAgentSitemapResponse(request) {
1765
2067
  origin: new URL(request.url).origin,
1766
2068
  config: farmAgentSitemapConfig,
1767
2069
  metadataBase: rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
1768
- basePath: ${JSON.stringify(ctx.basePath)},
2070
+ basePath: ${JSON.stringify(ctx.basePath)},${ctx.trailingSlash ? "\n // Each page at the URL it answers at: '/console/about/'.\n trailingSlash: true," : ""}
2071
+ i18n: farmRouteI18n,
1769
2072
  },
1770
2073
  ),
1771
2074
  {},
@@ -1784,6 +2087,310 @@ function getFarmAgentOrigin(request) {
1784
2087
  );
1785
2088
  }
1786
2089
 
2090
+ `
2091
+ : ""}${servesAgentRobots
2092
+ ? `/**
2093
+ * agent.crawlers, built the same way as core's servers build it: rules for AI search and training
2094
+ * crawlers, and a Sitemap line for the app's sitemap.xml below the basePath when the root layout
2095
+ * has a metadataBase (the request's host is not trusted in a file crawlers and CDNs cache).
2096
+ */
2097
+ function createFarmAgentRobotsResponse(request) {
2098
+ const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
2099
+ return createFarmMetadataRouteResponse(
2100
+ 'robots',
2101
+ createFarmAgentRobots({
2102
+ crawlers: farmAgentCrawlers,
2103
+ sitemapPath: ${ctx.sitemap?.enabled
2104
+ ? "'/sitemap.xml'"
2105
+ : servesAppMetadataRoutes
2106
+ ? "farmAppMetadataRoutes.some((route) => route.kind === 'sitemap' && route.segments.length === 0)\n ? '/sitemap.xml'\n : undefined"
2107
+ : "undefined"},
2108
+ metadataBase: rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
2109
+ basePath: ${JSON.stringify(ctx.basePath)},
2110
+ }),
2111
+ {},
2112
+ { method: request.method },
2113
+ );
2114
+ }
2115
+
2116
+ `
2117
+ : ""}${servesAppMetadataRoutes
2118
+ ? `const FARM_APP_METADATA_OUTPUTS = {
2119
+ sitemap: 'sitemap.xml',
2120
+ robots: 'robots.txt',
2121
+ manifest: 'manifest.webmanifest',
2122
+ llms: 'llms.txt',
2123
+ 'llms-full': 'llms-full.txt',
2124
+ };
2125
+
2126
+ // The app's metadata route files, most specific first, as core's router ranks them.
2127
+ const farmAppMetadataRoutes = Object.entries(
2128
+ mergeRouteModules([${routeRoots
2129
+ .map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: appMetadataRoutes${index} }`)
2130
+ .join(", ")}]),
2131
+ )
2132
+ .map(([filePath, module]) => {
2133
+ const fileName = filePath.slice(filePath.lastIndexOf('/') + 1);
2134
+ const kind = fileName.slice(0, fileName.lastIndexOf('.'));
2135
+ return {
2136
+ filePath,
2137
+ module,
2138
+ kind,
2139
+ outputName: FARM_APP_METADATA_OUTPUTS[kind],
2140
+ segments: parseRoutePath(filePath).segments,
2141
+ specificity: getRoutePatternSpecificity(filePath.slice(0, filePath.lastIndexOf('/')) || '/'),
2142
+ };
2143
+ })
2144
+ .sort((left, right) => compareRouteSpecificity(left.specificity, right.specificity));
2145
+
2146
+ /**
2147
+ * A sitemap.ts, robots.ts, manifest.ts, llms.ts or llms-full.ts route file, served as core
2148
+ * serves it: at '<segment>/<file>' on the route path (below the basePath and locale), from its
2149
+ * default export, a value or a function given the request, params, search params and the
2150
+ * segment's path. llms.ts and llms-full.ts also receive the pages and defaults the generated llms.txt would use, and
2151
+ * llms-full.ts the Markdown reader; an llms-full.ts object inlines each page's Markdown.
2152
+ */
2153
+ async function handleFarmAppMetadataRoute(request, context) {
2154
+ const url = new URL(request.url);
2155
+ const matched = matchFarmAppMetadataRoute(
2156
+ getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/'),
2157
+ );
2158
+ if (matched) {
2159
+ const { route, routePath, match } = matched;
2160
+ const method = request.method.toUpperCase();
2161
+ if (method !== 'GET' && method !== 'HEAD') {
2162
+ return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
2163
+ }
2164
+ try {
2165
+ const routeModule = route.module;
2166
+ if (!routeModule || routeModule.default === undefined) {
2167
+ throw new Error('Metadata route module does not export a default value or handler');
2168
+ }
2169
+ const full = route.kind === 'llms-full';
2170
+ const llms = route.kind === 'llms' || full
2171
+ ? createFarmLlmsTxtContext(request, context, full)
2172
+ : undefined;
2173
+ const value = typeof routeModule.default === 'function'
2174
+ ? await routeModule.default({
2175
+ request,
2176
+ params: match.params,
2177
+ searchParams: url.searchParams,
2178
+ path: routePath,
2179
+ ...(llms ? { pages: llms.pages, defaults: llms.defaults } : {}),
2180
+ ...(full ? { markdown: llms.markdown } : {}),
2181
+ })
2182
+ : routeModule.default;
2183
+ const body = full && !(value instanceof Response)
2184
+ ? await renderFarmLlmsFullTxt(value, { origin: llms.origin, readMarkdown: llms.markdown })
2185
+ : value;
2186
+ return createFarmMetadataRouteResponse(route.kind, body, routeModule, { method, request });
2187
+ } catch (error) {
2188
+ console.error('[Farm.js] Metadata route ' + route.filePath + ' failed:', error);
2189
+ return new Response('Internal Server Error', {
2190
+ status: 500,
2191
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
2192
+ });
2193
+ }
2194
+ }
2195
+ return null;
2196
+ }
2197
+
2198
+ /** The route file that answers a route path ('<segment>/<file>'), most specific first, or null. */
2199
+ function matchFarmAppMetadataRoute(pathname) {
2200
+ for (const route of farmAppMetadataRoutes) {
2201
+ const suffix = '/' + route.outputName;
2202
+ if (pathname !== suffix && !pathname.endsWith(suffix)) continue;
2203
+ const routePath = pathname.slice(0, -suffix.length) || '/';
2204
+ const match = matchFarmPageRoute(routePath, route.segments);
2205
+ if (match.matches) return { route, routePath, match };
2206
+ }
2207
+ return null;
2208
+ }
2209
+
2210
+ `
2211
+ : ""}${servesMetadataImages
2212
+ ? `const FARM_METADATA_IMAGE_KINDS = { 'opengraph-image': 'opengraph', 'twitter-image': 'twitter' };
2213
+
2214
+ /** A metadata image route from its file path ('/products/[id]/opengraph-image.png'). */
2215
+ function createFarmMetadataImageRoute(filePath, image) {
2216
+ const directory = filePath.slice(0, filePath.lastIndexOf('/'));
2217
+ const baseName = filePath.slice(directory.length + 1);
2218
+ const fileName = baseName.slice(0, baseName.indexOf('.'));
2219
+ return {
2220
+ ...image,
2221
+ filePath,
2222
+ kind: FARM_METADATA_IMAGE_KINDS[fileName],
2223
+ fileName,
2224
+ segments: parseRoutePath(filePath).segments,
2225
+ specificity: getRoutePatternSpecificity(directory || '/'),
2226
+ };
2227
+ }
2228
+
2229
+ // The app's opengraph-image and twitter-image files, most specific first: generated modules and
2230
+ // static images, whose dimensions, alt text and hash were read as core's router reads them.
2231
+ const farmMetadataImages = [${generatedMetadataImages
2232
+ ? `
2233
+ ...Object.entries(mergeRouteModules([${routeRoots
2234
+ .map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: metadataImageModules${index} }`)
2235
+ .join(", ")}])).map(([filePath, module]) => createFarmMetadataImageRoute(filePath, { sourceType: 'module', module })),`
2236
+ : ""}${staticMetadataImages
2237
+ ? `
2238
+ ...Object.entries(mergeRouteModules([${routeRoots
2239
+ .map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: metadataImageFiles${index} }`)
2240
+ .join(", ")}])).map(([filePath, file]) => createFarmMetadataImageRoute(filePath, { sourceType: 'static', staticInfo: file.info, data: file.data })),`
2241
+ : ""}
2242
+ ].sort((left, right) => compareRouteSpecificity(left.specificity, right.specificity));
2243
+
2244
+ /**
2245
+ * An opengraph-image or twitter-image request, served as core serves it: at '<segment>/<file>' on
2246
+ * the route path (below the basePath and locale), GET and HEAD only. A static image answers with
2247
+ * its bytes, an ETag, and immutable caching when the URL names its hash (the head's
2248
+ * '?v=<hash>'); a generated module renders through core's metadata image response, given the
2249
+ * segment's params, search params and path.
2250
+ */
2251
+ async function handleFarmMetadataImageRequest(request) {
2252
+ const url = new URL(request.url);
2253
+ const matched = matchFarmMetadataImageRequest(
2254
+ getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/'),
2255
+ );
2256
+ if (matched) {
2257
+ const { image, match, pagePath } = matched;
2258
+ const method = request.method.toUpperCase();
2259
+ if (method !== 'GET' && method !== 'HEAD') {
2260
+ return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
2261
+ }
2262
+ if (image.sourceType === 'static') {
2263
+ const etag = '"' + image.staticInfo.hash + '"';
2264
+ const headers = new Headers({
2265
+ 'Content-Type': image.staticInfo.contentType,
2266
+ 'Content-Length': String(image.staticInfo.byteLength),
2267
+ 'Cache-Control': url.searchParams.get('v') === image.staticInfo.hash
2268
+ ? 'public, max-age=31536000, immutable'
2269
+ : 'public, max-age=0, must-revalidate',
2270
+ ETag: etag,
2271
+ 'X-Content-Type-Options': 'nosniff',
2272
+ });
2273
+ if (matchesFarmIfNoneMatch(request.headers.get('if-none-match'), etag)) {
2274
+ return new Response(null, { status: 304, headers });
2275
+ }
2276
+ if (!image.bytes) image.bytes = Uint8Array.from(atob(image.data), (char) => char.charCodeAt(0));
2277
+ return new Response(method === 'HEAD' ? null : image.bytes, { status: 200, headers });
2278
+ }
2279
+ ${generatedMetadataImages
2280
+ ? `try {
2281
+ const imageModule = image.module;
2282
+ if (!imageModule || !imageModule.default) {
2283
+ throw new Error('Metadata image module does not export a default component or handler');
2284
+ }
2285
+ const value = typeof imageModule.default === 'function'
2286
+ ? await imageModule.default({
2287
+ params: match.params,
2288
+ searchParams: createFarmSearchParams(searchParamsToObject(url.searchParams)),
2289
+ path: pagePath,
2290
+ })
2291
+ : imageModule.default;
2292
+ return await createFarmMetadataImageResponse(value, imageModule, {
2293
+ method,
2294
+ ifNoneMatch: request.headers.get('if-none-match'),
2295
+ });
2296
+ } catch (error) {
2297
+ console.error('[Farm.js] Metadata image ' + image.filePath + ' failed:', error);
2298
+ return new Response('Internal Server Error', {
2299
+ status: 500,
2300
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
2301
+ });
2302
+ }`
2303
+ : ""}
2304
+ }
2305
+ return null;
2306
+ }
2307
+
2308
+ /** The image that answers a route path ('<segment>/opengraph-image'), most specific first, or null. */
2309
+ function matchFarmMetadataImageRequest(pathname) {
2310
+ const fileName = ['opengraph-image', 'twitter-image'].find(
2311
+ (candidate) => pathname === '/' + candidate || pathname.endsWith('/' + candidate),
2312
+ );
2313
+ if (!fileName) return null;
2314
+ const pagePath = pathname.slice(0, -fileName.length - 1) || '/';
2315
+ for (const image of farmMetadataImages) {
2316
+ if (image.fileName !== fileName) continue;
2317
+ const match = matchFarmPageRoute(pagePath, image.segments);
2318
+ if (match.matches) return { image, match, pagePath };
2319
+ }
2320
+ return null;
2321
+ }
2322
+
2323
+ `
2324
+ : ""}${servesAppMetadataRoutes || servesMetadataImages
2325
+ ? `/**
2326
+ * The nearest file of a kind for a route path, as core's servers pick it for the head: the deepest
2327
+ * segment whose path prefixes the route path, with that prefix's params.
2328
+ */
2329
+ function findFarmNearestMetadataFile(files, routePathname) {
2330
+ const segments = routePathname.split('/').filter(Boolean);
2331
+ let nearest = null;
2332
+ for (const file of files) {
2333
+ const depth = file.segments.length;
2334
+ if (depth > segments.length) continue;
2335
+ const routePath = depth === 0 ? '/' : '/' + segments.slice(0, depth).join('/');
2336
+ if (!matchFarmPageRoute(routePath, file.segments).matches) continue;
2337
+ if (!nearest || depth > nearest.file.segments.length) nearest = { file, routePath };
2338
+ }
2339
+ return nearest;
2340
+ }
2341
+
2342
+ /** A metadata file's URL in the head: below its segment, in the request's locale and basePath. */
2343
+ function farmMetadataFileHref(routePath, file) {
2344
+ const href = (routePath === '/' ? '' : routePath) + '/' + file;${i18n
2345
+ ? `
2346
+ const snapshot = getFarmI18nClientSnapshot();
2347
+ const localized = snapshot ? localizeFarmHref(href, snapshot.locale, snapshot) : href;`
2348
+ : `
2349
+ const localized = href;`}
2350
+ return ${hasBasePath ? `applyFarmBasePath(localized, ${JSON.stringify(ctx.basePath)})` : "localized"};
2351
+ }
2352
+
2353
+ /**
2354
+ * The route's metadata with the nearest manifest.ts as its manifest and the nearest
2355
+ * opengraph-image and twitter-image as Open Graph and Twitter images, unless the metadata sets
2356
+ * them, as core's servers add them.
2357
+ */
2358
+ function addFarmMetadataFileReferences(metadata, pathname) {
2359
+ const routePathname = getFarmRoutePathname(pathname.replace(/\\/+$/, '') || '/');${servesAppMetadataRoutes
2360
+ ? `
2361
+ if (!metadata.manifest) {
2362
+ const manifest = findFarmNearestMetadataFile(
2363
+ farmAppMetadataRoutes.filter((route) => route.kind === 'manifest'),
2364
+ routePathname,
2365
+ );
2366
+ if (manifest) {
2367
+ metadata = { ...metadata, manifest: farmMetadataFileHref(manifest.routePath, 'manifest.webmanifest') };
2368
+ }
2369
+ }`
2370
+ : ""}${servesMetadataImages
2371
+ ? `
2372
+ for (const kind of ['opengraph', 'twitter']) {
2373
+ const nearest = findFarmNearestMetadataFile(
2374
+ farmMetadataImages.filter((image) => image.kind === kind),
2375
+ routePathname,
2376
+ );
2377
+ if (!nearest) continue;
2378
+ const image = nearest.file;
2379
+ const info = image.sourceType === 'static' ? image.staticInfo : image.module;
2380
+ const version = image.sourceType === 'static' ? '?v=' + image.staticInfo.hash : '';
2381
+ metadata = addMetadataImageReference(metadata, {
2382
+ kind,
2383
+ href: farmMetadataFileHref(nearest.routePath, image.fileName + version),
2384
+ width: info?.width ?? info?.size?.width,
2385
+ height: info?.height ?? info?.size?.height,
2386
+ alt: info?.alt,
2387
+ contentType: info?.contentType,
2388
+ });
2389
+ }`
2390
+ : ""}
2391
+ return metadata;
2392
+ }
2393
+
1787
2394
  `
1788
2395
  : ""}/**
1789
2396
  * Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
@@ -1846,7 +2453,7 @@ function toFarmPayloadRequest(request) {
1846
2453
  farmPayloadRequests.add(payloadRequest);
1847
2454
  return payloadRequest;
1848
2455
  }
1849
-
2456
+ ${generateConfigRoutesRuntime(ctx, configRoutes, localRouteCheck)}
1850
2457
  // The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
1851
2458
  // route that lists the static pages, and each prerendered page queues its payload, both through
1852
2459
  // Nitro's x-nitro-prerender response header. Production servers never answer either.
@@ -1910,8 +2517,30 @@ ${ctx.mobileClient
1910
2517
  });
1911
2518
  }
1912
2519
  `
1913
- : ""} const pageRequest = toFarmPayloadRequest(request);
1914
- const response = await handleFarmRequestWithRuntime(pageRequest, context${i18n ? ", pageRequest !== request" : ""});
2520
+ : ""} const pageRequest = toFarmPayloadRequest(request);${configHeaders
2521
+ ? `
2522
+ // Config headers() apply to whatever answers the URL as requested (a payload's page), redirects
2523
+ // included, after middleware let it through, so a guarded response stays private.
2524
+ const farmConfigHeaders = matchFarmConfigHeaders(new URL(pageRequest.url));
2525
+ let farmGuardedResponse = false;
2526
+ if (farmConfigHeaders.length > 0) {
2527
+ const adapterContext = context;
2528
+ context = {
2529
+ ...adapterContext,
2530
+ onGuardedResponse() {
2531
+ farmGuardedResponse = true;
2532
+ adapterContext?.onGuardedResponse?.();
2533
+ },
2534
+ };
2535
+ }`
2536
+ : ""}
2537
+ ${configHeaders ? "let" : "const"} response = await handleFarmRequestWithRuntime(pageRequest, context${i18n ? ", pageRequest !== request" : ""});${configHeaders
2538
+ ? `
2539
+ if (farmConfigHeaders.length > 0) {
2540
+ response = applyConfigResponseHeaders(response, farmConfigHeaders);
2541
+ if (farmGuardedResponse) response = _withFarmGuardedResponseCache(response);
2542
+ }`
2543
+ : ""}
1915
2544
  if (
1916
2545
  prerendering &&
1917
2546
  pageRequest === request &&
@@ -1922,7 +2551,9 @@ ${ctx.mobileClient
1922
2551
  headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
1923
2552
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
1924
2553
  }
1925
- return ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
2554
+ const finalResponse = ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
2555
+ // A prerendered page is a file served to every visitor, so it never sets the cookie.
2556
+ return prerendering ? finalResponse : withFarmDeploymentCookie(pageRequest, finalResponse);
1926
2557
  }
1927
2558
  ${ctx.mobileClient === "entry"
1928
2559
  ? `