@farm.js/plugin 0.1.68 → 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.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rsc/entries/client.d.ts +2 -0
- package/dist/rsc/entries/client.d.ts.map +1 -1
- package/dist/rsc/entries/client.js +59 -5
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +423 -50
- package/dist/rsc/index.d.ts +12 -4
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +36 -9
- package/dist/rsc/types.d.ts +16 -2
- package/dist/rsc/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { EntryContext } from "../types.js";
|
|
2
2
|
export declare const CLIENT_ENTRY_CORE_IMPORTS: readonly ["@farm.js/core/client", "@farm.js/core/deployment", "@farm.js/core/internal/client-runtime", "@farm.js/core/server-query/client"];
|
|
3
|
+
/** What the browser entry of an app with i18n imports as well. */
|
|
4
|
+
export declare const CLIENT_ENTRY_I18N_IMPORTS: readonly ["@farm.js/core/i18n", "@farm.js/core/i18n/client"];
|
|
3
5
|
export declare const serverFnTransportErrorClientRuntime = "function createFarmServerFnTransportError(value) {\n const message = value && typeof value === 'object' && typeof value.message === 'string'\n ? value.message\n : 'Server function failed';\n const error = new Error(message);\n\n if (\n value &&\n typeof value === 'object' &&\n value.name === 'ServerFnFailure' &&\n typeof value.code === 'string' &&\n Number.isInteger(value.status) &&\n value.status >= 400 &&\n value.status <= 599 &&\n Object.prototype.hasOwnProperty.call(value, 'data')\n ) {\n error.name = 'ServerFnFailure';\n error.code = value.code;\n error.status = value.status;\n error.data = value.data;\n Object.defineProperty(error, Symbol.for('farm.server-fn.failure'), {\n value: true,\n enumerable: false,\n });\n return error;\n }\n\n error.name = 'ServerActionError';\n return error;\n}";
|
|
4
6
|
/**
|
|
5
7
|
* Generates the browser entry file.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIhD,eAAO,MAAM,yBAAyB,6IAK5B,CAAC;AAEX,eAAO,MAAM,mCAAmC,62BA6B9C,CAAC;AAEH;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIhD,eAAO,MAAM,yBAAyB,6IAK5B,CAAC;AAEX,kEAAkE;AAClE,eAAO,MAAM,yBAAyB,8DAG5B,CAAC;AAEX,eAAO,MAAM,mCAAmC,62BA6B9C,CAAC;AAEH;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAmkB7D"}
|
|
@@ -6,6 +6,11 @@ export const CLIENT_ENTRY_CORE_IMPORTS = [
|
|
|
6
6
|
"@farm.js/core/internal/client-runtime",
|
|
7
7
|
"@farm.js/core/server-query/client",
|
|
8
8
|
];
|
|
9
|
+
/** What the browser entry of an app with i18n imports as well. */
|
|
10
|
+
export const CLIENT_ENTRY_I18N_IMPORTS = [
|
|
11
|
+
"@farm.js/core/i18n",
|
|
12
|
+
"@farm.js/core/i18n/client",
|
|
13
|
+
];
|
|
9
14
|
export const serverFnTransportErrorClientRuntime = `function createFarmServerFnTransportError(value) {
|
|
10
15
|
const message = value && typeof value === 'object' && typeof value.message === 'string'
|
|
11
16
|
? value.message
|
|
@@ -70,6 +75,43 @@ import {
|
|
|
70
75
|
} from '@farm.js/core/deployment';
|
|
71
76
|
import { createFarmRouteAnnouncer, runFarmNavigationDelegates } from '@farm.js/core/internal/client-runtime';
|
|
72
77
|
`;
|
|
78
|
+
// <Link href="/about"> renders /console/about under basePath "/console", as the RSC server
|
|
79
|
+
// rendered it, so the page hydrates with the same href.
|
|
80
|
+
if (!["", "/"].includes(ctx.basePath.trim())) {
|
|
81
|
+
imports += `import { setFarmBasePath } from '@farm.js/core/internal/client-runtime';
|
|
82
|
+
setFarmBasePath(${JSON.stringify(ctx.basePath)});
|
|
83
|
+
`;
|
|
84
|
+
}
|
|
85
|
+
// trailingSlash: <Link href="/about"> renders /about/, as the RSC server rendered it.
|
|
86
|
+
if (ctx.trailingSlash) {
|
|
87
|
+
imports += `import { setFarmTrailingSlashPreference } from '@farm.js/core/internal/client-runtime';
|
|
88
|
+
setFarmTrailingSlashPreference(true);
|
|
89
|
+
`;
|
|
90
|
+
}
|
|
91
|
+
const i18n = ctx.i18n?.enabled === true;
|
|
92
|
+
if (i18n) {
|
|
93
|
+
imports += `import { localizeFarmHref, resolveFarmLocalePath } from '@farm.js/core/i18n';
|
|
94
|
+
import { _setFarmI18nClientSnapshot } from '@farm.js/core/i18n/client';
|
|
95
|
+
|
|
96
|
+
// A link to another locale loads as a document, as Farm's <Link> does in other apps, so the page
|
|
97
|
+
// and the catalog its client components read change together.
|
|
98
|
+
function farmIsLocaleChange(url) {
|
|
99
|
+
const snapshot = window.__FARM_I18N__;
|
|
100
|
+
if (!snapshot || snapshot.routing === 'none') return false;
|
|
101
|
+
const target = resolveFarmLocalePath(url.pathname, snapshot);
|
|
102
|
+
return (target.locale || snapshot.defaultLocale) !== snapshot.locale;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A redirect() thrown while a navigation renders goes to its target in the page's locale, as the
|
|
106
|
+
// server localizes the redirects it answers.
|
|
107
|
+
function farmLocalizeRedirect(url) {
|
|
108
|
+
const snapshot = window.__FARM_I18N__;
|
|
109
|
+
return snapshot && url.startsWith('/') && !url.startsWith('//')
|
|
110
|
+
? localizeFarmHref(url, snapshot.locale, snapshot)
|
|
111
|
+
: url;
|
|
112
|
+
}
|
|
113
|
+
`;
|
|
114
|
+
}
|
|
73
115
|
// farm dev --mobile: every page runs in the shell's WebView, so this entry is the mobile client.
|
|
74
116
|
if (ctx.mobileClient === "inline") {
|
|
75
117
|
imports += generateMobileShellNavigation();
|
|
@@ -264,7 +306,7 @@ class FarmNavigationErrorBoundary extends React.Component {
|
|
|
264
306
|
componentDidCatch(error) {
|
|
265
307
|
const digest = error && typeof error.digest === 'string' ? error.digest : '';
|
|
266
308
|
if (digest.startsWith('FARM_REDIRECT;')) {
|
|
267
|
-
farmNavigateRef.current?.(digest.split(';').slice(2).join(';'), 'replace');
|
|
309
|
+
farmNavigateRef.current?.(${i18n ? "farmLocalizeRedirect(digest.split(';').slice(2).join(';'))" : "digest.split(';').slice(2).join(';')"}, 'replace');
|
|
268
310
|
return;
|
|
269
311
|
}
|
|
270
312
|
location.reload();
|
|
@@ -299,10 +341,14 @@ async function main() {
|
|
|
299
341
|
console.error('[Farm.js] Failed to deserialize RSC payload:', e);
|
|
300
342
|
return;
|
|
301
343
|
}
|
|
302
|
-
|
|
344
|
+
|
|
303
345
|
// The page the document loaded with is the baseline: it is never announced.
|
|
304
346
|
const announceRoute = createFarmRouteAnnouncer();
|
|
305
|
-
|
|
347
|
+
${i18n
|
|
348
|
+
? ` // The locale the server rendered with, before anything hydrates (window.__FARM_I18N__).
|
|
349
|
+
if (initial.i18n) _setFarmI18nClientSnapshot(initial.i18n);
|
|
350
|
+
`
|
|
351
|
+
: ""}
|
|
306
352
|
// Root component that manages RSC state
|
|
307
353
|
function BrowserRoot() {
|
|
308
354
|
const [payload, set] = React.useState(initial);
|
|
@@ -337,7 +383,15 @@ async function main() {
|
|
|
337
383
|
description?.remove();
|
|
338
384
|
}
|
|
339
385
|
}, [payload.metadata?.title, payload.metadata?.description]);
|
|
340
|
-
|
|
386
|
+
${i18n
|
|
387
|
+
? `
|
|
388
|
+
// A payload from back/forward or a refresh carries its locale (and, in development, edited
|
|
389
|
+
// messages): client components re-read it before the browser paints.
|
|
390
|
+
React.useLayoutEffect(() => {
|
|
391
|
+
if (payload !== initial && payload.i18n) _setFarmI18nClientSnapshot(payload.i18n);
|
|
392
|
+
}, [payload]);
|
|
393
|
+
`
|
|
394
|
+
: ""}
|
|
341
395
|
// Announce a client navigation to screen readers once its page and title are in place.
|
|
342
396
|
React.useEffect(() => {
|
|
343
397
|
if (payload !== initial) announceRoute();
|
|
@@ -411,7 +465,7 @@ ${withPlugins(`
|
|
|
411
465
|
// Back/forward, refreshes and same-page moves are not offered; other origins load as documents.
|
|
412
466
|
async function navigate(href, action) {
|
|
413
467
|
const url = new URL(href, location.href);
|
|
414
|
-
if (url.origin !== location.origin) {
|
|
468
|
+
if (url.origin !== location.origin${i18n ? " || farmIsLocaleChange(url)" : ""}) {
|
|
415
469
|
location.assign(url.href);
|
|
416
470
|
return;
|
|
417
471
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/rsc.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"rsc.d.ts","sourceRoot":"","sources":["../../../src/rsc/entries/rsc.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA+HhD;;;GAGG;AACH,wBAAgB,mCAAmC,IAAI,MAAM,CAe5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAu4D1D"}
|
package/dist/rsc/entries/rsc.js
CHANGED
|
@@ -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}`;
|
|
@@ -129,8 +239,28 @@ import {
|
|
|
129
239
|
createMarkdownMirrorResponse,
|
|
130
240
|
farmRequestWantsMarkdown,
|
|
131
241
|
} from '@farm.js/core/markdown';
|
|
132
|
-
|
|
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';
|
|
133
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
|
+
: ""}
|
|
134
264
|
${ctx.images && ctx.images.runtime !== "none"
|
|
135
265
|
? `import { createCloudflareImageTransformer, createFarmImageHandler } from '@farm.js/core/image/server';
|
|
136
266
|
${ctx.images.runtime === "node"
|
|
@@ -162,29 +292,46 @@ const farmRouteI18n = ${JSON.stringify(ctx.i18n ?? { enabled: false, basePath: c
|
|
|
162
292
|
|
|
163
293
|
/**
|
|
164
294
|
* A request path without the app's basePath and locale prefix, as core's servers and the
|
|
165
|
-
* middleware runner read it: '/console/fr/about' is '/about'.
|
|
166
|
-
* '<prefix>/index.md' and matches md.expose on it.
|
|
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.
|
|
167
297
|
*/
|
|
168
298
|
function getFarmRoutePathname(pathname) {
|
|
169
299
|
return farmRouteI18n.enabled
|
|
170
300
|
? stripFarmLocaleFromPathname(pathname, farmRouteI18n)
|
|
171
301
|
: stripFarmBasePath(pathname, farmRouteI18n.basePath);
|
|
172
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';
|
|
173
313
|
`;
|
|
314
|
+
}
|
|
174
315
|
if (ctx.llmsTxt?.enabled) {
|
|
175
316
|
code += `import {
|
|
176
317
|
collectFarmLlmsTxtPages,
|
|
177
318
|
createFarmDefaultLlmsTxt,
|
|
178
319
|
createFarmLlmsFullRenderer,
|
|
179
320
|
createFarmLlmsMarkdownReader,
|
|
180
|
-
createFarmMetadataRouteResponse,
|
|
181
|
-
farmPathGuardCoversPage,
|
|
182
321
|
renderFarmLlmsFullTxt,
|
|
183
322
|
} from '@farm.js/core/internal/production-runtime';
|
|
184
323
|
import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
|
|
185
324
|
|
|
186
325
|
const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
|
|
187
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 ?? {})};
|
|
188
335
|
`;
|
|
189
336
|
}
|
|
190
337
|
if (ctx.actionsEnabled) {
|
|
@@ -532,7 +679,8 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
|
|
|
532
679
|
i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
|
|
533
680
|
server: ${JSON.stringify(ctx.server) ?? "undefined"},
|
|
534
681
|
apiBasePath: farmApiBasePath,
|
|
535
|
-
// matchRoute()
|
|
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.
|
|
536
684
|
rawPathRouting: true,
|
|
537
685
|
});
|
|
538
686
|
|
|
@@ -651,12 +799,48 @@ const pageRoutes = Object.entries(pages)
|
|
|
651
799
|
* Simple file-based router
|
|
652
800
|
* Converts URL pathname to matching page component
|
|
653
801
|
*/
|
|
654
|
-
|
|
802
|
+
${routesBelowPrefix
|
|
803
|
+
? `function matchRoute(pathname) {
|
|
655
804
|
const normalized = pathname.replace(/\\/$/, '') || '/';
|
|
656
|
-
|
|
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) {
|
|
657
841
|
for (const { filePath, module, segments } of pageRoutes) {
|
|
658
842
|
const match = matchFarmPageRoute(normalized, segments);
|
|
659
|
-
|
|
843
|
+
|
|
660
844
|
if (match.matches) {
|
|
661
845
|
debug('Matched route:', filePath, 'for path:', normalized);
|
|
662
846
|
return {
|
|
@@ -664,10 +848,11 @@ function matchRoute(pathname) {
|
|
|
664
848
|
pattern: filePath,
|
|
665
849
|
params: match.params,
|
|
666
850
|
module,
|
|
851
|
+
segments,
|
|
667
852
|
};
|
|
668
853
|
}
|
|
669
854
|
}
|
|
670
|
-
|
|
855
|
+
|
|
671
856
|
debug('No route matched for:', normalized);
|
|
672
857
|
return null;
|
|
673
858
|
}
|
|
@@ -683,8 +868,9 @@ const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives
|
|
|
683
868
|
* path any middleware may handle stays server-rendered.
|
|
684
869
|
*/
|
|
685
870
|
async function collectFarmStaticPages() {
|
|
686
|
-
${
|
|
687
|
-
?
|
|
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.');
|
|
688
874
|
return [];`
|
|
689
875
|
: ""}
|
|
690
876
|
const middlewareRoutes = Object.keys(middlewares)
|
|
@@ -721,12 +907,69 @@ async function collectFarmStaticPages() {
|
|
|
721
907
|
) {
|
|
722
908
|
continue;
|
|
723
909
|
}
|
|
724
|
-
|
|
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);"}
|
|
725
936
|
}
|
|
726
937
|
}
|
|
727
938
|
return [...paths];
|
|
728
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
|
+
}
|
|
729
970
|
|
|
971
|
+
`
|
|
972
|
+
: ""}
|
|
730
973
|
// The route's metadata as core's server resolves it: layouts root to leaf, then the page, each
|
|
731
974
|
// module's \`metadata\`, \`generateMetadata()\` and viewport exports merged in order.
|
|
732
975
|
async function resolveFarmRouteMetadata(layoutModules, pageModule, pageProps) {
|
|
@@ -815,6 +1058,7 @@ async function handleFarmRequest(request, context) {
|
|
|
815
1058
|
|
|
816
1059
|
async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
817
1060
|
let url = new URL(request.url);
|
|
1061
|
+
const isFarmPayloadRequest = farmPayloadRequests.has(request);
|
|
818
1062
|
let matchedPage = null;
|
|
819
1063
|
let errorData = new Map();
|
|
820
1064
|
let errorContext = new Map();
|
|
@@ -891,6 +1135,12 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
891
1135
|
? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
|
|
892
1136
|
const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
|
|
893
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
|
+
}
|
|
894
1144
|
`
|
|
895
1145
|
: ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
896
1146
|
return applyProductionMiddlewareHeaders(new Response(
|
|
@@ -898,6 +1148,20 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
898
1148
|
{ status: 404, headers: { 'Content-Type': 'application/json' } },
|
|
899
1149
|
), middlewareHeaders);
|
|
900
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
|
+
}
|
|
901
1165
|
`;
|
|
902
1166
|
// If actions enabled, add action handling before rendering
|
|
903
1167
|
if (ctx.actionsEnabled) {
|
|
@@ -972,7 +1236,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
972
1236
|
// sanitizeServerActionError untouched.
|
|
973
1237
|
const actionRedirect = getFarmRedirectError(e);
|
|
974
1238
|
if (actionRedirect) {
|
|
975
|
-
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 } };
|
|
976
1240
|
debug('Server action redirected:', actionId, actionRedirect.url);
|
|
977
1241
|
} else {
|
|
978
1242
|
const actionError = sanitizeServerActionError(e);
|
|
@@ -1019,7 +1283,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1019
1283
|
debug('Form action redirected:', formRedirect.url);
|
|
1020
1284
|
return new Response(null, {
|
|
1021
1285
|
status: 303,
|
|
1022
|
-
headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
|
|
1286
|
+
headers: { location: ${i18n ? "localizeFarmRedirectUrl(formRedirect.url)" : "formRedirect.url"}, 'Cache-Control': 'no-store' },
|
|
1023
1287
|
});
|
|
1024
1288
|
}
|
|
1025
1289
|
const actionError = sanitizeServerActionError(e);
|
|
@@ -1080,7 +1344,13 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1080
1344
|
|
|
1081
1345
|
// Page props passed to components (includes middleware shared data)
|
|
1082
1346
|
const pageProps = { params, searchParams, middlewareData };
|
|
1083
|
-
|
|
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);"}
|
|
1084
1354
|
const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
|
|
1085
1355
|
// Injected into <head> by the SSR entry; React renders only the charset.
|
|
1086
1356
|
const metadataHead =
|
|
@@ -1152,10 +1422,15 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1152
1422
|
layoutContent,
|
|
1153
1423
|
)
|
|
1154
1424
|
: h('div', { 'data-farm-root': 'true' }, layoutContent);
|
|
1155
|
-
|
|
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.
|
|
1156
1431
|
const payload = {
|
|
1157
1432
|
ownsDocument,
|
|
1158
|
-
root: ownsDocument ? rootInner : h('html', null,
|
|
1433
|
+
root: ownsDocument ? rootInner : h('html', ${i18n ? "farmI18nSnapshot && { lang: farmI18nSnapshot.locale, dir: farmI18nSnapshot.direction }" : "null"},
|
|
1159
1434
|
h('head', null,
|
|
1160
1435
|
h('meta', { charSet: 'utf-8' }),
|
|
1161
1436
|
renderedHead.hasFavicon ? null : h('link', { rel: 'icon', href: 'data:,' }),
|
|
@@ -1170,7 +1445,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1170
1445
|
title: metadataTitle,
|
|
1171
1446
|
description: typeof metadata.description === 'string' ? metadata.description : undefined,
|
|
1172
1447
|
},
|
|
1173
|
-
`;
|
|
1448
|
+
${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
|
|
1174
1449
|
// Include action results in payload if actions are enabled
|
|
1175
1450
|
if (ctx.actionsEnabled) {
|
|
1176
1451
|
code += ` returnValue,
|
|
@@ -1251,7 +1526,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1251
1526
|
if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
|
|
1252
1527
|
`
|
|
1253
1528
|
: ""}const redirect = getFarmRedirectError(err);
|
|
1254
|
-
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' } });
|
|
1255
1530
|
if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
|
|
1256
1531
|
console.error('[RSC] Handler error:', err);
|
|
1257
1532
|
if (request.method === 'POST') {
|
|
@@ -1297,7 +1572,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1297
1572
|
h('head', null, h('meta', { charSet: 'utf-8' }), h('title', null, 'Error')),
|
|
1298
1573
|
h('body', null, h('div', { id: 'root' }, rootInner))),
|
|
1299
1574
|
rootContent: rootInner,
|
|
1300
|
-
metadata: { title: 'Error' },
|
|
1575
|
+
metadata: { title: 'Error' },${i18n ? "\n i18n: getFarmI18nClientSnapshot() ?? null," : ""}
|
|
1301
1576
|
};
|
|
1302
1577
|
const rscStream = renderToReadableStream(payload, { onError: farmRscOnError });
|
|
1303
1578
|
const headers = new Headers(errorHeaders);
|
|
@@ -1343,27 +1618,17 @@ ${ctx.llmsTxt?.enabled
|
|
|
1343
1618
|
* /llms-full.txt inlines each mirror.
|
|
1344
1619
|
*/
|
|
1345
1620
|
function createFarmLlmsTxtContext(request, context, full) {
|
|
1346
|
-
const origin =
|
|
1347
|
-
//
|
|
1348
|
-
//
|
|
1349
|
-
const guard = {
|
|
1350
|
-
config: { middleware: farmConfigMiddleware },
|
|
1351
|
-
middlewareRoutes: Object.keys(middlewares)
|
|
1352
|
-
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
1353
|
-
.filter((route) => route.path !== null),
|
|
1354
|
-
};
|
|
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.
|
|
1355
1624
|
const pages = collectFarmLlmsTxtPages(
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
.map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
|
|
1361
|
-
.join('/'),
|
|
1362
|
-
metadata: module && module.metadata,
|
|
1363
|
-
}))
|
|
1364
|
-
.filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
|
|
1625
|
+
getFarmAgentListedPages().map(({ pattern, module }) => ({
|
|
1626
|
+
pattern,
|
|
1627
|
+
metadata: module && module.metadata,
|
|
1628
|
+
})),
|
|
1365
1629
|
{
|
|
1366
1630
|
origin,
|
|
1631
|
+
basePath: ${JSON.stringify(ctx.basePath)},
|
|
1367
1632
|
markdown: farmMarkdownConfig,
|
|
1368
1633
|
include: farmLlmsTxtConfig.include,
|
|
1369
1634
|
exclude: farmLlmsTxtConfig.exclude,
|
|
@@ -1371,6 +1636,7 @@ function createFarmLlmsTxtContext(request, context, full) {
|
|
|
1371
1636
|
);
|
|
1372
1637
|
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
1373
1638
|
return {
|
|
1639
|
+
origin,
|
|
1374
1640
|
defaults: createFarmDefaultLlmsTxt({
|
|
1375
1641
|
origin,
|
|
1376
1642
|
pages,
|
|
@@ -1394,9 +1660,11 @@ function createFarmLlmsTxtContext(request, context, full) {
|
|
|
1394
1660
|
|
|
1395
1661
|
async function handleFarmLlmsTxtRequest(request, context) {
|
|
1396
1662
|
const { origin, pathname } = new URL(request.url);
|
|
1397
|
-
|
|
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'
|
|
1398
1666
|
? 'llms'
|
|
1399
|
-
: farmLlmsTxtConfig.full &&
|
|
1667
|
+
: farmLlmsTxtConfig.full && routePathname === '/llms-full.txt' ? 'llms-full' : null;
|
|
1400
1668
|
if (!kind) return null;
|
|
1401
1669
|
const method = request.method.toUpperCase();
|
|
1402
1670
|
if (method !== 'GET' && method !== 'HEAD') {
|
|
@@ -1407,7 +1675,7 @@ async function handleFarmLlmsTxtRequest(request, context) {
|
|
|
1407
1675
|
let complete = true;
|
|
1408
1676
|
const renderFull = (shared) =>
|
|
1409
1677
|
renderFarmLlmsFullTxt(llmsContext.defaults, {
|
|
1410
|
-
origin,
|
|
1678
|
+
origin: llmsContext.origin,
|
|
1411
1679
|
readMarkdown: llmsContext.markdown,
|
|
1412
1680
|
onIncomplete: () => {
|
|
1413
1681
|
complete = false;
|
|
@@ -1432,6 +1700,90 @@ async function handleFarmLlmsTxtRequest(request, context) {
|
|
|
1432
1700
|
return response;
|
|
1433
1701
|
}
|
|
1434
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
|
+
|
|
1435
1787
|
`
|
|
1436
1788
|
: ""}/**
|
|
1437
1789
|
* Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
|
|
@@ -1445,9 +1797,9 @@ async function handleFarmPageOrMarkdown(request, context) {
|
|
|
1445
1797
|
request,
|
|
1446
1798
|
config: farmMarkdownConfig,
|
|
1447
1799
|
routePathname: getFarmRoutePathname,
|
|
1448
|
-
//
|
|
1800
|
+
// The page the render below selects for the mirrored URL, below the basePath and locale.
|
|
1449
1801
|
routeExists: (pathname) => Boolean(matchRoute(pathname)),
|
|
1450
|
-
renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
|
|
1802
|
+
renderPage: (pageRequest) => handleFarmRequest(${ctx.trailingSlash ? "toFarmTrailingSlashPageRequest(pageRequest)" : "pageRequest"}, context),
|
|
1451
1803
|
apiServerBasePath: farmApiBasePath,
|
|
1452
1804
|
});
|
|
1453
1805
|
if (markdown) return markdown;
|
|
@@ -1458,7 +1810,19 @@ async function handleFarmPageOrMarkdown(request, context) {
|
|
|
1458
1810
|
routePathname: getFarmRoutePathname,
|
|
1459
1811
|
});
|
|
1460
1812
|
}
|
|
1461
|
-
|
|
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
|
+
: ""}
|
|
1462
1826
|
// Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
|
|
1463
1827
|
// trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
|
|
1464
1828
|
// 'Accept: text/x-component' on the page URL keeps working.
|
|
@@ -1466,6 +1830,9 @@ function farmPayloadPath(pathname) {
|
|
|
1466
1830
|
return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
|
|
1467
1831
|
}
|
|
1468
1832
|
|
|
1833
|
+
// The requests made from a '<page>.rsc' URL, whose redirects name a payload URL too.
|
|
1834
|
+
const farmPayloadRequests = new WeakSet();
|
|
1835
|
+
|
|
1469
1836
|
function toFarmPayloadRequest(request) {
|
|
1470
1837
|
if (request.method !== 'GET' && request.method !== 'HEAD') return request;
|
|
1471
1838
|
const url = new URL(request.url);
|
|
@@ -1475,7 +1842,9 @@ function toFarmPayloadRequest(request) {
|
|
|
1475
1842
|
url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
|
|
1476
1843
|
const headers = new Headers(request.headers);
|
|
1477
1844
|
headers.set('accept', 'text/x-component');
|
|
1478
|
-
|
|
1845
|
+
const payloadRequest = new Request(url, { method: request.method, headers, signal: request.signal });
|
|
1846
|
+
farmPayloadRequests.add(payloadRequest);
|
|
1847
|
+
return payloadRequest;
|
|
1479
1848
|
}
|
|
1480
1849
|
|
|
1481
1850
|
// The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
|
|
@@ -1542,7 +1911,7 @@ ${ctx.mobileClient
|
|
|
1542
1911
|
}
|
|
1543
1912
|
`
|
|
1544
1913
|
: ""} const pageRequest = toFarmPayloadRequest(request);
|
|
1545
|
-
const response = await handleFarmRequestWithRuntime(pageRequest, context);
|
|
1914
|
+
const response = await handleFarmRequestWithRuntime(pageRequest, context${i18n ? ", pageRequest !== request" : ""});
|
|
1546
1915
|
if (
|
|
1547
1916
|
prerendering &&
|
|
1548
1917
|
pageRequest === request &&
|
|
@@ -1579,14 +1948,18 @@ const farmNativeStylesheets = (() => {
|
|
|
1579
1948
|
`
|
|
1580
1949
|
: ""}
|
|
1581
1950
|
|
|
1582
|
-
|
|
1583
|
-
|
|
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({`}
|
|
1584
1957
|
basePath: farmApiBasePath,
|
|
1585
1958
|
dispatch: async (localRequest) =>
|
|
1586
1959
|
(await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
|
|
1587
1960
|
}, () => _runWithCurrentRequest(request, () =>
|
|
1588
1961
|
_runWithAfterRequest(request, () => handleFarmPageOrMarkdown(request, context), context)
|
|
1589
|
-
));
|
|
1962
|
+
))${i18n ? ")" : ""};
|
|
1590
1963
|
}
|
|
1591
1964
|
|
|
1592
1965
|
export default { fetch: handler };
|
package/dist/rsc/index.d.ts
CHANGED
|
@@ -30,7 +30,7 @@ import type { FarmServerConfig } from "@farm.js/core/internal/production-runtime
|
|
|
30
30
|
import type { FarmLayerEntry, ResolvedFarmLayer } from "@farm.js/core/server";
|
|
31
31
|
import { resolveFarmImageConfig } from "@farm.js/core/vite";
|
|
32
32
|
import { type FarmMarkdownUserConfig } from "@farm.js/core/markdown";
|
|
33
|
-
import type { FarmLlmsTxtUserConfig } from "@farm.js/core/internal/production-runtime";
|
|
33
|
+
import type { FarmAgentSitemapUserConfig, FarmLlmsTxtUserConfig } from "@farm.js/core/internal/production-runtime";
|
|
34
34
|
import type { FarmMCPUserConfig } from "@farm.js/core/server";
|
|
35
35
|
export type { FarmRscPluginOptions, EntryContext };
|
|
36
36
|
export { buildRscNitro, waitForRscManifest, waitForRscOutputs } from "./nitro-build.js";
|
|
@@ -44,6 +44,12 @@ export interface FarmRscConfig {
|
|
|
44
44
|
layers?: readonly ResolvedFarmLayer[];
|
|
45
45
|
outDir?: string;
|
|
46
46
|
basePath?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Same as core's `trailingSlash`: pages answer at `/about/`, `<Link>` renders that URL, and
|
|
49
|
+
* `/about` redirects (308) to it. Without it, `/about/` redirects to `/about`.
|
|
50
|
+
* @default false
|
|
51
|
+
*/
|
|
52
|
+
trailingSlash?: boolean;
|
|
47
53
|
api?: FarmAPIConfig;
|
|
48
54
|
server?: FarmServerConfig;
|
|
49
55
|
middleware?: FarmMiddlewareConfig;
|
|
@@ -96,12 +102,14 @@ export interface FarmRscConfig {
|
|
|
96
102
|
/**
|
|
97
103
|
* Agent-facing files. `llmsTxt` serves `/llms.txt`, an index of the app's
|
|
98
104
|
* static pages that links to their Markdown mirrors, and with `full: true`
|
|
99
|
-
* also `/llms-full.txt`, which inlines them.
|
|
100
|
-
* `agent.llmsTxt
|
|
101
|
-
*
|
|
105
|
+
* also `/llms-full.txt`, which inlines them. `sitemap` serves `/sitemap.xml`
|
|
106
|
+
* of the same pages. Same options as core's `agent.llmsTxt` and
|
|
107
|
+
* `agent.sitemap`; `false` turns each off.
|
|
108
|
+
* @default { llmsTxt: { full: false }, sitemap: true }
|
|
102
109
|
*/
|
|
103
110
|
agent?: {
|
|
104
111
|
llmsTxt?: boolean | FarmLlmsTxtUserConfig;
|
|
112
|
+
sitemap?: boolean | FarmAgentSitemapUserConfig;
|
|
105
113
|
};
|
|
106
114
|
/**
|
|
107
115
|
* An MCP endpoint for agents, with the same options as core's top-level
|
package/dist/rsc/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rsc/index.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAIL,KAAK,MAAM,EACX,KAAK,UAAU,EAChB,MAAM,MAAM,CAAC;AAEd,OAAO,KAAK,EACV,oBAAoB,EACpB,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAGpB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAI9E,OAAO,EAQL,sBAAsB,EAIvB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAyB,KAAK,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAC5F,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rsc/index.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAIL,KAAK,MAAM,EACX,KAAK,UAAU,EAChB,MAAM,MAAM,CAAC;AAEd,OAAO,KAAK,EACV,oBAAoB,EACpB,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAGpB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0BAA0B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;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,GAAE,aAAkB,GAAG,UAAU,CAgFnE;AAubD;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,OAAO,CAAC,OAAO,GAAE,oBAAyB,GAAG,MAAM,EAAE,CAq0C5E"}
|
package/dist/rsc/index.js
CHANGED
|
@@ -32,7 +32,7 @@ import { generateRscEntry } from "./entries/rsc.js";
|
|
|
32
32
|
import { resolveMarkdownConfig } from "@farm.js/core/markdown";
|
|
33
33
|
import { generateSsrEntry } from "./entries/ssr.js";
|
|
34
34
|
import { generateErrorFallbackEntry } from "./entries/error-fallback.js";
|
|
35
|
-
import { CLIENT_ENTRY_CORE_IMPORTS, generateClientEntry, serverFnTransportErrorClientRuntime, } from "./entries/client.js";
|
|
35
|
+
import { CLIENT_ENTRY_CORE_IMPORTS, CLIENT_ENTRY_I18N_IMPORTS, generateClientEntry, serverFnTransportErrorClientRuntime, } from "./entries/client.js";
|
|
36
36
|
import { transformFarmRouteActionClients } from "./route-action-transform.js";
|
|
37
37
|
import { createFarmServerFnBoundaryModule, isFarmServerFnBoundaryId, transformFarmServerFns, } from "./server-fn-transform.js";
|
|
38
38
|
import { transformAutomaticOptimizedBoundaries } from "./automatic-optimized-boundary.js";
|
|
@@ -57,7 +57,7 @@ const { farmMiddlewarePlugin } = require_("@farm.js/core/middleware");
|
|
|
57
57
|
const { resolveServerActionsConfig, validateServerActionRequest, createServerActionRequestErrorResponse, } = require_("@farm.js/core/server-action-security");
|
|
58
58
|
const { normalizeFarmDeploymentId } = require_("@farm.js/core/deployment");
|
|
59
59
|
const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers, resolveFarmMCPConfig, resolveFarmMCPPlugin, } = require_("@farm.js/core/server");
|
|
60
|
-
const { readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, createDefaultErrorMarkup, resolveFarmLlmsTxtConfig, } = require_("@farm.js/core/internal/production-runtime");
|
|
60
|
+
const { readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, createDefaultErrorMarkup, resolveFarmLlmsTxtConfig, resolveFarmAgentSitemap, } = require_("@farm.js/core/internal/production-runtime");
|
|
61
61
|
const { isFarmAPIPathname } = require_("@farm.js/core/api/runtime");
|
|
62
62
|
const { resolveFarmAPIConfig, resolveFarmAPIServerBasePath } = require_("@farm.js/core/api");
|
|
63
63
|
const { getResolvedEnv } = require_("@farm.js/core/env");
|
|
@@ -87,6 +87,7 @@ export function defineConfig(config = {}) {
|
|
|
87
87
|
layers: config.layers,
|
|
88
88
|
outDir: config.outDir ?? "dist",
|
|
89
89
|
basePath: config.basePath ?? "/",
|
|
90
|
+
trailingSlash: config.trailingSlash,
|
|
90
91
|
api: config.api,
|
|
91
92
|
serverActions: config.serverActions,
|
|
92
93
|
deploymentId: config.deploymentId,
|
|
@@ -850,6 +851,10 @@ export default function farmRsc(options = {}) {
|
|
|
850
851
|
// runtime cannot see from module exports: the same baked input core's server merges.
|
|
851
852
|
// Later roots override earlier ones, as the entry's merged page map does.
|
|
852
853
|
const pageRenderingDirectives = {};
|
|
854
|
+
// Core's default for an app without docs, as for llms.txt: the sitemap is on.
|
|
855
|
+
const sitemap = resolveFarmAgentSitemap(c.agent?.sitemap ?? true);
|
|
856
|
+
// Each page file's last change, for the sitemap's lastmod, as core's build reads it.
|
|
857
|
+
const pageLastModified = {};
|
|
853
858
|
for (const source of getFarmSourceRoots(c)) {
|
|
854
859
|
const routesRoot = path.resolve(root, source.srcDir, configuredRoutesDir);
|
|
855
860
|
for (const { key, file } of await findRouteFiles(routesRoot, (name) => PAGE_FILE.test(name))) {
|
|
@@ -858,6 +863,13 @@ export default function farmRsc(options = {}) {
|
|
|
858
863
|
pageRenderingDirectives[key] = directive;
|
|
859
864
|
else
|
|
860
865
|
delete pageRenderingDirectives[key];
|
|
866
|
+
if (sitemap.enabled) {
|
|
867
|
+
const modified = await fs.stat(file).then((stat) => stat.mtime.toISOString(), () => undefined);
|
|
868
|
+
if (modified)
|
|
869
|
+
pageLastModified[key] = modified;
|
|
870
|
+
else
|
|
871
|
+
delete pageLastModified[key];
|
|
872
|
+
}
|
|
861
873
|
}
|
|
862
874
|
}
|
|
863
875
|
// Root layouts that render <html> own the document (Next.js's root layout contract).
|
|
@@ -891,6 +903,22 @@ export default function farmRsc(options = {}) {
|
|
|
891
903
|
if (env.command === "build" && mobileClient !== "entry") {
|
|
892
904
|
removeFarmRscMobileClientManifest(root);
|
|
893
905
|
}
|
|
906
|
+
// Resolved the same way core resolves it for the config, so RSC and
|
|
907
|
+
// non-RSC apps match middleware against the same pathname.
|
|
908
|
+
const i18n = resolveFarmI18nConfig(c.i18n, {
|
|
909
|
+
root,
|
|
910
|
+
mode: env.command === "serve" ? "development" : "production",
|
|
911
|
+
basePath: c.basePath ?? "/",
|
|
912
|
+
});
|
|
913
|
+
// A build inlines the catalogs, read and validated as core's build reads them (a strict
|
|
914
|
+
// mismatch fails the build), so the server needs no catalog files.
|
|
915
|
+
let i18nCatalogs;
|
|
916
|
+
if (i18n.enabled && env.command === "build") {
|
|
917
|
+
const { createFarmI18nRuntime } = require_("@farm.js/core/i18n/server");
|
|
918
|
+
const catalogRuntime = createFarmI18nRuntime(i18n);
|
|
919
|
+
await catalogRuntime.initialize();
|
|
920
|
+
i18nCatalogs = catalogRuntime.getCatalogs();
|
|
921
|
+
}
|
|
894
922
|
// Development always optimizes with Sharp, as core's dev server does.
|
|
895
923
|
const imageRuntime = env.command === "serve"
|
|
896
924
|
? imageConfig.provider === "none"
|
|
@@ -911,6 +939,7 @@ export default function farmRsc(options = {}) {
|
|
|
911
939
|
srcDir,
|
|
912
940
|
outDir,
|
|
913
941
|
basePath: c.basePath ?? "/",
|
|
942
|
+
trailingSlash: c.trailingSlash === true,
|
|
914
943
|
apiBasePath: resolveFarmAPIServerBasePath(api),
|
|
915
944
|
routesDir: options.routesDir,
|
|
916
945
|
globalCssPath,
|
|
@@ -925,13 +954,10 @@ export default function farmRsc(options = {}) {
|
|
|
925
954
|
markdown: resolveMarkdownConfig(c.md),
|
|
926
955
|
// Core's default for an app without docs: llms.txt on, llms-full.txt off.
|
|
927
956
|
llmsTxt: resolveFarmLlmsTxtConfig(c.agent?.llmsTxt ?? { full: false }),
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
i18n
|
|
931
|
-
|
|
932
|
-
mode: env.command === "serve" ? "development" : "production",
|
|
933
|
-
basePath: c.basePath ?? "/",
|
|
934
|
-
}),
|
|
957
|
+
sitemap,
|
|
958
|
+
...(sitemap.enabled ? { pageLastModified } : {}),
|
|
959
|
+
i18n,
|
|
960
|
+
...(i18nCatalogs ? { i18nCatalogs } : {}),
|
|
935
961
|
server: { trustProxy: resolveFarmServerConfig(c.server).trustProxy },
|
|
936
962
|
middlewareConfigPaths,
|
|
937
963
|
pluginsConfigPaths,
|
|
@@ -1136,6 +1162,7 @@ export default function farmRsc(options = {}) {
|
|
|
1136
1162
|
"react-dom/client",
|
|
1137
1163
|
"rsc-html-stream/client",
|
|
1138
1164
|
...CLIENT_ENTRY_CORE_IMPORTS,
|
|
1165
|
+
...(i18n.enabled ? CLIENT_ENTRY_I18N_IMPORTS : []),
|
|
1139
1166
|
// Client components and the packages they use load only once a page renders
|
|
1140
1167
|
// (client references), so they would be found late too.
|
|
1141
1168
|
...clientOptimizeDeps.include,
|
package/dist/rsc/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { FarmMarkdownResolvedConfig } from "@farm.js/core/markdown";
|
|
2
|
-
import type { ResolvedFarmLlmsTxtConfig } from "@farm.js/core/internal/production-runtime";
|
|
3
|
-
import type { ResolvedFarmI18nConfig } from "@farm.js/core/i18n";
|
|
2
|
+
import type { ResolvedFarmAgentSitemap, ResolvedFarmLlmsTxtConfig } from "@farm.js/core/internal/production-runtime";
|
|
3
|
+
import type { FarmI18nCatalogs, ResolvedFarmI18nConfig } from "@farm.js/core/i18n";
|
|
4
4
|
import type { FarmServerActionsConfig, ResolvedFarmServerActionsConfig } from "@farm.js/core/server-action-security";
|
|
5
5
|
/**
|
|
6
6
|
* Configuration options for the Farm.js RSC plugin.
|
|
@@ -96,6 +96,11 @@ export interface EntryContext {
|
|
|
96
96
|
outDir: string;
|
|
97
97
|
/** Base URL path, e.g. '/' */
|
|
98
98
|
basePath: string;
|
|
99
|
+
/**
|
|
100
|
+
* Core's `trailingSlash`: pages answer at `/about/` instead of `/about`, and `<Link>` renders
|
|
101
|
+
* that URL. Either way a page's other spelling redirects (308) to it.
|
|
102
|
+
*/
|
|
103
|
+
trailingSlash?: boolean;
|
|
99
104
|
/** Resolved same-origin mount for canonical /api routes. */
|
|
100
105
|
apiBasePath?: string;
|
|
101
106
|
/** Route files subdirectory within srcDir */
|
|
@@ -145,6 +150,11 @@ export interface EntryContext {
|
|
|
145
150
|
* matches a `/dashboard` middleware.
|
|
146
151
|
*/
|
|
147
152
|
i18n?: ResolvedFarmI18nConfig;
|
|
153
|
+
/**
|
|
154
|
+
* The i18n catalogs a build inlines, read and validated as core's build reads them, so the
|
|
155
|
+
* server needs no catalog files. Development reads them from disk instead.
|
|
156
|
+
*/
|
|
157
|
+
i18nCatalogs?: FarmI18nCatalogs;
|
|
148
158
|
/**
|
|
149
159
|
* Server settings the request path needs. `trustProxy` decides whether
|
|
150
160
|
* forwarded headers are believed when middleware reads the client address.
|
|
@@ -166,6 +176,10 @@ export interface EntryContext {
|
|
|
166
176
|
markdown?: FarmMarkdownResolvedConfig;
|
|
167
177
|
/** Resolved `agent.llmsTxt`: the generated `/llms.txt` and `/llms-full.txt`. */
|
|
168
178
|
llmsTxt?: ResolvedFarmLlmsTxtConfig;
|
|
179
|
+
/** Resolved `agent.sitemap`: the generated `/sitemap.xml`. */
|
|
180
|
+
sitemap?: ResolvedFarmAgentSitemap;
|
|
181
|
+
/** Route-relative page keys to their file's last change (ISO), the sitemap's lastmod. */
|
|
182
|
+
pageLastModified?: Record<string, string>;
|
|
169
183
|
/** Whether debug mode is enabled */
|
|
170
184
|
debug: boolean;
|
|
171
185
|
/** True only for the Vite serve command, never for a production build. */
|
package/dist/rsc/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/rsc/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/rsc/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EAC1B,MAAM,2CAA2C,CAAC;AACnD,OAAO,KAAK,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACnF,OAAO,KAAK,EACV,uBAAuB,EACvB,+BAA+B,EAChC,MAAM,sCAAsC,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,yDAAyD;IACzD,aAAa,CAAC,EAAE,uBAAuB,CAAC;IAExC,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;OAIG;IACH,OAAO,CAAC,EAAE;QACR,wCAAwC;QACxC,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,wCAAwC;QACxC,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,2CAA2C;QAC3C,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;IAEF;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,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": "@farm.js/plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.69",
|
|
4
4
|
"description": "Official plugins for Farm.js framework",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Farm.js Team",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"nitro": "3.0.260903-beta",
|
|
64
64
|
"picocolors": "^1.0.0",
|
|
65
65
|
"rsc-html-stream": "^0.0.4",
|
|
66
|
-
"@farm.js/core": "0.1.
|
|
66
|
+
"@farm.js/core": "0.1.69"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
69
|
"@types/node": "^22.20.5",
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"react-dom": "19.2.8",
|
|
85
85
|
"react-server-dom-webpack": "19.2.8",
|
|
86
86
|
"vite": ">=6.0.0",
|
|
87
|
-
"@farm.js/core": "0.1.
|
|
87
|
+
"@farm.js/core": "0.1.69"
|
|
88
88
|
},
|
|
89
89
|
"peerDependenciesMeta": {
|
|
90
90
|
"@vitejs/plugin-rsc": {
|