@farm.js/plugin 0.1.60 → 0.1.61

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.
Files changed (40) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/middleware/index.d.ts +1 -8
  4. package/dist/middleware/index.d.ts.map +1 -1
  5. package/dist/middleware/index.js +10 -16
  6. package/dist/middleware/matching.d.ts +2 -4
  7. package/dist/middleware/matching.d.ts.map +1 -1
  8. package/dist/middleware/matching.js +47 -7
  9. package/dist/rsc/entries/client.d.ts.map +1 -1
  10. package/dist/rsc/entries/client.js +15 -85
  11. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  12. package/dist/rsc/entries/rsc.js +45 -563
  13. package/dist/rsc/entries/ssr.d.ts.map +1 -1
  14. package/dist/rsc/entries/ssr.js +6 -7
  15. package/dist/rsc/index.d.ts +3 -38
  16. package/dist/rsc/index.d.ts.map +1 -1
  17. package/dist/rsc/index.js +292 -279
  18. package/dist/rsc/middleware-config-module.d.ts +0 -3
  19. package/dist/rsc/middleware-config-module.d.ts.map +1 -1
  20. package/dist/rsc/middleware-config-module.js +28 -41
  21. package/dist/rsc/nitro-build.d.ts.map +1 -1
  22. package/dist/rsc/nitro-build.js +81 -268
  23. package/dist/rsc/server-fn-transform.d.ts +5 -1
  24. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  25. package/dist/rsc/server-fn-transform.js +338 -3
  26. package/dist/rsc/types.d.ts +0 -39
  27. package/dist/rsc/types.d.ts.map +1 -1
  28. package/dist/rsc/vite-plugin-nitro.d.ts +0 -2
  29. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  30. package/dist/rsc/vite-plugin-nitro.js +2 -12
  31. package/package.json +3 -3
  32. package/dist/rsc/client-sourcemaps.d.ts +0 -13
  33. package/dist/rsc/client-sourcemaps.d.ts.map +0 -1
  34. package/dist/rsc/client-sourcemaps.js +0 -52
  35. package/dist/rsc/document-layouts.d.ts +0 -16
  36. package/dist/rsc/document-layouts.d.ts.map +0 -1
  37. package/dist/rsc/document-layouts.js +0 -82
  38. package/dist/rsc/mobile-client.d.ts +0 -67
  39. package/dist/rsc/mobile-client.d.ts.map +0 -1
  40. package/dist/rsc/mobile-client.js +0 -148
package/dist/rsc/index.js CHANGED
@@ -25,22 +25,18 @@ import { loadFarmDevModule, FarmDevEnvironmentError } from "@farm.js/core/plugin
25
25
  import { parseAst, version as viteVersion, } from "vite";
26
26
  import { init as initModuleLexer, parse as parseModuleImports } from "es-module-lexer";
27
27
  import { farmEnvironmentFunctionsPlugin } from "@farm.js/core/environment/vite";
28
- import { farmFontImportsPlugin, farmImageImportsPlugin, generateClientCachePersistenceCode, getPublicFarmImageConfig, resolveFarmClientCacheAdapterEntry, resolveFarmImageConfig, resolveFarmImageProviderForRuntime, resolveFarmImageServerRuntime, readRouteRenderingDirectiveFromFile, } from "@farm.js/core/vite";
28
+ import { generateClientCachePersistenceCode, resolveFarmClientCacheAdapterEntry, } from "@farm.js/core/vite";
29
29
  import { generateRscEntry } from "./entries/rsc.js";
30
- import { resolveMarkdownConfig } from "@farm.js/core/markdown";
31
30
  import { generateSsrEntry } from "./entries/ssr.js";
32
31
  import { generateErrorFallbackEntry } from "./entries/error-fallback.js";
33
32
  import { generateClientEntry, serverFnTransportErrorClientRuntime } from "./entries/client.js";
34
33
  import { transformFarmRouteActionClients } from "./route-action-transform.js";
35
- import { createFarmServerFnBoundaryModule, isFarmServerFnBoundaryId, transformFarmServerFns, } from "./server-fn-transform.js";
34
+ import { transformFarmServerFns } from "./server-fn-transform.js";
36
35
  import { transformAutomaticOptimizedBoundaries } from "./automatic-optimized-boundary.js";
37
36
  import { resolveRscBuildOutputPath } from "./build-paths.js";
38
- import { FARM_RSC_MOBILE_CLIENT_ENTRY_NAME, createFarmRscMobileClientManifestPlugin, generateMobileClientEntry, removeFarmRscMobileClientManifest, } from "./mobile-client.js";
39
- import { rscPrivateClientSourcemaps } from "./client-sourcemaps.js";
40
- import { findDocumentLayouts, findRouteFiles } from "./document-layouts.js";
41
37
  import { assertRscPackageCompatibility } from "./compatibility.js";
42
38
  import { sendRscDevelopmentResponse } from "./dev-response.js";
43
- import { loadRscConfigPropertyModule, loadRscMiddlewareConfigModule, } from "./middleware-config-module.js";
39
+ import { loadRscMiddlewareConfigModule } from "./middleware-config-module.js";
44
40
  import fs from "fs/promises";
45
41
  import path from "path";
46
42
  import { devServableFileExists } from "../dev-static.js";
@@ -50,21 +46,17 @@ import { createRequire } from "node:module";
50
46
  // Use API and middleware plugins from @farm.js/core (require so CJS build resolves when ESM .mjs is missing)
51
47
  const require_ = createRequire(import.meta.url);
52
48
  const { farmApiPlugin } = require_("@farm.js/core");
53
- const { FARM_VERSION } = require_("@farm.js/core/version");
54
49
  const { farmMiddlewarePlugin } = require_("@farm.js/core/middleware");
55
50
  const { resolveServerActionsConfig, validateServerActionRequest, createServerActionRequestErrorResponse, } = require_("@farm.js/core/server-action-security");
56
51
  const { normalizeFarmDeploymentId } = require_("@farm.js/core/deployment");
57
- const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers, resolveFarmMCPConfig, resolveFarmMCPPlugin, } = require_("@farm.js/core/server");
58
- const { readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, createDefaultErrorMarkup, resolveFarmLlmsTxtConfig, } = require_("@farm.js/core/internal/production-runtime");
52
+ const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers } = require_("@farm.js/core/server");
53
+ const { searchParamsToObject, readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, } = require_("@farm.js/core/internal/production-runtime");
59
54
  const { isFarmAPIPathname } = require_("@farm.js/core/api/runtime");
60
55
  const { resolveFarmAPIConfig, resolveFarmAPIServerBasePath } = require_("@farm.js/core/api");
61
56
  const { getResolvedEnv } = require_("@farm.js/core/env");
62
57
  export { buildRscNitro, waitForRscManifest, waitForRscOutputs } from "./nitro-build.js";
63
58
  import { registerRscNitroRuntimePackage } from "./nitro-build.js";
64
59
  export { default as nitro } from "./vite-plugin-nitro.js";
65
- const PAGE_FILE = /^page\.(tsx|jsx|ts|js)$/;
66
- /** Packages the generated RSC entries import that belong to this plugin, not to the app. */
67
- const PLUGIN_OWNED_ENTRY_IMPORTS = ["rsc-html-stream/server", "rsc-html-stream/client"];
68
60
  /**
69
61
  * Define a Farm.js RSC configuration
70
62
  * This is the recommended way to configure your RSC app
@@ -88,11 +80,6 @@ export function defineConfig(config = {}) {
88
80
  serverActions: config.serverActions,
89
81
  deploymentId: config.deploymentId,
90
82
  generateBuildId: config.generateBuildId,
91
- md: config.md,
92
- agent: config.agent,
93
- mcp: config.mcp,
94
- middleware: config.middleware,
95
- images: config.images,
96
83
  // Vite server configuration
97
84
  server: {
98
85
  ...config.server,
@@ -101,28 +88,22 @@ export function defineConfig(config = {}) {
101
88
  },
102
89
  // Custom logger to hide Vite's default startup banner
103
90
  customLogger: createFarmLogger(port, debug),
91
+ // Configure esbuild for JSX transformation
92
+ esbuild: {
93
+ jsx: "automatic",
94
+ jsxImportSource: "react",
95
+ },
104
96
  plugins: [
105
97
  farmMiddlewarePlugin({
106
98
  srcDir: config.srcDir ?? "src",
107
99
  basePath: config.basePath ?? "/",
108
- // API routes in development run through this plugin's middleware, not the RSC entry's.
109
- middleware: config.middleware,
110
100
  debug,
111
101
  }),
112
102
  farmApiPlugin({
113
103
  srcDir: config.srcDir ?? "src",
114
- // The production entry serves API routes from the routes directory; so does development.
115
- apiDir: path.join(config.srcDir ?? "src", config.routesDir === undefined ? "app" : config.routesDir.trim(), "api"),
116
104
  debug,
117
105
  bodySizeLimit: config.server?.bodySizeLimit,
118
- // The dev API server mounts the MCP endpoint, as core's does.
119
- ...(config.mcp ? { plugins: ({ root }) => resolveRscMCPPlugins(config.mcp, root) } : {}),
120
106
  }),
121
- // localFont() from @farm.js/core/font, with its CSS carried by the bundler: this pipeline
122
- // has no step that merges font CSS into a global stylesheet.
123
- farmFontImportsPlugin({ basePath: config.basePath ?? "/", importCss: true }),
124
- // Static image imports as { src, width, height }, which <Image> sizes from.
125
- farmImageImportsPlugin(),
126
107
  farmRsc({
127
108
  debug,
128
109
  encryptActions: config.encryptActions,
@@ -130,7 +111,6 @@ export function defineConfig(config = {}) {
130
111
  deploymentId: config.deploymentId,
131
112
  routesDir: config.routesDir,
132
113
  entries: config.entries,
133
- mobileClient: config.mobileClient,
134
114
  }),
135
115
  ...(Array.isArray(config.plugins) ? config.plugins : []),
136
116
  ],
@@ -200,16 +180,10 @@ const VIRTUAL_PREFIX = "\0";
200
180
  const VIRTUAL_RSC_ENTRY = "virtual:@farm.js/rsc/entry-rsc";
201
181
  const VIRTUAL_SSR_ENTRY = "virtual:@farm.js/rsc/entry-ssr";
202
182
  const VIRTUAL_CLIENT_ENTRY = "virtual:@farm.js/rsc/entry-client";
203
- const VIRTUAL_MOBILE_CLIENT_ENTRY = "virtual:@farm.js/rsc/entry-mobile";
204
- /** The browser entry, as the client build's `index` input names it. */
205
- const RSC_CLIENT_ENTRY = "./.farm/rsc-entries/entry.browser.tsx";
206
- /** The mobile client entry a build of an app with a `mobile` block adds. */
207
- const RSC_MOBILE_CLIENT_ENTRY = "./.farm/rsc-entries/entry.mobile.tsx";
208
183
  const VIRTUAL_HYDRATE_ENTRY = "virtual:@farm.js/rsc/hydrate";
209
184
  const OPTIMIZED_BOUNDARY_ADAPTER = "@farm.js/plugin/rsc/optimized-boundary";
210
185
  const STRATA_PACKAGE = "@farming-labs/strata";
211
186
  const RSC_MIDDLEWARE_CONFIG_QUERY = "?farm-rsc-middleware";
212
- const RSC_MCP_CONFIG_QUERY = "?farm-rsc-mcp";
213
187
  const FARM_CORE_PACKAGE_ROOT = path.resolve(path.dirname(require_.resolve("@farm.js/core")), "..");
214
188
  const FARM_CONFIG_FILENAMES = [
215
189
  "farm.config.ts",
@@ -254,19 +228,6 @@ async function findFarmConfigPath(root) {
254
228
  }
255
229
  return null;
256
230
  }
257
- /** Resolves `mcp` for an RSC app, rejecting what the RSC server cannot serve yet. */
258
- function resolveRscMCPConfig(input) {
259
- const config = resolveFarmMCPConfig(input);
260
- if (config.enabled && config.oauth) {
261
- throw new Error("[Farm.js] mcp.oauth is not supported in RSC apps yet: the RSC server does not serve " +
262
- "the protected-resource metadata. Remove oauth, or validate tokens in mcp.authorize.");
263
- }
264
- return config;
265
- }
266
- async function resolveRscMCPPlugins(input, root) {
267
- const plugin = await resolveFarmMCPPlugin(resolveRscMCPConfig(input), { root });
268
- return plugin ? [plugin] : [];
269
- }
270
231
  async function resolveMiddlewareConfigPaths(root, layers) {
271
232
  const paths = (layers ?? []).flatMap((layer) => layer.configFile ? [path.resolve(layer.configFile)] : []);
272
233
  const projectConfigPath = await findFarmConfigPath(root);
@@ -274,50 +235,11 @@ async function resolveMiddlewareConfigPaths(root, layers) {
274
235
  paths.push(projectConfigPath);
275
236
  return [...new Set(paths)];
276
237
  }
277
- // Vite's default config names: `defineConfig` from this package is written in one of them.
278
- const VITE_CONFIG_FILENAMES = [
279
- "vite.config.js",
280
- "vite.config.mjs",
281
- "vite.config.ts",
282
- "vite.config.cjs",
283
- "vite.config.mts",
284
- "vite.config.cts",
285
- ];
286
- async function findViteConfigPath(root) {
287
- for (const fileName of VITE_CONFIG_FILENAMES) {
288
- const candidate = path.join(root, fileName);
289
- try {
290
- if ((await fs.stat(candidate)).isFile())
291
- return candidate;
292
- }
293
- catch {
294
- // Continue checking supported config names.
295
- }
296
- }
297
- return null;
298
- }
299
238
  function isOptimizedBoundaryModule(id) {
300
239
  return (id === OPTIMIZED_BOUNDARY_ADAPTER ||
301
240
  id === STRATA_PACKAGE ||
302
241
  id.startsWith(`${STRATA_PACKAGE}/`));
303
242
  }
304
- /** The development error page for a failed RSC render: core's error page, with the real error. */
305
- function createRscDevErrorDocument(error, method, pathname) {
306
- const failure = error instanceof Error ? error : new Error(String(error));
307
- const markup = createDefaultErrorMarkup({
308
- statusCode: 500,
309
- requestPath: pathname,
310
- method,
311
- message: failure.message,
312
- errorName: failure.name,
313
- stack: failure.stack,
314
- development: true,
315
- mode: "development",
316
- farmVersion: FARM_VERSION,
317
- nodeVersion: process.version,
318
- });
319
- return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>500 · Farm.js</title></head><body>${markup}</body></html>`;
320
- }
321
243
  function resolveOptimizedBoundaryRuntimeRoot() {
322
244
  try {
323
245
  return path.dirname(require_.resolve(`${STRATA_PACKAGE}/package.json`));
@@ -528,10 +450,7 @@ export default function farmRsc(options = {}) {
528
450
  // Context passed to entry generators
529
451
  let entryContext;
530
452
  let rscBuildRoot;
531
- /** The app root, when this build adds the mobile client entry. */
532
- let mobileClientRoot;
533
453
  const middlewareConfigModules = new Map();
534
- let mcpConfigCandidates = null;
535
454
  // Store for debugging
536
455
  const debug = options.debug ?? false;
537
456
  const automaticDeploymentId = `build-${Date.now()}`;
@@ -621,44 +540,14 @@ export default function farmRsc(options = {}) {
621
540
  };
622
541
  return [
623
542
  farmEnvironmentFunctionsPlugin(),
624
- rscPrivateClientSourcemaps(),
625
- createFarmRscMobileClientManifestPlugin(() => mobileClientRoot),
626
543
  {
627
544
  name: "@farm.js/plugin/rsc:middleware-config",
628
545
  enforce: "pre",
629
546
  resolveId(id) {
630
- if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY) && !id.endsWith(RSC_MCP_CONFIG_QUERY)) {
547
+ if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY))
631
548
  return null;
632
- }
633
549
  return id.replace(/\\/g, "/");
634
550
  },
635
- // The MCP config is read from the Vite config file too, whose path is
636
- // only known here. Entries are generated on load, after this runs.
637
- async configResolved(resolved) {
638
- if (!mcpConfigCandidates || !entryContext)
639
- return;
640
- const configPaths = [...mcpConfigCandidates];
641
- if (resolved.configFile)
642
- configPaths.push(path.resolve(resolved.configFile));
643
- const mcpConfigPaths = [];
644
- for (const configPath of new Set(configPaths)) {
645
- const extracted = await loadRscConfigPropertyModule(configPath, "mcp");
646
- if (extracted.kind === "unsupported") {
647
- throw new Error(`[Farm.js] Cannot read mcp for the RSC server from ${configPath}: ${extracted.reason}. ` +
648
- "Declare mcp directly in defineConfig({ mcp: ... }).");
649
- }
650
- if (extracted.kind === "absent")
651
- continue;
652
- const moduleId = `${configPath.replace(/\\/g, "/")}${RSC_MCP_CONFIG_QUERY}`;
653
- middlewareConfigModules.set(moduleId, extracted.code);
654
- mcpConfigPaths.push(moduleId);
655
- }
656
- if (mcpConfigPaths.length === 0) {
657
- throw new Error("[Farm.js] The RSC server could not find the mcp config. " +
658
- "Declare mcp directly in defineConfig({ mcp: ... }) in your Vite or Farm config file.");
659
- }
660
- entryContext.mcpConfigPaths = mcpConfigPaths;
661
- },
662
551
  load(id) {
663
552
  return middlewareConfigModules.get(id.replace(/\\/g, "/")) ?? null;
664
553
  },
@@ -696,15 +585,7 @@ export default function farmRsc(options = {}) {
696
585
  async config(config, env) {
697
586
  const c = config;
698
587
  // Check if user enabled RSC in their config
699
- const serverComponents = c.experimental?.serverComponents;
700
- if (typeof serverComponents === "object" &&
701
- serverComponents !== null &&
702
- serverComponents.mode !== "rsc") {
703
- throw new Error(`[Farm.js] @farm.js/plugin/rsc runs the "rsc" engine; experimental.serverComponents.mode "${String(serverComponents.mode)}" is not supported here.`);
704
- }
705
- rscEnabled =
706
- serverComponents === true ||
707
- (typeof serverComponents === "object" && serverComponents !== null);
588
+ rscEnabled = c.experimental?.serverComponents === true;
708
589
  actionsEnabled = c.experimental?.serverActions === true;
709
590
  bodySizeLimit = resolveFarmServerConfig(c.server).bodySizeLimit;
710
591
  optimizedBoundaryEnabled = c.experimental?.optimizedBoundary === true;
@@ -731,19 +612,11 @@ export default function farmRsc(options = {}) {
731
612
  Object.assign(c, layerResolution.config);
732
613
  }
733
614
  middlewareConfigModules.clear();
734
- // The config files mcp is read from at runtime; the Vite config file is
735
- // added once it is known, in configResolved.
736
- mcpConfigCandidates = resolveRscMCPConfig(c.mcp).enabled
737
- ? await resolveMiddlewareConfigPaths(root, c.layers)
738
- : null;
739
615
  const middlewareConfigPaths = [];
740
616
  if (hasFarmMiddlewareConfig(c.middleware)) {
741
617
  const configPaths = await resolveMiddlewareConfigPaths(root, c.layers);
742
- const viteConfigPath = await findViteConfigPath(root);
743
- if (viteConfigPath)
744
- configPaths.push(viteConfigPath);
745
618
  if (configPaths.length === 0) {
746
- throw new Error("[Farm.js] RSC config middleware requires an importable farm.config or vite.config file. " +
619
+ throw new Error("[Farm.js] RSC config middleware requires an importable farm.config file. " +
747
620
  "Move the middleware to farm.config.ts or src/app/middleware.ts.");
748
621
  }
749
622
  for (const configPath of configPaths) {
@@ -804,61 +677,8 @@ export default function farmRsc(options = {}) {
804
677
  : `/${projectSourceDir}${routeSuffix}`;
805
678
  return { name: source.name, base, glob: base };
806
679
  });
807
- // Each page's rendering directive and whether its source reads request state, which the
808
- // runtime cannot see from module exports: the same baked input core's server merges.
809
- // Later roots override earlier ones, as the entry's merged page map does.
810
- const pageRenderingDirectives = {};
811
- for (const source of getFarmSourceRoots(c)) {
812
- const routesRoot = path.resolve(root, source.srcDir, configuredRoutesDir);
813
- for (const { key, file } of await findRouteFiles(routesRoot, (name) => PAGE_FILE.test(name))) {
814
- const directive = readRouteRenderingDirectiveFromFile(file);
815
- if (directive)
816
- pageRenderingDirectives[key] = directive;
817
- else
818
- delete pageRenderingDirectives[key];
819
- }
820
- }
821
- // Root layouts that render <html> own the document (Next.js's root layout contract).
822
- const documentLayouts = [
823
- ...new Set((await Promise.all(getFarmSourceRoots(c).map((source) => findDocumentLayouts(path.resolve(root, source.srcDir, configuredRoutesDir))))).flat()),
824
- ];
825
- // The same images contract as core: without Sharp, "auto" keeps original URLs
826
- // (provider "none") instead of pointing <Image> at an optimizer that cannot run.
827
- const nitroPreset = process.env.NITRO_PRESET || "vercel";
828
- const imageConfig = resolveFarmImageConfig(resolveFarmImageProviderForRuntime(c.images, {
829
- root,
830
- preset: nitroPreset,
831
- dev: env.command === "serve",
832
- }));
833
- const publicImageConfig = getPublicFarmImageConfig(imageConfig);
834
- // An app with a `mobile` block (RFC 0004): a build adds the mobile entry, and
835
- // `farm dev --mobile` makes the browser entry itself the mobile client.
836
- const mobileClient = options.mobileClient === "entry" && env.command === "build"
837
- ? "entry"
838
- : options.mobileClient === "inline" && env.command === "serve"
839
- ? "inline"
840
- : undefined;
841
- mobileClientRoot = mobileClient === "entry" ? root : undefined;
842
- // A mobile client from an earlier build must not outlive the `mobile` block.
843
- if (env.command === "build" && mobileClient !== "entry") {
844
- removeFarmRscMobileClientManifest(root);
845
- }
846
- // Development always optimizes with Sharp, as core's dev server does.
847
- const imageRuntime = env.command === "serve"
848
- ? imageConfig.provider === "none"
849
- ? "none"
850
- : "node"
851
- : resolveFarmImageServerRuntime(imageConfig, nitroPreset);
852
680
  // Build context for entry generators
853
681
  entryContext = {
854
- documentLayouts,
855
- pageRenderingDirectives,
856
- images: {
857
- config: imageConfig,
858
- public: publicImageConfig,
859
- path: imageConfig.path,
860
- runtime: imageRuntime,
861
- },
862
682
  srcDir,
863
683
  outDir,
864
684
  basePath: c.basePath ?? "/",
@@ -873,9 +693,6 @@ export default function farmRsc(options = {}) {
873
693
  allowedOrigins: options.serverActions?.allowedOrigins ?? c.serverActions?.allowedOrigins,
874
694
  }),
875
695
  deploymentId,
876
- markdown: resolveMarkdownConfig(c.md),
877
- // Core's default for an app without docs: llms.txt on, llms-full.txt off.
878
- llmsTxt: resolveFarmLlmsTxtConfig(c.agent?.llmsTxt ?? { full: false }),
879
696
  // Resolved the same way core resolves it for the config, so RSC and
880
697
  // non-RSC apps match middleware against the same pathname.
881
698
  i18n: resolveFarmI18nConfig(c.i18n, {
@@ -888,7 +705,6 @@ export default function farmRsc(options = {}) {
888
705
  debug,
889
706
  development: env.command === "serve",
890
707
  clientCachePersistence: generateClientCachePersistenceCode(resolveFarmClientCacheAdapterEntry(root, c.cache)),
891
- mobileClient,
892
708
  };
893
709
  logInfo(`srcDir: ${entryContext.srcDir}, outDir: ${entryContext.outDir}`);
894
710
  // Write real entry files so @vitejs/plugin-rsc can use file-based entries.
@@ -899,9 +715,6 @@ export default function farmRsc(options = {}) {
899
715
  await fs.writeFile(entryRscPath, generateRscEntry(entryContext));
900
716
  await fs.writeFile(entrySsrPath, generateSsrEntry(entryContext));
901
717
  await fs.writeFile(entryClientPath, generateClientEntry(entryContext));
902
- if (mobileClient === "entry") {
903
- await fs.writeFile(path.join(entriesDir, "entry.mobile.tsx"), generateMobileClientEntry(RSC_CLIENT_ENTRY));
904
- }
905
718
  await fs.writeFile(path.join(entriesDir, "error-fallback.tsx"), generateErrorFallbackEntry());
906
719
  logInfo(`Wrote RSC entries to ${entriesDir}`);
907
720
  // User must add rsc({ entries: { rsc, ssr, client } }) to config.plugins so the RSC plugin
@@ -909,7 +722,7 @@ export default function farmRsc(options = {}) {
909
722
  // Entry paths (relative to root) so Vite runs rsc/ssr/client builds (not index.html).
910
723
  const entryRsc = "./.farm/rsc-entries/entry.rsc.tsx";
911
724
  const entrySsr = "./.farm/rsc-entries/entry.ssr.tsx";
912
- const entryClient = RSC_CLIENT_ENTRY;
725
+ const entryClient = "./.farm/rsc-entries/entry.browser.tsx";
913
726
  // Resolve @farm.js/core so Vite (and rsc/ssr envs) can load it when app code imports it (fixes "Failed to resolve entry" in dev).
914
727
  let farmCorePath = null;
915
728
  try {
@@ -931,7 +744,6 @@ export default function farmRsc(options = {}) {
931
744
  builder: { sharedConfigBuild: true },
932
745
  define: {
933
746
  __FARM_API_BASE_URL__: JSON.stringify(api.baseURL),
934
- __FARM_IMAGE_CONFIG__: JSON.stringify(entryContext.images?.public),
935
747
  },
936
748
  ssr: {
937
749
  external: [
@@ -955,21 +767,6 @@ export default function farmRsc(options = {}) {
955
767
  resolve: {
956
768
  dedupe: ["react", "react-dom", "react-server-dom-webpack"],
957
769
  alias: [
958
- // The generated entries import the plugin's own dependencies; resolve them from here
959
- // so an app (strict pnpm layout) does not have to install them itself.
960
- ...PLUGIN_OWNED_ENTRY_IMPORTS.flatMap((specifier) => {
961
- try {
962
- return [
963
- {
964
- find: new RegExp(`^${specifier.replace(/[/.]/g, "\\$&")}$`),
965
- replacement: require_.resolve(specifier),
966
- },
967
- ];
968
- }
969
- catch {
970
- return [];
971
- }
972
- }),
973
770
  ...Object.entries(layerAliases).map(([find, replacement]) => ({
974
771
  find,
975
772
  replacement,
@@ -1012,11 +809,10 @@ export default function farmRsc(options = {}) {
1012
809
  : []),
1013
810
  ],
1014
811
  },
1015
- // Vite 8 compiles with oxc, which already uses the automatic runtime;
1016
- // setting esbuild there only prints a "both options were set" warning.
1017
- ...(this?.meta?.rolldownVersion
1018
- ? {}
1019
- : { esbuild: { jsx: "automatic", jsxImportSource: "react" } }),
812
+ esbuild: {
813
+ jsx: "automatic",
814
+ jsxImportSource: "react",
815
+ },
1020
816
  ...(c.layers?.length
1021
817
  ? {
1022
818
  server: {
@@ -1033,14 +829,7 @@ export default function farmRsc(options = {}) {
1033
829
  copyPublicDir: false,
1034
830
  rollupOptions: { input: { index: entryRsc } },
1035
831
  },
1036
- resolve: {
1037
- conditions: ["react-server", "node", "import"],
1038
- // Strata is a native CommonJS loader: Node must load it, not Vite's
1039
- // module runner. ssr.external does not reach this environment.
1040
- ...(optimizedBoundaryEnabled
1041
- ? { external: [STRATA_PACKAGE, `${STRATA_PACKAGE}/react-server`] }
1042
- : {}),
1043
- },
832
+ resolve: { conditions: ["react-server", "node", "import"] },
1044
833
  },
1045
834
  ssr: {
1046
835
  build: {
@@ -1053,29 +842,9 @@ export default function farmRsc(options = {}) {
1053
842
  client: {
1054
843
  build: {
1055
844
  outDir: `${outDir}/client`,
1056
- rollupOptions: {
1057
- input: {
1058
- index: entryClient,
1059
- ...(mobileClient === "entry"
1060
- ? { [FARM_RSC_MOBILE_CLIENT_ENTRY_NAME]: RSC_MOBILE_CLIENT_ENTRY }
1061
- : {}),
1062
- },
1063
- },
845
+ rollupOptions: { input: { index: entryClient } },
1064
846
  },
1065
847
  resolve: { conditions: ["browser", "import"] },
1066
- // Optimize what the browser entry needs up front. A dependency first
1067
- // found on page load makes Vite re-optimize and reload, and until the
1068
- // reload client components can see two React copies ("Invalid hook call").
1069
- optimizeDeps: {
1070
- include: [
1071
- "react",
1072
- "react/jsx-runtime",
1073
- "react/jsx-dev-runtime",
1074
- "react-dom",
1075
- "react-dom/client",
1076
- "rsc-html-stream/client",
1077
- ],
1078
- },
1079
848
  },
1080
849
  },
1081
850
  };
@@ -1144,22 +913,10 @@ export default function farmRsc(options = {}) {
1144
913
  {
1145
914
  name: "@farm.js/plugin/rsc:server-fn-actions",
1146
915
  enforce: "pre",
1147
- // The "use server" boundary for a module whose server functions were
1148
- // found without an explicit directive. Its exports come from the source
1149
- // file on disk, never from the request, so nothing else can be named.
1150
- async load(id) {
1151
- if (!rscEnabled || !actionsEnabled || !isFarmServerFnBoundaryId(id))
1152
- return null;
1153
- const file = id.split("?", 1)[0];
1154
- this.addWatchFile(file);
1155
- const source = await fs.readFile(file, "utf8");
1156
- return createFarmServerFnBoundaryModule(source, file) ?? "export {};\n";
1157
- },
1158
916
  transform(code, id) {
1159
- if (!rscEnabled || !actionsEnabled || isFarmServerFnBoundaryId(id))
917
+ if (!rscEnabled || !actionsEnabled)
1160
918
  return null;
1161
- const environment = this.environment?.name;
1162
- const result = transformFarmServerFns(code, id, { environment: environment ?? "rsc" });
919
+ const result = transformFarmServerFns(code, id);
1163
920
  if (!result)
1164
921
  return null;
1165
922
  return {
@@ -1226,9 +983,6 @@ export default function farmRsc(options = {}) {
1226
983
  if (source.includes("rsc-entries") && source.includes("entry.browser.tsx")) {
1227
984
  return VIRTUAL_PREFIX + VIRTUAL_CLIENT_ENTRY;
1228
985
  }
1229
- if (source.includes("rsc-entries") && source.includes("entry.mobile.tsx")) {
1230
- return VIRTUAL_PREFIX + VIRTUAL_MOBILE_CLIENT_ENTRY;
1231
- }
1232
986
  if (source.includes("rsc-entries") && source.includes("entry.rsc.tsx")) {
1233
987
  return VIRTUAL_PREFIX + VIRTUAL_RSC_ENTRY;
1234
988
  }
@@ -1259,9 +1013,6 @@ export default function farmRsc(options = {}) {
1259
1013
  logInfo("Generating client entry");
1260
1014
  return generateClientEntry(entryContext);
1261
1015
  }
1262
- if (id === VIRTUAL_PREFIX + VIRTUAL_MOBILE_CLIENT_ENTRY) {
1263
- return generateMobileClientEntry(RSC_CLIENT_ENTRY);
1264
- }
1265
1016
  // Handle dynamic hydration entries
1266
1017
  if (id.startsWith(VIRTUAL_PREFIX + "/@rsc-hydrate/")) {
1267
1018
  const pagePath = id.replace(VIRTUAL_PREFIX + "/@rsc-hydrate", "");
@@ -1358,6 +1109,7 @@ if (document.readyState === 'loading') {
1358
1109
  logInfo("Dev server middleware ready");
1359
1110
  const serverStartTime = Date.now();
1360
1111
  let bannerPrinted = false;
1112
+ const pageCache = new Map();
1361
1113
  server.httpServer?.once("listening", () => {
1362
1114
  if (bannerPrinted)
1363
1115
  return;
@@ -1367,7 +1119,7 @@ if (document.readyState === 'loading') {
1367
1119
  const port = typeof address === "object" && address ? address.port : 3000;
1368
1120
  const colors = getColors();
1369
1121
  console.log("");
1370
- console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim(`v${FARM_VERSION}`)} ${colors.dim(`ready in ${elapsed}ms`)}`);
1122
+ console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim("v1.0.0")} ${colors.dim(`ready in ${elapsed}ms`)}`);
1371
1123
  console.log("");
1372
1124
  console.log(` ${colors.dim("➜")} ${colors.bold("Local:")} ${colors.cyan(`http://localhost:${port}/`)}`);
1373
1125
  console.log(` ${colors.dim("➜")} ${colors.bold("Network:")} ${colors.dim("use --host to expose")}`);
@@ -1477,15 +1229,276 @@ if (document.readyState === 'loading') {
1477
1229
  res.destroy(rscError instanceof Error ? rscError : new Error(String(rscError)));
1478
1230
  return;
1479
1231
  }
1480
- // Show the failure. Rendering another page instead (the old legacy
1481
- // SSR fallback) served the wrong page and hid the error.
1232
+ // RSC pipeline failed; fall back to legacy SSR for GET only
1233
+ if (method !== "GET" || rscError instanceof FarmDevEnvironmentError) {
1234
+ const duration = Date.now() - startTime;
1235
+ logResponse(method, pathname, 500, duration);
1236
+ console.error("[Farm.js] RSC dev handler error:", rscError);
1237
+ res.statusCode = 500;
1238
+ res.setHeader("Content-Type", "text/html");
1239
+ res.end(`<!DOCTYPE html><html><head><title>Error</title></head><body><pre>${rscError.message}</pre></body></html>`);
1240
+ return;
1241
+ }
1242
+ }
1243
+ try {
1244
+ if (method !== "GET")
1245
+ return next();
1246
+ // Get middleware data from standalone middleware plugin
1247
+ const middlewareData = req.__FARM_MIDDLEWARE_DATA__ || {};
1248
+ // Build the glob pattern for discovering routes (Farm convention: src/app when routesDir unset)
1249
+ const srcDir = entryContext.srcDir;
1250
+ const appSegment = entryContext.routesDir === undefined ? "app" : entryContext.routesDir.trim();
1251
+ const glob = appSegment ? `/${srcDir}/${appSegment}` : `/${srcDir}`;
1252
+ // Find matching page file
1253
+ const normalized = pathname.replace(/\/$/, "") || "/";
1254
+ // Common page file patterns
1255
+ const possiblePaths = [
1256
+ `${glob}${normalized === "/" ? "" : normalized}/page.tsx`,
1257
+ `${glob}${normalized === "/" ? "" : normalized}/page.jsx`,
1258
+ `${glob}/page.tsx`,
1259
+ `${glob}/page.jsx`,
1260
+ ];
1261
+ // Also check for dynamic routes by walking up the path
1262
+ const parts = normalized.split("/").filter(Boolean);
1263
+ for (let i = parts.length; i >= 0; i--) {
1264
+ const base = parts.slice(0, i).join("/");
1265
+ possiblePaths.push(base ? `${glob}/${base}/page.tsx` : `${glob}/page.tsx`);
1266
+ possiblePaths.push(base ? `${glob}/${base}/page.jsx` : `${glob}/page.jsx`);
1267
+ }
1268
+ let pageModule = null;
1269
+ let matchedPath = "";
1270
+ let layoutModule = null;
1271
+ // Try to find and load the page
1272
+ for (const pagePath of possiblePaths) {
1273
+ try {
1274
+ // Convert glob path to actual file path
1275
+ const actualPath = pagePath.startsWith("/") ? `.${pagePath}` : pagePath;
1276
+ if (pageCache.has(pagePath)) {
1277
+ pageModule = pageCache.get(pagePath);
1278
+ matchedPath = pagePath;
1279
+ break;
1280
+ }
1281
+ pageModule = await loadFarmDevModule(server, actualPath);
1282
+ if (pageModule?.default) {
1283
+ pageCache.set(pagePath, pageModule);
1284
+ matchedPath = pagePath;
1285
+ // Page loaded successfully
1286
+ break;
1287
+ }
1288
+ }
1289
+ catch (e) {
1290
+ // Page not found at this path, continue
1291
+ }
1292
+ }
1293
+ if (!pageModule?.default) {
1294
+ return next();
1295
+ }
1296
+ try {
1297
+ const layoutPath = `./${srcDir}${appSegment ? `/${appSegment}` : ""}/layout.tsx`;
1298
+ layoutModule = await loadFarmDevModule(server, layoutPath);
1299
+ }
1300
+ catch { }
1301
+ const React = await import("react");
1302
+ const ReactDOMServer = await import("react-dom/server");
1303
+ const Page = pageModule.default;
1304
+ const metadata = {
1305
+ title: typeof pageModule.metadata?.title === "string"
1306
+ ? pageModule.metadata.title
1307
+ : layoutModule?.metadata?.title,
1308
+ description: typeof pageModule.metadata?.description === "string"
1309
+ ? pageModule.metadata.description
1310
+ : layoutModule?.metadata?.description,
1311
+ };
1312
+ const Layout = layoutModule?.default;
1313
+ // Parse URL params (basic dynamic route support)
1314
+ const params = {};
1315
+ const searchParams = searchParamsToObject(resolveDevRequestURL(req).searchParams);
1316
+ // Render the page with middleware data
1317
+ const pageProps = {
1318
+ params,
1319
+ searchParams,
1320
+ // Middleware shared data is available to pages
1321
+ middlewareData,
1322
+ };
1323
+ // Helper to check if a function is async or returns a Promise
1324
+ // We need to actually call the function to detect this reliably
1325
+ // since transpiled async functions may not be detectable by constructor
1326
+ const isAsyncFunction = (fn) => {
1327
+ if (!fn)
1328
+ return false;
1329
+ // Check if it's an AsyncFunction
1330
+ if (fn.constructor?.name === "AsyncFunction")
1331
+ return true;
1332
+ // Check if function.toString() contains async
1333
+ try {
1334
+ const str = fn.toString();
1335
+ // Check for "async function" or "async (" patterns
1336
+ if (/^async\s/.test(str) || /^async\s*\(/.test(str))
1337
+ return true;
1338
+ }
1339
+ catch { }
1340
+ return false;
1341
+ };
1342
+ // Try to render the page - if it returns a Promise, it's async
1343
+ let pageContent;
1344
+ let isAsyncPage = isAsyncFunction(Page);
1345
+ try {
1346
+ const result = Page(pageProps);
1347
+ // Check if result is a Promise (thenable)
1348
+ if (result && typeof result.then === "function") {
1349
+ isAsyncPage = true;
1350
+ pageContent = await result;
1351
+ }
1352
+ else {
1353
+ // If it's not a Promise, it's a React element or we need to use createElement
1354
+ if (React.default.isValidElement(result)) {
1355
+ pageContent = result;
1356
+ }
1357
+ else {
1358
+ pageContent = React.default.createElement(Page, pageProps);
1359
+ }
1360
+ }
1361
+ }
1362
+ catch (e) {
1363
+ // If calling directly failed, use createElement
1364
+ pageContent = React.default.createElement(Page, pageProps);
1365
+ }
1366
+ // Check if Layout is async
1367
+ let isAsyncLayout = isAsyncFunction(Layout);
1368
+ // Wrap in layout if available
1369
+ let content = pageContent;
1370
+ if (Layout) {
1371
+ try {
1372
+ const layoutResult = Layout({ children: pageContent });
1373
+ if (layoutResult && typeof layoutResult.then === "function") {
1374
+ isAsyncLayout = true;
1375
+ content = await layoutResult;
1376
+ }
1377
+ else if (React.default.isValidElement(layoutResult)) {
1378
+ content = layoutResult;
1379
+ }
1380
+ else {
1381
+ content = React.default.createElement(Layout, null, pageContent);
1382
+ }
1383
+ }
1384
+ catch (e) {
1385
+ content = React.default.createElement(Layout, null, pageContent);
1386
+ }
1387
+ }
1388
+ // Create full HTML page
1389
+ const h = React.default.createElement;
1390
+ const isSyncPage = !isAsyncPage && !isAsyncLayout;
1391
+ // For sync pages we load preamble + vite client + hydrate in one script below; do not load vite-client in head so order is guaranteed.
1392
+ const routesDir = entryContext.routesDir === undefined ? "app" : entryContext.routesDir.trim();
1393
+ const routesPath = routesDir ? `/${routesDir}` : "";
1394
+ const headElements = [
1395
+ h("meta", { key: "charset", charSet: "utf-8" }),
1396
+ h("meta", {
1397
+ key: "viewport",
1398
+ name: "viewport",
1399
+ content: "width=device-width, initial-scale=1",
1400
+ }),
1401
+ metadata.title
1402
+ ? h("title", { key: "title" }, metadata.title)
1403
+ : h("title", { key: "title" }, "Farm.js"),
1404
+ metadata.description
1405
+ ? h("meta", {
1406
+ key: "description",
1407
+ name: "description",
1408
+ content: metadata.description,
1409
+ })
1410
+ : null,
1411
+ h("link", {
1412
+ key: "globals-css",
1413
+ rel: "stylesheet",
1414
+ href: `/${srcDir}${routesPath}/globals.css`,
1415
+ }),
1416
+ ...(isSyncPage
1417
+ ? []
1418
+ : [
1419
+ h("script", {
1420
+ key: "vite-client",
1421
+ type: "module",
1422
+ src: "/@vite/client",
1423
+ }),
1424
+ ]),
1425
+ ].filter(Boolean);
1426
+ // Create body elements
1427
+ // For async (server) pages, we don't hydrate the page itself - only client components within
1428
+ // For sync pages, we can hydrate the whole thing
1429
+ const bodyElements = [h("div", { key: "root", id: "root" }, content)];
1430
+ // Only add hydration script for sync pages (non-async)
1431
+ // When server actions are enabled, set __viteRscCallServer first so form submission works.
1432
+ if (actionsEnabled) {
1433
+ bodyElements.push(h("script", {
1434
+ key: "rsc-call-server",
1435
+ dangerouslySetInnerHTML: {
1436
+ __html: `(function(){if(typeof globalThis.__viteRscCallServer!=='function'){globalThis.__viteRscCallServer=function(){return Promise.reject(new Error('Farm.js: server actions not ready'));}}})();`,
1437
+ },
1438
+ }));
1439
+ }
1440
+ // Set React refresh preamble synchronously first so "use client" components don't throw when they load.
1441
+ if (!isAsyncPage && !isAsyncLayout) {
1442
+ bodyElements.push(h("script", {
1443
+ key: "preamble-sync",
1444
+ dangerouslySetInnerHTML: {
1445
+ __html: `window.__vite_plugin_react_preamble_installed__=true;window.$RefreshReg$=function(){};window.$RefreshSig$=function(){return function(t){return t;}};`,
1446
+ },
1447
+ }), h("script", {
1448
+ key: "page-props",
1449
+ dangerouslySetInnerHTML: {
1450
+ __html: `window.__PAGE_PROPS__ = ${JSON.stringify(pageProps)};`,
1451
+ },
1452
+ }), h("script", {
1453
+ key: "hydrate",
1454
+ type: "module",
1455
+ dangerouslySetInnerHTML: {
1456
+ __html: `import("/@react-refresh").then(m=>{m.default.injectIntoGlobalHook(window);return import("/@vite/client");}).then(()=>import(${JSON.stringify(`/@rsc-hydrate${normalized}`)}));`,
1457
+ },
1458
+ }));
1459
+ }
1460
+ else {
1461
+ // For async pages, we need to hydrate client component islands
1462
+ // Load a minimal script that finds and hydrates "use client" components
1463
+ bodyElements.push(h("script", {
1464
+ key: "client-islands",
1465
+ type: "module",
1466
+ dangerouslySetInnerHTML: {
1467
+ __html: `
1468
+ // Hydrate client component islands
1469
+ import '/@vite/client';
1470
+
1471
+ // Find all client components and hydrate them
1472
+ // The actual hydration is handled by @vitejs/plugin-rsc transforms
1473
+ `,
1474
+ },
1475
+ }));
1476
+ }
1477
+ const fullPage = h("html", { lang: "en" }, h("head", null, ...headElements), h("body", null, ...bodyElements));
1478
+ const html = "<!DOCTYPE html>" + ReactDOMServer.renderToString(fullPage);
1479
+ res.statusCode = 200;
1480
+ res.setHeader("Content-Type", "text/html");
1481
+ res.end(html);
1482
+ const duration = Date.now() - startTime;
1483
+ logResponse("GET", pathname, 200, duration);
1484
+ }
1485
+ catch (error) {
1482
1486
  const duration = Date.now() - startTime;
1483
- logResponse(method, pathname, 500, duration);
1484
- console.error(`[Farm.js] RSC render failed for ${method} ${pathname}:`, rscError);
1487
+ logResponse("GET", pathname, 500, duration);
1488
+ console.error(error);
1489
+ // Return error page
1485
1490
  res.statusCode = 500;
1486
- res.setHeader("Content-Type", "text/html; charset=utf-8");
1487
- res.setHeader("Cache-Control", "no-store");
1488
- res.end(createRscDevErrorDocument(rscError, method, pathname));
1491
+ res.setHeader("Content-Type", "text/html");
1492
+ res.end(`
1493
+ <!DOCTYPE html>
1494
+ <html>
1495
+ <head><title>Error</title></head>
1496
+ <body style="font-family: system-ui; padding: 2rem; background: #1a1a2e; color: #eee;">
1497
+ <h1 style="color: #ff6b6b;">Error</h1>
1498
+ <pre style="background: #16213e; padding: 1rem; border-radius: 8px; overflow: auto;">${error.stack || error.message}</pre>
1499
+ </body>
1500
+ </html>
1501
+ `);
1489
1502
  }
1490
1503
  });
1491
1504
  };