@vitejs/plugin-rsc 0.4.20 → 0.4.22

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 (51) hide show
  1. package/README.md +64 -60
  2. package/dist/{browser-mbRygLxB.d.ts → browser-DUDACP5e.d.ts} +1 -1
  3. package/dist/browser.d.ts +3 -3
  4. package/dist/core/browser.d.ts +1 -1
  5. package/dist/core/rsc.d.ts +2 -2
  6. package/dist/core/rsc.js +1 -1
  7. package/dist/core/ssr.d.ts +2 -2
  8. package/dist/core/ssr.js +1 -1
  9. package/dist/{encryption-runtime-CJUalqt3.js → encryption-runtime-z7X8aRLB.js} +1 -1
  10. package/dist/extra/browser.d.ts +1 -1
  11. package/dist/extra/browser.js +1 -1
  12. package/dist/extra/rsc.d.ts +1 -1
  13. package/dist/extra/rsc.js +4 -4
  14. package/dist/extra/ssr.js +5 -4
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +2 -1
  17. package/dist/{plugin-DYOxE_xg.js → plugin-BLljgx4e.js} +408 -300
  18. package/dist/{plugin-BQszG7oj.d.ts → plugin-CrIhPWor.d.ts} +28 -12
  19. package/dist/plugin.d.ts +2 -2
  20. package/dist/plugin.js +3 -2
  21. package/dist/react/browser.d.ts +3 -3
  22. package/dist/react/rsc.d.ts +3 -3
  23. package/dist/react/rsc.js +2 -2
  24. package/dist/react/ssr.d.ts +3 -3
  25. package/dist/react/ssr.js +2 -2
  26. package/dist/{rsc-BwEwbLG4.js → rsc-0ugrKC93.js} +1 -1
  27. package/dist/{rsc-CxDPDiLz.d.ts → rsc-BeJKxeMX.d.ts} +1 -1
  28. package/dist/{rsc-VjVw_i-M.js → rsc-K03z8Dh0.js} +1 -1
  29. package/dist/rsc-html-stream/browser.js +1 -1
  30. package/dist/rsc-html-stream/ssr.js +1 -1
  31. package/dist/rsc.d.ts +4 -4
  32. package/dist/rsc.js +4 -4
  33. package/dist/shared-Cwk6fxfN.js +22 -0
  34. package/dist/{ssr-BMTRhW5g.js → ssr-BnEu3hbo.js} +6 -2
  35. package/dist/{ssr-BoNKka-5.d.ts → ssr-Bv84RACl.d.ts} +1 -1
  36. package/dist/{ssr-BEKKb_cw.js → ssr-D154nyka.js} +1 -1
  37. package/dist/ssr.d.ts +3 -3
  38. package/dist/ssr.js +4 -3
  39. package/dist/utils/encryption-runtime.d.ts +1 -1
  40. package/dist/utils/encryption-runtime.js +3 -3
  41. package/package.json +4 -5
  42. /package/dist/{browser-CuwQIlVY.d.ts → browser-CyGTajab.d.ts} +0 -0
  43. /package/dist/{client-C1J4FCf5.js → client-BPIq1kGs.js} +0 -0
  44. /package/dist/{encryption-runtime-SgJRa9yj.d.ts → encryption-runtime-BmDC7d-3.d.ts} +0 -0
  45. /package/dist/{index-QWzVHuya.d.ts → index-CrcbP1rd.d.ts} +0 -0
  46. /package/dist/{rsc-CFtzqEG8.d.ts → rsc-A9Zr9bEE.d.ts} +0 -0
  47. /package/dist/{rsc-BfBPoIV8.js → rsc-C54XEgZY.js} +0 -0
  48. /package/dist/{rsc-Cv3XEZqB.d.ts → rsc-D-lnfNSa.d.ts} +0 -0
  49. /package/dist/{server-D0-DavPP.js → server-DoWzqBNF.js} +0 -0
  50. /package/dist/{ssr-D6GTzOzx.d.ts → ssr-EOoYUXrM.d.ts} +0 -0
  51. /package/dist/{ssr--rFiBtws.js → ssr-v4qYqcXu.js} +0 -0
@@ -3,9 +3,9 @@ import { vitePluginRscCore } from "./plugin-CZbI4rhS.js";
3
3
  import { generateEncryptionKey, toBase64 } from "./encryption-utils-BDwwcMVT.js";
4
4
  import { createRpcServer } from "./rpc-tGuLT8PD.js";
5
5
  import { cleanUrl, normalizeViteImportAnalysisUrl, prepareError } from "./vite-utils-Vzd7cqfv.js";
6
+ import { parseCssVirtual, parseIdQuery, toCssVirtual } from "./shared-Cwk6fxfN.js";
6
7
  import { createRequire } from "node:module";
7
8
  import assert from "node:assert";
8
- import { createHash } from "node:crypto";
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -16,6 +16,7 @@ import { defaultServerConditions, isCSSRequest, normalizePath, parseAstAsync } f
16
16
  import { crawlFrameworkPkgs, findClosestPkgJsonPath } from "vitefu";
17
17
  import { walk } from "estree-walker";
18
18
  import { analyze, extract_names } from "periscopic";
19
+ import { createHash } from "node:crypto";
19
20
 
20
21
  //#region src/transforms/hoist.ts
21
22
  function transformHoistInlineDirective(input, ast, { runtime, rejectNonAsyncFunction,...options }) {
@@ -87,26 +88,29 @@ function transformWrapExport(input, ast, options) {
87
88
  const toAppend = [];
88
89
  const filter = options.filter ?? (() => true);
89
90
  function wrapSimple(start, end, exports) {
91
+ exportNames.push(...exports.map((e) => e.name));
90
92
  const newCode = exports.map((e) => [filter(e.name, e.meta) && `${e.name} = /* #__PURE__ */ ${options.runtime(e.name, e.name, e.meta)};\n`, `export { ${e.name} };\n`]).flat().filter(Boolean).join("");
91
93
  output.update(start, end, newCode);
92
94
  output.move(start, end, input.length);
93
95
  }
94
96
  function wrapExport(name, exportName, meta = {}) {
97
+ exportNames.push(exportName);
95
98
  if (!filter(exportName, meta)) {
96
99
  toAppend.push(`export { ${name} as ${exportName} }`);
97
100
  return;
98
101
  }
99
102
  toAppend.push(`const $$wrap_${name} = /* #__PURE__ */ ${options.runtime(name, exportName, meta)}`, `export { $$wrap_${name} as ${exportName} }`);
100
103
  }
101
- function validateNonAsyncFunction(node, ok) {
102
- if (options.rejectNonAsyncFunction && !ok) throw Object.assign(/* @__PURE__ */ new Error(`unsupported non async function`), { pos: node.start });
104
+ function validateNonAsyncFunction(node) {
105
+ if (!options.rejectNonAsyncFunction) return;
106
+ if (node.type === "ClassDeclaration" || (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && !node.async) throw Object.assign(/* @__PURE__ */ new Error(`unsupported non async function`), { pos: node.start });
103
107
  }
104
108
  for (const node of ast.body) {
105
109
  if (node.type === "ExportNamedDeclaration") if (node.declaration) if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
106
110
  /**
107
111
  * export function foo() {}
108
112
  */
109
- validateNonAsyncFunction(node, node.declaration.type === "FunctionDeclaration" && node.declaration.async);
113
+ validateNonAsyncFunction(node.declaration);
110
114
  const name = node.declaration.id.name;
111
115
  wrapSimple(node.start, node.declaration.start, [{
112
116
  name,
@@ -119,7 +123,7 @@ function transformWrapExport(input, ast, options) {
119
123
  /**
120
124
  * export const foo = 1, bar = 2
121
125
  */
122
- validateNonAsyncFunction(node, node.declaration.declarations.every((decl) => decl.init?.type === "ArrowFunctionExpression" && decl.init.async));
126
+ for (const decl of node.declaration.declarations) if (decl.init) validateNonAsyncFunction(decl.init);
123
127
  if (node.declaration.kind === "const") output.update(node.declaration.start, node.declaration.start + 5, "let");
124
128
  const names = node.declaration.declarations.flatMap((decl) => extract_names(decl.id));
125
129
  let isFunction = false;
@@ -168,7 +172,7 @@ function transformWrapExport(input, ast, options) {
168
172
  * export default () => {}
169
173
  */
170
174
  if (node.type === "ExportDefaultDeclaration") {
171
- validateNonAsyncFunction(node, node.declaration.type === "Identifier" || node.declaration.type === "FunctionDeclaration" && node.declaration.async);
175
+ validateNonAsyncFunction(node.declaration);
172
176
  let localName;
173
177
  let isFunction = false;
174
178
  let declName;
@@ -301,28 +305,6 @@ function transformServerActionServer(input, ast, options) {
301
305
  });
302
306
  }
303
307
 
304
- //#endregion
305
- //#region src/plugins/utils.ts
306
- function evalValue(rawValue) {
307
- const fn = new Function(`
308
- var console, exports, global, module, process, require
309
- return (\n${rawValue}\n)
310
- `);
311
- return fn();
312
- }
313
- function parseIdQuery(id) {
314
- if (!id.includes("?")) return {
315
- filename: id,
316
- query: {}
317
- };
318
- const [filename, rawQuery] = id.split(`?`, 2);
319
- const query = Object.fromEntries(new URLSearchParams(rawQuery));
320
- return {
321
- filename,
322
- query
323
- };
324
- }
325
-
326
308
  //#endregion
327
309
  //#region src/transforms/cjs.ts
328
310
  function transformCjsToEsm(code, ast) {
@@ -417,17 +399,174 @@ function extractPackageKey(id) {
417
399
  return id;
418
400
  }
419
401
 
402
+ //#endregion
403
+ //#region src/plugins/utils.ts
404
+ function evalValue(rawValue) {
405
+ const fn = new Function(`
406
+ var console, exports, global, module, process, require
407
+ return (\n${rawValue}\n)
408
+ `);
409
+ return fn();
410
+ }
411
+ function sortObject(o) {
412
+ return Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
413
+ }
414
+ function withRollupError(ctx, f) {
415
+ function processError(e) {
416
+ if (e && typeof e === "object" && typeof e.pos === "number") return ctx.error(e, e.pos);
417
+ throw e;
418
+ }
419
+ return function(...args) {
420
+ try {
421
+ const result = f.apply(this, args);
422
+ if (result instanceof Promise) return result.catch((e) => processError(e));
423
+ return result;
424
+ } catch (e) {
425
+ processError(e);
426
+ }
427
+ };
428
+ }
429
+ function createVirtualPlugin(name, load) {
430
+ name = "virtual:" + name;
431
+ return {
432
+ name: `rsc:virtual-${name}`,
433
+ resolveId(source, _importer, _options) {
434
+ return source === name ? "\0" + name : void 0;
435
+ },
436
+ load(id, options) {
437
+ if (id === "\0" + name) return load.apply(this, [id, options]);
438
+ }
439
+ };
440
+ }
441
+ function normalizeRelativePath(s) {
442
+ s = normalizePath(s);
443
+ return s[0] === "." ? s : "./" + s;
444
+ }
445
+ function getEntrySource(config, name = "index") {
446
+ const input = config.build.rollupOptions.input;
447
+ assert(typeof input === "object" && !Array.isArray(input) && name in input && typeof input[name] === "string", `[vite-rsc:getEntrySource] expected 'build.rollupOptions.input' to be an object with a '${name}' property that is a string, but got ${JSON.stringify(input)}`);
448
+ return input[name];
449
+ }
450
+ function hashString(v) {
451
+ return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
452
+ }
453
+
454
+ //#endregion
455
+ //#region src/plugins/scan.ts
456
+ const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
457
+ async function transformScanBuildStrip(code) {
458
+ const [imports] = esModuleLexer.parse(code);
459
+ let output = imports.map((e) => e.n && `import ${JSON.stringify(e.n)};\n`).filter(Boolean).join("");
460
+ if (importGlobRE.test(code)) {
461
+ const ast = await parseAstAsync(code);
462
+ walk(ast, { enter(node) {
463
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "MetaProperty" && node.callee.object.meta.type === "Identifier" && node.callee.object.meta.name === "import" && node.callee.object.property.type === "Identifier" && node.callee.object.property.name === "meta" && node.callee.property.type === "Identifier" && node.callee.property.name === "glob") {
464
+ const importMetaGlob = code.slice(node.start, node.end);
465
+ output += `console.log(${importMetaGlob});\n`;
466
+ }
467
+ } });
468
+ output += "";
469
+ }
470
+ return output;
471
+ }
472
+
473
+ //#endregion
474
+ //#region src/plugins/validate-import.ts
475
+ function validateImportPlugin() {
476
+ return {
477
+ name: "rsc:validate-imports",
478
+ resolveId: {
479
+ order: "pre",
480
+ async handler(source, importer, options) {
481
+ if ("scan" in options && options.scan) return;
482
+ if (source === "client-only") {
483
+ if (this.environment.name === "rsc") throw new Error(`'client-only' cannot be imported in server build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
484
+ return {
485
+ id: `\0virtual:vite-rsc/empty`,
486
+ moduleSideEffects: false
487
+ };
488
+ }
489
+ if (source === "server-only") {
490
+ if (this.environment.name !== "rsc") throw new Error(`'server-only' cannot be imported in client build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
491
+ return {
492
+ id: `\0virtual:vite-rsc/empty`,
493
+ moduleSideEffects: false
494
+ };
495
+ }
496
+ }
497
+ },
498
+ load(id) {
499
+ if (id.startsWith("\0virtual:vite-rsc/empty")) return `export {}`;
500
+ }
501
+ };
502
+ }
503
+
504
+ //#endregion
505
+ //#region src/plugins/find-source-map-url.ts
506
+ function vitePluginFindSourceMapURL() {
507
+ return [{
508
+ name: "rsc:findSourceMapURL",
509
+ apply: "serve",
510
+ configureServer(server) {
511
+ server.middlewares.use(async (req, res, next) => {
512
+ const url = new URL(req.url, `http://localhost`);
513
+ if (url.pathname === "/__vite_rsc_findSourceMapURL") {
514
+ let filename = url.searchParams.get("filename");
515
+ let environmentName = url.searchParams.get("environmentName");
516
+ try {
517
+ const map = await findSourceMapURL(server, filename, environmentName);
518
+ res.setHeader("content-type", "application/json");
519
+ if (!map) res.statusCode = 404;
520
+ res.end(JSON.stringify(map ?? {}));
521
+ } catch (e) {
522
+ next(e);
523
+ }
524
+ return;
525
+ }
526
+ next();
527
+ });
528
+ }
529
+ }];
530
+ }
531
+ async function findSourceMapURL(server, filename, environmentName) {
532
+ if (filename.startsWith("file://")) {
533
+ filename = fileURLToPath(filename);
534
+ if (fs.existsSync(filename)) {
535
+ const content = fs.readFileSync(filename, "utf-8");
536
+ return {
537
+ version: 3,
538
+ sources: [filename],
539
+ sourcesContent: [content],
540
+ mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
541
+ };
542
+ }
543
+ return;
544
+ }
545
+ let mod;
546
+ let map;
547
+ if (environmentName === "Server") {
548
+ mod = server.environments.rsc.moduleGraph.getModuleById(filename);
549
+ map = mod?.transformResult?.map;
550
+ if (map && map.mappings) map = {
551
+ ...map,
552
+ mappings: ";;" + map.mappings
553
+ };
554
+ }
555
+ const base = server.config.base.slice(0, -1);
556
+ if (environmentName === "Client") try {
557
+ const url = new URL(filename).pathname.slice(base.length);
558
+ mod = server.environments.client.moduleGraph.urlToModuleMap.get(url);
559
+ map = mod?.transformResult?.map;
560
+ } catch (e) {}
561
+ if (mod && map) return {
562
+ ...map,
563
+ sources: [base + mod.url]
564
+ };
565
+ }
566
+
420
567
  //#endregion
421
568
  //#region src/plugin.ts
422
- let serverReferences = {};
423
- let server;
424
- let config;
425
- let rscBundle;
426
- let buildAssetsManifest;
427
- let isScanBuild = false;
428
569
  const BUILD_ASSETS_MANIFEST_NAME = "__vite_rsc_assets_manifest.js";
429
- let clientReferenceMetaMap = {};
430
- let serverResourcesMetaMap = {};
431
570
  const PKG_NAME = "@vitejs/plugin-rsc";
432
571
  const REACT_SERVER_DOM_NAME = `${PKG_NAME}/vendor/react-server-dom`;
433
572
  const VIRTUAL_ENTRIES = { browser: "virtual:vite-rsc/entry-browser" };
@@ -435,8 +574,22 @@ const require = createRequire(import.meta.url);
435
574
  function resolvePackage(name) {
436
575
  return pathToFileURL(require.resolve(name)).href;
437
576
  }
577
+ var RscPluginManager = class {
578
+ server;
579
+ config;
580
+ rscBundle;
581
+ buildAssetsManifest;
582
+ isScanBuild = false;
583
+ clientReferenceMetaMap = {};
584
+ serverReferenceMetaMap = {};
585
+ serverResourcesMetaMap = {};
586
+ stabilize() {
587
+ this.clientReferenceMetaMap = sortObject(this.clientReferenceMetaMap);
588
+ this.serverResourcesMetaMap = sortObject(this.serverResourcesMetaMap);
589
+ }
590
+ };
438
591
  /** @experimental */
439
- function vitePluginRscMinimal(rscPluginOptions = {}) {
592
+ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginManager()) {
440
593
  return [
441
594
  {
442
595
  name: "rsc:minimal",
@@ -444,11 +597,12 @@ function vitePluginRscMinimal(rscPluginOptions = {}) {
444
597
  async config() {
445
598
  await esModuleLexer.init;
446
599
  },
447
- configResolved(config_) {
448
- config = config_;
600
+ configResolved(config) {
601
+ manager.config = config;
602
+ for (const e of Object.values(config.environments)) e.build.outDir = path.resolve(config.root, e.build.outDir);
449
603
  },
450
604
  configureServer(server_) {
451
- server = server_;
605
+ manager.server = server_;
452
606
  }
453
607
  },
454
608
  {
@@ -461,55 +615,54 @@ function vitePluginRscMinimal(rscPluginOptions = {}) {
461
615
  }
462
616
  },
463
617
  ...vitePluginRscCore(),
464
- ...vitePluginUseClient(rscPluginOptions),
465
- ...vitePluginUseServer(rscPluginOptions),
618
+ ...vitePluginUseClient(rscPluginOptions, manager),
619
+ ...vitePluginUseServer(rscPluginOptions, manager),
466
620
  ...vitePluginDefineEncryptionKey(rscPluginOptions)
467
621
  ];
468
622
  }
469
623
  function vitePluginRsc(rscPluginOptions = {}) {
624
+ const manager = new RscPluginManager();
470
625
  const buildApp = async (builder) => {
471
626
  if (!builder.environments.ssr?.config.build.rollupOptions.input) {
472
- isScanBuild = true;
627
+ manager.isScanBuild = true;
473
628
  builder.environments.rsc.config.build.write = false;
474
629
  builder.environments.client.config.build.write = false;
475
630
  await builder.build(builder.environments.rsc);
476
631
  await builder.build(builder.environments.client);
477
- isScanBuild = false;
632
+ manager.isScanBuild = false;
478
633
  builder.environments.rsc.config.build.write = true;
479
634
  builder.environments.client.config.build.write = true;
480
635
  await builder.build(builder.environments.rsc);
481
- clientReferenceMetaMap = sortObject(clientReferenceMetaMap);
482
- serverResourcesMetaMap = sortObject(serverResourcesMetaMap);
636
+ manager.stabilize();
483
637
  await builder.build(builder.environments.client);
484
638
  writeAssetsManifest(["rsc"]);
485
639
  return;
486
640
  }
487
- isScanBuild = true;
641
+ manager.isScanBuild = true;
488
642
  builder.environments.rsc.config.build.write = false;
489
643
  builder.environments.ssr.config.build.write = false;
490
644
  await builder.build(builder.environments.rsc);
491
645
  await builder.build(builder.environments.ssr);
492
- isScanBuild = false;
646
+ manager.isScanBuild = false;
493
647
  builder.environments.rsc.config.build.write = true;
494
648
  builder.environments.ssr.config.build.write = true;
495
649
  await builder.build(builder.environments.rsc);
496
- clientReferenceMetaMap = sortObject(clientReferenceMetaMap);
497
- serverResourcesMetaMap = sortObject(serverResourcesMetaMap);
650
+ manager.stabilize();
498
651
  await builder.build(builder.environments.client);
499
652
  await builder.build(builder.environments.ssr);
500
653
  writeAssetsManifest(["ssr", "rsc"]);
501
654
  };
502
655
  function writeAssetsManifest(environmentNames) {
503
- const assetsManifestCode = `export default ${serializeValueWithRuntime(buildAssetsManifest)}`;
656
+ const assetsManifestCode = `export default ${serializeValueWithRuntime(manager.buildAssetsManifest)}`;
504
657
  for (const name of environmentNames) {
505
- const manifestPath = path.join(config.environments[name].build.outDir, BUILD_ASSETS_MANIFEST_NAME);
658
+ const manifestPath = path.join(manager.config.environments[name].build.outDir, BUILD_ASSETS_MANIFEST_NAME);
506
659
  fs.writeFileSync(manifestPath, assetsManifestCode);
507
660
  }
508
661
  }
509
662
  return [
510
663
  {
511
664
  name: "rsc",
512
- async config(config$1, env) {
665
+ async config(config, env) {
513
666
  const result = await crawlFrameworkPkgs({
514
667
  root: process.cwd(),
515
668
  isBuild: env.command === "build",
@@ -533,7 +686,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
533
686
  environments: {
534
687
  client: {
535
688
  build: {
536
- outDir: config$1.environments?.client?.build?.outDir ?? "dist/client",
689
+ outDir: config.environments?.client?.build?.outDir ?? "dist/client",
537
690
  rollupOptions: { input: rscPluginOptions.entries?.client && { index: rscPluginOptions.entries.client } }
538
691
  },
539
692
  optimizeDeps: {
@@ -543,7 +696,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
543
696
  },
544
697
  ssr: {
545
698
  build: {
546
- outDir: config$1.environments?.ssr?.build?.outDir ?? "dist/ssr",
699
+ outDir: config.environments?.ssr?.build?.outDir ?? "dist/ssr",
547
700
  rollupOptions: { input: rscPluginOptions.entries?.ssr && { index: rscPluginOptions.entries.ssr } }
548
701
  },
549
702
  resolve: { noExternal },
@@ -561,7 +714,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
561
714
  },
562
715
  rsc: {
563
716
  build: {
564
- outDir: config$1.environments?.rsc?.build?.outDir ?? "dist/rsc",
717
+ outDir: config.environments?.rsc?.build?.outDir ?? "dist/rsc",
565
718
  emitAssets: true,
566
719
  rollupOptions: { input: rscPluginOptions.entries?.rsc && { index: rscPluginOptions.entries.rsc } }
567
720
  },
@@ -590,7 +743,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
590
743
  };
591
744
  },
592
745
  buildApp: rscPluginOptions.useBuildAppHook ? buildApp : void 0,
593
- configureServer() {
746
+ configureServer(server) {
594
747
  globalThis.__viteRscDevServer = server;
595
748
  if (rscPluginOptions.disableServerHandler) return;
596
749
  if (rscPluginOptions.serverHandler === false) return;
@@ -613,26 +766,26 @@ function vitePluginRsc(rscPluginOptions = {}) {
613
766
  });
614
767
  };
615
768
  },
616
- async configurePreviewServer(server$1) {
769
+ async configurePreviewServer(server) {
617
770
  if (rscPluginOptions.disableServerHandler) return;
618
771
  if (rscPluginOptions.serverHandler === false) return;
619
772
  const options = rscPluginOptions.serverHandler ?? {
620
773
  environmentName: "rsc",
621
774
  entryName: "index"
622
775
  };
623
- const entryFile = path.join(config.environments[options.environmentName].build.outDir, `${options.entryName}.js`);
776
+ const entryFile = path.join(manager.config.environments[options.environmentName].build.outDir, `${options.entryName}.js`);
624
777
  const entry = pathToFileURL(entryFile).href;
625
778
  const mod = await import(
626
779
  /* @vite-ignore */
627
780
  entry
628
781
  );
629
782
  const handler = createRequestListener(mod.default);
630
- server$1.middlewares.use((req, _res, next) => {
783
+ server.middlewares.use((req, _res, next) => {
631
784
  delete req.headers["accept-encoding"];
632
785
  next();
633
786
  });
634
787
  return () => {
635
- server$1.middlewares.use(async (req, res, next) => {
788
+ server.middlewares.use(async (req, res, next) => {
636
789
  try {
637
790
  await handler(req, res);
638
791
  } catch (e) {
@@ -647,11 +800,16 @@ function vitePluginRsc(rscPluginOptions = {}) {
647
800
  }
648
801
  const ids = ctx.modules.map((mod) => mod.id).filter((v) => v !== null);
649
802
  if (ids.length === 0) return;
803
+ if (this.environment.name === "rsc") {
804
+ for (const mod of ctx.modules) if (mod.type === "js" && mod.id && mod.id in manager.clientReferenceMetaMap) try {
805
+ await this.environment.transformRequest(mod.url);
806
+ } catch {}
807
+ }
650
808
  function isInsideClientBoundary(mods) {
651
809
  const visited = /* @__PURE__ */ new Set();
652
810
  function recurse(mod) {
653
811
  if (!mod.id) return false;
654
- if (clientReferenceMetaMap[mod.id]) return true;
812
+ if (manager.clientReferenceMetaMap[mod.id]) return true;
655
813
  if (visited.has(mod.id)) return false;
656
814
  visited.add(mod.id);
657
815
  for (const importer of mod.importers) if (recurse(importer)) return true;
@@ -668,7 +826,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
668
826
  for (const mod of ctx.modules) if (mod.type === "js") try {
669
827
  await this.environment.transformRequest(mod.url);
670
828
  } catch (e) {
671
- server.environments.client.hot.send({
829
+ manager.server.environments.client.hot.send({
672
830
  type: "error",
673
831
  err: prepareError(e)
674
832
  });
@@ -701,6 +859,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
701
859
  name: "rsc:load-environment-module",
702
860
  async transform(code) {
703
861
  if (!code.includes("import.meta.viteRsc.loadModule")) return;
862
+ const { server } = manager;
704
863
  const s = new MagicString(code);
705
864
  for (const match of code.matchAll(/import\.meta\.viteRsc\.loadModule\(([\s\S]*?)\)/dg)) {
706
865
  const argCode = match[1].trim();
@@ -732,6 +891,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
732
891
  },
733
892
  renderChunk(code, chunk) {
734
893
  if (!code.includes("__vite_rsc_load_module")) return;
894
+ const { config } = manager;
735
895
  const s = new MagicString(code);
736
896
  for (const match of code.matchAll(/['"]__vite_rsc_load_module:(\w+):(\w+):(\w+)['"]/dg)) {
737
897
  const [fromEnv, toEnv, entryName] = match.slice(1);
@@ -749,12 +909,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
749
909
  {
750
910
  name: "vite-rsc-load-module-dev-proxy",
751
911
  apply: () => !!rscPluginOptions.loadModuleDevProxy,
752
- configureServer(server$1) {
912
+ configureServer(server) {
753
913
  async function createHandler(url) {
754
914
  const { environmentName, entryName } = Object.fromEntries(url.searchParams);
755
915
  assert(environmentName);
756
916
  assert(entryName);
757
- const environment = server$1.environments[environmentName];
917
+ const environment = server.environments[environmentName];
758
918
  const source = getEntrySource(environment.config, entryName);
759
919
  const resolvedEntry = await environment.pluginContainer.resolveId(source);
760
920
  assert(resolvedEntry, `[vite-rsc] failed to resolve entry '${source}'`);
@@ -767,7 +927,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
767
927
  } });
768
928
  return createRpcServer(runnerProxy);
769
929
  }
770
- server$1.middlewares.use(async (req, res, next) => {
930
+ server.middlewares.use(async (req, res, next) => {
771
931
  const url = new URL(req.url ?? "/", `http://localhost`);
772
932
  if (url.pathname === "/__vite_rsc_load_module_dev_proxy") {
773
933
  try {
@@ -797,7 +957,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
797
957
  if (id === "\0virtual:vite-rsc/assets-manifest") {
798
958
  assert(this.environment.name !== "client");
799
959
  assert(this.environment.mode === "dev");
800
- const entryUrl = assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser);
960
+ const entryUrl = assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser, manager);
801
961
  const manifest = {
802
962
  bootstrapScriptContent: `import(${serializeValueWithRuntime(entryUrl)})`,
803
963
  clientReferenceDeps: {}
@@ -806,12 +966,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
806
966
  }
807
967
  },
808
968
  generateBundle(_options, bundle) {
809
- if (this.environment.name === "rsc") rscBundle = bundle;
969
+ if (this.environment.name === "rsc") manager.rscBundle = bundle;
810
970
  if (this.environment.name === "client") {
811
971
  const filterAssets = rscPluginOptions.copyServerAssetsToClient ?? (() => true);
812
- const rscBuildOptions = config.environments.rsc.build;
972
+ const rscBuildOptions = manager.config.environments.rsc.build;
813
973
  const rscViteManifest = typeof rscBuildOptions.manifest === "string" ? rscBuildOptions.manifest : rscBuildOptions.manifest && ".vite/manifest.json";
814
- for (const asset of Object.values(rscBundle)) {
974
+ for (const asset of Object.values(manager.rscBundle)) {
815
975
  if (asset.fileName === rscViteManifest) continue;
816
976
  if (asset.type === "asset" && filterAssets(asset.fileName)) this.emitFile({
817
977
  type: "asset",
@@ -820,27 +980,27 @@ function vitePluginRsc(rscPluginOptions = {}) {
820
980
  });
821
981
  }
822
982
  const serverResources = {};
823
- const rscAssetDeps = collectAssetDeps(rscBundle);
824
- for (const [id, meta] of Object.entries(serverResourcesMetaMap)) serverResources[meta.key] = assetsURLOfDeps({
983
+ const rscAssetDeps = collectAssetDeps(manager.rscBundle);
984
+ for (const [id, meta] of Object.entries(manager.serverResourcesMetaMap)) serverResources[meta.key] = assetsURLOfDeps({
825
985
  js: [],
826
986
  css: rscAssetDeps[id]?.deps.css ?? []
827
- });
987
+ }, manager);
828
988
  const assetDeps = collectAssetDeps(bundle);
829
989
  const entry = Object.values(assetDeps).find((v) => v.chunk.name === "index");
830
990
  assert(entry);
831
- const entryUrl = assetsURL(entry.chunk.fileName);
991
+ const entryUrl = assetsURL(entry.chunk.fileName, manager);
832
992
  const clientReferenceDeps = {};
833
- for (const [id, meta] of Object.entries(clientReferenceMetaMap)) {
993
+ for (const [id, meta] of Object.entries(manager.clientReferenceMetaMap)) {
834
994
  const deps = assetDeps[id]?.deps ?? {
835
995
  js: [],
836
996
  css: []
837
997
  };
838
- clientReferenceDeps[meta.referenceKey] = assetsURLOfDeps(mergeAssetDeps(deps, entry.deps));
998
+ clientReferenceDeps[meta.referenceKey] = assetsURLOfDeps(mergeAssetDeps(deps, entry.deps), manager);
839
999
  }
840
1000
  let bootstrapScriptContent;
841
1001
  if (typeof entryUrl === "string") bootstrapScriptContent = `import(${JSON.stringify(entryUrl)})`;
842
1002
  else bootstrapScriptContent = new RuntimeAsset(`"import(" + JSON.stringify(${entryUrl.runtime}) + ")"`);
843
- buildAssetsManifest = {
1003
+ manager.buildAssetsManifest = {
844
1004
  bootstrapScriptContent,
845
1005
  clientReferenceDeps,
846
1006
  serverResources
@@ -932,23 +1092,22 @@ globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
932
1092
  return "";
933
1093
  }
934
1094
  },
935
- ...vitePluginRscMinimal(rscPluginOptions),
1095
+ ...vitePluginRscMinimal(rscPluginOptions, manager),
936
1096
  ...vitePluginFindSourceMapURL(),
937
- ...vitePluginRscCss({ rscCssTransform: rscPluginOptions.rscCssTransform }),
1097
+ ...vitePluginRscCss(rscPluginOptions, manager),
938
1098
  ...rscPluginOptions.validateImports !== false ? [validateImportPlugin()] : [],
939
- scanBuildStripPlugin(),
1099
+ scanBuildStripPlugin({ manager }),
940
1100
  ...cjsModuleRunnerPlugin()
941
1101
  ];
942
1102
  }
943
- function scanBuildStripPlugin() {
1103
+ function scanBuildStripPlugin({ manager }) {
944
1104
  return {
945
1105
  name: "rsc:scan-strip",
946
1106
  apply: "build",
947
1107
  enforce: "post",
948
- transform(code, _id, _options) {
949
- if (!isScanBuild) return;
950
- const [imports] = esModuleLexer.parse(code);
951
- const output = imports.map((e) => e.n && `import ${JSON.stringify(e.n)};\n`).filter(Boolean).join("");
1108
+ async transform(code, _id, _options) {
1109
+ if (!manager.isScanBuild) return;
1110
+ const output = await transformScanBuildStrip(code);
952
1111
  return {
953
1112
  code: output,
954
1113
  map: { mappings: "" }
@@ -956,28 +1115,15 @@ function scanBuildStripPlugin() {
956
1115
  }
957
1116
  };
958
1117
  }
959
- function normalizeRelativePath(s) {
960
- s = normalizePath(s);
961
- return s[0] === "." ? s : "./" + s;
962
- }
963
- function getEntrySource(config$1, name = "index") {
964
- const input = config$1.build.rollupOptions.input;
965
- assert(typeof input === "object" && !Array.isArray(input) && name in input && typeof input[name] === "string", `[vite-rsc:getEntrySource] expected 'build.rollupOptions.input' to be an object with a '${name}' property that is a string, but got ${JSON.stringify(input)}`);
966
- return input[name];
967
- }
968
- function hashString(v) {
969
- return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
970
- }
971
- function vitePluginUseClient(useClientPluginOptions) {
1118
+ function vitePluginUseClient(useClientPluginOptions, manager) {
972
1119
  const packageSources = /* @__PURE__ */ new Map();
973
1120
  const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
974
1121
  const serverEnvironmentName = useClientPluginOptions.environment?.rsc ?? "rsc";
975
1122
  const browserEnvironmentName = useClientPluginOptions.environment?.browser ?? "client";
1123
+ let optimizerMetadata;
976
1124
  function warnInoncistentClientOptimization(ctx, id) {
977
- const { depsOptimizer } = server.environments.client;
978
- if (depsOptimizer) {
979
- for (const dep of Object.values(depsOptimizer.metadata.optimized)) if (dep.src === id) ctx.warn("client component dependency is inconsistently optimized. It's recommended to add the dependency to 'optimizeDeps.exclude'.");
980
- }
1125
+ id = normalizePath(path.relative(process.cwd(), id));
1126
+ if (optimizerMetadata?.ids.includes(id)) ctx.warn("client component dependency is inconsistently optimized. It's recommended to add the dependency to 'optimizeDeps.exclude'.");
981
1127
  }
982
1128
  const debug$1 = createDebug("vite-rsc:use-client");
983
1129
  return [
@@ -985,9 +1131,15 @@ function vitePluginUseClient(useClientPluginOptions) {
985
1131
  name: "rsc:use-client",
986
1132
  async transform(code, id) {
987
1133
  if (this.environment.name !== serverEnvironmentName) return;
988
- if (!code.includes("use client")) return;
1134
+ if (!code.includes("use client")) {
1135
+ delete manager.clientReferenceMetaMap[id];
1136
+ return;
1137
+ }
989
1138
  const ast = await parseAstAsync(code);
990
- if (!hasDirective(ast.body, "use client")) return;
1139
+ if (!hasDirective(ast.body, "use client")) {
1140
+ delete manager.clientReferenceMetaMap[id];
1141
+ return;
1142
+ }
991
1143
  let importId;
992
1144
  let referenceKey;
993
1145
  const packageSource = packageSources.get(id);
@@ -1005,11 +1157,11 @@ function vitePluginUseClient(useClientPluginOptions) {
1005
1157
  referenceKey = hashString(packageSource);
1006
1158
  }
1007
1159
  else if (this.environment.mode === "dev") {
1008
- importId = normalizeViteImportAnalysisUrl(server.environments[browserEnvironmentName], id);
1160
+ importId = normalizeViteImportAnalysisUrl(manager.server.environments[browserEnvironmentName], id);
1009
1161
  referenceKey = importId;
1010
1162
  } else {
1011
1163
  importId = id;
1012
- referenceKey = hashString(normalizePath(path.relative(config.root, id)));
1164
+ referenceKey = hashString(normalizePath(path.relative(manager.config.root, id)));
1013
1165
  }
1014
1166
  const transformDirectiveProxyExport_ = withRollupError(this, transformDirectiveProxyExport);
1015
1167
  const result = transformDirectiveProxyExport_(ast, {
@@ -1024,7 +1176,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1024
1176
  });
1025
1177
  if (!result) return;
1026
1178
  const { output, exportNames } = result;
1027
- clientReferenceMetaMap[id] = {
1179
+ manager.clientReferenceMetaMap[id] = {
1028
1180
  importId,
1029
1181
  referenceKey,
1030
1182
  packageSource,
@@ -1045,7 +1197,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1045
1197
  map: null
1046
1198
  };
1047
1199
  let code = "";
1048
- for (const meta of Object.values(clientReferenceMetaMap)) {
1200
+ for (const meta of Object.values(manager.clientReferenceMetaMap)) {
1049
1201
  const key = JSON.stringify(meta.referenceKey);
1050
1202
  const id = JSON.stringify(meta.importId);
1051
1203
  const exports = meta.renderedExports.map((name) => name === "default" ? "default: _default" : name).sort();
@@ -1095,7 +1247,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1095
1247
  if (id.startsWith("\0virtual:vite-rsc/client-package-proxy/")) {
1096
1248
  assert(this.environment.mode === "dev");
1097
1249
  const source = id.slice(39);
1098
- const meta = Object.values(clientReferenceMetaMap).find((v) => v.packageSource === source);
1250
+ const meta = Object.values(manager.clientReferenceMetaMap).find((v) => v.packageSource === source);
1099
1251
  const exportNames = meta.exportNames;
1100
1252
  return `export {${exportNames.join(",")}} from ${JSON.stringify(source)};\n`;
1101
1253
  }
@@ -1103,13 +1255,61 @@ function vitePluginUseClient(useClientPluginOptions) {
1103
1255
  generateBundle(_options, bundle) {
1104
1256
  if (this.environment.name !== serverEnvironmentName) return;
1105
1257
  for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") for (const [id, mod] of Object.entries(chunk.modules)) {
1106
- const meta = clientReferenceMetaMap[id];
1258
+ const meta = manager.clientReferenceMetaMap[id];
1107
1259
  if (meta) meta.renderedExports = mod.renderedExports;
1108
1260
  }
1109
1261
  }
1110
- }
1262
+ },
1263
+ ...customOptimizerMetadataPlugin({ setMetadata: (metadata) => {
1264
+ optimizerMetadata = metadata;
1265
+ } })
1111
1266
  ];
1112
1267
  }
1268
+ function customOptimizerMetadataPlugin({ setMetadata }) {
1269
+ const MEATADATA_FILE = "_metadata-rsc.json";
1270
+ function optimizerPluginEsbuild() {
1271
+ return {
1272
+ name: "vite-rsc-metafile",
1273
+ setup(build) {
1274
+ build.onEnd((result) => {
1275
+ if (!result.metafile?.inputs || !build.initialOptions.outdir) return;
1276
+ const ids = Object.keys(result.metafile.inputs);
1277
+ const metadata = { ids };
1278
+ setMetadata(metadata);
1279
+ fs.writeFileSync(path.join(build.initialOptions.outdir, MEATADATA_FILE), JSON.stringify(metadata, null, 2));
1280
+ });
1281
+ }
1282
+ };
1283
+ }
1284
+ function optimizerPluginRolldown() {
1285
+ return {
1286
+ name: "vite-rsc-metafile",
1287
+ writeBundle(options) {
1288
+ assert(options.dir);
1289
+ const ids = [...this.getModuleIds()].map((id) => path.relative(process.cwd(), id));
1290
+ const metadata = { ids };
1291
+ setMetadata(metadata);
1292
+ fs.writeFileSync(path.join(options.dir, MEATADATA_FILE), JSON.stringify(metadata, null, 2));
1293
+ }
1294
+ };
1295
+ }
1296
+ return [{
1297
+ name: "rsc:use-client:optimizer-metadata",
1298
+ apply: "serve",
1299
+ config() {
1300
+ return { environments: { client: { optimizeDeps: "rolldownVersion" in this.meta ? { rolldownOptions: { plugins: [optimizerPluginRolldown()] } } : { esbuildOptions: { plugins: [optimizerPluginEsbuild()] } } } } };
1301
+ },
1302
+ configResolved(config) {
1303
+ const file = path.join(config.cacheDir, "deps", MEATADATA_FILE);
1304
+ if (fs.existsSync(file)) try {
1305
+ const metadata = JSON.parse(fs.readFileSync(file, "utf-8"));
1306
+ setMetadata(metadata);
1307
+ } catch (e) {
1308
+ this.warn(`failed to load '${file}'`);
1309
+ }
1310
+ }
1311
+ }];
1312
+ }
1113
1313
  function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1114
1314
  let defineEncryptionKey;
1115
1315
  let emitEncryptionKey = false;
@@ -1148,14 +1348,17 @@ function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1148
1348
  }
1149
1349
  }];
1150
1350
  }
1151
- function vitePluginUseServer(useServerPluginOptions) {
1351
+ function vitePluginUseServer(useServerPluginOptions, manager) {
1152
1352
  const serverEnvironmentName = useServerPluginOptions.environment?.rsc ?? "rsc";
1153
1353
  const browserEnvironmentName = useServerPluginOptions.environment?.browser ?? "client";
1154
1354
  const debug$1 = createDebug("vite-rsc:use-server");
1155
1355
  return [{
1156
1356
  name: "rsc:use-server",
1157
1357
  async transform(code, id) {
1158
- if (!code.includes("use server")) return;
1358
+ if (!code.includes("use server")) {
1359
+ delete manager.serverReferenceMetaMap[id];
1360
+ return;
1361
+ }
1159
1362
  const ast = await parseAstAsync(code);
1160
1363
  let normalizedId_;
1161
1364
  const getNormalizedId = () => {
@@ -1164,22 +1367,30 @@ function vitePluginUseServer(useServerPluginOptions) {
1164
1367
  debug$1(`internal server reference created through a package imported in ${this.environment.name} environment: ${id}`);
1165
1368
  id = cleanUrl(id);
1166
1369
  }
1167
- if (config.command === "build") normalizedId_ = hashString(path.relative(config.root, id));
1168
- else normalizedId_ = normalizeViteImportAnalysisUrl(server.environments[serverEnvironmentName], id);
1370
+ if (manager.config.command === "build") normalizedId_ = hashString(path.relative(manager.config.root, id));
1371
+ else normalizedId_ = normalizeViteImportAnalysisUrl(manager.server.environments[serverEnvironmentName], id);
1169
1372
  }
1170
1373
  return normalizedId_;
1171
1374
  };
1172
1375
  if (this.environment.name === serverEnvironmentName) {
1173
1376
  const transformServerActionServer_ = withRollupError(this, transformServerActionServer);
1174
1377
  const enableEncryption = useServerPluginOptions.enableActionEncryption ?? true;
1175
- const { output } = transformServerActionServer_(code, ast, {
1378
+ const result = transformServerActionServer_(code, ast, {
1176
1379
  runtime: (value, name) => `$$ReactServer.registerServerReference(${value}, ${JSON.stringify(getNormalizedId())}, ${JSON.stringify(name)})`,
1177
1380
  rejectNonAsyncFunction: true,
1178
1381
  encode: enableEncryption ? (value) => `__vite_rsc_encryption_runtime.encryptActionBoundArgs(${value})` : void 0,
1179
1382
  decode: enableEncryption ? (value) => `await __vite_rsc_encryption_runtime.decryptActionBoundArgs(${value})` : void 0
1180
1383
  });
1181
- if (!output.hasChanged()) return;
1182
- serverReferences[getNormalizedId()] = id;
1384
+ const output = result.output;
1385
+ if (!result || !output.hasChanged()) {
1386
+ delete manager.serverReferenceMetaMap[id];
1387
+ return;
1388
+ }
1389
+ manager.serverReferenceMetaMap[id] = {
1390
+ importId: id,
1391
+ referenceKey: getNormalizedId(),
1392
+ exportNames: "names" in result ? result.names : result.exportNames
1393
+ };
1183
1394
  const importSource = resolvePackage(`${PKG_NAME}/react/rsc`);
1184
1395
  output.prepend(`import * as $$ReactServer from "${importSource}";\n`);
1185
1396
  if (enableEncryption) {
@@ -1191,7 +1402,10 @@ function vitePluginUseServer(useServerPluginOptions) {
1191
1402
  map: output.generateMap({ hires: "boundary" })
1192
1403
  };
1193
1404
  } else {
1194
- if (!hasDirective(ast.body, "use server")) return;
1405
+ if (!hasDirective(ast.body, "use server")) {
1406
+ delete manager.serverReferenceMetaMap[id];
1407
+ return;
1408
+ }
1195
1409
  const transformDirectiveProxyExport_ = withRollupError(this, transformDirectiveProxyExport);
1196
1410
  const result = transformDirectiveProxyExport_(ast, {
1197
1411
  code,
@@ -1199,9 +1413,14 @@ function vitePluginUseServer(useServerPluginOptions) {
1199
1413
  directive: "use server",
1200
1414
  rejectNonAsyncFunction: true
1201
1415
  });
1416
+ if (!result) return;
1202
1417
  const output = result?.output;
1203
1418
  if (!output?.hasChanged()) return;
1204
- serverReferences[getNormalizedId()] = id;
1419
+ manager.serverReferenceMetaMap[id] = {
1420
+ importId: id,
1421
+ referenceKey: getNormalizedId(),
1422
+ exportNames: result.exportNames
1423
+ };
1205
1424
  const name = this.environment.name === browserEnvironmentName ? "browser" : "ssr";
1206
1425
  const importSource = resolvePackage(`${PKG_NAME}/react/${name}`);
1207
1426
  output.prepend(`import * as $$ReactClient from "${importSource}";\n`);
@@ -1216,44 +1435,25 @@ function vitePluginUseServer(useServerPluginOptions) {
1216
1435
  code: `export {}`,
1217
1436
  map: null
1218
1437
  };
1219
- const code = generateDynamicImportCode(serverReferences);
1438
+ let code = "";
1439
+ for (const meta of Object.values(manager.serverReferenceMetaMap)) {
1440
+ const key = JSON.stringify(meta.referenceKey);
1441
+ const id = JSON.stringify(meta.importId);
1442
+ const exports = meta.exportNames.map((name) => name === "default" ? "default: _default" : name).sort();
1443
+ code += `
1444
+ ${key}: async () => {
1445
+ const {${exports}} = await import(${id});
1446
+ return {${exports}};
1447
+ },
1448
+ `;
1449
+ }
1450
+ code = `export default {${code}};\n`;
1220
1451
  return {
1221
1452
  code,
1222
1453
  map: null
1223
1454
  };
1224
1455
  })];
1225
1456
  }
1226
- function withRollupError(ctx, f) {
1227
- function processError(e) {
1228
- if (e && typeof e === "object" && typeof e.pos === "number") return ctx.error(e, e.pos);
1229
- throw e;
1230
- }
1231
- return function(...args) {
1232
- try {
1233
- const result = f.apply(this, args);
1234
- if (result instanceof Promise) return result.catch((e) => processError(e));
1235
- return result;
1236
- } catch (e) {
1237
- processError(e);
1238
- }
1239
- };
1240
- }
1241
- function createVirtualPlugin(name, load) {
1242
- name = "virtual:" + name;
1243
- return {
1244
- name: `rsc:virtual-${name}`,
1245
- resolveId(source, _importer, _options) {
1246
- return source === name ? "\0" + name : void 0;
1247
- },
1248
- load(id, options) {
1249
- if (id === "\0" + name) return load.apply(this, [id, options]);
1250
- }
1251
- };
1252
- }
1253
- function generateDynamicImportCode(map) {
1254
- let code = Object.entries(map).map(([key, id]) => `${JSON.stringify(key)}: () => import(${JSON.stringify(id)}),`).join("\n");
1255
- return `export default {${code}};\n`;
1256
- }
1257
1457
  var RuntimeAsset = class {
1258
1458
  runtime;
1259
1459
  constructor(value) {
@@ -1273,7 +1473,8 @@ function serializeValueWithRuntime(value) {
1273
1473
  for (const [placeholder, runtime] of replacements) result = result.replace(`"${placeholder}"`, runtime);
1274
1474
  return result;
1275
1475
  }
1276
- function assetsURL(url) {
1476
+ function assetsURL(url, manager) {
1477
+ const { config } = manager;
1277
1478
  if (config.command === "build" && typeof config.experimental?.renderBuiltUrl === "function") {
1278
1479
  const result = config.experimental.renderBuiltUrl(url, {
1279
1480
  type: "asset",
@@ -1288,15 +1489,15 @@ function assetsURL(url) {
1288
1489
  }
1289
1490
  return config.base + url;
1290
1491
  }
1291
- function assetsURLOfDeps(deps) {
1492
+ function assetsURLOfDeps(deps, manager) {
1292
1493
  return {
1293
1494
  js: deps.js.map((href) => {
1294
1495
  assert(typeof href === "string");
1295
- return assetsURL(href);
1496
+ return assetsURL(href, manager);
1296
1497
  }),
1297
1498
  css: deps.css.map((href) => {
1298
1499
  assert(typeof href === "string");
1299
- return assetsURL(href);
1500
+ return assetsURL(href, manager);
1300
1501
  })
1301
1502
  };
1302
1503
  }
@@ -1335,67 +1536,10 @@ function collectAssetDepsInner(fileName, bundle) {
1335
1536
  css: [...new Set(css)]
1336
1537
  };
1337
1538
  }
1338
- function vitePluginFindSourceMapURL() {
1339
- return [{
1340
- name: "rsc:findSourceMapURL",
1341
- apply: "serve",
1342
- configureServer(server$1) {
1343
- server$1.middlewares.use(async (req, res, next) => {
1344
- const url = new URL(req.url, `http://localhost`);
1345
- if (url.pathname === "/__vite_rsc_findSourceMapURL") {
1346
- let filename = url.searchParams.get("filename");
1347
- let environmentName = url.searchParams.get("environmentName");
1348
- try {
1349
- const map = await findSourceMapURL(server$1, filename, environmentName);
1350
- res.setHeader("content-type", "application/json");
1351
- if (!map) res.statusCode = 404;
1352
- res.end(JSON.stringify(map ?? {}));
1353
- } catch (e) {
1354
- next(e);
1355
- }
1356
- return;
1357
- }
1358
- next();
1359
- });
1360
- }
1361
- }];
1362
- }
1363
- async function findSourceMapURL(server$1, filename, environmentName) {
1364
- if (filename.startsWith("file://")) {
1365
- filename = fileURLToPath(filename);
1366
- if (fs.existsSync(filename)) {
1367
- const content = fs.readFileSync(filename, "utf-8");
1368
- return {
1369
- version: 3,
1370
- sources: [filename],
1371
- sourcesContent: [content],
1372
- mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
1373
- };
1374
- }
1375
- return;
1376
- }
1377
- let mod;
1378
- let map;
1379
- if (environmentName === "Server") {
1380
- mod = server$1.environments.rsc.moduleGraph.getModuleById(filename);
1381
- map = mod?.transformResult?.map;
1382
- if (map && map.mappings) map = {
1383
- ...map,
1384
- mappings: ";;" + map.mappings
1385
- };
1539
+ function vitePluginRscCss(rscCssOptions = {}, manager) {
1540
+ function hasSpecialCssQuery(id) {
1541
+ return /[?&](url|inline|raw)(\b|=|&|$)/.test(id);
1386
1542
  }
1387
- const base = server$1.config.base.slice(0, -1);
1388
- if (environmentName === "Client") try {
1389
- const url = new URL(filename).pathname.slice(base.length);
1390
- mod = server$1.environments.client.moduleGraph.urlToModuleMap.get(url);
1391
- map = mod?.transformResult?.map;
1392
- } catch (e) {}
1393
- if (mod && map) return {
1394
- ...map,
1395
- sources: [base + mod.url]
1396
- };
1397
- }
1398
- function vitePluginRscCss(rscCssOptions) {
1399
1543
  function collectCss(environment, entryId) {
1400
1544
  const visited = /* @__PURE__ */ new Set();
1401
1545
  const cssIds = /* @__PURE__ */ new Set();
@@ -1405,8 +1549,10 @@ function vitePluginRscCss(rscCssOptions) {
1405
1549
  visited.add(id);
1406
1550
  const mod = environment.moduleGraph.getModuleById(id);
1407
1551
  if (mod?.file) visitedFiles.add(mod.file);
1408
- for (const next of mod?.importedModules ?? []) if (next.id) if (isCSSRequest(next.id)) cssIds.add(next.id);
1409
- else recurse(next.id);
1552
+ for (const next of mod?.importedModules ?? []) if (next.id) if (isCSSRequest(next.id)) {
1553
+ if (hasSpecialCssQuery(next.id)) continue;
1554
+ cssIds.add(next.id);
1555
+ } else recurse(next.id);
1410
1556
  }
1411
1557
  recurse(entryId);
1412
1558
  const hrefs = [...cssIds].map((id) => normalizeViteImportAnalysisUrl(environment, id));
@@ -1457,18 +1603,20 @@ function vitePluginRscCss(rscCssOptions) {
1457
1603
  }
1458
1604
  },
1459
1605
  {
1460
- name: "rsc:css/dev-ssr-virtual",
1606
+ name: "rsc:css-virtual",
1461
1607
  resolveId(source) {
1462
- if (source.startsWith("virtual:vite-rsc/css/dev-ssr/")) return "\0" + source;
1608
+ if (source.startsWith("virtual:vite-rsc/css?")) return "\0" + source;
1463
1609
  },
1464
1610
  async load(id) {
1465
- if (id.startsWith("\0virtual:vite-rsc/css/dev-ssr/")) {
1466
- id = id.slice(30);
1611
+ const parsed = parseCssVirtual(id);
1612
+ if (parsed?.type === "ssr") {
1613
+ id = parsed.id;
1614
+ const { server } = manager;
1467
1615
  const mod = await server.environments.ssr.moduleGraph.getModuleByUrl(id);
1468
1616
  if (!mod?.id || !mod?.file) return `export default []`;
1469
1617
  const result = collectCss(server.environments.ssr, mod.id);
1470
1618
  for (const file of [mod.file, ...result.visitedFiles]) this.addWatchFile(file);
1471
- const hrefs = result.hrefs.map((href) => assetsURL(href.slice(1)));
1619
+ const hrefs = result.hrefs.map((href) => assetsURL(href.slice(1), manager));
1472
1620
  return `export default ${serializeValueWithRuntime(hrefs)}`;
1473
1621
  }
1474
1622
  }
@@ -1479,6 +1627,7 @@ function vitePluginRscCss(rscCssOptions) {
1479
1627
  if (!code.includes("import.meta.viteRsc.loadCss")) return;
1480
1628
  assert(this.environment.name === "rsc");
1481
1629
  const output = new MagicString(code);
1630
+ let importAdded = false;
1482
1631
  for (const match of code.matchAll(/import\.meta\.viteRsc\.loadCss\(([\s\S]*?)\)/dg)) {
1483
1632
  const [start, end] = match.indices[0];
1484
1633
  const argCode = match[1].trim();
@@ -1493,7 +1642,10 @@ function vitePluginRscCss(rscCssOptions) {
1493
1642
  continue;
1494
1643
  }
1495
1644
  }
1496
- const importId = `virtual:vite-rsc/importer-resources?importer=${encodeURIComponent(importer)}`;
1645
+ const importId = toCssVirtual({
1646
+ id: importer,
1647
+ type: "rsc"
1648
+ });
1497
1649
  let replacement;
1498
1650
  if (this.environment.mode === "dev") replacement = `__vite_rsc_react__.createElement(async () => {
1499
1651
  const __m = await import(${JSON.stringify(importId)});
@@ -1501,7 +1653,10 @@ function vitePluginRscCss(rscCssOptions) {
1501
1653
  })`;
1502
1654
  else {
1503
1655
  const hash = hashString(importId);
1504
- if (!code.includes(`__vite_rsc_importer_resources_${hash}`)) output.prepend(`import * as __vite_rsc_importer_resources_${hash} from ${JSON.stringify(importId)};`);
1656
+ if (!importAdded && !code.includes(`__vite_rsc_importer_resources_${hash}`)) {
1657
+ importAdded = true;
1658
+ output.prepend(`import * as __vite_rsc_importer_resources_${hash} from ${JSON.stringify(importId)};`);
1659
+ }
1505
1660
  replacement = `__vite_rsc_react__.createElement(__vite_rsc_importer_resources_${hash}.Resources)`;
1506
1661
  }
1507
1662
  output.update(start, end, replacement);
@@ -1514,37 +1669,37 @@ function vitePluginRscCss(rscCssOptions) {
1514
1669
  };
1515
1670
  }
1516
1671
  },
1517
- resolveId(source) {
1518
- if (source.startsWith("virtual:vite-rsc/importer-resources?importer=")) {
1519
- assert(this.environment.name === "rsc");
1520
- return "\0" + source;
1521
- }
1522
- },
1523
1672
  load(id) {
1524
- if (id.startsWith("\0virtual:vite-rsc/importer-resources?importer=")) {
1525
- const importer = decodeURIComponent(parseIdQuery(id).query["importer"]);
1673
+ const { server } = manager;
1674
+ const parsed = parseCssVirtual(id);
1675
+ if (parsed?.type === "rsc") {
1676
+ assert(this.environment.name === "rsc");
1677
+ const importer = parsed.id;
1526
1678
  if (this.environment.mode === "dev") {
1527
1679
  const result = collectCss(server.environments.rsc, importer);
1528
1680
  const cssHrefs = result.hrefs.map((href) => href.slice(1));
1529
- const jsHrefs = ["@id/__x00__virtual:vite-rsc/importer-resources-browser?importer=" + encodeURIComponent(importer)];
1681
+ const jsHrefs = [`@id/__x00__${toCssVirtual({
1682
+ id: importer,
1683
+ type: "rsc-browser"
1684
+ })}`];
1530
1685
  const deps = assetsURLOfDeps({
1531
1686
  css: cssHrefs,
1532
1687
  js: jsHrefs
1533
- });
1534
- return generateResourcesCode(serializeValueWithRuntime(deps));
1688
+ }, manager);
1689
+ return generateResourcesCode(serializeValueWithRuntime(deps), manager);
1535
1690
  } else {
1536
- const key = normalizePath(path.relative(config.root, importer));
1537
- serverResourcesMetaMap[importer] = { key };
1691
+ const key = normalizePath(path.relative(manager.config.root, importer));
1692
+ manager.serverResourcesMetaMap[importer] = { key };
1538
1693
  return `
1539
1694
  import __vite_rsc_assets_manifest__ from "virtual:vite-rsc/assets-manifest";
1540
- ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`)}
1695
+ ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`, manager)}
1541
1696
  `;
1542
1697
  }
1543
1698
  }
1544
- if (id.startsWith("\0virtual:vite-rsc/importer-resources-browser?importer=")) {
1699
+ if (parsed?.type === "rsc-browser") {
1545
1700
  assert(this.environment.name === "client");
1546
1701
  assert(this.environment.mode === "dev");
1547
- const importer = decodeURIComponent(parseIdQuery(id).query["importer"]);
1702
+ const importer = parsed.id;
1548
1703
  const result = collectCss(server.environments.rsc, importer);
1549
1704
  let code = result.ids.map((id$1) => id$1.replace(/^\0/, "")).map((id$1) => `import ${JSON.stringify(id$1)};\n`).join("");
1550
1705
  code += `if (import.meta.hot) { import.meta.hot.accept() }\n`;
@@ -1553,11 +1708,17 @@ function vitePluginRscCss(rscCssOptions) {
1553
1708
  },
1554
1709
  hotUpdate(ctx) {
1555
1710
  if (this.environment.name === "rsc") {
1711
+ const { server } = manager;
1556
1712
  const mods = collectModuleDependents(ctx.modules);
1557
1713
  for (const mod of mods) if (mod.id) {
1558
- const importer = encodeURIComponent(mod.id);
1559
- invalidteModuleById(server.environments.rsc, `\0virtual:vite-rsc/importer-resources?importer=${importer}`);
1560
- invalidteModuleById(server.environments.client, `\0virtual:vite-rsc/importer-resources-browser?importer=${importer}`);
1714
+ invalidteModuleById(server.environments.rsc, `\0` + toCssVirtual({
1715
+ id: mod.id,
1716
+ type: "rsc"
1717
+ }));
1718
+ invalidteModuleById(server.environments.client, `\0` + toCssVirtual({
1719
+ id: mod.id,
1720
+ type: "rsc-browser"
1721
+ }));
1561
1722
  }
1562
1723
  }
1563
1724
  }
@@ -1597,7 +1758,7 @@ function collectModuleDependents(mods) {
1597
1758
  for (const mod of mods) recurse(mod);
1598
1759
  return [...visited];
1599
1760
  }
1600
- function generateResourcesCode(depsCode) {
1761
+ function generateResourcesCode(depsCode, manager) {
1601
1762
  const ResourcesFn = (React, deps, RemoveDuplicateServerCss) => {
1602
1763
  return function Resources() {
1603
1764
  return React.createElement(React.Fragment, null, [
@@ -1620,7 +1781,7 @@ function generateResourcesCode(depsCode) {
1620
1781
  return `
1621
1782
  import __vite_rsc_react__ from "react";
1622
1783
 
1623
- ${config.command === "serve" ? `import RemoveDuplicateServerCss from "virtual:vite-rsc/remove-duplicate-server-css";` : `const RemoveDuplicateServerCss = undefined;`}
1784
+ ${manager.config.command === "serve" ? `import RemoveDuplicateServerCss from "virtual:vite-rsc/remove-duplicate-server-css";` : `const RemoveDuplicateServerCss = undefined;`}
1624
1785
 
1625
1786
  export const Resources = (${ResourcesFn.toString()})(
1626
1787
  __vite_rsc_react__,
@@ -1657,59 +1818,6 @@ function __vite_rsc_wrap_css__(value, name) {
1657
1818
  return { output: result.output };
1658
1819
  }
1659
1820
  }
1660
- /**
1661
- * temporary workaround for
1662
- * - https://github.com/cloudflare/workers-sdk/issues/9538 (fixed in @cloudflare/vite-plugin@1.8.0)
1663
- * - https://github.com/vitejs/vite/pull/20077 (fixed in vite@7.0.0)
1664
- */
1665
- function __fix_cloudflare() {
1666
- return {
1667
- name: "rsc:workaround-cloudflare",
1668
- enforce: "post",
1669
- config(config$1) {
1670
- const plugin = config$1.plugins.flat().find((p) => p && "name" in p && p.name === "vite-plugin-cloudflare");
1671
- const original = plugin.configResolved;
1672
- plugin.configResolved = function(...args) {
1673
- try {
1674
- return original.apply(this, args);
1675
- } catch (e) {}
1676
- };
1677
- config$1.environments.ssr.resolve.noExternal = true;
1678
- config$1.environments.rsc.resolve.noExternal = true;
1679
- }
1680
- };
1681
- }
1682
- function validateImportPlugin() {
1683
- return {
1684
- name: "rsc:validate-imports",
1685
- resolveId: {
1686
- order: "pre",
1687
- async handler(source, importer, options) {
1688
- if ("scan" in options && options.scan) return;
1689
- if (source === "client-only") {
1690
- if (this.environment.name === "rsc") throw new Error(`'client-only' cannot be imported in server build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
1691
- return {
1692
- id: `\0virtual:vite-rsc/empty`,
1693
- moduleSideEffects: false
1694
- };
1695
- }
1696
- if (source === "server-only") {
1697
- if (this.environment.name !== "rsc") throw new Error(`'server-only' cannot be imported in client build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
1698
- return {
1699
- id: `\0virtual:vite-rsc/empty`,
1700
- moduleSideEffects: false
1701
- };
1702
- }
1703
- }
1704
- },
1705
- load(id) {
1706
- if (id.startsWith("\0virtual:vite-rsc/empty")) return `export {}`;
1707
- }
1708
- };
1709
- }
1710
- function sortObject(o) {
1711
- return Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
1712
- }
1713
1821
 
1714
1822
  //#endregion
1715
- export { __fix_cloudflare, findSourceMapURL, transformHoistInlineDirective, transformRscCssExport, vitePluginFindSourceMapURL, vitePluginRsc, vitePluginRscCss, vitePluginRscMinimal };
1823
+ export { transformHoistInlineDirective, transformRscCssExport, vitePluginRsc, vitePluginRscMinimal };