@farm.js/plugin 0.1.67 → 0.1.69

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.
@@ -1,4 +1,6 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { createRequire } from "node:module";
3
+ import path from "node:path";
2
4
  import { FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER, FARM_RSC_NATIVE_STYLESHEETS_PLACEHOLDER, } from "../mobile-client.js";
3
5
  const require_ = createRequire(import.meta.url);
4
6
  /** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
@@ -6,6 +8,110 @@ function generateMCPPluginSource() {
6
8
  const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
7
9
  return generateNativeMCPPluginSource({ enabled: true });
8
10
  }
11
+ /** Each locale's catalog file, where core's i18n config resolves it (resolveFarmI18nMessagePath). */
12
+ function farmI18nCatalogFiles(i18n) {
13
+ return i18n.locales.map((locale) => i18n.messages.includes("{locale}")
14
+ ? i18n.messages.split("{locale}").join(locale)
15
+ : path.join(i18n.messages, `${locale}.json`));
16
+ }
17
+ /**
18
+ * The request locale of an app with i18n, from core's runtime: each request resolves its locale
19
+ * as in core's servers, so `getLocale()`, `t()` and `format` from `@farm.js/core/i18n/server`
20
+ * work in server components, server actions, route handlers and middleware, and client
21
+ * components read the same locale.
22
+ */
23
+ function generateI18nRuntime(ctx, i18n) {
24
+ const catalogs = ctx.development === true
25
+ ? `// Development reads the catalogs from disk, as core's dev server does. Importing them makes an
26
+ // edited catalog reload this entry; a missing one fails initialize() with core's error.
27
+ ${farmI18nCatalogFiles(i18n)
28
+ .filter((file) => existsSync(file))
29
+ .map((file) => `import ${JSON.stringify(`${file.replace(/\\/g, "/")}?raw`)};`)
30
+ .join("\n")}
31
+ const farmI18nRuntime = createFarmI18nRuntime(farmRouteI18n);
32
+ await farmI18nRuntime.initialize();`
33
+ : `// The catalogs the build read and validated, inlined as core's build inlines them.
34
+ const farmI18nRuntime = createFarmI18nRuntime(farmRouteI18n, ${JSON.stringify(ctx.i18nCatalogs ?? {})});`;
35
+ return `import {
36
+ _runWithFarmI18nRequest,
37
+ _setDefaultFarmI18nRuntime,
38
+ createFarmI18nRuntime,
39
+ getFarmI18nClientSnapshot,
40
+ } from '@farm.js/core/i18n/server';
41
+ import {
42
+ createFarmLocaleCookie,
43
+ getFarmLocaleVaryHeaders,
44
+ localizeFarmHref,
45
+ localizeFarmPathname,
46
+ } from '@farm.js/core/internal/production-runtime';
47
+ ${catalogs}
48
+ // createTranslator(locale) and runWithLocale() outside a request.
49
+ _setDefaultFarmI18nRuntime(farmI18nRuntime);
50
+
51
+ /**
52
+ * Runs a request in its locale, as core's servers do. A page GET whose URL lacks the locale the
53
+ * visitor's cookie or Accept-Language picks is redirected to it (307), and a payload request to
54
+ * that page's payload; a response that depends on those signals varies on them and stays out of
55
+ * 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.
58
+ */
59
+ async function runFarmLocalizedRequest(request, payloadRequested, render) {
60
+ const { pathname } = new URL(request.url);
61
+ const redirect =
62
+ !isFarmAPIPathname(pathname, farmApiBasePath) &&
63
+ !isFarmAPIPathname(pathname) &&
64
+ pathname !== farmImagePath;
65
+ return _runWithFarmI18nRequest(farmI18nRuntime, request, async (resolution) => {
66
+ if (resolution.redirect && (request.method === 'GET' || request.method === 'HEAD')) {
67
+ let location = resolution.redirect;${ctx.trailingSlash
68
+ ? `
69
+ // With trailingSlash a page answers at '/fr/about/': send the visitor there at once rather
70
+ // than through the trailing-slash 308 that would follow (core's renderers redirect twice).
71
+ const localized = new URL(location, request.url);
72
+ if (matchRoute(localized.pathname)) {
73
+ location = normalizeFarmTrailingSlashPathname(localized.pathname, true) + localized.search;
74
+ }`
75
+ : ""}
76
+ if (payloadRequested) {
77
+ const target = new URL(location, request.url);
78
+ location = farmPayloadPath(target.pathname) + target.search;
79
+ }
80
+ return applyFarmI18nResponse(new Response(null, { status: 307, headers: { location } }), resolution);
81
+ }
82
+ return applyFarmI18nResponse(await render(), resolution);
83
+ }, { redirect });
84
+ }
85
+
86
+ /**
87
+ * redirect('/about') from a French page sends /fr/about, below the basePath, as core's servers
88
+ * localize a redirect: pages, server actions and form submissions alike. A URL that is not
89
+ * app-relative stays as written.
90
+ */
91
+ function localizeFarmRedirectUrl(url) {
92
+ const snapshot = getFarmI18nClientSnapshot();
93
+ return snapshot && url.startsWith('/') && !url.startsWith('//')
94
+ ? localizeFarmHref(url, snapshot.locale, snapshot)
95
+ : url;
96
+ }
97
+
98
+ function applyFarmI18nResponse(response, resolution) {
99
+ const varyHeaders = getFarmLocaleVaryHeaders(farmRouteI18n, resolution);
100
+ if (!resolution.persist && varyHeaders.length === 0) return response;
101
+ const headers = new Headers(response.headers);
102
+ if (resolution.persist) {
103
+ headers.append('set-cookie', createFarmLocaleCookie(resolution.locale, farmRouteI18n));
104
+ }
105
+ if (varyHeaders.length > 0) {
106
+ const vary = new Set((headers.get('vary') || '').split(',').map((entry) => entry.trim()).filter(Boolean));
107
+ for (const header of varyHeaders) vary.add(header);
108
+ headers.set('vary', [...vary].join(', '));
109
+ headers.set('cache-control', 'private, no-store');
110
+ }
111
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
112
+ }
113
+ `;
114
+ }
9
115
  /**
10
116
  * Generates the terminal middleware-result handling shared by the RSC entry
11
117
  * and its executable contract tests.
@@ -37,6 +143,10 @@ export function generateRscMiddlewareResultHandling() {
37
143
  * - Either returns the stream directly (for client navigation) or delegates to SSR (for initial page load)
38
144
  */
39
145
  export function generateRscEntry(ctx) {
146
+ // A root-mounted app without i18n matches pages on the path as received, with no extra work.
147
+ const hasBasePath = !["", "/"].includes(ctx.basePath.trim());
148
+ const i18n = ctx.i18n?.enabled === true ? ctx.i18n : undefined;
149
+ const routesBelowPrefix = hasBasePath || i18n !== undefined;
40
150
  // Build the glob pattern for discovering routes (Farm convention: src/app when routesDir unset)
41
151
  const appSegment = ctx.routesDir === undefined ? "app" : ctx.routesDir.trim();
42
152
  const glob = appSegment ? `/${ctx.srcDir}/${appSegment}` : `/${ctx.srcDir}`;
@@ -57,6 +167,10 @@ export function generateRscEntry(ctx) {
57
167
  const mcpConfigImports = (ctx.mcpConfigPaths ?? [])
58
168
  .map((configPath, index) => `import * as FarmMCPConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
59
169
  .join("\n");
170
+ // Imported for their factories, which register what a plugin's server functions use.
171
+ const pluginsConfigImports = (ctx.pluginsConfigPaths ?? [])
172
+ .map((configPath) => `import ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
173
+ .join("\n");
60
174
  const mcpSource = ctx.mcpConfigPaths?.length ? generateMCPPluginSource() : null;
61
175
  const middlewareConfigValues = (ctx.middlewareConfigPaths ?? []).map((_configPath, index) => `(FarmMiddlewareConfigModule${index}.default || FarmMiddlewareConfigModule${index})`);
62
176
  let code = `
@@ -64,6 +178,7 @@ import React from 'react';
64
178
  import ServerErrorFallback from '/.farm/rsc-entries/error-fallback.tsx';
65
179
  ${middlewareConfigImports}
66
180
  ${mcpConfigImports}
181
+ ${pluginsConfigImports}
67
182
  ${mcpSource ? `${mcpSource.importSource}\nimport { mergePluginAPIRoutes } from '@farm.js/core/api/runtime';` : ""}
68
183
  import { registerAPIRouteShape } from '@farm.js/core/api/runtime';
69
184
  import {
@@ -124,8 +239,28 @@ import {
124
239
  createMarkdownMirrorResponse,
125
240
  farmRequestWantsMarkdown,
126
241
  } from '@farm.js/core/markdown';
127
- import { stripFarmBasePath, stripFarmLocaleFromPathname } from '@farm.js/core/internal/production-runtime';
242
+ ${ctx.markdown?.enabled
243
+ ? `import { getFarmMarkdownAlternatePath } from '@farm.js/core/markdown';
244
+ import { addMetadataMarkdownAlternate } from '@farm.js/core/internal/production-runtime';
245
+ `
246
+ : ""}import { stripFarmBasePath, stripFarmLocaleFromPathname } from '@farm.js/core/internal/production-runtime';
247
+ import { resolveFarmTrailingSlashRedirect } from '@farm.js/core/internal/production-runtime';
248
+ ${ctx.trailingSlash
249
+ ? `import { normalizeFarmTrailingSlashPathname, setFarmTrailingSlashPreference } from '@farm.js/core/internal/production-runtime';
250
+
251
+ // trailingSlash: <Link href="/about"> renders /about/, as in core's renderers. Client components
252
+ // render in the SSR environment, which shares this process; the browser entry sets it too.
253
+ setFarmTrailingSlashPreference(true);
254
+ `
255
+ : ""}
256
+ ${hasBasePath
257
+ ? `import { applyFarmBasePath, setFarmBasePath } from '@farm.js/core/internal/production-runtime';
128
258
 
259
+ // <Link href="/about"> renders /console/about, as in core's renderers. Client components render in
260
+ // the SSR environment, which shares this process; the browser entry sets it for hydration.
261
+ setFarmBasePath(${JSON.stringify(ctx.basePath)});
262
+ `
263
+ : ""}
129
264
  ${ctx.images && ctx.images.runtime !== "none"
130
265
  ? `import { createCloudflareImageTransformer, createFarmImageHandler } from '@farm.js/core/image/server';
131
266
  ${ctx.images.runtime === "node"
@@ -157,29 +292,46 @@ const farmRouteI18n = ${JSON.stringify(ctx.i18n ?? { enabled: false, basePath: c
157
292
 
158
293
  /**
159
294
  * A request path without the app's basePath and locale prefix, as core's servers and the
160
- * middleware runner read it: '/console/fr/about' is '/about'. Markdown names a home page
161
- * '<prefix>/index.md' and matches md.expose on it. Pages still match the path as received.
295
+ * middleware runner read it: '/console/fr/about' is '/about'. Pages match it (matchRoute), and
296
+ * Markdown names a home page '<prefix>/index.md' and matches md.expose on it.
162
297
  */
163
298
  function getFarmRoutePathname(pathname) {
164
299
  return farmRouteI18n.enabled
165
300
  ? stripFarmLocaleFromPathname(pathname, farmRouteI18n)
166
301
  : stripFarmBasePath(pathname, farmRouteI18n.basePath);
167
302
  }
303
+ ${i18n ? generateI18nRuntime(ctx, i18n) : ""}`;
304
+ // The generated agent files list the app's static pages.
305
+ const listsAgentPages = ctx.llmsTxt?.enabled === true || ctx.sitemap?.enabled === true;
306
+ if (listsAgentPages) {
307
+ code += `import {
308
+ createFarmMetadataRouteResponse,
309
+ farmPathGuardCoversPage,
310
+ isFarmPageNoIndex,
311
+ resolveFarmAgentOrigin,
312
+ } from '@farm.js/core/internal/production-runtime';
168
313
  `;
314
+ }
169
315
  if (ctx.llmsTxt?.enabled) {
170
316
  code += `import {
171
317
  collectFarmLlmsTxtPages,
172
318
  createFarmDefaultLlmsTxt,
173
319
  createFarmLlmsFullRenderer,
174
320
  createFarmLlmsMarkdownReader,
175
- createFarmMetadataRouteResponse,
176
- farmPathGuardCoversPage,
177
321
  renderFarmLlmsFullTxt,
178
322
  } from '@farm.js/core/internal/production-runtime';
179
323
  import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
180
324
 
181
325
  const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
182
326
  const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
327
+ `;
328
+ }
329
+ if (ctx.sitemap?.enabled) {
330
+ code += `import { createFarmDefaultSitemap } from '@farm.js/core/internal/production-runtime';
331
+
332
+ const farmAgentSitemapConfig = ${JSON.stringify(ctx.sitemap)};
333
+ // Each page file's last change, read by the build (by farm dev when it starts).
334
+ const farmPageLastModified = ${JSON.stringify(ctx.pageLastModified ?? {})};
183
335
  `;
184
336
  }
185
337
  if (ctx.actionsEnabled) {
@@ -527,7 +679,8 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
527
679
  i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
528
680
  server: ${JSON.stringify(ctx.server) ?? "undefined"},
529
681
  apiBasePath: farmApiBasePath,
530
- // matchRoute() reads url.pathname as received, so middleware guards that path too.
682
+ // matchRoute() can select a page by the path as received (a page under app/<basePath>/ or
683
+ // app/[lang]/) as well as by the route path, so middleware guards both.
531
684
  rawPathRouting: true,
532
685
  });
533
686
 
@@ -646,12 +799,48 @@ const pageRoutes = Object.entries(pages)
646
799
  * Simple file-based router
647
800
  * Converts URL pathname to matching page component
648
801
  */
649
- function matchRoute(pathname) {
802
+ ${routesBelowPrefix
803
+ ? `function matchRoute(pathname) {
650
804
  const normalized = pathname.replace(/\\/$/, '') || '/';
651
-
805
+ const routePathname = getFarmRoutePathname(normalized);
806
+ if (routePathname === normalized) return matchFarmPagePath(normalized);
807
+ // Pages answer at their route path, as in core's renderers: app/about/page.tsx at
808
+ // '/console/about' under basePath "/console", and at '/console/fr/about' with an 'fr' locale.
809
+ // A page whose folders spell out the prefix the request carries (app/console/about, or
810
+ // app/[lang]/about for the locale) keeps the URL it had when RSC matched the path as received,
811
+ // and any other page matching only that path still answers there. Middleware runs for both
812
+ // paths (rawPathRouting), so the page that renders keeps its guards.
813
+ const asReceived = matchFarmPagePath(normalized);
814
+ if (asReceived && farmPageSpellsRoutePrefix(asReceived.segments, normalized, routePathname)) {
815
+ return asReceived;
816
+ }
817
+ return matchFarmPagePath(routePathname) ?? asReceived;
818
+ }
819
+
820
+ /**
821
+ * Whether a page matched on the path as received takes the prefix with its own folders: a static
822
+ * folder for each basePath segment, then any folder but a catch-all for the locale. A catch-all
823
+ * or dynamic folder that merely absorbs the basePath ('[...slug]' at the root) does not.
824
+ */
825
+ function farmPageSpellsRoutePrefix(segments, pathname, routePathname) {
826
+ const count = (path) => path.split('/').filter(Boolean).length;
827
+ const prefixLength = count(pathname) - count(routePathname);
828
+ const basePathLength = count(pathname) - count(stripFarmBasePath(pathname, farmRouteI18n.basePath));
829
+ for (let index = 0; index < prefixLength; index++) {
830
+ const segment = segments[index];
831
+ if (!segment || segment.isCatchAll || (index < basePathLength && segment.isDynamic)) return false;
832
+ }
833
+ return true;
834
+ }
835
+ `
836
+ : `function matchRoute(pathname) {
837
+ return matchFarmPagePath(pathname.replace(/\\/$/, '') || '/');
838
+ }
839
+ `}
840
+ function matchFarmPagePath(normalized) {
652
841
  for (const { filePath, module, segments } of pageRoutes) {
653
842
  const match = matchFarmPageRoute(normalized, segments);
654
-
843
+
655
844
  if (match.matches) {
656
845
  debug('Matched route:', filePath, 'for path:', normalized);
657
846
  return {
@@ -659,10 +848,11 @@ function matchRoute(pathname) {
659
848
  pattern: filePath,
660
849
  params: match.params,
661
850
  module,
851
+ segments,
662
852
  };
663
853
  }
664
854
  }
665
-
855
+
666
856
  debug('No route matched for:', normalized);
667
857
  return null;
668
858
  }
@@ -678,8 +868,9 @@ const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives
678
868
  * path any middleware may handle stays server-rendered.
679
869
  */
680
870
  async function collectFarmStaticPages() {
681
- ${ctx.i18n?.enabled
682
- ? `console.info('[Farm.js] Prerendering is off: i18n resolves the locale per request.');
871
+ ${i18n?.routing === "none"
872
+ ? `// As in core's SSG: one URL serves every locale, by the visitor's cookie or Accept-Language.
873
+ console.info('[Farm.js] Prerendering is off: with i18n routing "none" one URL serves every locale.');
683
874
  return [];`
684
875
  : ""}
685
876
  const middlewareRoutes = Object.keys(middlewares)
@@ -716,12 +907,69 @@ async function collectFarmStaticPages() {
716
907
  ) {
717
908
  continue;
718
909
  }
719
- paths.add(pagePath);
910
+ ${i18n
911
+ ? `for (const publicPath of farmLocalizedStaticPaths(pagePath)) {
912
+ // Only where the server would render this page, and no middleware may handle the URL.
913
+ const routePath = getFarmRoutePathname(publicPath);
914
+ if (
915
+ matchRoute(publicPath)?.pattern !== filePath ||
916
+ appMiddlewareMayHandlePath(middlewareRoutes, routePath) ||
917
+ configMiddlewareMayHandlePath(farmConfigMiddleware, routePath) ||
918
+ appMiddlewareMayHandlePath(middlewareRoutes, publicPath) ||
919
+ configMiddlewareMayHandlePath(farmConfigMiddleware, publicPath)
920
+ ) {
921
+ continue;
922
+ }
923
+ paths.add(publicPath);
924
+ }`
925
+ : hasBasePath
926
+ ? `// The platform serves a prerendered file only at the URL it was written for, below the
927
+ // basePath, as core's build writes it. A page nested under app/<basePath>/ already is.
928
+ const publicPath = applyFarmBasePath(pagePath, ${JSON.stringify(ctx.basePath)});
929
+ paths.add(${ctx.trailingSlash
930
+ ? "normalizeFarmTrailingSlashPathname(publicPath, true)"
931
+ : "publicPath.length > 1 ? publicPath.replace(/\\/$/, '') : publicPath"});`
932
+ : ctx.trailingSlash
933
+ ? // With trailingSlash the page's URL is '/about/', which Nitro writes as about/index.html.
934
+ "paths.add(normalizeFarmTrailingSlashPathname(pagePath, true));"
935
+ : "paths.add(pagePath);"}
720
936
  }
721
937
  }
722
938
  return [...paths];
723
939
  }
940
+ ${i18n
941
+ ? `/**
942
+ * The URLs a static page prerenders at with i18n, as core's SSG lists them: the page at each
943
+ * locale's URL below the basePath (localizeFarmPathname). A page whose folders name the locale
944
+ * (app/[lang]/...) listed its URLs itself; one the server redirects to its canonical URL (the
945
+ * default locale's prefix under "prefix-except-default") is left out. A URL without a locale (the
946
+ * default locale's, under "prefix-except-default") answers by the visitor's cookie or
947
+ * Accept-Language and redirects those that pick another locale, so it stays server-rendered while
948
+ * the app detects either.
949
+ */
950
+ function farmLocalizedStaticPaths(pagePath) {
951
+ const namesLocale = (pathname) =>
952
+ stripFarmLocaleFromPathname(pathname, farmRouteI18n) !==
953
+ stripFarmBasePath(pathname, farmRouteI18n.basePath);
954
+ const canonical = (pathname) =>
955
+ farmRouteI18n.locales.some(
956
+ (locale) => localizeFarmPathname(pathname, locale, farmRouteI18n) === pathname,
957
+ );
958
+ const detects = farmRouteI18n.detection.some((signal) => signal !== 'url');
959
+ const urls = namesLocale(pagePath)
960
+ ? [${hasBasePath ? `applyFarmBasePath(pagePath, ${JSON.stringify(ctx.basePath)})` : "pagePath"}]
961
+ : farmRouteI18n.locales.map((locale) => localizeFarmPathname(pagePath, locale, farmRouteI18n));
962
+ return urls
963
+ .map((url) => (url.length > 1 ? url.replace(/\\/$/, '') : url))
964
+ .filter((url) => canonical(url) && (namesLocale(url) || !detects))${ctx.trailingSlash
965
+ ? `
966
+ // With trailingSlash the page's URL is '/fr/about/', which Nitro writes as fr/about/index.html.
967
+ .map((url) => normalizeFarmTrailingSlashPathname(url, true))`
968
+ : ""};
969
+ }
724
970
 
971
+ `
972
+ : ""}
725
973
  // The route's metadata as core's server resolves it: layouts root to leaf, then the page, each
726
974
  // module's \`metadata\`, \`generateMetadata()\` and viewport exports merged in order.
727
975
  async function resolveFarmRouteMetadata(layoutModules, pageModule, pageProps) {
@@ -810,6 +1058,7 @@ async function handleFarmRequest(request, context) {
810
1058
 
811
1059
  async function resolveFarmRequest(farmCacheGuard, request, context) {
812
1060
  let url = new URL(request.url);
1061
+ const isFarmPayloadRequest = farmPayloadRequests.has(request);
813
1062
  let matchedPage = null;
814
1063
  let errorData = new Map();
815
1064
  let errorContext = new Map();
@@ -886,6 +1135,12 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
886
1135
  ? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
887
1136
  const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
888
1137
  if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
1138
+ `
1139
+ : ""}${ctx.sitemap?.enabled
1140
+ ? `// agent.sitemap: answered after middleware, as in core's servers.
1141
+ if (getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/') === '/sitemap.xml') {
1142
+ return applyProductionMiddlewareHeaders(createFarmAgentSitemapResponse(request), middlewareHeaders);
1143
+ }
889
1144
  `
890
1145
  : ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
891
1146
  return applyProductionMiddlewareHeaders(new Response(
@@ -893,6 +1148,20 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
893
1148
  { status: 404, headers: { 'Content-Type': 'application/json' } },
894
1149
  ), middlewareHeaders);
895
1150
  }
1151
+
1152
+ // A page answers at one spelling of its URL, as in core's servers: '/about/' with trailingSlash,
1153
+ // '/about' without. Any other spelling gets a 308 to it, before a server action runs, and a
1154
+ // '<page>.rsc' request is sent to the payload URL of that page.
1155
+ const trailingSlashLocation = resolveFarmTrailingSlashRedirect(url, ${JSON.stringify(ctx.trailingSlash === true)});
1156
+ if (trailingSlashLocation && matchRoute(url.pathname)) {
1157
+ const target = new URL(trailingSlashLocation, url);
1158
+ return applyProductionMiddlewareHeaders(new Response(null, {
1159
+ status: 308,
1160
+ headers: {
1161
+ location: isFarmPayloadRequest ? farmPayloadPath(target.pathname) + target.search : trailingSlashLocation,
1162
+ },
1163
+ }), middlewareHeaders);
1164
+ }
896
1165
  `;
897
1166
  // If actions enabled, add action handling before rendering
898
1167
  if (ctx.actionsEnabled) {
@@ -967,7 +1236,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
967
1236
  // sanitizeServerActionError untouched.
968
1237
  const actionRedirect = getFarmRedirectError(e);
969
1238
  if (actionRedirect) {
970
- returnValue = { ok: false, redirect: { url: actionRedirect.url, status: actionRedirect.status } };
1239
+ returnValue = { ok: false, redirect: { url: ${i18n ? "localizeFarmRedirectUrl(actionRedirect.url)" : "actionRedirect.url"}, status: actionRedirect.status } };
971
1240
  debug('Server action redirected:', actionId, actionRedirect.url);
972
1241
  } else {
973
1242
  const actionError = sanitizeServerActionError(e);
@@ -1014,7 +1283,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1014
1283
  debug('Form action redirected:', formRedirect.url);
1015
1284
  return new Response(null, {
1016
1285
  status: 303,
1017
- headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
1286
+ headers: { location: ${i18n ? "localizeFarmRedirectUrl(formRedirect.url)" : "formRedirect.url"}, 'Cache-Control': 'no-store' },
1018
1287
  });
1019
1288
  }
1020
1289
  const actionError = sanitizeServerActionError(e);
@@ -1075,7 +1344,13 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1075
1344
 
1076
1345
  // Page props passed to components (includes middleware shared data)
1077
1346
  const pageProps = { params, searchParams, middlewareData };
1078
- const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);
1347
+ ${ctx.markdown?.enabled
1348
+ ? `// The head advertises the page's Markdown mirror as the Link header does, as in core's servers.
1349
+ const metadata = addMetadataMarkdownAlternate(
1350
+ await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps),
1351
+ getFarmMarkdownAlternatePath(farmMarkdownConfig, url.pathname, { routePathname: getFarmRoutePathname }),
1352
+ );`
1353
+ : "const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);"}
1079
1354
  const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
1080
1355
  // Injected into <head> by the SSR entry; React renders only the charset.
1081
1356
  const metadataHead =
@@ -1147,10 +1422,15 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1147
1422
  layoutContent,
1148
1423
  )
1149
1424
  : h('div', { 'data-farm-root': 'true' }, layoutContent);
1150
- // Build the full page. root = full document (for SSR). rootContent = what the browser hydrates.
1425
+ ${i18n
1426
+ ? `// The request's locale, as core's renderers serialize it for hydration: client components
1427
+ // (Link, useLocale(), useTranslations()) read it in the browser as they did during SSR.
1428
+ const farmI18nSnapshot = getFarmI18nClientSnapshot() ?? null;
1429
+ `
1430
+ : ""}// Build the full page. root = full document (for SSR). rootContent = what the browser hydrates.
1151
1431
  const payload = {
1152
1432
  ownsDocument,
1153
- root: ownsDocument ? rootInner : h('html', null,
1433
+ root: ownsDocument ? rootInner : h('html', ${i18n ? "farmI18nSnapshot && { lang: farmI18nSnapshot.locale, dir: farmI18nSnapshot.direction }" : "null"},
1154
1434
  h('head', null,
1155
1435
  h('meta', { charSet: 'utf-8' }),
1156
1436
  renderedHead.hasFavicon ? null : h('link', { rel: 'icon', href: 'data:,' }),
@@ -1165,7 +1445,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1165
1445
  title: metadataTitle,
1166
1446
  description: typeof metadata.description === 'string' ? metadata.description : undefined,
1167
1447
  },
1168
- `;
1448
+ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1169
1449
  // Include action results in payload if actions are enabled
1170
1450
  if (ctx.actionsEnabled) {
1171
1451
  code += ` returnValue,
@@ -1246,7 +1526,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1246
1526
  if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
1247
1527
  `
1248
1528
  : ""}const redirect = getFarmRedirectError(err);
1249
- if (redirect) return new Response(null, { status: redirect.status, headers: { location: redirect.url, 'cache-control': 'no-store' } });
1529
+ if (redirect) return new Response(null, { status: redirect.status, headers: { location: ${i18n ? "localizeFarmRedirectUrl(redirect.url)" : "redirect.url"}, 'cache-control': 'no-store' } });
1250
1530
  if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
1251
1531
  console.error('[RSC] Handler error:', err);
1252
1532
  if (request.method === 'POST') {
@@ -1292,7 +1572,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1292
1572
  h('head', null, h('meta', { charSet: 'utf-8' }), h('title', null, 'Error')),
1293
1573
  h('body', null, h('div', { id: 'root' }, rootInner))),
1294
1574
  rootContent: rootInner,
1295
- metadata: { title: 'Error' },
1575
+ metadata: { title: 'Error' },${i18n ? "\n i18n: getFarmI18nClientSnapshot() ?? null," : ""}
1296
1576
  };
1297
1577
  const rscStream = renderToReadableStream(payload, { onError: farmRscOnError });
1298
1578
  const headers = new Headers(errorHeaders);
@@ -1338,27 +1618,17 @@ ${ctx.llmsTxt?.enabled
1338
1618
  * /llms-full.txt inlines each mirror.
1339
1619
  */
1340
1620
  function createFarmLlmsTxtContext(request, context, full) {
1341
- const origin = new URL(request.url).origin;
1342
- // A page a path-specific guard covers (a non-root middleware.ts, a config
1343
- // middleware matcher naming the path) is left out, as core's server does.
1344
- const guard = {
1345
- config: { middleware: farmConfigMiddleware },
1346
- middlewareRoutes: Object.keys(middlewares)
1347
- .map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
1348
- .filter((route) => route.path !== null),
1349
- };
1621
+ const origin = getFarmAgentOrigin(request);
1622
+ // Each page links to its public URL below the basePath ('/console/index.md' for the home page),
1623
+ // and include and exclude match its route path, as in core's servers.
1350
1624
  const pages = collectFarmLlmsTxtPages(
1351
- pageRoutes
1352
- .map(({ module, segments }) => ({
1353
- // Dynamic routes have no single URL, so the collector skips them.
1354
- pattern: '/' + segments
1355
- .map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
1356
- .join('/'),
1357
- metadata: module && module.metadata,
1358
- }))
1359
- .filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
1625
+ getFarmAgentListedPages().map(({ pattern, module }) => ({
1626
+ pattern,
1627
+ metadata: module && module.metadata,
1628
+ })),
1360
1629
  {
1361
1630
  origin,
1631
+ basePath: ${JSON.stringify(ctx.basePath)},
1362
1632
  markdown: farmMarkdownConfig,
1363
1633
  include: farmLlmsTxtConfig.include,
1364
1634
  exclude: farmLlmsTxtConfig.exclude,
@@ -1366,6 +1636,7 @@ function createFarmLlmsTxtContext(request, context, full) {
1366
1636
  );
1367
1637
  const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
1368
1638
  return {
1639
+ origin,
1369
1640
  defaults: createFarmDefaultLlmsTxt({
1370
1641
  origin,
1371
1642
  pages,
@@ -1389,9 +1660,11 @@ function createFarmLlmsTxtContext(request, context, full) {
1389
1660
 
1390
1661
  async function handleFarmLlmsTxtRequest(request, context) {
1391
1662
  const { origin, pathname } = new URL(request.url);
1392
- const kind = pathname === '/llms.txt'
1663
+ // Served at the path routes see, as core serves it: /console/llms.txt under basePath "/console".
1664
+ const routePathname = getFarmRoutePathname(pathname.replace(/\\/+$/, '') || '/');
1665
+ const kind = routePathname === '/llms.txt'
1393
1666
  ? 'llms'
1394
- : farmLlmsTxtConfig.full && pathname === '/llms-full.txt' ? 'llms-full' : null;
1667
+ : farmLlmsTxtConfig.full && routePathname === '/llms-full.txt' ? 'llms-full' : null;
1395
1668
  if (!kind) return null;
1396
1669
  const method = request.method.toUpperCase();
1397
1670
  if (method !== 'GET' && method !== 'HEAD') {
@@ -1402,7 +1675,7 @@ async function handleFarmLlmsTxtRequest(request, context) {
1402
1675
  let complete = true;
1403
1676
  const renderFull = (shared) =>
1404
1677
  renderFarmLlmsFullTxt(llmsContext.defaults, {
1405
- origin,
1678
+ origin: llmsContext.origin,
1406
1679
  readMarkdown: llmsContext.markdown,
1407
1680
  onIncomplete: () => {
1408
1681
  complete = false;
@@ -1427,6 +1700,90 @@ async function handleFarmLlmsTxtRequest(request, context) {
1427
1700
  return response;
1428
1701
  }
1429
1702
 
1703
+ `
1704
+ : ""}${listsAgentPages
1705
+ ? `/**
1706
+ * The static pages the generated agent files list, as core's servers pick them: each at its route
1707
+ * path, below the basePath and locale, leaving out a page a path-specific guard (a non-root
1708
+ * middleware.ts, a config middleware matcher naming the path) or a route guard covers, and one
1709
+ * that renders noindex through its own robots or, without one, its nearest layout's.
1710
+ */
1711
+ function getFarmAgentListedPages() {
1712
+ const guard = {
1713
+ config: { middleware: farmConfigMiddleware },
1714
+ middlewareRoutes: Object.keys(middlewares)
1715
+ .map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
1716
+ .filter((route) => route.path !== null),
1717
+ };
1718
+ const listed = new Map();
1719
+ for (const { filePath, module, segments } of pageRoutes) {
1720
+ // Dynamic routes have no single URL.
1721
+ if (segments.some((part) => part.isDynamic)) continue;
1722
+ const filePattern = '/' + segments.map((part) => part.segment).join('/');
1723
+ ${routesBelowPrefix
1724
+ ? `// A page nested under app/<basePath>/ answers at the path without it, and wins there, as
1725
+ // matchRoute() selects it.
1726
+ const routePathname = getFarmRoutePathname(filePattern);
1727
+ const nested = routePathname !== filePattern &&
1728
+ farmPageSpellsRoutePrefix(segments, filePattern, routePathname);
1729
+ const pattern = nested ? routePathname : filePattern;
1730
+ const current = listed.get(pattern);
1731
+ if (current && (current.nested || !nested)) continue;`
1732
+ : `const pattern = filePattern;
1733
+ const nested = false;
1734
+ if (listed.has(pattern)) continue;`}
1735
+ listed.set(pattern, { filePath, filePattern, pattern, module, nested });
1736
+ }
1737
+ // Middleware runs for both the path as received and the route path, so either may guard it.
1738
+ return [...listed.values()].filter(({ filePath, filePattern, pattern, module }) =>
1739
+ !farmPathGuardCoversPage(guard, filePattern) &&
1740
+ !farmPathGuardCoversPage(guard, pattern) &&
1741
+ !(module && module.__farmRouteGuard) &&
1742
+ !isFarmPageNoIndex(
1743
+ module && module.metadata,
1744
+ getRouteModules(filePath, layouts, 'layout').map((layout) => layout.metadata),
1745
+ ),
1746
+ );
1747
+ }
1748
+
1749
+ ${ctx.sitemap?.enabled
1750
+ ? `/**
1751
+ * agent.sitemap, built the same way as core's servers build it: the pages llms.txt lists, each at
1752
+ * its URL below the basePath, on the root layout's metadataBase or the request's origin.
1753
+ */
1754
+ function createFarmAgentSitemapResponse(request) {
1755
+ const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
1756
+ return createFarmMetadataRouteResponse(
1757
+ 'sitemap',
1758
+ createFarmDefaultSitemap(
1759
+ getFarmAgentListedPages().map(({ filePath, pattern, module }) => ({
1760
+ pattern,
1761
+ module,
1762
+ lastModified: farmPageLastModified[filePath],
1763
+ })),
1764
+ {
1765
+ origin: new URL(request.url).origin,
1766
+ config: farmAgentSitemapConfig,
1767
+ metadataBase: rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
1768
+ basePath: ${JSON.stringify(ctx.basePath)},
1769
+ },
1770
+ ),
1771
+ {},
1772
+ { method: request.method },
1773
+ );
1774
+ }
1775
+
1776
+ `
1777
+ : ""}// Agent files link to the root layout's metadataBase when it is an absolute URL, else to the
1778
+ // request's origin, as in core's servers.
1779
+ function getFarmAgentOrigin(request) {
1780
+ const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
1781
+ return resolveFarmAgentOrigin(
1782
+ rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
1783
+ new URL(request.url).origin,
1784
+ );
1785
+ }
1786
+
1430
1787
  `
1431
1788
  : ""}/**
1432
1789
  * Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
@@ -1440,9 +1797,9 @@ async function handleFarmPageOrMarkdown(request, context) {
1440
1797
  request,
1441
1798
  config: farmMarkdownConfig,
1442
1799
  routePathname: getFarmRoutePathname,
1443
- // matchRoute() reads the path as received, as the page render below does.
1800
+ // The page the render below selects for the mirrored URL, below the basePath and locale.
1444
1801
  routeExists: (pathname) => Boolean(matchRoute(pathname)),
1445
- renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
1802
+ renderPage: (pageRequest) => handleFarmRequest(${ctx.trailingSlash ? "toFarmTrailingSlashPageRequest(pageRequest)" : "pageRequest"}, context),
1446
1803
  apiServerBasePath: farmApiBasePath,
1447
1804
  });
1448
1805
  if (markdown) return markdown;
@@ -1453,7 +1810,19 @@ async function handleFarmPageOrMarkdown(request, context) {
1453
1810
  routePathname: getFarmRoutePathname,
1454
1811
  });
1455
1812
  }
1456
-
1813
+ ${ctx.trailingSlash
1814
+ ? `
1815
+ // The mirror reads the page at its canonical URL ('/about/'), so the trailing-slash redirect never
1816
+ // answers in its place.
1817
+ function toFarmTrailingSlashPageRequest(request) {
1818
+ const url = new URL(request.url);
1819
+ const pathname = normalizeFarmTrailingSlashPathname(url.pathname, true);
1820
+ if (pathname === url.pathname) return request;
1821
+ url.pathname = pathname;
1822
+ return new Request(url, request);
1823
+ }
1824
+ `
1825
+ : ""}
1457
1826
  // Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
1458
1827
  // trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
1459
1828
  // 'Accept: text/x-component' on the page URL keeps working.
@@ -1461,6 +1830,9 @@ function farmPayloadPath(pathname) {
1461
1830
  return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
1462
1831
  }
1463
1832
 
1833
+ // The requests made from a '<page>.rsc' URL, whose redirects name a payload URL too.
1834
+ const farmPayloadRequests = new WeakSet();
1835
+
1464
1836
  function toFarmPayloadRequest(request) {
1465
1837
  if (request.method !== 'GET' && request.method !== 'HEAD') return request;
1466
1838
  const url = new URL(request.url);
@@ -1470,7 +1842,9 @@ function toFarmPayloadRequest(request) {
1470
1842
  url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
1471
1843
  const headers = new Headers(request.headers);
1472
1844
  headers.set('accept', 'text/x-component');
1473
- return new Request(url, { method: request.method, headers, signal: request.signal });
1845
+ const payloadRequest = new Request(url, { method: request.method, headers, signal: request.signal });
1846
+ farmPayloadRequests.add(payloadRequest);
1847
+ return payloadRequest;
1474
1848
  }
1475
1849
 
1476
1850
  // The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
@@ -1537,7 +1911,7 @@ ${ctx.mobileClient
1537
1911
  }
1538
1912
  `
1539
1913
  : ""} const pageRequest = toFarmPayloadRequest(request);
1540
- const response = await handleFarmRequestWithRuntime(pageRequest, context);
1914
+ const response = await handleFarmRequestWithRuntime(pageRequest, context${i18n ? ", pageRequest !== request" : ""});
1541
1915
  if (
1542
1916
  prerendering &&
1543
1917
  pageRequest === request &&
@@ -1574,14 +1948,18 @@ const farmNativeStylesheets = (() => {
1574
1948
  `
1575
1949
  : ""}
1576
1950
 
1577
- async function handleFarmRequestWithRuntime(request, context) {
1578
- return _runWithAPIRequestRuntime({
1951
+ ${i18n
1952
+ ? `async function handleFarmRequestWithRuntime(request, context, payloadRequested) {
1953
+ // Outermost, so middleware, after() callbacks and local API calls read the locale too.
1954
+ return runFarmLocalizedRequest(request, payloadRequested, () => _runWithAPIRequestRuntime({`
1955
+ : `async function handleFarmRequestWithRuntime(request, context) {
1956
+ return _runWithAPIRequestRuntime({`}
1579
1957
  basePath: farmApiBasePath,
1580
1958
  dispatch: async (localRequest) =>
1581
1959
  (await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
1582
1960
  }, () => _runWithCurrentRequest(request, () =>
1583
1961
  _runWithAfterRequest(request, () => handleFarmPageOrMarkdown(request, context), context)
1584
- ));
1962
+ ))${i18n ? ")" : ""};
1585
1963
  }
1586
1964
 
1587
1965
  export default { fetch: handler };