@vitejs/plugin-rsc 0.4.21 → 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 (50) hide show
  1. package/dist/{browser-mbRygLxB.d.ts → browser-DUDACP5e.d.ts} +1 -1
  2. package/dist/browser.d.ts +3 -3
  3. package/dist/core/browser.d.ts +1 -1
  4. package/dist/core/rsc.d.ts +2 -2
  5. package/dist/core/rsc.js +1 -1
  6. package/dist/core/ssr.d.ts +2 -2
  7. package/dist/core/ssr.js +1 -1
  8. package/dist/{encryption-runtime-CJUalqt3.js → encryption-runtime-z7X8aRLB.js} +1 -1
  9. package/dist/extra/browser.d.ts +1 -1
  10. package/dist/extra/browser.js +1 -1
  11. package/dist/extra/rsc.d.ts +1 -1
  12. package/dist/extra/rsc.js +4 -4
  13. package/dist/extra/ssr.js +5 -4
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +2 -1
  16. package/dist/{plugin-CzZCeIwj.js → plugin-BLljgx4e.js} +380 -296
  17. package/dist/{plugin-BQszG7oj.d.ts → plugin-CrIhPWor.d.ts} +28 -12
  18. package/dist/plugin.d.ts +2 -2
  19. package/dist/plugin.js +3 -2
  20. package/dist/react/browser.d.ts +3 -3
  21. package/dist/react/rsc.d.ts +3 -3
  22. package/dist/react/rsc.js +2 -2
  23. package/dist/react/ssr.d.ts +3 -3
  24. package/dist/react/ssr.js +2 -2
  25. package/dist/{rsc-BwEwbLG4.js → rsc-0ugrKC93.js} +1 -1
  26. package/dist/{rsc-CxDPDiLz.d.ts → rsc-BeJKxeMX.d.ts} +1 -1
  27. package/dist/{rsc-VjVw_i-M.js → rsc-K03z8Dh0.js} +1 -1
  28. package/dist/rsc-html-stream/browser.js +1 -1
  29. package/dist/rsc-html-stream/ssr.js +1 -1
  30. package/dist/rsc.d.ts +4 -4
  31. package/dist/rsc.js +4 -4
  32. package/dist/shared-Cwk6fxfN.js +22 -0
  33. package/dist/{ssr-BMTRhW5g.js → ssr-BnEu3hbo.js} +6 -2
  34. package/dist/{ssr-BoNKka-5.d.ts → ssr-Bv84RACl.d.ts} +1 -1
  35. package/dist/{ssr-BEKKb_cw.js → ssr-D154nyka.js} +1 -1
  36. package/dist/ssr.d.ts +3 -3
  37. package/dist/ssr.js +4 -3
  38. package/dist/utils/encryption-runtime.d.ts +1 -1
  39. package/dist/utils/encryption-runtime.js +3 -3
  40. package/package.json +1 -1
  41. /package/dist/{browser-CuwQIlVY.d.ts → browser-CyGTajab.d.ts} +0 -0
  42. /package/dist/{client-C1J4FCf5.js → client-BPIq1kGs.js} +0 -0
  43. /package/dist/{encryption-runtime-SgJRa9yj.d.ts → encryption-runtime-BmDC7d-3.d.ts} +0 -0
  44. /package/dist/{index-QWzVHuya.d.ts → index-CrcbP1rd.d.ts} +0 -0
  45. /package/dist/{rsc-CFtzqEG8.d.ts → rsc-A9Zr9bEE.d.ts} +0 -0
  46. /package/dist/{rsc-BfBPoIV8.js → rsc-C54XEgZY.js} +0 -0
  47. /package/dist/{rsc-Cv3XEZqB.d.ts → rsc-D-lnfNSa.d.ts} +0 -0
  48. /package/dist/{server-D0-DavPP.js → server-DoWzqBNF.js} +0 -0
  49. /package/dist/{ssr-D6GTzOzx.d.ts → ssr-EOoYUXrM.d.ts} +0 -0
  50. /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,6 +399,58 @@ 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
+
420
454
  //#endregion
421
455
  //#region src/plugins/scan.ts
422
456
  const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
@@ -436,17 +470,103 @@ async function transformScanBuildStrip(code) {
436
470
  return output;
437
471
  }
438
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
+
439
567
  //#endregion
440
568
  //#region src/plugin.ts
441
- let serverReferences = {};
442
- let server;
443
- let config;
444
- let rscBundle;
445
- let buildAssetsManifest;
446
- let isScanBuild = false;
447
569
  const BUILD_ASSETS_MANIFEST_NAME = "__vite_rsc_assets_manifest.js";
448
- let clientReferenceMetaMap = {};
449
- let serverResourcesMetaMap = {};
450
570
  const PKG_NAME = "@vitejs/plugin-rsc";
451
571
  const REACT_SERVER_DOM_NAME = `${PKG_NAME}/vendor/react-server-dom`;
452
572
  const VIRTUAL_ENTRIES = { browser: "virtual:vite-rsc/entry-browser" };
@@ -454,8 +574,22 @@ const require = createRequire(import.meta.url);
454
574
  function resolvePackage(name) {
455
575
  return pathToFileURL(require.resolve(name)).href;
456
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
+ };
457
591
  /** @experimental */
458
- function vitePluginRscMinimal(rscPluginOptions = {}) {
592
+ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginManager()) {
459
593
  return [
460
594
  {
461
595
  name: "rsc:minimal",
@@ -463,12 +597,12 @@ function vitePluginRscMinimal(rscPluginOptions = {}) {
463
597
  async config() {
464
598
  await esModuleLexer.init;
465
599
  },
466
- configResolved(config_) {
467
- config = config_;
600
+ configResolved(config) {
601
+ manager.config = config;
468
602
  for (const e of Object.values(config.environments)) e.build.outDir = path.resolve(config.root, e.build.outDir);
469
603
  },
470
604
  configureServer(server_) {
471
- server = server_;
605
+ manager.server = server_;
472
606
  }
473
607
  },
474
608
  {
@@ -481,55 +615,54 @@ function vitePluginRscMinimal(rscPluginOptions = {}) {
481
615
  }
482
616
  },
483
617
  ...vitePluginRscCore(),
484
- ...vitePluginUseClient(rscPluginOptions),
485
- ...vitePluginUseServer(rscPluginOptions),
618
+ ...vitePluginUseClient(rscPluginOptions, manager),
619
+ ...vitePluginUseServer(rscPluginOptions, manager),
486
620
  ...vitePluginDefineEncryptionKey(rscPluginOptions)
487
621
  ];
488
622
  }
489
623
  function vitePluginRsc(rscPluginOptions = {}) {
624
+ const manager = new RscPluginManager();
490
625
  const buildApp = async (builder) => {
491
626
  if (!builder.environments.ssr?.config.build.rollupOptions.input) {
492
- isScanBuild = true;
627
+ manager.isScanBuild = true;
493
628
  builder.environments.rsc.config.build.write = false;
494
629
  builder.environments.client.config.build.write = false;
495
630
  await builder.build(builder.environments.rsc);
496
631
  await builder.build(builder.environments.client);
497
- isScanBuild = false;
632
+ manager.isScanBuild = false;
498
633
  builder.environments.rsc.config.build.write = true;
499
634
  builder.environments.client.config.build.write = true;
500
635
  await builder.build(builder.environments.rsc);
501
- clientReferenceMetaMap = sortObject(clientReferenceMetaMap);
502
- serverResourcesMetaMap = sortObject(serverResourcesMetaMap);
636
+ manager.stabilize();
503
637
  await builder.build(builder.environments.client);
504
638
  writeAssetsManifest(["rsc"]);
505
639
  return;
506
640
  }
507
- isScanBuild = true;
641
+ manager.isScanBuild = true;
508
642
  builder.environments.rsc.config.build.write = false;
509
643
  builder.environments.ssr.config.build.write = false;
510
644
  await builder.build(builder.environments.rsc);
511
645
  await builder.build(builder.environments.ssr);
512
- isScanBuild = false;
646
+ manager.isScanBuild = false;
513
647
  builder.environments.rsc.config.build.write = true;
514
648
  builder.environments.ssr.config.build.write = true;
515
649
  await builder.build(builder.environments.rsc);
516
- clientReferenceMetaMap = sortObject(clientReferenceMetaMap);
517
- serverResourcesMetaMap = sortObject(serverResourcesMetaMap);
650
+ manager.stabilize();
518
651
  await builder.build(builder.environments.client);
519
652
  await builder.build(builder.environments.ssr);
520
653
  writeAssetsManifest(["ssr", "rsc"]);
521
654
  };
522
655
  function writeAssetsManifest(environmentNames) {
523
- const assetsManifestCode = `export default ${serializeValueWithRuntime(buildAssetsManifest)}`;
656
+ const assetsManifestCode = `export default ${serializeValueWithRuntime(manager.buildAssetsManifest)}`;
524
657
  for (const name of environmentNames) {
525
- 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);
526
659
  fs.writeFileSync(manifestPath, assetsManifestCode);
527
660
  }
528
661
  }
529
662
  return [
530
663
  {
531
664
  name: "rsc",
532
- async config(config$1, env) {
665
+ async config(config, env) {
533
666
  const result = await crawlFrameworkPkgs({
534
667
  root: process.cwd(),
535
668
  isBuild: env.command === "build",
@@ -553,7 +686,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
553
686
  environments: {
554
687
  client: {
555
688
  build: {
556
- outDir: config$1.environments?.client?.build?.outDir ?? "dist/client",
689
+ outDir: config.environments?.client?.build?.outDir ?? "dist/client",
557
690
  rollupOptions: { input: rscPluginOptions.entries?.client && { index: rscPluginOptions.entries.client } }
558
691
  },
559
692
  optimizeDeps: {
@@ -563,7 +696,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
563
696
  },
564
697
  ssr: {
565
698
  build: {
566
- outDir: config$1.environments?.ssr?.build?.outDir ?? "dist/ssr",
699
+ outDir: config.environments?.ssr?.build?.outDir ?? "dist/ssr",
567
700
  rollupOptions: { input: rscPluginOptions.entries?.ssr && { index: rscPluginOptions.entries.ssr } }
568
701
  },
569
702
  resolve: { noExternal },
@@ -581,7 +714,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
581
714
  },
582
715
  rsc: {
583
716
  build: {
584
- outDir: config$1.environments?.rsc?.build?.outDir ?? "dist/rsc",
717
+ outDir: config.environments?.rsc?.build?.outDir ?? "dist/rsc",
585
718
  emitAssets: true,
586
719
  rollupOptions: { input: rscPluginOptions.entries?.rsc && { index: rscPluginOptions.entries.rsc } }
587
720
  },
@@ -610,7 +743,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
610
743
  };
611
744
  },
612
745
  buildApp: rscPluginOptions.useBuildAppHook ? buildApp : void 0,
613
- configureServer() {
746
+ configureServer(server) {
614
747
  globalThis.__viteRscDevServer = server;
615
748
  if (rscPluginOptions.disableServerHandler) return;
616
749
  if (rscPluginOptions.serverHandler === false) return;
@@ -633,26 +766,26 @@ function vitePluginRsc(rscPluginOptions = {}) {
633
766
  });
634
767
  };
635
768
  },
636
- async configurePreviewServer(server$1) {
769
+ async configurePreviewServer(server) {
637
770
  if (rscPluginOptions.disableServerHandler) return;
638
771
  if (rscPluginOptions.serverHandler === false) return;
639
772
  const options = rscPluginOptions.serverHandler ?? {
640
773
  environmentName: "rsc",
641
774
  entryName: "index"
642
775
  };
643
- 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`);
644
777
  const entry = pathToFileURL(entryFile).href;
645
778
  const mod = await import(
646
779
  /* @vite-ignore */
647
780
  entry
648
781
  );
649
782
  const handler = createRequestListener(mod.default);
650
- server$1.middlewares.use((req, _res, next) => {
783
+ server.middlewares.use((req, _res, next) => {
651
784
  delete req.headers["accept-encoding"];
652
785
  next();
653
786
  });
654
787
  return () => {
655
- server$1.middlewares.use(async (req, res, next) => {
788
+ server.middlewares.use(async (req, res, next) => {
656
789
  try {
657
790
  await handler(req, res);
658
791
  } catch (e) {
@@ -667,11 +800,16 @@ function vitePluginRsc(rscPluginOptions = {}) {
667
800
  }
668
801
  const ids = ctx.modules.map((mod) => mod.id).filter((v) => v !== null);
669
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
+ }
670
808
  function isInsideClientBoundary(mods) {
671
809
  const visited = /* @__PURE__ */ new Set();
672
810
  function recurse(mod) {
673
811
  if (!mod.id) return false;
674
- if (clientReferenceMetaMap[mod.id]) return true;
812
+ if (manager.clientReferenceMetaMap[mod.id]) return true;
675
813
  if (visited.has(mod.id)) return false;
676
814
  visited.add(mod.id);
677
815
  for (const importer of mod.importers) if (recurse(importer)) return true;
@@ -688,7 +826,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
688
826
  for (const mod of ctx.modules) if (mod.type === "js") try {
689
827
  await this.environment.transformRequest(mod.url);
690
828
  } catch (e) {
691
- server.environments.client.hot.send({
829
+ manager.server.environments.client.hot.send({
692
830
  type: "error",
693
831
  err: prepareError(e)
694
832
  });
@@ -721,6 +859,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
721
859
  name: "rsc:load-environment-module",
722
860
  async transform(code) {
723
861
  if (!code.includes("import.meta.viteRsc.loadModule")) return;
862
+ const { server } = manager;
724
863
  const s = new MagicString(code);
725
864
  for (const match of code.matchAll(/import\.meta\.viteRsc\.loadModule\(([\s\S]*?)\)/dg)) {
726
865
  const argCode = match[1].trim();
@@ -752,6 +891,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
752
891
  },
753
892
  renderChunk(code, chunk) {
754
893
  if (!code.includes("__vite_rsc_load_module")) return;
894
+ const { config } = manager;
755
895
  const s = new MagicString(code);
756
896
  for (const match of code.matchAll(/['"]__vite_rsc_load_module:(\w+):(\w+):(\w+)['"]/dg)) {
757
897
  const [fromEnv, toEnv, entryName] = match.slice(1);
@@ -769,12 +909,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
769
909
  {
770
910
  name: "vite-rsc-load-module-dev-proxy",
771
911
  apply: () => !!rscPluginOptions.loadModuleDevProxy,
772
- configureServer(server$1) {
912
+ configureServer(server) {
773
913
  async function createHandler(url) {
774
914
  const { environmentName, entryName } = Object.fromEntries(url.searchParams);
775
915
  assert(environmentName);
776
916
  assert(entryName);
777
- const environment = server$1.environments[environmentName];
917
+ const environment = server.environments[environmentName];
778
918
  const source = getEntrySource(environment.config, entryName);
779
919
  const resolvedEntry = await environment.pluginContainer.resolveId(source);
780
920
  assert(resolvedEntry, `[vite-rsc] failed to resolve entry '${source}'`);
@@ -787,7 +927,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
787
927
  } });
788
928
  return createRpcServer(runnerProxy);
789
929
  }
790
- server$1.middlewares.use(async (req, res, next) => {
930
+ server.middlewares.use(async (req, res, next) => {
791
931
  const url = new URL(req.url ?? "/", `http://localhost`);
792
932
  if (url.pathname === "/__vite_rsc_load_module_dev_proxy") {
793
933
  try {
@@ -817,7 +957,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
817
957
  if (id === "\0virtual:vite-rsc/assets-manifest") {
818
958
  assert(this.environment.name !== "client");
819
959
  assert(this.environment.mode === "dev");
820
- const entryUrl = assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser);
960
+ const entryUrl = assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser, manager);
821
961
  const manifest = {
822
962
  bootstrapScriptContent: `import(${serializeValueWithRuntime(entryUrl)})`,
823
963
  clientReferenceDeps: {}
@@ -826,12 +966,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
826
966
  }
827
967
  },
828
968
  generateBundle(_options, bundle) {
829
- if (this.environment.name === "rsc") rscBundle = bundle;
969
+ if (this.environment.name === "rsc") manager.rscBundle = bundle;
830
970
  if (this.environment.name === "client") {
831
971
  const filterAssets = rscPluginOptions.copyServerAssetsToClient ?? (() => true);
832
- const rscBuildOptions = config.environments.rsc.build;
972
+ const rscBuildOptions = manager.config.environments.rsc.build;
833
973
  const rscViteManifest = typeof rscBuildOptions.manifest === "string" ? rscBuildOptions.manifest : rscBuildOptions.manifest && ".vite/manifest.json";
834
- for (const asset of Object.values(rscBundle)) {
974
+ for (const asset of Object.values(manager.rscBundle)) {
835
975
  if (asset.fileName === rscViteManifest) continue;
836
976
  if (asset.type === "asset" && filterAssets(asset.fileName)) this.emitFile({
837
977
  type: "asset",
@@ -840,27 +980,27 @@ function vitePluginRsc(rscPluginOptions = {}) {
840
980
  });
841
981
  }
842
982
  const serverResources = {};
843
- const rscAssetDeps = collectAssetDeps(rscBundle);
844
- 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({
845
985
  js: [],
846
986
  css: rscAssetDeps[id]?.deps.css ?? []
847
- });
987
+ }, manager);
848
988
  const assetDeps = collectAssetDeps(bundle);
849
989
  const entry = Object.values(assetDeps).find((v) => v.chunk.name === "index");
850
990
  assert(entry);
851
- const entryUrl = assetsURL(entry.chunk.fileName);
991
+ const entryUrl = assetsURL(entry.chunk.fileName, manager);
852
992
  const clientReferenceDeps = {};
853
- for (const [id, meta] of Object.entries(clientReferenceMetaMap)) {
993
+ for (const [id, meta] of Object.entries(manager.clientReferenceMetaMap)) {
854
994
  const deps = assetDeps[id]?.deps ?? {
855
995
  js: [],
856
996
  css: []
857
997
  };
858
- clientReferenceDeps[meta.referenceKey] = assetsURLOfDeps(mergeAssetDeps(deps, entry.deps));
998
+ clientReferenceDeps[meta.referenceKey] = assetsURLOfDeps(mergeAssetDeps(deps, entry.deps), manager);
859
999
  }
860
1000
  let bootstrapScriptContent;
861
1001
  if (typeof entryUrl === "string") bootstrapScriptContent = `import(${JSON.stringify(entryUrl)})`;
862
1002
  else bootstrapScriptContent = new RuntimeAsset(`"import(" + JSON.stringify(${entryUrl.runtime}) + ")"`);
863
- buildAssetsManifest = {
1003
+ manager.buildAssetsManifest = {
864
1004
  bootstrapScriptContent,
865
1005
  clientReferenceDeps,
866
1006
  serverResources
@@ -952,21 +1092,21 @@ globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
952
1092
  return "";
953
1093
  }
954
1094
  },
955
- ...vitePluginRscMinimal(rscPluginOptions),
1095
+ ...vitePluginRscMinimal(rscPluginOptions, manager),
956
1096
  ...vitePluginFindSourceMapURL(),
957
- ...vitePluginRscCss({ rscCssTransform: rscPluginOptions.rscCssTransform }),
1097
+ ...vitePluginRscCss(rscPluginOptions, manager),
958
1098
  ...rscPluginOptions.validateImports !== false ? [validateImportPlugin()] : [],
959
- scanBuildStripPlugin(),
1099
+ scanBuildStripPlugin({ manager }),
960
1100
  ...cjsModuleRunnerPlugin()
961
1101
  ];
962
1102
  }
963
- function scanBuildStripPlugin() {
1103
+ function scanBuildStripPlugin({ manager }) {
964
1104
  return {
965
1105
  name: "rsc:scan-strip",
966
1106
  apply: "build",
967
1107
  enforce: "post",
968
1108
  async transform(code, _id, _options) {
969
- if (!isScanBuild) return;
1109
+ if (!manager.isScanBuild) return;
970
1110
  const output = await transformScanBuildStrip(code);
971
1111
  return {
972
1112
  code: output,
@@ -975,28 +1115,15 @@ function scanBuildStripPlugin() {
975
1115
  }
976
1116
  };
977
1117
  }
978
- function normalizeRelativePath(s) {
979
- s = normalizePath(s);
980
- return s[0] === "." ? s : "./" + s;
981
- }
982
- function getEntrySource(config$1, name = "index") {
983
- const input = config$1.build.rollupOptions.input;
984
- 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)}`);
985
- return input[name];
986
- }
987
- function hashString(v) {
988
- return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
989
- }
990
- function vitePluginUseClient(useClientPluginOptions) {
1118
+ function vitePluginUseClient(useClientPluginOptions, manager) {
991
1119
  const packageSources = /* @__PURE__ */ new Map();
992
1120
  const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
993
1121
  const serverEnvironmentName = useClientPluginOptions.environment?.rsc ?? "rsc";
994
1122
  const browserEnvironmentName = useClientPluginOptions.environment?.browser ?? "client";
1123
+ let optimizerMetadata;
995
1124
  function warnInoncistentClientOptimization(ctx, id) {
996
- const { depsOptimizer } = server.environments.client;
997
- if (depsOptimizer) {
998
- 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'.");
999
- }
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'.");
1000
1127
  }
1001
1128
  const debug$1 = createDebug("vite-rsc:use-client");
1002
1129
  return [
@@ -1004,9 +1131,15 @@ function vitePluginUseClient(useClientPluginOptions) {
1004
1131
  name: "rsc:use-client",
1005
1132
  async transform(code, id) {
1006
1133
  if (this.environment.name !== serverEnvironmentName) return;
1007
- if (!code.includes("use client")) return;
1134
+ if (!code.includes("use client")) {
1135
+ delete manager.clientReferenceMetaMap[id];
1136
+ return;
1137
+ }
1008
1138
  const ast = await parseAstAsync(code);
1009
- if (!hasDirective(ast.body, "use client")) return;
1139
+ if (!hasDirective(ast.body, "use client")) {
1140
+ delete manager.clientReferenceMetaMap[id];
1141
+ return;
1142
+ }
1010
1143
  let importId;
1011
1144
  let referenceKey;
1012
1145
  const packageSource = packageSources.get(id);
@@ -1024,11 +1157,11 @@ function vitePluginUseClient(useClientPluginOptions) {
1024
1157
  referenceKey = hashString(packageSource);
1025
1158
  }
1026
1159
  else if (this.environment.mode === "dev") {
1027
- importId = normalizeViteImportAnalysisUrl(server.environments[browserEnvironmentName], id);
1160
+ importId = normalizeViteImportAnalysisUrl(manager.server.environments[browserEnvironmentName], id);
1028
1161
  referenceKey = importId;
1029
1162
  } else {
1030
1163
  importId = id;
1031
- referenceKey = hashString(normalizePath(path.relative(config.root, id)));
1164
+ referenceKey = hashString(normalizePath(path.relative(manager.config.root, id)));
1032
1165
  }
1033
1166
  const transformDirectiveProxyExport_ = withRollupError(this, transformDirectiveProxyExport);
1034
1167
  const result = transformDirectiveProxyExport_(ast, {
@@ -1043,7 +1176,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1043
1176
  });
1044
1177
  if (!result) return;
1045
1178
  const { output, exportNames } = result;
1046
- clientReferenceMetaMap[id] = {
1179
+ manager.clientReferenceMetaMap[id] = {
1047
1180
  importId,
1048
1181
  referenceKey,
1049
1182
  packageSource,
@@ -1064,7 +1197,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1064
1197
  map: null
1065
1198
  };
1066
1199
  let code = "";
1067
- for (const meta of Object.values(clientReferenceMetaMap)) {
1200
+ for (const meta of Object.values(manager.clientReferenceMetaMap)) {
1068
1201
  const key = JSON.stringify(meta.referenceKey);
1069
1202
  const id = JSON.stringify(meta.importId);
1070
1203
  const exports = meta.renderedExports.map((name) => name === "default" ? "default: _default" : name).sort();
@@ -1114,7 +1247,7 @@ function vitePluginUseClient(useClientPluginOptions) {
1114
1247
  if (id.startsWith("\0virtual:vite-rsc/client-package-proxy/")) {
1115
1248
  assert(this.environment.mode === "dev");
1116
1249
  const source = id.slice(39);
1117
- const meta = Object.values(clientReferenceMetaMap).find((v) => v.packageSource === source);
1250
+ const meta = Object.values(manager.clientReferenceMetaMap).find((v) => v.packageSource === source);
1118
1251
  const exportNames = meta.exportNames;
1119
1252
  return `export {${exportNames.join(",")}} from ${JSON.stringify(source)};\n`;
1120
1253
  }
@@ -1122,13 +1255,61 @@ function vitePluginUseClient(useClientPluginOptions) {
1122
1255
  generateBundle(_options, bundle) {
1123
1256
  if (this.environment.name !== serverEnvironmentName) return;
1124
1257
  for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") for (const [id, mod] of Object.entries(chunk.modules)) {
1125
- const meta = clientReferenceMetaMap[id];
1258
+ const meta = manager.clientReferenceMetaMap[id];
1126
1259
  if (meta) meta.renderedExports = mod.renderedExports;
1127
1260
  }
1128
1261
  }
1129
- }
1262
+ },
1263
+ ...customOptimizerMetadataPlugin({ setMetadata: (metadata) => {
1264
+ optimizerMetadata = metadata;
1265
+ } })
1130
1266
  ];
1131
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
+ }
1132
1313
  function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1133
1314
  let defineEncryptionKey;
1134
1315
  let emitEncryptionKey = false;
@@ -1167,14 +1348,17 @@ function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1167
1348
  }
1168
1349
  }];
1169
1350
  }
1170
- function vitePluginUseServer(useServerPluginOptions) {
1351
+ function vitePluginUseServer(useServerPluginOptions, manager) {
1171
1352
  const serverEnvironmentName = useServerPluginOptions.environment?.rsc ?? "rsc";
1172
1353
  const browserEnvironmentName = useServerPluginOptions.environment?.browser ?? "client";
1173
1354
  const debug$1 = createDebug("vite-rsc:use-server");
1174
1355
  return [{
1175
1356
  name: "rsc:use-server",
1176
1357
  async transform(code, id) {
1177
- if (!code.includes("use server")) return;
1358
+ if (!code.includes("use server")) {
1359
+ delete manager.serverReferenceMetaMap[id];
1360
+ return;
1361
+ }
1178
1362
  const ast = await parseAstAsync(code);
1179
1363
  let normalizedId_;
1180
1364
  const getNormalizedId = () => {
@@ -1183,22 +1367,30 @@ function vitePluginUseServer(useServerPluginOptions) {
1183
1367
  debug$1(`internal server reference created through a package imported in ${this.environment.name} environment: ${id}`);
1184
1368
  id = cleanUrl(id);
1185
1369
  }
1186
- if (config.command === "build") normalizedId_ = hashString(path.relative(config.root, id));
1187
- 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);
1188
1372
  }
1189
1373
  return normalizedId_;
1190
1374
  };
1191
1375
  if (this.environment.name === serverEnvironmentName) {
1192
1376
  const transformServerActionServer_ = withRollupError(this, transformServerActionServer);
1193
1377
  const enableEncryption = useServerPluginOptions.enableActionEncryption ?? true;
1194
- const { output } = transformServerActionServer_(code, ast, {
1378
+ const result = transformServerActionServer_(code, ast, {
1195
1379
  runtime: (value, name) => `$$ReactServer.registerServerReference(${value}, ${JSON.stringify(getNormalizedId())}, ${JSON.stringify(name)})`,
1196
1380
  rejectNonAsyncFunction: true,
1197
1381
  encode: enableEncryption ? (value) => `__vite_rsc_encryption_runtime.encryptActionBoundArgs(${value})` : void 0,
1198
1382
  decode: enableEncryption ? (value) => `await __vite_rsc_encryption_runtime.decryptActionBoundArgs(${value})` : void 0
1199
1383
  });
1200
- if (!output.hasChanged()) return;
1201
- 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
+ };
1202
1394
  const importSource = resolvePackage(`${PKG_NAME}/react/rsc`);
1203
1395
  output.prepend(`import * as $$ReactServer from "${importSource}";\n`);
1204
1396
  if (enableEncryption) {
@@ -1210,7 +1402,10 @@ function vitePluginUseServer(useServerPluginOptions) {
1210
1402
  map: output.generateMap({ hires: "boundary" })
1211
1403
  };
1212
1404
  } else {
1213
- if (!hasDirective(ast.body, "use server")) return;
1405
+ if (!hasDirective(ast.body, "use server")) {
1406
+ delete manager.serverReferenceMetaMap[id];
1407
+ return;
1408
+ }
1214
1409
  const transformDirectiveProxyExport_ = withRollupError(this, transformDirectiveProxyExport);
1215
1410
  const result = transformDirectiveProxyExport_(ast, {
1216
1411
  code,
@@ -1218,9 +1413,14 @@ function vitePluginUseServer(useServerPluginOptions) {
1218
1413
  directive: "use server",
1219
1414
  rejectNonAsyncFunction: true
1220
1415
  });
1416
+ if (!result) return;
1221
1417
  const output = result?.output;
1222
1418
  if (!output?.hasChanged()) return;
1223
- serverReferences[getNormalizedId()] = id;
1419
+ manager.serverReferenceMetaMap[id] = {
1420
+ importId: id,
1421
+ referenceKey: getNormalizedId(),
1422
+ exportNames: result.exportNames
1423
+ };
1224
1424
  const name = this.environment.name === browserEnvironmentName ? "browser" : "ssr";
1225
1425
  const importSource = resolvePackage(`${PKG_NAME}/react/${name}`);
1226
1426
  output.prepend(`import * as $$ReactClient from "${importSource}";\n`);
@@ -1235,44 +1435,25 @@ function vitePluginUseServer(useServerPluginOptions) {
1235
1435
  code: `export {}`,
1236
1436
  map: null
1237
1437
  };
1238
- 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`;
1239
1451
  return {
1240
1452
  code,
1241
1453
  map: null
1242
1454
  };
1243
1455
  })];
1244
1456
  }
1245
- function withRollupError(ctx, f) {
1246
- function processError(e) {
1247
- if (e && typeof e === "object" && typeof e.pos === "number") return ctx.error(e, e.pos);
1248
- throw e;
1249
- }
1250
- return function(...args) {
1251
- try {
1252
- const result = f.apply(this, args);
1253
- if (result instanceof Promise) return result.catch((e) => processError(e));
1254
- return result;
1255
- } catch (e) {
1256
- processError(e);
1257
- }
1258
- };
1259
- }
1260
- function createVirtualPlugin(name, load) {
1261
- name = "virtual:" + name;
1262
- return {
1263
- name: `rsc:virtual-${name}`,
1264
- resolveId(source, _importer, _options) {
1265
- return source === name ? "\0" + name : void 0;
1266
- },
1267
- load(id, options) {
1268
- if (id === "\0" + name) return load.apply(this, [id, options]);
1269
- }
1270
- };
1271
- }
1272
- function generateDynamicImportCode(map) {
1273
- let code = Object.entries(map).map(([key, id]) => `${JSON.stringify(key)}: () => import(${JSON.stringify(id)}),`).join("\n");
1274
- return `export default {${code}};\n`;
1275
- }
1276
1457
  var RuntimeAsset = class {
1277
1458
  runtime;
1278
1459
  constructor(value) {
@@ -1292,7 +1473,8 @@ function serializeValueWithRuntime(value) {
1292
1473
  for (const [placeholder, runtime] of replacements) result = result.replace(`"${placeholder}"`, runtime);
1293
1474
  return result;
1294
1475
  }
1295
- function assetsURL(url) {
1476
+ function assetsURL(url, manager) {
1477
+ const { config } = manager;
1296
1478
  if (config.command === "build" && typeof config.experimental?.renderBuiltUrl === "function") {
1297
1479
  const result = config.experimental.renderBuiltUrl(url, {
1298
1480
  type: "asset",
@@ -1307,15 +1489,15 @@ function assetsURL(url) {
1307
1489
  }
1308
1490
  return config.base + url;
1309
1491
  }
1310
- function assetsURLOfDeps(deps) {
1492
+ function assetsURLOfDeps(deps, manager) {
1311
1493
  return {
1312
1494
  js: deps.js.map((href) => {
1313
1495
  assert(typeof href === "string");
1314
- return assetsURL(href);
1496
+ return assetsURL(href, manager);
1315
1497
  }),
1316
1498
  css: deps.css.map((href) => {
1317
1499
  assert(typeof href === "string");
1318
- return assetsURL(href);
1500
+ return assetsURL(href, manager);
1319
1501
  })
1320
1502
  };
1321
1503
  }
@@ -1354,67 +1536,7 @@ function collectAssetDepsInner(fileName, bundle) {
1354
1536
  css: [...new Set(css)]
1355
1537
  };
1356
1538
  }
1357
- function vitePluginFindSourceMapURL() {
1358
- return [{
1359
- name: "rsc:findSourceMapURL",
1360
- apply: "serve",
1361
- configureServer(server$1) {
1362
- server$1.middlewares.use(async (req, res, next) => {
1363
- const url = new URL(req.url, `http://localhost`);
1364
- if (url.pathname === "/__vite_rsc_findSourceMapURL") {
1365
- let filename = url.searchParams.get("filename");
1366
- let environmentName = url.searchParams.get("environmentName");
1367
- try {
1368
- const map = await findSourceMapURL(server$1, filename, environmentName);
1369
- res.setHeader("content-type", "application/json");
1370
- if (!map) res.statusCode = 404;
1371
- res.end(JSON.stringify(map ?? {}));
1372
- } catch (e) {
1373
- next(e);
1374
- }
1375
- return;
1376
- }
1377
- next();
1378
- });
1379
- }
1380
- }];
1381
- }
1382
- async function findSourceMapURL(server$1, filename, environmentName) {
1383
- if (filename.startsWith("file://")) {
1384
- filename = fileURLToPath(filename);
1385
- if (fs.existsSync(filename)) {
1386
- const content = fs.readFileSync(filename, "utf-8");
1387
- return {
1388
- version: 3,
1389
- sources: [filename],
1390
- sourcesContent: [content],
1391
- mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
1392
- };
1393
- }
1394
- return;
1395
- }
1396
- let mod;
1397
- let map;
1398
- if (environmentName === "Server") {
1399
- mod = server$1.environments.rsc.moduleGraph.getModuleById(filename);
1400
- map = mod?.transformResult?.map;
1401
- if (map && map.mappings) map = {
1402
- ...map,
1403
- mappings: ";;" + map.mappings
1404
- };
1405
- }
1406
- const base = server$1.config.base.slice(0, -1);
1407
- if (environmentName === "Client") try {
1408
- const url = new URL(filename).pathname.slice(base.length);
1409
- mod = server$1.environments.client.moduleGraph.urlToModuleMap.get(url);
1410
- map = mod?.transformResult?.map;
1411
- } catch (e) {}
1412
- if (mod && map) return {
1413
- ...map,
1414
- sources: [base + mod.url]
1415
- };
1416
- }
1417
- function vitePluginRscCss(rscCssOptions) {
1539
+ function vitePluginRscCss(rscCssOptions = {}, manager) {
1418
1540
  function hasSpecialCssQuery(id) {
1419
1541
  return /[?&](url|inline|raw)(\b|=|&|$)/.test(id);
1420
1542
  }
@@ -1481,18 +1603,20 @@ function vitePluginRscCss(rscCssOptions) {
1481
1603
  }
1482
1604
  },
1483
1605
  {
1484
- name: "rsc:css/dev-ssr-virtual",
1606
+ name: "rsc:css-virtual",
1485
1607
  resolveId(source) {
1486
- if (source.startsWith("virtual:vite-rsc/css/dev-ssr/")) return "\0" + source;
1608
+ if (source.startsWith("virtual:vite-rsc/css?")) return "\0" + source;
1487
1609
  },
1488
1610
  async load(id) {
1489
- if (id.startsWith("\0virtual:vite-rsc/css/dev-ssr/")) {
1490
- id = id.slice(30);
1611
+ const parsed = parseCssVirtual(id);
1612
+ if (parsed?.type === "ssr") {
1613
+ id = parsed.id;
1614
+ const { server } = manager;
1491
1615
  const mod = await server.environments.ssr.moduleGraph.getModuleByUrl(id);
1492
1616
  if (!mod?.id || !mod?.file) return `export default []`;
1493
1617
  const result = collectCss(server.environments.ssr, mod.id);
1494
1618
  for (const file of [mod.file, ...result.visitedFiles]) this.addWatchFile(file);
1495
- const hrefs = result.hrefs.map((href) => assetsURL(href.slice(1)));
1619
+ const hrefs = result.hrefs.map((href) => assetsURL(href.slice(1), manager));
1496
1620
  return `export default ${serializeValueWithRuntime(hrefs)}`;
1497
1621
  }
1498
1622
  }
@@ -1503,6 +1627,7 @@ function vitePluginRscCss(rscCssOptions) {
1503
1627
  if (!code.includes("import.meta.viteRsc.loadCss")) return;
1504
1628
  assert(this.environment.name === "rsc");
1505
1629
  const output = new MagicString(code);
1630
+ let importAdded = false;
1506
1631
  for (const match of code.matchAll(/import\.meta\.viteRsc\.loadCss\(([\s\S]*?)\)/dg)) {
1507
1632
  const [start, end] = match.indices[0];
1508
1633
  const argCode = match[1].trim();
@@ -1517,7 +1642,10 @@ function vitePluginRscCss(rscCssOptions) {
1517
1642
  continue;
1518
1643
  }
1519
1644
  }
1520
- const importId = `virtual:vite-rsc/importer-resources?importer=${encodeURIComponent(importer)}`;
1645
+ const importId = toCssVirtual({
1646
+ id: importer,
1647
+ type: "rsc"
1648
+ });
1521
1649
  let replacement;
1522
1650
  if (this.environment.mode === "dev") replacement = `__vite_rsc_react__.createElement(async () => {
1523
1651
  const __m = await import(${JSON.stringify(importId)});
@@ -1525,7 +1653,10 @@ function vitePluginRscCss(rscCssOptions) {
1525
1653
  })`;
1526
1654
  else {
1527
1655
  const hash = hashString(importId);
1528
- 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
+ }
1529
1660
  replacement = `__vite_rsc_react__.createElement(__vite_rsc_importer_resources_${hash}.Resources)`;
1530
1661
  }
1531
1662
  output.update(start, end, replacement);
@@ -1538,37 +1669,37 @@ function vitePluginRscCss(rscCssOptions) {
1538
1669
  };
1539
1670
  }
1540
1671
  },
1541
- resolveId(source) {
1542
- if (source.startsWith("virtual:vite-rsc/importer-resources?importer=")) {
1543
- assert(this.environment.name === "rsc");
1544
- return "\0" + source;
1545
- }
1546
- },
1547
1672
  load(id) {
1548
- if (id.startsWith("\0virtual:vite-rsc/importer-resources?importer=")) {
1549
- 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;
1550
1678
  if (this.environment.mode === "dev") {
1551
1679
  const result = collectCss(server.environments.rsc, importer);
1552
1680
  const cssHrefs = result.hrefs.map((href) => href.slice(1));
1553
- 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
+ })}`];
1554
1685
  const deps = assetsURLOfDeps({
1555
1686
  css: cssHrefs,
1556
1687
  js: jsHrefs
1557
- });
1558
- return generateResourcesCode(serializeValueWithRuntime(deps));
1688
+ }, manager);
1689
+ return generateResourcesCode(serializeValueWithRuntime(deps), manager);
1559
1690
  } else {
1560
- const key = normalizePath(path.relative(config.root, importer));
1561
- serverResourcesMetaMap[importer] = { key };
1691
+ const key = normalizePath(path.relative(manager.config.root, importer));
1692
+ manager.serverResourcesMetaMap[importer] = { key };
1562
1693
  return `
1563
1694
  import __vite_rsc_assets_manifest__ from "virtual:vite-rsc/assets-manifest";
1564
- ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`)}
1695
+ ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`, manager)}
1565
1696
  `;
1566
1697
  }
1567
1698
  }
1568
- if (id.startsWith("\0virtual:vite-rsc/importer-resources-browser?importer=")) {
1699
+ if (parsed?.type === "rsc-browser") {
1569
1700
  assert(this.environment.name === "client");
1570
1701
  assert(this.environment.mode === "dev");
1571
- const importer = decodeURIComponent(parseIdQuery(id).query["importer"]);
1702
+ const importer = parsed.id;
1572
1703
  const result = collectCss(server.environments.rsc, importer);
1573
1704
  let code = result.ids.map((id$1) => id$1.replace(/^\0/, "")).map((id$1) => `import ${JSON.stringify(id$1)};\n`).join("");
1574
1705
  code += `if (import.meta.hot) { import.meta.hot.accept() }\n`;
@@ -1577,11 +1708,17 @@ function vitePluginRscCss(rscCssOptions) {
1577
1708
  },
1578
1709
  hotUpdate(ctx) {
1579
1710
  if (this.environment.name === "rsc") {
1711
+ const { server } = manager;
1580
1712
  const mods = collectModuleDependents(ctx.modules);
1581
1713
  for (const mod of mods) if (mod.id) {
1582
- const importer = encodeURIComponent(mod.id);
1583
- invalidteModuleById(server.environments.rsc, `\0virtual:vite-rsc/importer-resources?importer=${importer}`);
1584
- 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
+ }));
1585
1722
  }
1586
1723
  }
1587
1724
  }
@@ -1621,7 +1758,7 @@ function collectModuleDependents(mods) {
1621
1758
  for (const mod of mods) recurse(mod);
1622
1759
  return [...visited];
1623
1760
  }
1624
- function generateResourcesCode(depsCode) {
1761
+ function generateResourcesCode(depsCode, manager) {
1625
1762
  const ResourcesFn = (React, deps, RemoveDuplicateServerCss) => {
1626
1763
  return function Resources() {
1627
1764
  return React.createElement(React.Fragment, null, [
@@ -1644,7 +1781,7 @@ function generateResourcesCode(depsCode) {
1644
1781
  return `
1645
1782
  import __vite_rsc_react__ from "react";
1646
1783
 
1647
- ${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;`}
1648
1785
 
1649
1786
  export const Resources = (${ResourcesFn.toString()})(
1650
1787
  __vite_rsc_react__,
@@ -1681,59 +1818,6 @@ function __vite_rsc_wrap_css__(value, name) {
1681
1818
  return { output: result.output };
1682
1819
  }
1683
1820
  }
1684
- /**
1685
- * temporary workaround for
1686
- * - https://github.com/cloudflare/workers-sdk/issues/9538 (fixed in @cloudflare/vite-plugin@1.8.0)
1687
- * - https://github.com/vitejs/vite/pull/20077 (fixed in vite@7.0.0)
1688
- */
1689
- function __fix_cloudflare() {
1690
- return {
1691
- name: "rsc:workaround-cloudflare",
1692
- enforce: "post",
1693
- config(config$1) {
1694
- const plugin = config$1.plugins.flat().find((p) => p && "name" in p && p.name === "vite-plugin-cloudflare");
1695
- const original = plugin.configResolved;
1696
- plugin.configResolved = function(...args) {
1697
- try {
1698
- return original.apply(this, args);
1699
- } catch (e) {}
1700
- };
1701
- config$1.environments.ssr.resolve.noExternal = true;
1702
- config$1.environments.rsc.resolve.noExternal = true;
1703
- }
1704
- };
1705
- }
1706
- function validateImportPlugin() {
1707
- return {
1708
- name: "rsc:validate-imports",
1709
- resolveId: {
1710
- order: "pre",
1711
- async handler(source, importer, options) {
1712
- if ("scan" in options && options.scan) return;
1713
- if (source === "client-only") {
1714
- if (this.environment.name === "rsc") throw new Error(`'client-only' cannot be imported in server build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
1715
- return {
1716
- id: `\0virtual:vite-rsc/empty`,
1717
- moduleSideEffects: false
1718
- };
1719
- }
1720
- if (source === "server-only") {
1721
- if (this.environment.name !== "rsc") throw new Error(`'server-only' cannot be imported in client build (importer: '${importer ?? "unknown"}', environment: ${this.environment.name})`);
1722
- return {
1723
- id: `\0virtual:vite-rsc/empty`,
1724
- moduleSideEffects: false
1725
- };
1726
- }
1727
- }
1728
- },
1729
- load(id) {
1730
- if (id.startsWith("\0virtual:vite-rsc/empty")) return `export {}`;
1731
- }
1732
- };
1733
- }
1734
- function sortObject(o) {
1735
- return Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
1736
- }
1737
1821
 
1738
1822
  //#endregion
1739
- export { __fix_cloudflare, findSourceMapURL, transformHoistInlineDirective, transformRscCssExport, vitePluginFindSourceMapURL, vitePluginRsc, vitePluginRscCss, vitePluginRscMinimal };
1823
+ export { transformHoistInlineDirective, transformRscCssExport, vitePluginRsc, vitePluginRscMinimal };