@farm.js/plugin 0.1.61 → 0.1.62
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/middleware/index.d.ts +8 -1
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/middleware/index.js +16 -10
- package/dist/middleware/matching.d.ts +4 -2
- package/dist/middleware/matching.d.ts.map +1 -1
- package/dist/middleware/matching.js +7 -47
- package/dist/rsc/client-sourcemaps.d.ts +13 -0
- package/dist/rsc/client-sourcemaps.d.ts.map +1 -0
- package/dist/rsc/client-sourcemaps.js +52 -0
- package/dist/rsc/document-layouts.d.ts +16 -0
- package/dist/rsc/document-layouts.d.ts.map +1 -0
- package/dist/rsc/document-layouts.js +82 -0
- package/dist/rsc/entries/client.d.ts.map +1 -1
- package/dist/rsc/entries/client.js +92 -16
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +563 -45
- package/dist/rsc/entries/ssr.d.ts.map +1 -1
- package/dist/rsc/entries/ssr.js +7 -6
- package/dist/rsc/index.d.ts +38 -3
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +282 -292
- package/dist/rsc/middleware-config-module.d.ts +3 -0
- package/dist/rsc/middleware-config-module.d.ts.map +1 -1
- package/dist/rsc/middleware-config-module.js +41 -28
- package/dist/rsc/mobile-client.d.ts +67 -0
- package/dist/rsc/mobile-client.d.ts.map +1 -0
- package/dist/rsc/mobile-client.js +148 -0
- package/dist/rsc/nitro-build.d.ts.map +1 -1
- package/dist/rsc/nitro-build.js +268 -81
- package/dist/rsc/server-fn-transform.d.ts +1 -5
- package/dist/rsc/server-fn-transform.d.ts.map +1 -1
- package/dist/rsc/server-fn-transform.js +3 -338
- package/dist/rsc/types.d.ts +39 -0
- package/dist/rsc/types.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.d.ts +2 -0
- package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.js +12 -2
- package/package.json +3 -3
package/dist/rsc/entries/rsc.js
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER } from "../mobile-client.js";
|
|
3
|
+
const require_ = createRequire(import.meta.url);
|
|
4
|
+
/** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
|
|
5
|
+
function generateMCPPluginSource() {
|
|
6
|
+
const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
|
|
7
|
+
return generateNativeMCPPluginSource({ enabled: true });
|
|
8
|
+
}
|
|
1
9
|
/**
|
|
2
10
|
* Generates the terminal middleware-result handling shared by the RSC entry
|
|
3
11
|
* and its executable contract tests.
|
|
@@ -46,11 +54,17 @@ export function generateRscEntry(ctx) {
|
|
|
46
54
|
const middlewareConfigImports = (ctx.middlewareConfigPaths ?? [])
|
|
47
55
|
.map((configPath, index) => `import * as FarmMiddlewareConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
|
|
48
56
|
.join("\n");
|
|
57
|
+
const mcpConfigImports = (ctx.mcpConfigPaths ?? [])
|
|
58
|
+
.map((configPath, index) => `import * as FarmMCPConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
|
|
59
|
+
.join("\n");
|
|
60
|
+
const mcpSource = ctx.mcpConfigPaths?.length ? generateMCPPluginSource() : null;
|
|
49
61
|
const middlewareConfigValues = (ctx.middlewareConfigPaths ?? []).map((_configPath, index) => `(FarmMiddlewareConfigModule${index}.default || FarmMiddlewareConfigModule${index})`);
|
|
50
62
|
let code = `
|
|
51
63
|
import React from 'react';
|
|
52
64
|
import ServerErrorFallback from '/.farm/rsc-entries/error-fallback.tsx';
|
|
53
65
|
${middlewareConfigImports}
|
|
66
|
+
${mcpConfigImports}
|
|
67
|
+
${mcpSource ? `${mcpSource.importSource}\nimport { mergePluginAPIRoutes } from '@farm.js/core/api/runtime';` : ""}
|
|
54
68
|
import { registerAPIRouteShape } from '@farm.js/core/api/runtime';
|
|
55
69
|
import {
|
|
56
70
|
renderToReadableStream,
|
|
@@ -76,7 +90,8 @@ import {
|
|
|
76
90
|
applyProductionMiddlewareHeaders,
|
|
77
91
|
createProductionMiddlewareRunner,
|
|
78
92
|
} from '@farm.js/core/middleware';
|
|
79
|
-
import {
|
|
93
|
+
import { _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
|
|
94
|
+
${ctx.mobileClient === "entry" ? "import { _applyFarmMobileShellClient } from '@farm.js/core/internal/production-runtime';\n" : ""}import {
|
|
80
95
|
getAllowedAPIRouteMethods,
|
|
81
96
|
invokeAPIRouteEndpoint,
|
|
82
97
|
isFarmAPIPathname,
|
|
@@ -91,10 +106,69 @@ import {
|
|
|
91
106
|
compareRouteSpecificity,
|
|
92
107
|
getRoutePatternSpecificity,
|
|
93
108
|
} from '@farm.js/core/internal/production-runtime';
|
|
109
|
+
import {
|
|
110
|
+
appMiddlewareMayHandlePath,
|
|
111
|
+
configMiddlewareMayHandlePath,
|
|
112
|
+
materializeSSGRoutePath,
|
|
113
|
+
mergeMetadata,
|
|
114
|
+
mergeModuleViewport,
|
|
115
|
+
mergeRouteRenderingDirectiveConfig,
|
|
116
|
+
renderMetadataHead,
|
|
117
|
+
resolveMetadataTitle,
|
|
118
|
+
} from '@farm.js/core/internal/production-runtime';
|
|
119
|
+
|
|
120
|
+
import {
|
|
121
|
+
FARM_MARKDOWN_CONTENT_TYPE,
|
|
122
|
+
applyMarkdownNegotiationHeaders,
|
|
123
|
+
createFarmMarkdownErrorBody,
|
|
124
|
+
createMarkdownMirrorResponse,
|
|
125
|
+
farmRequestWantsMarkdown,
|
|
126
|
+
} from '@farm.js/core/markdown';
|
|
94
127
|
|
|
128
|
+
${ctx.images && ctx.images.runtime !== "none"
|
|
129
|
+
? `import { createCloudflareImageTransformer, createFarmImageHandler } from '@farm.js/core/image/server';
|
|
130
|
+
${ctx.images.runtime === "node"
|
|
131
|
+
? "import { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } from '@farm.js/core/image/sharp';"
|
|
132
|
+
: ""}
|
|
133
|
+
const farmImageConfig = ${JSON.stringify(ctx.images.config)};
|
|
134
|
+
const farmImageHandler = createFarmImageHandler(farmImageConfig, ${ctx.images.runtime === "cloudflare"
|
|
135
|
+
? `{
|
|
136
|
+
transform: createCloudflareImageTransformer(),
|
|
137
|
+
onError(error) { console.error('[Farm Image]', error); },
|
|
138
|
+
}`
|
|
139
|
+
: `{
|
|
140
|
+
transform: createSharpImageTransformer(),
|
|
141
|
+
fetchRemote: createNodeImageFetcher(farmImageConfig),
|
|
142
|
+
validateRemoteUrl: createNodeImageUrlValidator(farmImageConfig),
|
|
143
|
+
onError(error) { console.error('[Farm Image]', error); },
|
|
144
|
+
}`});`
|
|
145
|
+
: "const farmImageHandler = null;"}
|
|
146
|
+
const farmImagePath = ${JSON.stringify(ctx.images?.path ?? "/_farm/image")};
|
|
147
|
+
${ctx.images
|
|
148
|
+
? `// <Image> reads this when @farm.js/core/image is not bundled (dev, or an external dependency),
|
|
149
|
+
// where the __FARM_IMAGE_CONFIG__ define never reaches it. The SSR environment shares the process.
|
|
150
|
+
globalThis.__FARM_IMAGE_CONFIG__ = ${JSON.stringify(ctx.images.public)};`
|
|
151
|
+
: ""}
|
|
95
152
|
const farmDeploymentId = ${JSON.stringify(ctx.deploymentId)};
|
|
96
153
|
const farmApiBasePath = ${JSON.stringify(ctx.apiBasePath ?? "/api")};
|
|
154
|
+
const farmMarkdownConfig = ${JSON.stringify(ctx.markdown ?? { enabled: false, expose: [], cache: false, includeMetadata: true })};
|
|
97
155
|
`;
|
|
156
|
+
if (ctx.llmsTxt?.enabled) {
|
|
157
|
+
code += `import {
|
|
158
|
+
collectFarmLlmsTxtPages,
|
|
159
|
+
createFarmDefaultLlmsTxt,
|
|
160
|
+
createFarmLlmsFullRenderer,
|
|
161
|
+
createFarmLlmsMarkdownReader,
|
|
162
|
+
createFarmMetadataRouteResponse,
|
|
163
|
+
farmPathGuardCoversPage,
|
|
164
|
+
renderFarmLlmsFullTxt,
|
|
165
|
+
} from '@farm.js/core/internal/production-runtime';
|
|
166
|
+
import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
|
|
167
|
+
|
|
168
|
+
const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
|
|
169
|
+
const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
|
|
170
|
+
`;
|
|
171
|
+
}
|
|
98
172
|
if (ctx.actionsEnabled) {
|
|
99
173
|
code += `import {
|
|
100
174
|
createServerActionRequestErrorResponse,
|
|
@@ -106,6 +180,56 @@ const farmApiBasePath = ${JSON.stringify(ctx.apiBasePath ?? "/api")};
|
|
|
106
180
|
} from '@farm.js/core/server-action-security';
|
|
107
181
|
|
|
108
182
|
const serverActionSecurity = ${JSON.stringify(ctx.serverActions)};
|
|
183
|
+
`;
|
|
184
|
+
}
|
|
185
|
+
// In development, a page, layout, loading or error file that fails to load
|
|
186
|
+
// fails only the routes that use it. Eager globs would fail the whole entry,
|
|
187
|
+
// so every route returned the same error until the file was fixed. The
|
|
188
|
+
// modules still load once, in order, before the first request. Middleware
|
|
189
|
+
// and API routes stay eager: skipping a broken auth middleware would leave
|
|
190
|
+
// its routes unprotected. Production keeps eager globs, where a broken
|
|
191
|
+
// import already fails the build.
|
|
192
|
+
const isolateRouteModules = ctx.development === true;
|
|
193
|
+
const uiRouteGlob = (pattern) => isolateRouteModules
|
|
194
|
+
? `await loadFarmDevRouteModules(import.meta.glob(${JSON.stringify(pattern)}))`
|
|
195
|
+
: `import.meta.glob(${JSON.stringify(pattern)}, { eager: true })`;
|
|
196
|
+
if (isolateRouteModules) {
|
|
197
|
+
code += `
|
|
198
|
+
const farmRouteLoadErrors = new Map();
|
|
199
|
+
|
|
200
|
+
async function loadFarmDevRouteModules(loaders) {
|
|
201
|
+
const modules = {};
|
|
202
|
+
for (const [filePath, load] of Object.entries(loaders)) {
|
|
203
|
+
try {
|
|
204
|
+
modules[filePath] = await load();
|
|
205
|
+
} catch (error) {
|
|
206
|
+
console.error('[Farm.js] Could not load ' + filePath + ':', error);
|
|
207
|
+
const failed = {
|
|
208
|
+
default: function FarmRouteLoadFailure() {
|
|
209
|
+
throw error;
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
farmRouteLoadErrors.set(failed, error);
|
|
213
|
+
modules[filePath] = failed;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return modules;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The load error of a module the matched route renders with, if any. */
|
|
220
|
+
function findFarmRouteLoadError(matched) {
|
|
221
|
+
if (farmRouteLoadErrors.size === 0) return undefined;
|
|
222
|
+
const routeModules = [
|
|
223
|
+
pages[matched.pattern],
|
|
224
|
+
...getRouteModules(matched.pattern, layouts, 'layout'),
|
|
225
|
+
...getRouteModules(matched.pattern, loadings, 'loading'),
|
|
226
|
+
...getRouteModules(matched.pattern, errors, 'error'),
|
|
227
|
+
];
|
|
228
|
+
for (const module of routeModules) {
|
|
229
|
+
if (farmRouteLoadErrors.has(module)) return farmRouteLoadErrors.get(module);
|
|
230
|
+
}
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
109
233
|
`;
|
|
110
234
|
}
|
|
111
235
|
// Auto-discover pages, layouts, and middleware using Vite's glob import
|
|
@@ -132,14 +256,18 @@ function applyActionResponseHeaders(headers, request) {
|
|
|
132
256
|
headers.set('cache-control', 'no-store');
|
|
133
257
|
headers.set('x-content-type-options', 'nosniff');
|
|
134
258
|
}
|
|
259
|
+
// A page renders per request (cookies, headers, client address), so a shared
|
|
260
|
+
// cache must not keep its HTML or Flight payload unless middleware chose a
|
|
261
|
+
// policy. Core's server defaults pages the same way.
|
|
262
|
+
if (!headers.has('cache-control')) headers.set('cache-control', 'private, no-store');
|
|
135
263
|
}
|
|
136
264
|
|
|
137
265
|
// Auto-discover all route modules. Every glob remains a literal so Vite can analyze it.
|
|
138
266
|
${routeSourceRoots
|
|
139
|
-
.map((root, index) => `const pages${index} =
|
|
140
|
-
const layouts${index} =
|
|
141
|
-
const loadings${index} =
|
|
142
|
-
const errors${index} =
|
|
267
|
+
.map((root, index) => `const pages${index} = ${uiRouteGlob(`${root.glob}/**/page.{tsx,jsx,ts,js}`)};
|
|
268
|
+
const layouts${index} = ${uiRouteGlob(`${root.glob}/**/layout.{tsx,jsx,ts,js}`)};
|
|
269
|
+
const loadings${index} = ${uiRouteGlob(`${root.glob}/**/loading.{tsx,jsx,ts,js}`)};
|
|
270
|
+
const errors${index} = ${uiRouteGlob(`${root.glob}/**/error.{tsx,jsx,ts,js}`)};
|
|
143
271
|
const middlewares${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/middleware.{tsx,jsx,ts,js}`)}, { eager: true });
|
|
144
272
|
const apiRouteModules${index} = import.meta.glob(${JSON.stringify(`${root.glob}/api/**/route.{tsx,jsx,ts,js}`)}, { eager: true });
|
|
145
273
|
const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.sourceGlob === root.glob
|
|
@@ -192,6 +320,14 @@ const pages = mergeRouteModules([${routeRoots
|
|
|
192
320
|
const layouts = mergeRouteModules([${routeRoots
|
|
193
321
|
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: layouts${index} }`)
|
|
194
322
|
.join(", ")}]);
|
|
323
|
+
// Root layouts that render <html> themselves own the document, as in Next.js.
|
|
324
|
+
const farmDocumentLayoutKeys = new Set(${JSON.stringify(ctx.documentLayouts ?? [])});
|
|
325
|
+
const farmDocumentLayoutModules = new Set(
|
|
326
|
+
Object.entries(layouts)
|
|
327
|
+
.filter(([key]) => farmDocumentLayoutKeys.has(key))
|
|
328
|
+
.map(([, module]) => module),
|
|
329
|
+
);
|
|
330
|
+
|
|
195
331
|
const loadings = mergeRouteModules([${routeRoots
|
|
196
332
|
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: loadings${index} }`)
|
|
197
333
|
.join(", ")}]);
|
|
@@ -283,7 +419,42 @@ function registerApiRouteSources(fileModules, definitionModules, sourceCount) {
|
|
|
283
419
|
}
|
|
284
420
|
|
|
285
421
|
registerApiRouteSources(apiRouteModules, routeDefinitionModules, ${routeSourceRoots.length});
|
|
286
|
-
|
|
422
|
+
${mcpSource
|
|
423
|
+
? `
|
|
424
|
+
// mcp: the same plugin core's production server mounts, built from the mcp
|
|
425
|
+
// config read from each config file, layers first.
|
|
426
|
+
const farmNativeMCPPlugin = (() => {
|
|
427
|
+
const farmRuntimeConfigs = [${(ctx.mcpConfigPaths ?? [])
|
|
428
|
+
.map((_path, index) => `(FarmMCPConfigModule${index}.default || FarmMCPConfigModule${index})`)
|
|
429
|
+
.join(", ")}];
|
|
430
|
+
${mcpSource.registerSource}
|
|
431
|
+
return farmNativeMCPPlugin;
|
|
432
|
+
})();
|
|
433
|
+
if (farmNativeMCPPlugin) {
|
|
434
|
+
const mountedRoutes = [...apiRouteMap.values()].map((route) => ({
|
|
435
|
+
path: route.path,
|
|
436
|
+
methods: [...route.methods],
|
|
437
|
+
endpoints: { ...route.handlers },
|
|
438
|
+
}));
|
|
439
|
+
// Rejects a plugin route that would replace an app endpoint. An MCP tool calls its
|
|
440
|
+
// endpoint through handler(), so the middleware guarding that path runs for it.
|
|
441
|
+
for (const route of mergePluginAPIRoutes(mountedRoutes, [farmNativeMCPPlugin], undefined, {
|
|
442
|
+
dispatch: (request) => handler(request),
|
|
443
|
+
})) {
|
|
444
|
+
for (const method of route.pluginMethods ?? []) {
|
|
445
|
+
let target = apiRouteMap.get(route.path);
|
|
446
|
+
if (!target) {
|
|
447
|
+
target = { path: route.path, methods: [], handlers: {}, files: {}, sources: {} };
|
|
448
|
+
apiRouteMap.set(route.path, target);
|
|
449
|
+
}
|
|
450
|
+
target.methods.push(method);
|
|
451
|
+
target.handlers[method] = route.endpoints[method];
|
|
452
|
+
target.files[method] = 'plugin:' + farmNativeMCPPlugin.name;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
`
|
|
457
|
+
: ""}
|
|
287
458
|
async function handleAPIRequest(request) {
|
|
288
459
|
const url = new URL(request.url);
|
|
289
460
|
const match = matchAPIRouteAtBasePath(apiRouteMap, url.pathname, farmApiBasePath);
|
|
@@ -331,9 +502,20 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
|
|
|
331
502
|
.filter((entry) => entry.path !== null)
|
|
332
503
|
// Root first, as core runs them: a nested guard can rely on what its
|
|
333
504
|
// parent middleware set, and glob order is alphabetical, not by depth.
|
|
334
|
-
|
|
505
|
+
// Route groups share a URL path; the shallower file runs first, so
|
|
506
|
+
// '/middleware.ts' precedes '/(app)/middleware.ts'.
|
|
507
|
+
.sort(
|
|
508
|
+
(left, right) =>
|
|
509
|
+
middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path) ||
|
|
510
|
+
left.path.localeCompare(right.path) ||
|
|
511
|
+
middlewareRouteDepth(left.filePath) - middlewareRouteDepth(right.filePath) ||
|
|
512
|
+
left.filePath.localeCompare(right.filePath),
|
|
513
|
+
),
|
|
335
514
|
i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
|
|
336
515
|
server: ${JSON.stringify(ctx.server) ?? "undefined"},
|
|
516
|
+
apiBasePath: farmApiBasePath,
|
|
517
|
+
// matchRoute() reads url.pathname as received, so middleware guards that path too.
|
|
518
|
+
rawPathRouting: true,
|
|
337
519
|
});
|
|
338
520
|
|
|
339
521
|
debug('Discovered pages:', Object.keys(pages));
|
|
@@ -346,22 +528,37 @@ debug('Discovered API routes:', Array.from(apiRouteMap.keys()));
|
|
|
346
528
|
/**
|
|
347
529
|
* Convert an app-relative middleware file path to the route it guards, with the
|
|
348
530
|
* same rules as core's middleware discovery: a route group such as
|
|
349
|
-
* '(protected)'
|
|
531
|
+
* '(protected)' or a parallel route slot such as '@team' adds no URL segment,
|
|
532
|
+
* an intercepting folder guards the URL it intercepts, a '_private' folder
|
|
533
|
+
* routes its pages so its middleware guards them, and a dot-prefixed folder
|
|
350
534
|
* holds no routes, so its middleware never runs (null).
|
|
351
535
|
* e.g., '/middleware.ts' -> '/'
|
|
352
536
|
* e.g., '/(protected)/dashboard/middleware.ts' -> '/dashboard'
|
|
537
|
+
* e.g., '/dashboard/@team/middleware.ts' -> '/dashboard'
|
|
538
|
+
* e.g., '/feed/@modal/(.)photo/middleware.ts' -> '/feed/photo'
|
|
353
539
|
*/
|
|
354
540
|
function middlewarePathToRoute(filePath) {
|
|
355
541
|
const segments = filePath
|
|
356
542
|
.replace(/\\/middleware\\.[tj]sx?$/, '')
|
|
357
543
|
.split('/')
|
|
358
544
|
.filter(Boolean);
|
|
359
|
-
if (segments.some((segment) => segment.startsWith('
|
|
545
|
+
if (segments.some((segment) => segment.startsWith('.'))) {
|
|
360
546
|
return null;
|
|
361
547
|
}
|
|
362
|
-
const routeSegments =
|
|
363
|
-
|
|
364
|
-
|
|
548
|
+
const routeSegments = [];
|
|
549
|
+
for (const segment of segments) {
|
|
550
|
+
const marker = /^((?:\\(\\.\\.\\))+|\\(\\.\\.\\.\\)|\\(\\.\\))(.*)$/.exec(segment);
|
|
551
|
+
if (marker) {
|
|
552
|
+
if (marker[1] === '(...)') routeSegments.length = 0;
|
|
553
|
+
else if (marker[1] !== '(.)') routeSegments.splice(-(marker[1].length / 4));
|
|
554
|
+
if (marker[2]) routeSegments.push(marker[2]);
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if ((segment.startsWith('(') && segment.endsWith(')')) || /^@[A-Za-z][A-Za-z0-9_-]*$/.test(segment)) {
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
routeSegments.push(segment);
|
|
561
|
+
}
|
|
365
562
|
return routeSegments.length === 0 ? '/' : '/' + routeSegments.join('/');
|
|
366
563
|
}
|
|
367
564
|
|
|
@@ -420,7 +617,12 @@ const RouteErrorBoundary = React.Component
|
|
|
420
617
|
|
|
421
618
|
// Parse and rank once per entry initialization, not on every request. Use the
|
|
422
619
|
// same validation, decoding and specificity rules as Farm's ordinary router.
|
|
423
|
-
|
|
620
|
+
// RSC renders no parallel route slots, so a page inside '@modal/...' would otherwise
|
|
621
|
+
// answer at its literal folder path ('/feed/@modal/(.)photo/1'), past the middleware
|
|
622
|
+
// that guards the URL it intercepts.
|
|
623
|
+
const pageRoutes = Object.entries(pages)
|
|
624
|
+
.filter(([filePath]) => !filePath.split('/').some((segment) => /^@[A-Za-z][A-Za-z0-9_-]*$/.test(segment)))
|
|
625
|
+
.map(([filePath, module]) => ({
|
|
424
626
|
filePath,
|
|
425
627
|
module,
|
|
426
628
|
segments: parseRoutePath(filePath).segments,
|
|
@@ -443,7 +645,7 @@ function matchRoute(pathname) {
|
|
|
443
645
|
Page: module.default,
|
|
444
646
|
pattern: filePath,
|
|
445
647
|
params: match.params,
|
|
446
|
-
|
|
648
|
+
module,
|
|
447
649
|
};
|
|
448
650
|
}
|
|
449
651
|
}
|
|
@@ -452,13 +654,77 @@ function matchRoute(pathname) {
|
|
|
452
654
|
return null;
|
|
453
655
|
}
|
|
454
656
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
657
|
+
// Each page's parsed rendering directive and whether its source reads request state, baked by
|
|
658
|
+
// the build because module exports cannot tell.
|
|
659
|
+
const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives ?? {})};
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* The URL paths the build prerenders, by core's SSG rules: a page asks to be static
|
|
663
|
+
* (dynamic = "force-static", generateStaticParams, "use ssg"), does not read request
|
|
664
|
+
* state, and does not revalidate. A prerendered page is a static file the server never sees, so a
|
|
665
|
+
* path any middleware may handle stays server-rendered.
|
|
666
|
+
*/
|
|
667
|
+
async function collectFarmStaticPages() {
|
|
668
|
+
${ctx.i18n?.enabled
|
|
669
|
+
? `console.info('[Farm.js] Prerendering is off: i18n resolves the locale per request.');
|
|
670
|
+
return [];`
|
|
671
|
+
: ""}
|
|
672
|
+
const middlewareRoutes = Object.keys(middlewares)
|
|
673
|
+
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
674
|
+
.filter((route) => route.path !== null);
|
|
675
|
+
const paths = new Set();
|
|
676
|
+
for (const { filePath, module, segments } of pageRoutes) {
|
|
677
|
+
const rendering = mergeRouteRenderingDirectiveConfig(farmPageRenderingDirectives[filePath], module);
|
|
678
|
+
if (!rendering.ssg || rendering.revalidate !== undefined) continue;
|
|
679
|
+
const pattern = '/' + segments
|
|
680
|
+
.map((part) => part.isCatchAll
|
|
681
|
+
? (part.isOptional ? '[[...' + part.segment + ']]' : '[...' + part.segment + ']')
|
|
682
|
+
: part.isDynamic ? '[' + part.segment + ']' : part.segment)
|
|
683
|
+
.join('/');
|
|
684
|
+
let pagePaths;
|
|
685
|
+
try {
|
|
686
|
+
if (!segments.some((part) => part.isDynamic)) {
|
|
687
|
+
pagePaths = [pattern];
|
|
688
|
+
} else {
|
|
689
|
+
const getStaticPaths = module.getStaticPaths || module.generateStaticParams;
|
|
690
|
+
if (typeof getStaticPaths !== 'function') {
|
|
691
|
+
throw new Error('a static route with dynamic segments needs generateStaticParams()');
|
|
692
|
+
}
|
|
693
|
+
pagePaths = (await getStaticPaths()).map((params) => materializeSSGRoutePath(pattern, params));
|
|
694
|
+
}
|
|
695
|
+
} catch (error) {
|
|
696
|
+
console.error('[Farm.js] Rendering ' + filePath + ' on each request: could not list its static paths.', error);
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
for (const pagePath of pagePaths) {
|
|
700
|
+
if (
|
|
701
|
+
appMiddlewareMayHandlePath(middlewareRoutes, pagePath) ||
|
|
702
|
+
configMiddlewareMayHandlePath(farmConfigMiddleware, pagePath)
|
|
703
|
+
) {
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
paths.add(pagePath);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return [...paths];
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// The route's metadata as core's server resolves it: layouts root to leaf, then the page, each
|
|
713
|
+
// module's \`metadata\`, \`generateMetadata()\` and viewport exports merged in order.
|
|
714
|
+
async function resolveFarmRouteMetadata(layoutModules, pageModule, pageProps) {
|
|
715
|
+
let metadata = {};
|
|
716
|
+
for (const layoutModule of layoutModules) {
|
|
717
|
+
metadata = mergeMetadata(metadata, layoutModule.metadata);
|
|
718
|
+
if (typeof layoutModule.generateMetadata === 'function') {
|
|
719
|
+
metadata = mergeMetadata(metadata, await layoutModule.generateMetadata({ params: pageProps.params }));
|
|
720
|
+
}
|
|
721
|
+
metadata = await mergeModuleViewport(metadata, layoutModule, { params: pageProps.params });
|
|
460
722
|
}
|
|
461
|
-
|
|
723
|
+
metadata = mergeMetadata(metadata, pageModule?.metadata);
|
|
724
|
+
if (typeof pageModule?.generateMetadata === 'function') {
|
|
725
|
+
metadata = mergeMetadata(metadata, await pageModule.generateMetadata(pageProps));
|
|
726
|
+
}
|
|
727
|
+
return mergeModuleViewport(metadata, pageModule ?? {}, pageProps);
|
|
462
728
|
}
|
|
463
729
|
|
|
464
730
|
/**
|
|
@@ -499,6 +765,14 @@ function getLayoutModules(pageFilePath) {
|
|
|
499
765
|
return getRouteModules(pageFilePath, layouts, 'layout');
|
|
500
766
|
}
|
|
501
767
|
|
|
768
|
+
// Flight keeps only the digest onError returns for a server error. A notFound() or redirect() keeps
|
|
769
|
+
// its own, so the request handler still answers 404 or the redirect; other errors are logged as
|
|
770
|
+
// React's default handler logs them.
|
|
771
|
+
function farmRscOnError(error) {
|
|
772
|
+
if (getFarmRedirectError(error) || isFarmNotFoundError(error)) return error.digest;
|
|
773
|
+
console.error(error);
|
|
774
|
+
}
|
|
775
|
+
|
|
502
776
|
function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
503
777
|
// Before page selection (for example, middleware failure), only the root
|
|
504
778
|
// boundary applies. Do not guess a route from a partially processed URL.
|
|
@@ -509,8 +783,19 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
|
509
783
|
/**
|
|
510
784
|
* Main request handler - entry point for both dev and production (Nitro).
|
|
511
785
|
* Exported as { fetch: handler } for the RSC/Nitro contract (see vite-plugin-rsc-deploy-example).
|
|
786
|
+
*
|
|
787
|
+
* Middleware that let a request through may have been a guard: an IP allowlist, an API key
|
|
788
|
+
* header, a VPN header. A CDN keys its copy by URL and never runs the guard on a hit, so
|
|
789
|
+
* whatever such a request answers stays out of shared caches, as in core's server. Only
|
|
790
|
+
* middleware declaring cache: "public" leaves the policy alone.
|
|
512
791
|
*/
|
|
513
792
|
async function handleFarmRequest(request, context) {
|
|
793
|
+
const farmCacheGuard = { guarded: false };
|
|
794
|
+
const response = await resolveFarmRequest(farmCacheGuard, request, context);
|
|
795
|
+
return farmCacheGuard.guarded ? _withFarmGuardedResponseCache(response) : response;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
514
799
|
let url = new URL(request.url);
|
|
515
800
|
let matchedPage = null;
|
|
516
801
|
let errorData = new Map();
|
|
@@ -550,6 +835,7 @@ async function handleFarmRequest(request, context) {
|
|
|
550
835
|
// Execute middleware first
|
|
551
836
|
const middlewareResult = await executeMiddleware(request, context);
|
|
552
837
|
${generateRscMiddlewareResultHandling()}
|
|
838
|
+
if (middlewareResult.guarded) farmCacheGuard.guarded = true;
|
|
553
839
|
|
|
554
840
|
request = middlewareResult.request;
|
|
555
841
|
url = new URL(request.url);
|
|
@@ -572,11 +858,21 @@ async function handleFarmRequest(request, context) {
|
|
|
572
858
|
_runWithMiddlewareContext(middlewareContext, async () => {
|
|
573
859
|
const glob = '';
|
|
574
860
|
|
|
861
|
+
if (farmImageHandler && url.pathname === farmImagePath) {
|
|
862
|
+
const imageResponse = await farmImageHandler(request);
|
|
863
|
+
if (imageResponse) return imageResponse;
|
|
864
|
+
}
|
|
865
|
+
|
|
575
866
|
const apiResponse = await handleAPIRequest(request.clone());
|
|
576
867
|
if (apiResponse) {
|
|
577
868
|
return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
|
|
578
869
|
}
|
|
579
|
-
|
|
870
|
+
${ctx.llmsTxt?.enabled
|
|
871
|
+
? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
|
|
872
|
+
const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
|
|
873
|
+
if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
|
|
874
|
+
`
|
|
875
|
+
: ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
580
876
|
return applyProductionMiddlewareHeaders(new Response(
|
|
581
877
|
JSON.stringify({ error: 'API route not found', pathname: url.pathname }),
|
|
582
878
|
{ status: 404, headers: { 'Content-Type': 'application/json' } },
|
|
@@ -696,12 +992,13 @@ async function handleFarmRequest(request, context) {
|
|
|
696
992
|
return new Response(null, { status: 499, headers: { 'Cache-Control': 'no-store' } });
|
|
697
993
|
}
|
|
698
994
|
// No client router here, so the redirect has to be a real HTTP
|
|
699
|
-
// redirect the browser follows on its own.
|
|
995
|
+
// redirect the browser follows on its own. 303 makes it a GET, as islands mode
|
|
996
|
+
// answers: a 307 or 308 would post the form again to the target.
|
|
700
997
|
const formRedirect = getFarmRedirectError(e);
|
|
701
998
|
if (formRedirect) {
|
|
702
999
|
debug('Form action redirected:', formRedirect.url);
|
|
703
1000
|
return new Response(null, {
|
|
704
|
-
status:
|
|
1001
|
+
status: 303,
|
|
705
1002
|
headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
|
|
706
1003
|
});
|
|
707
1004
|
}
|
|
@@ -731,15 +1028,26 @@ async function handleFarmRequest(request, context) {
|
|
|
731
1028
|
|
|
732
1029
|
if (!matched) {
|
|
733
1030
|
debug('404 - No route found for:', url.pathname);
|
|
1031
|
+
// Agents that read in Markdown get a Markdown 404, as in core's server.
|
|
1032
|
+
if (farmMarkdownConfig.enabled && farmRequestWantsMarkdown(url.pathname, request.headers.get('accept'))) {
|
|
1033
|
+
return new Response(createFarmMarkdownErrorBody(404, url.pathname), {
|
|
1034
|
+
status: 404,
|
|
1035
|
+
headers: {
|
|
1036
|
+
'Content-Type': FARM_MARKDOWN_CONTENT_TYPE,
|
|
1037
|
+
'X-Farm-Markdown-Error': '404',
|
|
1038
|
+
'Cache-Control': 'no-store',
|
|
1039
|
+
},
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
734
1042
|
return new Response('Not Found', { status: 404 });
|
|
735
1043
|
}
|
|
736
1044
|
|
|
737
|
-
const { Page, pattern, params,
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
1045
|
+
const { Page, pattern, params, module: pageModule } = matched;
|
|
1046
|
+
${isolateRouteModules
|
|
1047
|
+
? `const routeLoadError = findFarmRouteLoadError(matched);
|
|
1048
|
+
if (routeLoadError) throw routeLoadError;
|
|
1049
|
+
`
|
|
1050
|
+
: ""}const LayoutModules = getLayoutModules(pattern);
|
|
743
1051
|
const configuredRoutesDir = ${ctx.routesDir === undefined ? "undefined" : JSON.stringify(ctx.routesDir)};
|
|
744
1052
|
const routesDir = configuredRoutesDir === undefined ? 'app' : configuredRoutesDir.trim();
|
|
745
1053
|
const routesPath = routesDir ? '/' + routesDir : '';
|
|
@@ -752,6 +1060,14 @@ async function handleFarmRequest(request, context) {
|
|
|
752
1060
|
|
|
753
1061
|
// Page props passed to components (includes middleware shared data)
|
|
754
1062
|
const pageProps = { params, searchParams, middlewareData };
|
|
1063
|
+
const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);
|
|
1064
|
+
const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
|
|
1065
|
+
// Injected into <head> by the SSR entry; React renders only the charset.
|
|
1066
|
+
const metadataHead =
|
|
1067
|
+
(renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
|
|
1068
|
+
renderedHead.viewport +
|
|
1069
|
+
renderedHead.tags;
|
|
1070
|
+
const metadataTitle = resolveMetadataTitle(metadata.title);
|
|
755
1071
|
|
|
756
1072
|
debug('Rendering page:', pattern, 'with props:', pageProps);
|
|
757
1073
|
|
|
@@ -797,26 +1113,36 @@ async function handleFarmRequest(request, context) {
|
|
|
797
1113
|
}
|
|
798
1114
|
}
|
|
799
1115
|
|
|
800
|
-
//
|
|
801
|
-
|
|
802
|
-
|
|
1116
|
+
// A root layout that renders <html> owns the document, as in Next.js: the head elements below
|
|
1117
|
+
// are hoisted into its <head> by React, and the browser hydrates the whole document.
|
|
1118
|
+
const ownsDocument =
|
|
1119
|
+
LayoutModules.length > 0 && farmDocumentLayoutModules.has(LayoutModules[0]);
|
|
1120
|
+
// Otherwise a single wrapper, so #root has exactly one child (avoids a duplicate block in the DOM).
|
|
1121
|
+
const rootInner = ownsDocument
|
|
1122
|
+
? h(
|
|
1123
|
+
React.Fragment,
|
|
1124
|
+
null,
|
|
1125
|
+
h('meta', { charSet: 'utf-8' }),
|
|
1126
|
+
layoutContent,
|
|
1127
|
+
)
|
|
1128
|
+
: h('div', { 'data-farm-root': 'true' }, layoutContent);
|
|
1129
|
+
// Build the full page. root = full document (for SSR). rootContent = what the browser hydrates.
|
|
803
1130
|
const payload = {
|
|
804
|
-
|
|
1131
|
+
ownsDocument,
|
|
1132
|
+
root: ownsDocument ? rootInner : h('html', null,
|
|
805
1133
|
h('head', null,
|
|
806
1134
|
h('meta', { charSet: 'utf-8' }),
|
|
807
|
-
h('
|
|
808
|
-
h('link', { rel: 'icon', href: 'data:,' }),
|
|
809
|
-
metadata?.title ? h('title', null, metadata.title) : null,
|
|
810
|
-
metadata?.description ? h('meta', { name: 'description', content: metadata.description }) : null
|
|
1135
|
+
renderedHead.hasFavicon ? null : h('link', { rel: 'icon', href: 'data:,' }),
|
|
811
1136
|
),
|
|
812
1137
|
h('body', null,
|
|
813
1138
|
h('div', { id: 'root' }, rootInner)
|
|
814
1139
|
)
|
|
815
1140
|
),
|
|
816
1141
|
rootContent: rootInner,
|
|
1142
|
+
metadataHead,
|
|
817
1143
|
metadata: {
|
|
818
|
-
title:
|
|
819
|
-
description: typeof metadata
|
|
1144
|
+
title: metadataTitle,
|
|
1145
|
+
description: typeof metadata.description === 'string' ? metadata.description : undefined,
|
|
820
1146
|
},
|
|
821
1147
|
`;
|
|
822
1148
|
// Include action results in payload if actions are enabled
|
|
@@ -835,7 +1161,7 @@ async function handleFarmRequest(request, context) {
|
|
|
835
1161
|
// Full RSC mode with streaming
|
|
836
1162
|
debug('Using RSC streaming mode');
|
|
837
1163
|
|
|
838
|
-
const rscStream = renderToReadableStream(payload${ctx.actionsEnabled ? ",
|
|
1164
|
+
const rscStream = renderToReadableStream(payload, { onError: farmRscOnError${ctx.actionsEnabled ? ", temporaryReferences" : ""} });
|
|
839
1165
|
|
|
840
1166
|
if (acceptHeader.includes('text/x-component')) {
|
|
841
1167
|
debug('Returning RSC stream for client navigation');
|
|
@@ -874,8 +1200,8 @@ async function handleFarmRequest(request, context) {
|
|
|
874
1200
|
h('meta', { charSet: 'utf-8' }),
|
|
875
1201
|
h('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }),
|
|
876
1202
|
h('link', { rel: 'icon', href: 'data:,' }),
|
|
877
|
-
|
|
878
|
-
metadata
|
|
1203
|
+
metadataTitle ? h('title', null, metadataTitle) : null,
|
|
1204
|
+
typeof metadata.description === 'string' ? h('meta', { name: 'description', content: metadata.description }) : null,
|
|
879
1205
|
h('link', { rel: 'stylesheet', href: globalsCssPath, as: 'style', precedence: 'default' }),
|
|
880
1206
|
h('script', { type: 'module', src: '/@vite/client' })
|
|
881
1207
|
),
|
|
@@ -894,7 +1220,11 @@ async function handleFarmRequest(request, context) {
|
|
|
894
1220
|
)
|
|
895
1221
|
);
|
|
896
1222
|
} catch (err) {
|
|
897
|
-
|
|
1223
|
+
${isolateRouteModules
|
|
1224
|
+
? `// A file that failed to load: show the dev error page, not error.tsx.
|
|
1225
|
+
if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
|
|
1226
|
+
`
|
|
1227
|
+
: ""}const redirect = getFarmRedirectError(err);
|
|
898
1228
|
if (redirect) return new Response(null, { status: redirect.status, headers: { location: redirect.url, 'cache-control': 'no-store' } });
|
|
899
1229
|
if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
|
|
900
1230
|
console.error('[RSC] Handler error:', err);
|
|
@@ -943,7 +1273,7 @@ async function handleFarmRequest(request, context) {
|
|
|
943
1273
|
rootContent: rootInner,
|
|
944
1274
|
metadata: { title: 'Error' },
|
|
945
1275
|
};
|
|
946
|
-
const rscStream = renderToReadableStream(payload);
|
|
1276
|
+
const rscStream = renderToReadableStream(payload, { onError: farmRscOnError });
|
|
947
1277
|
const headers = new Headers(errorHeaders);
|
|
948
1278
|
headers.set('cache-control', 'private, no-store');
|
|
949
1279
|
headers.set('x-content-type-options', 'nosniff');
|
|
@@ -980,13 +1310,201 @@ async function handleFarmRequest(request, context) {
|
|
|
980
1310
|
}
|
|
981
1311
|
}
|
|
982
1312
|
|
|
1313
|
+
${ctx.llmsTxt?.enabled
|
|
1314
|
+
? `/**
|
|
1315
|
+
* agent.llmsTxt, built the same way as core's production server: /llms.txt
|
|
1316
|
+
* lists the app's static pages and links to their Markdown mirrors, and
|
|
1317
|
+
* /llms-full.txt inlines each mirror.
|
|
1318
|
+
*/
|
|
1319
|
+
function createFarmLlmsTxtContext(request, context, full) {
|
|
1320
|
+
const origin = new URL(request.url).origin;
|
|
1321
|
+
// A page a path-specific guard covers (a non-root middleware.ts, a config
|
|
1322
|
+
// middleware matcher naming the path) is left out, as core's server does.
|
|
1323
|
+
const guard = {
|
|
1324
|
+
config: { middleware: farmConfigMiddleware },
|
|
1325
|
+
middlewareRoutes: Object.keys(middlewares)
|
|
1326
|
+
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
1327
|
+
.filter((route) => route.path !== null),
|
|
1328
|
+
};
|
|
1329
|
+
const pages = collectFarmLlmsTxtPages(
|
|
1330
|
+
pageRoutes
|
|
1331
|
+
.map(({ module, segments }) => ({
|
|
1332
|
+
// Dynamic routes have no single URL, so the collector skips them.
|
|
1333
|
+
pattern: '/' + segments
|
|
1334
|
+
.map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
|
|
1335
|
+
.join('/'),
|
|
1336
|
+
metadata: module && module.metadata,
|
|
1337
|
+
}))
|
|
1338
|
+
.filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
|
|
1339
|
+
{
|
|
1340
|
+
origin,
|
|
1341
|
+
markdown: farmMarkdownConfig,
|
|
1342
|
+
include: farmLlmsTxtConfig.include,
|
|
1343
|
+
exclude: farmLlmsTxtConfig.exclude,
|
|
1344
|
+
},
|
|
1345
|
+
);
|
|
1346
|
+
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
1347
|
+
return {
|
|
1348
|
+
defaults: createFarmDefaultLlmsTxt({
|
|
1349
|
+
origin,
|
|
1350
|
+
pages,
|
|
1351
|
+
config: farmLlmsTxtConfig,
|
|
1352
|
+
rootMetadata: rootLayout && rootLayout.metadata,
|
|
1353
|
+
}),
|
|
1354
|
+
// Pages are read in-process through the full handler as an anonymous
|
|
1355
|
+
// visitor: a fresh request, so the caller's cookies never shape the file,
|
|
1356
|
+
// and a neutral client address, so an IP allowlist never admits the read.
|
|
1357
|
+
// The body is shared across callers. HEAD reads nothing.
|
|
1358
|
+
markdown: full && request.method.toUpperCase() !== 'HEAD'
|
|
1359
|
+
? createFarmLlmsMarkdownReader((page) =>
|
|
1360
|
+
handler(page, {
|
|
1361
|
+
waitUntil: context && context.waitUntil,
|
|
1362
|
+
clientAddress: FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS,
|
|
1363
|
+
}),
|
|
1364
|
+
)
|
|
1365
|
+
: async () => null,
|
|
1366
|
+
};
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
async function handleFarmLlmsTxtRequest(request, context) {
|
|
1370
|
+
const { origin, pathname } = new URL(request.url);
|
|
1371
|
+
const kind = pathname === '/llms.txt'
|
|
1372
|
+
? 'llms'
|
|
1373
|
+
: farmLlmsTxtConfig.full && pathname === '/llms-full.txt' ? 'llms-full' : null;
|
|
1374
|
+
if (!kind) return null;
|
|
1375
|
+
const method = request.method.toUpperCase();
|
|
1376
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
1377
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
1378
|
+
}
|
|
1379
|
+
const llmsContext = createFarmLlmsTxtContext(request, context, kind === 'llms-full');
|
|
1380
|
+
// A page that times out is left out, and that response is neither reused nor cached.
|
|
1381
|
+
let complete = true;
|
|
1382
|
+
const renderFull = (shared) =>
|
|
1383
|
+
renderFarmLlmsFullTxt(llmsContext.defaults, {
|
|
1384
|
+
origin,
|
|
1385
|
+
readMarkdown: llmsContext.markdown,
|
|
1386
|
+
onIncomplete: () => {
|
|
1387
|
+
complete = false;
|
|
1388
|
+
if (shared) shared.incomplete();
|
|
1389
|
+
},
|
|
1390
|
+
});
|
|
1391
|
+
// HEAD reads no pages, so it neither waits for nor fills the shared render.
|
|
1392
|
+
const body = kind === 'llms'
|
|
1393
|
+
? llmsContext.defaults
|
|
1394
|
+
: method === 'HEAD'
|
|
1395
|
+
? await renderFull()
|
|
1396
|
+
: await farmLlmsFullRenderer(origin, renderFull, (settled) => {
|
|
1397
|
+
complete = settled;
|
|
1398
|
+
});
|
|
1399
|
+
const response = createFarmMetadataRouteResponse(
|
|
1400
|
+
kind,
|
|
1401
|
+
body,
|
|
1402
|
+
{ revalidate: complete ? farmLlmsTxtConfig.revalidate : 0 },
|
|
1403
|
+
{ method, request },
|
|
1404
|
+
);
|
|
1405
|
+
if (!complete) response.headers.set('cache-control', 'no-store');
|
|
1406
|
+
return response;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
`
|
|
1410
|
+
: ""}/**
|
|
1411
|
+
* Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
|
|
1412
|
+
* rendering the page through the normal request path, so middleware and sign-in
|
|
1413
|
+
* gates apply; every other request renders as usual, and HTML pages advertise
|
|
1414
|
+
* their mirror with a Link header.
|
|
1415
|
+
*/
|
|
1416
|
+
async function handleFarmPageOrMarkdown(request, context) {
|
|
1417
|
+
if (!farmMarkdownConfig.enabled) return handleFarmRequest(request, context);
|
|
1418
|
+
const markdown = await createMarkdownMirrorResponse({
|
|
1419
|
+
request,
|
|
1420
|
+
config: farmMarkdownConfig,
|
|
1421
|
+
routeExists: (pathname) => Boolean(matchRoute(pathname)),
|
|
1422
|
+
renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
|
|
1423
|
+
apiServerBasePath: farmApiBasePath,
|
|
1424
|
+
});
|
|
1425
|
+
if (markdown) return markdown;
|
|
1426
|
+
const response = await handleFarmRequest(request, context);
|
|
1427
|
+
return applyMarkdownNegotiationHeaders(response, {
|
|
1428
|
+
config: farmMarkdownConfig,
|
|
1429
|
+
pathname: new URL(request.url).pathname,
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
// Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
|
|
1434
|
+
// trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
|
|
1435
|
+
// 'Accept: text/x-component' on the page URL keeps working.
|
|
1436
|
+
function farmPayloadPath(pathname) {
|
|
1437
|
+
return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
function toFarmPayloadRequest(request) {
|
|
1441
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return request;
|
|
1442
|
+
const url = new URL(request.url);
|
|
1443
|
+
if (!url.pathname.endsWith('.rsc')) return request;
|
|
1444
|
+
if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) return request;
|
|
1445
|
+
const page = url.pathname.slice(0, -'.rsc'.length);
|
|
1446
|
+
url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
|
|
1447
|
+
const headers = new Headers(request.headers);
|
|
1448
|
+
headers.set('accept', 'text/x-component');
|
|
1449
|
+
return new Request(url, { method: request.method, headers, signal: request.signal });
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
// The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
|
|
1453
|
+
// route that lists the static pages, and each prerendered page queues its payload, both through
|
|
1454
|
+
// Nitro's x-nitro-prerender response header. Production servers never answer either.
|
|
1455
|
+
const FARM_PRERENDER_ROUTES_PATH = '/__farm/rsc-prerender-routes';
|
|
1456
|
+
function isFarmPrerenderRequest(request) {
|
|
1457
|
+
return globalThis.process?.env?.FARM_RSC_PRERENDER === '1' && request.headers.has('x-nitro-prerender');
|
|
1458
|
+
}
|
|
1459
|
+
|
|
983
1460
|
async function handler(request, context) {
|
|
1461
|
+
const prerendering = isFarmPrerenderRequest(request);
|
|
1462
|
+
if (prerendering && new URL(request.url).pathname === FARM_PRERENDER_ROUTES_PATH) {
|
|
1463
|
+
const pages = await collectFarmStaticPages();
|
|
1464
|
+
return new Response('<!doctype html>', {
|
|
1465
|
+
headers: {
|
|
1466
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1467
|
+
'x-nitro-prerender': pages.map(encodeURIComponent).join(','),
|
|
1468
|
+
},
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
const pageRequest = toFarmPayloadRequest(request);
|
|
1472
|
+
const response = await handleFarmRequestWithRuntime(pageRequest, context);
|
|
1473
|
+
if (
|
|
1474
|
+
prerendering &&
|
|
1475
|
+
pageRequest === request &&
|
|
1476
|
+
response.status === 200 &&
|
|
1477
|
+
(response.headers.get('content-type') || '').includes('text/html')
|
|
1478
|
+
) {
|
|
1479
|
+
const headers = new Headers(response.headers);
|
|
1480
|
+
headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
|
|
1481
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
1482
|
+
}
|
|
1483
|
+
return ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
|
|
1484
|
+
}
|
|
1485
|
+
${ctx.mobileClient === "entry"
|
|
1486
|
+
? `
|
|
1487
|
+
// The mobile client (RFC 0004): the documents a mobile shell asks for (X-Farm-Shell) load its
|
|
1488
|
+
// entry instead of the web one, privately, and every HTML response varies on the header. The
|
|
1489
|
+
// Nitro build fills this in once the client is built; null leaves responses as they are.
|
|
1490
|
+
function readFarmMobileShellClient() {
|
|
1491
|
+
try {
|
|
1492
|
+
return JSON.parse("${FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER}");
|
|
1493
|
+
} catch {
|
|
1494
|
+
return null;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
const farmMobileShellClient = readFarmMobileShellClient();
|
|
1498
|
+
`
|
|
1499
|
+
: ""}
|
|
1500
|
+
|
|
1501
|
+
async function handleFarmRequestWithRuntime(request, context) {
|
|
984
1502
|
return _runWithAPIRequestRuntime({
|
|
985
1503
|
basePath: farmApiBasePath,
|
|
986
1504
|
dispatch: async (localRequest) =>
|
|
987
1505
|
(await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
|
|
988
1506
|
}, () => _runWithCurrentRequest(request, () =>
|
|
989
|
-
_runWithAfterRequest(request, () =>
|
|
1507
|
+
_runWithAfterRequest(request, () => handleFarmPageOrMarkdown(request, context), context)
|
|
990
1508
|
));
|
|
991
1509
|
}
|
|
992
1510
|
|