@farm.js/plugin 0.1.51-beta.3 → 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 (38) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/middleware/index.d.ts +1 -8
  5. package/dist/middleware/index.d.ts.map +1 -1
  6. package/dist/middleware/index.js +10 -16
  7. package/dist/middleware/matching.d.ts +2 -4
  8. package/dist/middleware/matching.d.ts.map +1 -1
  9. package/dist/middleware/matching.js +47 -7
  10. package/dist/rsc/entries/client.d.ts.map +1 -1
  11. package/dist/rsc/entries/client.js +9 -22
  12. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  13. package/dist/rsc/entries/rsc.js +40 -533
  14. package/dist/rsc/entries/ssr.d.ts.map +1 -1
  15. package/dist/rsc/entries/ssr.js +6 -7
  16. package/dist/rsc/index.d.ts +2 -35
  17. package/dist/rsc/index.d.ts.map +1 -1
  18. package/dist/rsc/index.js +290 -238
  19. package/dist/rsc/middleware-config-module.d.ts +0 -3
  20. package/dist/rsc/middleware-config-module.d.ts.map +1 -1
  21. package/dist/rsc/middleware-config-module.js +28 -41
  22. package/dist/rsc/nitro-build.d.ts.map +1 -1
  23. package/dist/rsc/nitro-build.js +81 -259
  24. package/dist/rsc/server-fn-transform.d.ts +5 -1
  25. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  26. package/dist/rsc/server-fn-transform.js +338 -3
  27. package/dist/rsc/types.d.ts +0 -28
  28. package/dist/rsc/types.d.ts.map +1 -1
  29. package/dist/rsc/vite-plugin-nitro.d.ts +0 -2
  30. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  31. package/dist/rsc/vite-plugin-nitro.js +2 -12
  32. package/package.json +3 -3
  33. package/dist/rsc/client-sourcemaps.d.ts +0 -13
  34. package/dist/rsc/client-sourcemaps.d.ts.map +0 -1
  35. package/dist/rsc/client-sourcemaps.js +0 -52
  36. package/dist/rsc/document-layouts.d.ts +0 -16
  37. package/dist/rsc/document-layouts.d.ts.map +0 -1
  38. package/dist/rsc/document-layouts.js +0 -82
@@ -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;AA+BH;;;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;AA+MF,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAuIhF"}
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,8 +5,7 @@
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
10
  const MANIFEST_FILENAME = "__vite_rsc_assets_manifest.js";
12
11
  const MIN_MANIFEST_BYTES = 100; // real manifest is ~500+, stub is 64
@@ -63,16 +62,9 @@ export function rewriteRscEntryImports(serverDir, serverDistDir) {
63
62
  const relative = path.relative(path.dirname(entryChunkPath), target).replace(/\\/g, "/");
64
63
  return relative.startsWith(".") ? relative : `./${relative}`;
65
64
  };
66
- // Match any path that ends with dist/rsc/index.js, dist/ssr/index.js or the NODE_ENV module
67
- // (minified, no spaces)
68
- for (const [environment, file] of [
69
- ["rsc", "index.js"],
70
- ["rsc", FARM_NODE_ENV_MODULE_FILE],
71
- ["ssr", "index.js"],
72
- ]) {
73
- const pattern = new RegExp(`(["'\`])[^"'\`]*?dist/${environment}/${file.replace(/\./g, "\\.")}\\1`, "g");
74
- code = code.replace(pattern, JSON.stringify(relativeImport(path.join(serverDistDir, environment, file))));
75
- }
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"))));
76
68
  writeFileSync(entryChunkPath, code, "utf-8");
77
69
  }
78
70
  }
@@ -106,36 +98,6 @@ function detectBundledRscRuntimes(rendererPath) {
106
98
  }
107
99
  return packages;
108
100
  }
109
- /**
110
- * The prerender server runs the Vite output in place, before the runtime packages are copied next
111
- * to the server output, and a strict install (pnpm) does not expose a package the plugin depends
112
- * on from the app root. Links them where the Vite output resolves from; returns the cleanup.
113
- */
114
- function linkRuntimePackages(viteDistDir, packages) {
115
- const nodeModules = path.join(viteDistDir, "node_modules");
116
- const ownsNodeModules = !existsSync(nodeModules);
117
- const links = [];
118
- for (const [packageName, packageRoot] of packages) {
119
- const link = path.join(nodeModules, ...packageName.split("/"));
120
- try {
121
- lstatSync(link);
122
- continue;
123
- }
124
- catch { }
125
- mkdirSync(path.dirname(link), { recursive: true });
126
- // A junction needs no privileges on Windows; elsewhere the type is ignored.
127
- symlinkSync(packageRoot, link, "junction");
128
- links.push(link);
129
- }
130
- return () => {
131
- // Removes the links, never what they point at.
132
- if (ownsNodeModules)
133
- rmSync(nodeModules, { recursive: true, force: true });
134
- else
135
- for (const link of links)
136
- rmSync(link, { force: true });
137
- };
138
- }
139
101
  function copyRuntimePackages(serverDir, packages) {
140
102
  if (packages.size === 0)
141
103
  return;
@@ -245,13 +207,7 @@ function writeRscEntryFile(buildDir, rendererPath, ssrPath) {
245
207
  const setSsLoader = relSsr
246
208
  ? `globalThis.__VITE_RSC_LOAD_SSR__ = () => import("./${relSsr}");`
247
209
  : "";
248
- // Imported first and kept external like the bundles, so it runs before React picks its
249
- // development or production build from NODE_ENV. Inlined, it would run after them.
250
- const relNodeEnv = path
251
- .relative(buildDir, path.join(path.dirname(resolvedRenderer), FARM_NODE_ENV_MODULE_FILE))
252
- .replace(/\\/g, "/");
253
210
  const code = `
254
- import "./${relNodeEnv}";
255
211
  ${setSsLoader}
256
212
  import * as entryExports from "./${relRenderer}";
257
213
  import { defineEventHandler } from "h3";
@@ -326,200 +282,13 @@ export default defineEventHandler(async (event) => {
326
282
  writeFileSync(entryPath, code, "utf-8");
327
283
  return entryPath;
328
284
  }
329
- function listModuleFiles(dir) {
330
- if (!existsSync(dir))
331
- return [];
332
- const files = [];
333
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
334
- const full = path.join(dir, entry.name);
335
- if (entry.isDirectory())
336
- files.push(...listModuleFiles(full));
337
- else if (/\.(?:m|c)?js$/.test(entry.name))
338
- files.push(full);
339
- }
340
- return files;
341
- }
342
- /**
343
- * Copy the packages the RSC and SSR bundles load into the server output. Nitro traces only its own
344
- * bundle, and these are copied in afterwards; their code-split chunks and dynamic imports (such as
345
- * shiki's WebAssembly engine) reach package files the entry files alone do not. The RSC bundle
346
- * resolves packages with the react-server condition, the SSR bundle without it.
347
- */
348
- async function traceRscBundleDependencies(root, serverDir, rscDir, ssrDir) {
349
- const { traceNodeModules } = await import("nf3");
350
- const traces = [
351
- [listModuleFiles(rscDir), ["react-server", "node", "import", "default"]],
352
- [ssrDir ? listModuleFiles(ssrDir) : [], ["node", "import", "default"]],
353
- ];
354
- for (const [files, conditions] of traces) {
355
- if (files.length === 0)
356
- continue;
357
- await traceNodeModules(files, { rootDir: root, outDir: serverDir, conditions });
358
- }
359
- }
360
- /**
361
- * Give the SSR bundle the production client CSS href and bootstrap script, so its HTML has styles
362
- * and hydrates. Runs on the Vite output before Nitro, so the prerender pass and the copies in the
363
- * server output render the same document. Only placeholders are replaced, so it is idempotent.
364
- */
365
- function patchRscServerBundles(rscDir, ssrDir, publicDir, assetsDir) {
366
- // Patch SSR bundle: inject production client CSS href and bootstrap script so HTML has styles and hydration works
367
- const ssrIndexPath = path.join(ssrDir, "index.js");
368
- const manifestPath = path.join(rscDir, MANIFEST_FILENAME);
369
- let bootstrapScriptContent = "";
370
- let clientEntryHref = "";
371
- 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";
372
- if (existsSync(manifestPath)) {
373
- try {
374
- const manifestContent = readFileSync(manifestPath, "utf-8");
375
- const start = manifestContent.indexOf("{");
376
- const end = manifestContent.lastIndexOf("}") + 1;
377
- if (start >= 0 && end > start) {
378
- const manifest = JSON.parse(manifestContent.slice(start, end));
379
- bootstrapScriptContent = manifest.bootstrapScriptContent || "";
380
- const importMatch = bootstrapScriptContent.match(/^import\s*\(\s*["']([^"']+)["']\s*\)\s*$/);
381
- if (importMatch)
382
- clientEntryHref = importMatch[1];
383
- }
384
- }
385
- catch {
386
- // ignore
387
- }
388
- }
389
- const fullBootstrap = bootstrapScriptContent
390
- ? RSC_CALL_SERVER_PLACEHOLDER + bootstrapScriptContent
391
- : "";
392
- // Patch manifest so production SSR gets bootstrap with __viteRscCallServer placeholder (SSR reads assetsManifest.bootstrapScriptContent)
393
- if (fullBootstrap && existsSync(manifestPath)) {
394
- try {
395
- let manifestCode = readFileSync(manifestPath, "utf-8");
396
- const escaped = JSON.stringify(bootstrapScriptContent);
397
- const escapedFull = JSON.stringify(fullBootstrap);
398
- if (manifestCode.includes(escaped) && escaped !== escapedFull) {
399
- manifestCode = manifestCode.replace(escaped, escapedFull);
400
- writeFileSync(manifestPath, manifestCode, "utf-8");
401
- }
402
- }
403
- catch {
404
- // ignore
405
- }
406
- }
407
- if (existsSync(ssrIndexPath)) {
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
- try {
418
- let ssrCode = readFileSync(ssrIndexPath, "utf-8");
419
- // Only the assignment: the bundle also compares against the placeholder, and a second
420
- // run over an already patched bundle must leave that comparison intact.
421
- ssrCode = ssrCode.replace(/(CLIENT_CSS_HREF\s*=\s*)"__FARM_CLIENT_CSS_HREF__"/, "$1" + JSON.stringify(clientCssHref));
422
- if (clientEntryHref && ssrCode.includes("__FARM_CLIENT_ENTRY_HREF__")) {
423
- ssrCode = ssrCode.replace(/(CLIENT_ENTRY_HREF\s*=\s*)"__FARM_CLIENT_ENTRY_HREF__"/, "$1" + JSON.stringify(clientEntryHref));
424
- }
425
- if (fullBootstrap && ssrCode.includes("__FARM_BOOTSTRAP_SCRIPT__")) {
426
- ssrCode = ssrCode.replace(/=\s*["']__FARM_BOOTSTRAP_SCRIPT__["']/, "= " + JSON.stringify(fullBootstrap));
427
- }
428
- writeFileSync(ssrIndexPath, ssrCode, "utf-8");
429
- }
430
- catch {
431
- // ignore
432
- }
433
- }
434
- }
435
- /** The route the RSC entry answers, during the prerender pass only, with its static pages. */
436
- const FARM_PRERENDER_ROUTES_PATH = "/__farm/rsc-prerender-routes";
437
- /**
438
- * Prerender the app's static pages and their RSC payloads into the public output with Nitro's
439
- * prerenderer, which serves them before the server on every preset. The RSC entry lists the pages
440
- * (it has the route modules and their generateStaticParams), through Nitro's x-nitro-prerender
441
- * header on a seed route that is removed afterwards.
442
- */
443
- async function prerenderRscPages(nitro, prerender, viteDistDir) {
444
- nitro.options.prerender = {
445
- ...nitro.options.prerender,
446
- routes: [FARM_PRERENDER_ROUTES_PATH],
447
- crawlLinks: false,
448
- // Failures are judged below: a seed that cannot run only skips prerendering.
449
- failOnError: false,
450
- };
451
- // The prerender server is a separate Nitro build of the same renderer entry. Point its imports of
452
- // the prebuilt bundles at the Vite output, as the server output's are pointed at their copies.
453
- nitro.hooks.hook("prerender:init", (prerenderer) => {
454
- prerenderer.hooks.hook("compiled", () => {
455
- rewriteRscEntryImports(prerenderer.options.output.serverDir, viteDistDir);
456
- });
457
- });
458
- let seedError;
459
- const failedPages = [];
460
- nitro.hooks.hook("prerender:route", (route) => {
461
- if (route.route !== FARM_PRERENDER_ROUTES_PATH) {
462
- if (route.error)
463
- failedPages.push(`${route.route} (${route.error.message})`);
464
- return;
465
- }
466
- seedError = route.error;
467
- removeSeedOutput(nitro, route.fileName);
468
- });
469
- const previous = process.env.FARM_RSC_PRERENDER;
470
- process.env.FARM_RSC_PRERENDER = "1";
471
- try {
472
- await prerender(nitro);
473
- }
474
- finally {
475
- if (previous === undefined)
476
- delete process.env.FARM_RSC_PRERENDER;
477
- else
478
- process.env.FARM_RSC_PRERENDER = previous;
479
- }
480
- if (seedError) {
481
- // The server could not start in place (for example, a runtime package only the server output
482
- // carries). Every page still renders on request, so the build goes on without static files.
483
- console.warn(`[FARM] Prerendering skipped: the server could not list its static pages (${seedError.message}). Pages render on each request.`);
484
- return;
485
- }
486
- if (failedPages.length > 0) {
487
- // A page that asks to be static and fails to render fails the build, as in Next.js.
488
- throw new Error(`[FARM] Prerendering failed for:\n ${failedPages.join("\n ")}`);
489
- }
490
- }
491
- /** Remove the seed route's file, and the directories it created, from the public output. */
492
- function removeSeedOutput(nitro, fileName) {
493
- const publicDir = path.resolve(nitro.options.output.publicDir);
494
- const prerendered = nitro
495
- ._prerenderedRoutes;
496
- const index = prerendered?.findIndex((entry) => entry.route === FARM_PRERENDER_ROUTES_PATH) ?? -1;
497
- if (index >= 0)
498
- prerendered.splice(index, 1);
499
- if (!fileName)
500
- return;
501
- let target = path.join(publicDir, fileName);
502
- rmSync(target, { force: true });
503
- for (target = path.dirname(target); target.startsWith(publicDir + path.sep) &&
504
- existsSync(target) &&
505
- readdirSync(target).length === 0; target = path.dirname(target)) {
506
- rmSync(target, { recursive: true });
507
- }
508
- }
509
285
  export async function buildRscNitro(options) {
510
- const { rendererPath, publicDir, ssrPath, assetsDir, root, preset = "vercel" } = options;
511
- const outputDir = options.outputDir ?? path.join(root, ".output");
512
- 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");
513
288
  console.log(`[FARM] Building RSC server with Nitro (preset: ${preset})...`);
514
289
  const buildDir = path.join(root, ".nitro");
515
- // Vercel's Build Output API has its own layout (functions/, static/), which the preset owns when
516
- // the caller names the deployment directory (`farm build`). Without one, the output keeps the
517
- // server/ and public/ layout that hand-written post-build scripts copy from.
518
- const presetOwnsLayout = options.outputDir !== undefined && (preset === "vercel" || preset === "vercel-edge");
519
- // The server sets NODE_ENV to "production" unless the deployment chose one, as the core
520
- // node-server output does. The RSC and SSR bundles read it at runtime: left unset, React loads
521
- // its development builds and Flight responses carry server component props, stacks and paths.
522
- 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");
523
292
  const entryPath = writeRscEntryFile(buildDir, rendererPath, ssrPath);
524
293
  const registeredRuntimePackages = new Map(runtimePackagesByRoot.get(path.resolve(root)) ?? []);
525
294
  for (const [packageName, packageRoot] of detectBundledRscRuntimes(rendererPath)) {
@@ -548,13 +317,11 @@ export async function buildRscNitro(options) {
548
317
  alias: {
549
318
  h3: runtimeRequire.resolve("h3"),
550
319
  },
551
- output: presetOwnsLayout
552
- ? { dir: outputDir }
553
- : {
554
- dir: outputDir,
555
- serverDir: path.join(outputDir, "server"),
556
- publicDir: path.join(outputDir, "public"),
557
- },
320
+ output: {
321
+ dir: outputDir,
322
+ serverDir,
323
+ publicDir: publicOutDir,
324
+ },
558
325
  publicAssets,
559
326
  renderer: { handler: entryPath },
560
327
  // The prebuilt RSC/SSR bundles are copied after Nitro finishes, so Nitro's
@@ -576,21 +343,9 @@ export async function buildRscNitro(options) {
576
343
  compatibilityDate: "2024-12-01",
577
344
  minify: true,
578
345
  };
579
- if (ssrPath) {
580
- patchRscServerBundles(path.dirname(path.resolve(rendererPath)), path.dirname(path.resolve(ssrPath)), publicDir, assetsDir);
581
- }
582
346
  const nitro = await createNitro(config);
583
- const serverDir = nitro.options.output.serverDir;
584
347
  await prepare(nitro);
585
348
  await copyPublicAssets(nitro);
586
- const viteDistDir = path.dirname(path.dirname(path.resolve(rendererPath)));
587
- const unlinkRuntimePackages = linkRuntimePackages(viteDistDir, registeredRuntimePackages);
588
- try {
589
- await prerenderRscPages(nitro, prerender, viteDistDir);
590
- }
591
- finally {
592
- unlinkRuntimePackages();
593
- }
594
349
  await build(nitro);
595
350
  await nitro.close();
596
351
  copyRuntimePackages(serverDir, registeredRuntimePackages);
@@ -602,7 +357,6 @@ export async function buildRscNitro(options) {
602
357
  copyDir(rscSrc, path.join(serverDistDir, "rsc"));
603
358
  if (ssrSrc)
604
359
  copyDir(ssrSrc, path.join(serverDistDir, "ssr"));
605
- await traceRscBundleDependencies(root, serverDir, rscSrc, ssrSrc);
606
360
  // Stub manifest if missing (RSC plugin may write it after our hook runs)
607
361
  const rscDestDir = path.join(serverDistDir, "rsc");
608
362
  const manifestDest = path.join(rscDestDir, "__vite_rsc_assets_manifest.js");
@@ -613,6 +367,74 @@ export async function buildRscNitro(options) {
613
367
  // Nitro may group the entry differently by builder. Make copied-dist imports
614
368
  // relative to the emitted chunk so output survives moving away from the project.
615
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
+ }
616
438
  console.log("[FARM] RSC Nitro build completed");
617
439
  console.log(`[FARM] Output: ${outputDir}`);
618
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"}