@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
@@ -14,9 +14,6 @@ type ExtractionResult = {
14
14
  reason: string;
15
15
  };
16
16
  export declare function extractRscMiddlewareConfigModule(source: string, program: AstNode): ExtractionResult;
17
- /** Extracts `key` from the default-exported config, as a module that exports `{ [key] }`. */
18
- export declare function extractRscConfigPropertyModule(source: string, program: AstNode, key: "middleware" | "mcp"): ExtractionResult;
19
17
  export declare function loadRscMiddlewareConfigModule(configPath: string): Promise<ExtractionResult>;
20
- export declare function loadRscConfigPropertyModule(configPath: string, key: "middleware" | "mcp"): Promise<ExtractionResult>;
21
18
  export {};
22
19
  //# sourceMappingURL=middleware-config-module.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-config-module.d.ts","sourceRoot":"","sources":["../../src/rsc/middleware-config-module.ts"],"names":[],"mappings":"AAQA,KAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AASF,KAAK,gBAAgB,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAgQ5C,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,GACf,gBAAgB,CAElB;AAED,6FAA6F;AAC7F,wBAAgB,8BAA8B,CAC5C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,YAAY,GAAG,KAAK,GACxB,gBAAgB,CA+IlB;AAiBD,wBAAsB,6BAA6B,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEjG;AAED,wBAAsB,2BAA2B,CAC/C,UAAU,EAAE,MAAM,EAClB,GAAG,EAAE,YAAY,GAAG,KAAK,GACxB,OAAO,CAAC,gBAAgB,CAAC,CAuB3B"}
1
+ {"version":3,"file":"middleware-config-module.d.ts","sourceRoot":"","sources":["../../src/rsc/middleware-config-module.ts"],"names":[],"mappings":"AAQA,KAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AASF,KAAK,gBAAgB,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AA4P5C,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,GACf,gBAAgB,CA+IlB;AAiBD,wBAAsB,6BAA6B,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAejG"}
@@ -202,7 +202,7 @@ function resolveConfigObject(node, variableInitializers, configHelpers, seen = n
202
202
  * leave the guard with a different matcher than the config it came from. Fail
203
203
  * on those instead of producing a module that disagrees with the config.
204
204
  */
205
- function unsupportedStatementReason(statement, source, key) {
205
+ function unsupportedStatementReason(statement, source) {
206
206
  switch (statement.type) {
207
207
  case "ImportDeclaration":
208
208
  if ((statement.specifiers ?? []).length > 0)
@@ -224,14 +224,10 @@ function unsupportedStatementReason(statement, source, key) {
224
224
  const text = source.slice(statement.start, statement.end).replace(/\s+/g, " ").trim();
225
225
  const snippet = text.length > 80 ? `${text.slice(0, 77)}...` : text;
226
226
  return statement.type === "ImportDeclaration"
227
- ? `the side-effect import \`${snippet}\` would not run with the extracted ${key}`
228
- : `the top-level statement \`${snippet}\` would not run with the extracted ${key}`;
227
+ ? `the side-effect import \`${snippet}\` would not run with the extracted middleware`
228
+ : `the top-level statement \`${snippet}\` would not run with the extracted middleware`;
229
229
  }
230
230
  export function extractRscMiddlewareConfigModule(source, program) {
231
- return extractRscConfigPropertyModule(source, program, "middleware");
232
- }
233
- /** Extracts `key` from the default-exported config, as a module that exports `{ [key] }`. */
234
- export function extractRscConfigPropertyModule(source, program, key) {
235
231
  const body = program.body ?? [];
236
232
  const bindings = new Map();
237
233
  const variableInitializers = new Map();
@@ -239,7 +235,7 @@ export function extractRscConfigPropertyModule(source, program, key) {
239
235
  let defaultExport = null;
240
236
  let order = 0;
241
237
  for (const statement of body) {
242
- const unsupported = unsupportedStatementReason(statement, source, key);
238
+ const unsupported = unsupportedStatementReason(statement, source);
243
239
  if (unsupported)
244
240
  return { kind: "unsupported", reason: unsupported };
245
241
  if (statement.type === "ImportDeclaration") {
@@ -317,33 +313,33 @@ export function extractRscConfigPropertyModule(source, program, key) {
317
313
  };
318
314
  }
319
315
  const properties = configObject.properties ?? [];
320
- let keyProperty = null;
321
- let keyIndex = -1;
316
+ let middlewareProperty = null;
317
+ let middlewareIndex = -1;
322
318
  for (const [index, property] of properties.entries()) {
323
- if (property.type === "Property" && propertyName(property) === key) {
324
- keyProperty = property;
325
- keyIndex = index;
319
+ if (property.type === "Property" && propertyName(property) === "middleware") {
320
+ middlewareProperty = property;
321
+ middlewareIndex = index;
326
322
  }
327
323
  }
328
- if (!keyProperty) {
324
+ if (!middlewareProperty) {
329
325
  if (properties.some((property) => property.type === "SpreadElement")) {
330
326
  return {
331
327
  kind: "unsupported",
332
- reason: `${key} may be supplied through a config spread`,
328
+ reason: "middleware may be supplied through a config spread",
333
329
  };
334
330
  }
335
331
  return { kind: "absent" };
336
332
  }
337
- if (properties.slice(keyIndex + 1).some((property) => property.type === "SpreadElement")) {
333
+ if (properties.slice(middlewareIndex + 1).some((property) => property.type === "SpreadElement")) {
338
334
  return {
339
335
  kind: "unsupported",
340
- reason: `a config spread after ${key} may override it`,
336
+ reason: "a config spread after middleware may override it",
341
337
  };
342
338
  }
343
- const keyValue = keyProperty.value;
339
+ const middlewareValue = middlewareProperty.value;
344
340
  const candidateNames = new Set(bindings.keys());
345
341
  const selectedBindings = new Set();
346
- const pending = [...referencedTopLevelNames(keyValue, candidateNames)];
342
+ const pending = [...referencedTopLevelNames(middlewareValue, candidateNames)];
347
343
  while (pending.length > 0) {
348
344
  const name = pending.pop();
349
345
  const binding = bindings.get(name);
@@ -359,13 +355,13 @@ export function extractRscConfigPropertyModule(source, program, key) {
359
355
  const declarations = [...selectedBindings]
360
356
  .sort((a, b) => a.order - b.order)
361
357
  .map((binding) => binding.render());
362
- const valueSource = source.slice(keyValue.start, keyValue.end);
358
+ const middlewareSource = source.slice(middlewareValue.start, middlewareValue.end);
363
359
  return {
364
360
  kind: "module",
365
- code: `${declarations.join("\n")}${declarations.length ? "\n" : ""}export default { ${key}: ${valueSource} };\n`,
361
+ code: `${declarations.join("\n")}${declarations.length ? "\n" : ""}export default { middleware: ${middlewareSource} };\n`,
366
362
  };
367
363
  }
368
- function sourceLang(file) {
364
+ function esbuildLoader(file) {
369
365
  switch (path.extname(file)) {
370
366
  case ".ts":
371
367
  case ".mts":
@@ -380,24 +376,15 @@ function sourceLang(file) {
380
376
  }
381
377
  }
382
378
  export async function loadRscMiddlewareConfigModule(configPath) {
383
- return loadRscConfigPropertyModule(configPath, "middleware");
384
- }
385
- export async function loadRscConfigPropertyModule(configPath, key) {
386
- const [{ readFile }, vite] = await Promise.all([import("node:fs/promises"), import("vite")]);
379
+ const [{ readFile }, { parseAst, transformWithEsbuild }] = await Promise.all([
380
+ import("node:fs/promises"),
381
+ import("vite"),
382
+ ]);
387
383
  const source = await readFile(configPath, "utf8");
388
- const lang = sourceLang(configPath);
389
- // Vite 8 transforms with Oxc and only reaches esbuild when the app installs it.
390
- // Vite 6 and 7 have no transformWithOxc and always ship esbuild.
391
- const transformed = typeof vite.transformWithOxc === "function"
392
- ? await vite.transformWithOxc(source, configPath, {
393
- lang,
394
- sourceType: "module",
395
- jsx: { runtime: "automatic" },
396
- })
397
- : await vite.transformWithEsbuild(source, configPath, {
398
- format: "esm",
399
- jsx: "automatic",
400
- loader: lang,
401
- });
402
- return extractRscConfigPropertyModule(transformed.code, vite.parseAst(transformed.code), key);
384
+ const transformed = await transformWithEsbuild(source, configPath, {
385
+ format: "esm",
386
+ jsx: "automatic",
387
+ loader: esbuildLoader(configPath),
388
+ });
389
+ return extractRscMiddlewareConfigModule(transformed.code, parseAst(transformed.code));
403
390
  }
@@ -1 +1 @@
1
- {"version":3,"file":"nitro-build.d.ts","sourceRoot":"","sources":["../../src/rsc/nitro-build.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgCH;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,GAClB,IAAI,CAKN;AAcD,gBAAgB;AAChB,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CAqCrF;AAuGD;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CA0Bf;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CAgCf;AA8FD,MAAM,MAAM,oBAAoB,GAAG;IACjC,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AA0NF,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAwIhF"}
1
+ {"version":3,"file":"nitro-build.d.ts","sourceRoot":"","sources":["../../src/rsc/nitro-build.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAwBH;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,GAClB,IAAI,CAKN;AAcD,gBAAgB;AAChB,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CA8BrF;AA4ED;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CA0Bf;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CAgCf;AAwFD,MAAM,MAAM,oBAAoB,GAAG;IACjC,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAyLhF"}
@@ -5,10 +5,8 @@
5
5
  */
6
6
  import path from "path";
7
7
  import { createRequire } from "node:module";
8
- import { writeFileSync, readFileSync, mkdirSync, copyFileSync, existsSync, readdirSync, lstatSync, rmSync, statSync, symlinkSync, } from "fs";
9
- import { FARM_NODE_ENV_MODULE_FILE, FARM_NODE_ENV_MODULE_SOURCE, } from "@farm.js/core/internal/production-node-env";
8
+ import { writeFileSync, readFileSync, mkdirSync, copyFileSync, existsSync, readdirSync, statSync, } from "fs";
10
9
  import { resolveRscBuildOutputPath } from "./build-paths.js";
11
- import { finalizeFarmRscMobileClient, patchFarmRscMobileShellClient } from "./mobile-client.js";
12
10
  const MANIFEST_FILENAME = "__vite_rsc_assets_manifest.js";
13
11
  const MIN_MANIFEST_BYTES = 100; // real manifest is ~500+, stub is 64
14
12
  const POLL_INTERVAL_MS = 50;
@@ -64,16 +62,9 @@ export function rewriteRscEntryImports(serverDir, serverDistDir) {
64
62
  const relative = path.relative(path.dirname(entryChunkPath), target).replace(/\\/g, "/");
65
63
  return relative.startsWith(".") ? relative : `./${relative}`;
66
64
  };
67
- // Match any path that ends with dist/rsc/index.js, dist/ssr/index.js or the NODE_ENV module
68
- // (minified, no spaces)
69
- for (const [environment, file] of [
70
- ["rsc", "index.js"],
71
- ["rsc", FARM_NODE_ENV_MODULE_FILE],
72
- ["ssr", "index.js"],
73
- ]) {
74
- const pattern = new RegExp(`(["'\`])[^"'\`]*?dist/${environment}/${file.replace(/\./g, "\\.")}\\1`, "g");
75
- code = code.replace(pattern, JSON.stringify(relativeImport(path.join(serverDistDir, environment, file))));
76
- }
65
+ // Match any path that ends with dist/rsc/index.js or dist/ssr/index.js (minified, no spaces)
66
+ code = code.replace(/(["'`])[^"'`]*?dist\/rsc\/index\.js\1/g, JSON.stringify(relativeImport(path.join(serverDistDir, "rsc", "index.js"))));
67
+ code = code.replace(/(["'`])[^"'`]*?dist\/ssr\/index\.js\1/g, JSON.stringify(relativeImport(path.join(serverDistDir, "ssr", "index.js"))));
77
68
  writeFileSync(entryChunkPath, code, "utf-8");
78
69
  }
79
70
  }
@@ -107,36 +98,6 @@ function detectBundledRscRuntimes(rendererPath) {
107
98
  }
108
99
  return packages;
109
100
  }
110
- /**
111
- * The prerender server runs the Vite output in place, before the runtime packages are copied next
112
- * to the server output, and a strict install (pnpm) does not expose a package the plugin depends
113
- * on from the app root. Links them where the Vite output resolves from; returns the cleanup.
114
- */
115
- function linkRuntimePackages(viteDistDir, packages) {
116
- const nodeModules = path.join(viteDistDir, "node_modules");
117
- const ownsNodeModules = !existsSync(nodeModules);
118
- const links = [];
119
- for (const [packageName, packageRoot] of packages) {
120
- const link = path.join(nodeModules, ...packageName.split("/"));
121
- try {
122
- lstatSync(link);
123
- continue;
124
- }
125
- catch { }
126
- mkdirSync(path.dirname(link), { recursive: true });
127
- // A junction needs no privileges on Windows; elsewhere the type is ignored.
128
- symlinkSync(packageRoot, link, "junction");
129
- links.push(link);
130
- }
131
- return () => {
132
- // Removes the links, never what they point at.
133
- if (ownsNodeModules)
134
- rmSync(nodeModules, { recursive: true, force: true });
135
- else
136
- for (const link of links)
137
- rmSync(link, { force: true });
138
- };
139
- }
140
101
  function copyRuntimePackages(serverDir, packages) {
141
102
  if (packages.size === 0)
142
103
  return;
@@ -246,13 +207,7 @@ function writeRscEntryFile(buildDir, rendererPath, ssrPath) {
246
207
  const setSsLoader = relSsr
247
208
  ? `globalThis.__VITE_RSC_LOAD_SSR__ = () => import("./${relSsr}");`
248
209
  : "";
249
- // Imported first and kept external like the bundles, so it runs before React picks its
250
- // development or production build from NODE_ENV. Inlined, it would run after them.
251
- const relNodeEnv = path
252
- .relative(buildDir, path.join(path.dirname(resolvedRenderer), FARM_NODE_ENV_MODULE_FILE))
253
- .replace(/\\/g, "/");
254
210
  const code = `
255
- import "./${relNodeEnv}";
256
211
  ${setSsLoader}
257
212
  import * as entryExports from "./${relRenderer}";
258
213
  import { defineEventHandler } from "h3";
@@ -327,208 +282,13 @@ export default defineEventHandler(async (event) => {
327
282
  writeFileSync(entryPath, code, "utf-8");
328
283
  return entryPath;
329
284
  }
330
- function listModuleFiles(dir) {
331
- if (!existsSync(dir))
332
- return [];
333
- const files = [];
334
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
335
- const full = path.join(dir, entry.name);
336
- if (entry.isDirectory())
337
- files.push(...listModuleFiles(full));
338
- else if (/\.(?:m|c)?js$/.test(entry.name))
339
- files.push(full);
340
- }
341
- return files;
342
- }
343
- /**
344
- * Copy the packages the RSC and SSR bundles load into the server output. Nitro traces only its own
345
- * bundle, and these are copied in afterwards; their code-split chunks and dynamic imports (such as
346
- * shiki's WebAssembly engine) reach package files the entry files alone do not. The RSC bundle
347
- * resolves packages with the react-server condition, the SSR bundle without it.
348
- */
349
- async function traceRscBundleDependencies(root, serverDir, rscDir, ssrDir) {
350
- const { traceNodeModules } = await import("nf3");
351
- const traces = [
352
- [listModuleFiles(rscDir), ["react-server", "node", "import", "default"]],
353
- [ssrDir ? listModuleFiles(ssrDir) : [], ["node", "import", "default"]],
354
- ];
355
- for (const [files, conditions] of traces) {
356
- if (files.length === 0)
357
- continue;
358
- await traceNodeModules(files, { rootDir: root, outDir: serverDir, conditions });
359
- }
360
- }
361
- /**
362
- * Give the SSR bundle the production client CSS href and bootstrap script, so its HTML has styles
363
- * and hydrates. Runs on the Vite output before Nitro, so the prerender pass and the copies in the
364
- * server output render the same document. Only placeholders are replaced, so it is idempotent.
365
- */
366
- function patchRscServerBundles(root, rscDir, ssrDir, publicDir, assetsDir) {
367
- // Patch SSR bundle: inject production client CSS href and bootstrap script so HTML has styles and hydration works
368
- const ssrIndexPath = path.join(ssrDir, "index.js");
369
- const manifestPath = path.join(rscDir, MANIFEST_FILENAME);
370
- let bootstrapScriptContent = "";
371
- let clientEntryHref = "";
372
- const RSC_CALL_SERVER_PLACEHOLDER = "(function(){if(typeof globalThis.__viteRscCallServer!=='function'){globalThis.__viteRscCallServer=function(){return Promise.reject(new Error(\"Farm.js: server actions not ready\"));}}})();\n";
373
- if (existsSync(manifestPath)) {
374
- try {
375
- const manifestContent = readFileSync(manifestPath, "utf-8");
376
- const start = manifestContent.indexOf("{");
377
- const end = manifestContent.lastIndexOf("}") + 1;
378
- if (start >= 0 && end > start) {
379
- const manifest = JSON.parse(manifestContent.slice(start, end));
380
- bootstrapScriptContent = manifest.bootstrapScriptContent || "";
381
- const importMatch = bootstrapScriptContent.match(/^import\s*\(\s*["']([^"']+)["']\s*\)\s*$/);
382
- if (importMatch)
383
- clientEntryHref = importMatch[1];
384
- }
385
- }
386
- catch {
387
- // ignore
388
- }
389
- }
390
- const fullBootstrap = bootstrapScriptContent
391
- ? RSC_CALL_SERVER_PLACEHOLDER + bootstrapScriptContent
392
- : "";
393
- // Patch manifest so production SSR gets bootstrap with __viteRscCallServer placeholder (SSR reads assetsManifest.bootstrapScriptContent)
394
- if (fullBootstrap && existsSync(manifestPath)) {
395
- try {
396
- let manifestCode = readFileSync(manifestPath, "utf-8");
397
- const escaped = JSON.stringify(bootstrapScriptContent);
398
- const escapedFull = JSON.stringify(fullBootstrap);
399
- if (manifestCode.includes(escaped) && escaped !== escapedFull) {
400
- manifestCode = manifestCode.replace(escaped, escapedFull);
401
- writeFileSync(manifestPath, manifestCode, "utf-8");
402
- }
403
- }
404
- catch {
405
- // ignore
406
- }
407
- }
408
- const assetsDirName = assetsDir ?? "assets";
409
- const assetsRoot = path.join(publicDir, assetsDirName);
410
- let clientCssHref = "";
411
- if (existsSync(assetsRoot)) {
412
- const files = readdirSync(assetsRoot);
413
- const cssFile = files.find((f) => f.endsWith(".css"));
414
- if (cssFile)
415
- clientCssHref = `/${assetsDirName}/${cssFile}`;
416
- }
417
- // An app with a `mobile` block: the server learns the mobile entry its shell documents load.
418
- // Only a build with the mobile entry has the placeholder, so other apps are left as they are.
419
- patchFarmRscMobileShellClient(rscDir, () => finalizeFarmRscMobileClient({
420
- root,
421
- clientDir: publicDir,
422
- webEntry: clientEntryHref,
423
- stylesheet: clientCssHref,
424
- }));
425
- if (existsSync(ssrIndexPath)) {
426
- try {
427
- let ssrCode = readFileSync(ssrIndexPath, "utf-8");
428
- // Only the assignment: the bundle also compares against the placeholder, and a second
429
- // run over an already patched bundle must leave that comparison intact.
430
- ssrCode = ssrCode.replace(/(CLIENT_CSS_HREF\s*=\s*)"__FARM_CLIENT_CSS_HREF__"/, "$1" + JSON.stringify(clientCssHref));
431
- if (clientEntryHref && ssrCode.includes("__FARM_CLIENT_ENTRY_HREF__")) {
432
- ssrCode = ssrCode.replace(/(CLIENT_ENTRY_HREF\s*=\s*)"__FARM_CLIENT_ENTRY_HREF__"/, "$1" + JSON.stringify(clientEntryHref));
433
- }
434
- if (fullBootstrap && ssrCode.includes("__FARM_BOOTSTRAP_SCRIPT__")) {
435
- ssrCode = ssrCode.replace(/=\s*["']__FARM_BOOTSTRAP_SCRIPT__["']/, "= " + JSON.stringify(fullBootstrap));
436
- }
437
- writeFileSync(ssrIndexPath, ssrCode, "utf-8");
438
- }
439
- catch {
440
- // ignore
441
- }
442
- }
443
- }
444
- /** The route the RSC entry answers, during the prerender pass only, with its static pages. */
445
- const FARM_PRERENDER_ROUTES_PATH = "/__farm/rsc-prerender-routes";
446
- /**
447
- * Prerender the app's static pages and their RSC payloads into the public output with Nitro's
448
- * prerenderer, which serves them before the server on every preset. The RSC entry lists the pages
449
- * (it has the route modules and their generateStaticParams), through Nitro's x-nitro-prerender
450
- * header on a seed route that is removed afterwards.
451
- */
452
- async function prerenderRscPages(nitro, prerender, viteDistDir) {
453
- nitro.options.prerender = {
454
- ...nitro.options.prerender,
455
- routes: [FARM_PRERENDER_ROUTES_PATH],
456
- crawlLinks: false,
457
- // Failures are judged below: a seed that cannot run only skips prerendering.
458
- failOnError: false,
459
- };
460
- // The prerender server is a separate Nitro build of the same renderer entry. Point its imports of
461
- // the prebuilt bundles at the Vite output, as the server output's are pointed at their copies.
462
- nitro.hooks.hook("prerender:init", (prerenderer) => {
463
- prerenderer.hooks.hook("compiled", () => {
464
- rewriteRscEntryImports(prerenderer.options.output.serverDir, viteDistDir);
465
- });
466
- });
467
- let seedError;
468
- const failedPages = [];
469
- nitro.hooks.hook("prerender:route", (route) => {
470
- if (route.route !== FARM_PRERENDER_ROUTES_PATH) {
471
- if (route.error)
472
- failedPages.push(`${route.route} (${route.error.message})`);
473
- return;
474
- }
475
- seedError = route.error;
476
- removeSeedOutput(nitro, route.fileName);
477
- });
478
- const previous = process.env.FARM_RSC_PRERENDER;
479
- process.env.FARM_RSC_PRERENDER = "1";
480
- try {
481
- await prerender(nitro);
482
- }
483
- finally {
484
- if (previous === undefined)
485
- delete process.env.FARM_RSC_PRERENDER;
486
- else
487
- process.env.FARM_RSC_PRERENDER = previous;
488
- }
489
- if (seedError) {
490
- // The server could not start in place (for example, a runtime package only the server output
491
- // carries). Every page still renders on request, so the build goes on without static files.
492
- console.warn(`[FARM] Prerendering skipped: the server could not list its static pages (${seedError.message}). Pages render on each request.`);
493
- return;
494
- }
495
- if (failedPages.length > 0) {
496
- // A page that asks to be static and fails to render fails the build, as in Next.js.
497
- throw new Error(`[FARM] Prerendering failed for:\n ${failedPages.join("\n ")}`);
498
- }
499
- }
500
- /** Remove the seed route's file, and the directories it created, from the public output. */
501
- function removeSeedOutput(nitro, fileName) {
502
- const publicDir = path.resolve(nitro.options.output.publicDir);
503
- const prerendered = nitro
504
- ._prerenderedRoutes;
505
- const index = prerendered?.findIndex((entry) => entry.route === FARM_PRERENDER_ROUTES_PATH) ?? -1;
506
- if (index >= 0)
507
- prerendered.splice(index, 1);
508
- if (!fileName)
509
- return;
510
- let target = path.join(publicDir, fileName);
511
- rmSync(target, { force: true });
512
- for (target = path.dirname(target); target.startsWith(publicDir + path.sep) &&
513
- existsSync(target) &&
514
- readdirSync(target).length === 0; target = path.dirname(target)) {
515
- rmSync(target, { recursive: true });
516
- }
517
- }
518
285
  export async function buildRscNitro(options) {
519
- const { rendererPath, publicDir, ssrPath, assetsDir, root, preset = "vercel" } = options;
520
- const outputDir = options.outputDir ?? path.join(root, ".output");
521
- const { build, copyPublicAssets, createNitro, prepare, prerender } = await import("nitro/builder");
286
+ const { rendererPath, publicDir, ssrPath, assetsDir, root, outputDir = path.join(root, ".output"), preset = "vercel", } = options;
287
+ const { build, copyPublicAssets, createNitro, prepare } = await import("nitro/builder");
522
288
  console.log(`[FARM] Building RSC server with Nitro (preset: ${preset})...`);
523
289
  const buildDir = path.join(root, ".nitro");
524
- // Vercel's Build Output API has its own layout (functions/, static/), which the preset owns when
525
- // the caller names the deployment directory (`farm build`). Without one, the output keeps the
526
- // server/ and public/ layout that hand-written post-build scripts copy from.
527
- const presetOwnsLayout = options.outputDir !== undefined && (preset === "vercel" || preset === "vercel-edge");
528
- // The server sets NODE_ENV to "production" unless the deployment chose one, as the core
529
- // node-server output does. The RSC and SSR bundles read it at runtime: left unset, React loads
530
- // its development builds and Flight responses carry server component props, stacks and paths.
531
- writeFileSync(path.join(path.dirname(path.resolve(rendererPath)), FARM_NODE_ENV_MODULE_FILE), FARM_NODE_ENV_MODULE_SOURCE, "utf-8");
290
+ const serverDir = path.join(outputDir, "server");
291
+ const publicOutDir = path.join(outputDir, "public");
532
292
  const entryPath = writeRscEntryFile(buildDir, rendererPath, ssrPath);
533
293
  const registeredRuntimePackages = new Map(runtimePackagesByRoot.get(path.resolve(root)) ?? []);
534
294
  for (const [packageName, packageRoot] of detectBundledRscRuntimes(rendererPath)) {
@@ -557,13 +317,11 @@ export async function buildRscNitro(options) {
557
317
  alias: {
558
318
  h3: runtimeRequire.resolve("h3"),
559
319
  },
560
- output: presetOwnsLayout
561
- ? { dir: outputDir }
562
- : {
563
- dir: outputDir,
564
- serverDir: path.join(outputDir, "server"),
565
- publicDir: path.join(outputDir, "public"),
566
- },
320
+ output: {
321
+ dir: outputDir,
322
+ serverDir,
323
+ publicDir: publicOutDir,
324
+ },
567
325
  publicAssets,
568
326
  renderer: { handler: entryPath },
569
327
  // The prebuilt RSC/SSR bundles are copied after Nitro finishes, so Nitro's
@@ -585,21 +343,9 @@ export async function buildRscNitro(options) {
585
343
  compatibilityDate: "2024-12-01",
586
344
  minify: true,
587
345
  };
588
- if (ssrPath) {
589
- patchRscServerBundles(path.resolve(root), path.dirname(path.resolve(rendererPath)), path.dirname(path.resolve(ssrPath)), publicDir, assetsDir);
590
- }
591
346
  const nitro = await createNitro(config);
592
- const serverDir = nitro.options.output.serverDir;
593
347
  await prepare(nitro);
594
348
  await copyPublicAssets(nitro);
595
- const viteDistDir = path.dirname(path.dirname(path.resolve(rendererPath)));
596
- const unlinkRuntimePackages = linkRuntimePackages(viteDistDir, registeredRuntimePackages);
597
- try {
598
- await prerenderRscPages(nitro, prerender, viteDistDir);
599
- }
600
- finally {
601
- unlinkRuntimePackages();
602
- }
603
349
  await build(nitro);
604
350
  await nitro.close();
605
351
  copyRuntimePackages(serverDir, registeredRuntimePackages);
@@ -611,7 +357,6 @@ export async function buildRscNitro(options) {
611
357
  copyDir(rscSrc, path.join(serverDistDir, "rsc"));
612
358
  if (ssrSrc)
613
359
  copyDir(ssrSrc, path.join(serverDistDir, "ssr"));
614
- await traceRscBundleDependencies(root, serverDir, rscSrc, ssrSrc);
615
360
  // Stub manifest if missing (RSC plugin may write it after our hook runs)
616
361
  const rscDestDir = path.join(serverDistDir, "rsc");
617
362
  const manifestDest = path.join(rscDestDir, "__vite_rsc_assets_manifest.js");
@@ -622,6 +367,74 @@ export async function buildRscNitro(options) {
622
367
  // Nitro may group the entry differently by builder. Make copied-dist imports
623
368
  // relative to the emitted chunk so output survives moving away from the project.
624
369
  rewriteRscEntryImports(serverDir, serverDistDir);
370
+ // Patch SSR bundle: inject production client CSS href and bootstrap script so HTML has styles and hydration works
371
+ const ssrIndexPath = path.join(serverDistDir, "ssr", "index.js");
372
+ const manifestPath = path.join(serverDistDir, "rsc", MANIFEST_FILENAME);
373
+ let bootstrapScriptContent = "";
374
+ let clientEntryHref = "";
375
+ const RSC_CALL_SERVER_PLACEHOLDER = "(function(){if(typeof globalThis.__viteRscCallServer!=='function'){globalThis.__viteRscCallServer=function(){return Promise.reject(new Error(\"Farm.js: server actions not ready\"));}}})();\n";
376
+ if (existsSync(manifestPath)) {
377
+ try {
378
+ const manifestContent = readFileSync(manifestPath, "utf-8");
379
+ const start = manifestContent.indexOf("{");
380
+ const end = manifestContent.lastIndexOf("}") + 1;
381
+ if (start >= 0 && end > start) {
382
+ const manifest = JSON.parse(manifestContent.slice(start, end));
383
+ bootstrapScriptContent = manifest.bootstrapScriptContent || "";
384
+ const importMatch = bootstrapScriptContent.match(/^import\s*\(\s*["']([^"']+)["']\s*\)\s*$/);
385
+ if (importMatch)
386
+ clientEntryHref = importMatch[1];
387
+ }
388
+ }
389
+ catch {
390
+ // ignore
391
+ }
392
+ }
393
+ const fullBootstrap = bootstrapScriptContent
394
+ ? RSC_CALL_SERVER_PLACEHOLDER + bootstrapScriptContent
395
+ : "";
396
+ // Patch manifest so production SSR gets bootstrap with __viteRscCallServer placeholder (SSR reads assetsManifest.bootstrapScriptContent)
397
+ if (fullBootstrap && existsSync(manifestPath)) {
398
+ try {
399
+ let manifestCode = readFileSync(manifestPath, "utf-8");
400
+ const escaped = JSON.stringify(bootstrapScriptContent);
401
+ const escapedFull = JSON.stringify(fullBootstrap);
402
+ if (manifestCode.includes(escaped) && escaped !== escapedFull) {
403
+ manifestCode = manifestCode.replace(escaped, escapedFull);
404
+ writeFileSync(manifestPath, manifestCode, "utf-8");
405
+ }
406
+ }
407
+ catch {
408
+ // ignore
409
+ }
410
+ }
411
+ if (existsSync(ssrIndexPath)) {
412
+ const assetsDirName = assetsDir ?? "assets";
413
+ const assetsRoot = path.join(publicDir, assetsDirName);
414
+ let clientCssHref = "";
415
+ if (existsSync(assetsRoot)) {
416
+ const files = readdirSync(assetsRoot);
417
+ const cssFile = files.find((f) => f.endsWith(".css"));
418
+ if (cssFile)
419
+ clientCssHref = `/${assetsDirName}/${cssFile}`;
420
+ }
421
+ try {
422
+ let ssrCode = readFileSync(ssrIndexPath, "utf-8");
423
+ if (ssrCode.includes("__FARM_CLIENT_CSS_HREF__")) {
424
+ ssrCode = ssrCode.replace("__FARM_CLIENT_CSS_HREF__", clientCssHref);
425
+ }
426
+ if (clientEntryHref && ssrCode.includes("__FARM_CLIENT_ENTRY_HREF__")) {
427
+ ssrCode = ssrCode.replace(/(CLIENT_ENTRY_HREF\s*=\s*)"__FARM_CLIENT_ENTRY_HREF__"/, "$1" + JSON.stringify(clientEntryHref));
428
+ }
429
+ if (fullBootstrap && ssrCode.includes("__FARM_BOOTSTRAP_SCRIPT__")) {
430
+ ssrCode = ssrCode.replace(/=\s*["']__FARM_BOOTSTRAP_SCRIPT__["']/, "= " + JSON.stringify(fullBootstrap));
431
+ }
432
+ writeFileSync(ssrIndexPath, ssrCode, "utf-8");
433
+ }
434
+ catch {
435
+ // ignore
436
+ }
437
+ }
625
438
  console.log("[FARM] RSC Nitro build completed");
626
439
  console.log(`[FARM] Output: ${outputDir}`);
627
440
  }
@@ -1,2 +1,6 @@
1
- export * from "@farm.js/core/internal/server-fn-transform";
1
+ export type FarmServerFnTransformResult = {
2
+ code: string;
3
+ exports: string[];
4
+ };
5
+ export declare function transformFarmServerFns(code: string, id: string): FarmServerFnTransformResult | null;
2
6
  //# sourceMappingURL=server-fn-transform.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-fn-transform.d.ts","sourceRoot":"","sources":["../../src/rsc/server-fn-transform.ts"],"names":[],"mappings":"AAEA,cAAc,4CAA4C,CAAC"}
1
+ {"version":3,"file":"server-fn-transform.d.ts","sourceRoot":"","sources":["../../src/rsc/server-fn-transform.ts"],"names":[],"mappings":"AAkBA,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,2BAA2B,GAAG,IAAI,CAoDpC"}