@vitejs/plugin-rsc 0.5.16 → 0.5.18

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 (55) hide show
  1. package/dist/browser.d.ts +2 -2
  2. package/dist/{cjs-DH9Oa3zy.js → cjs-D2v1gYgq.js} +33 -24
  3. package/dist/core/browser.d.ts +1 -1
  4. package/dist/core/browser.js +2 -2
  5. package/dist/core/plugin.js +1 -1
  6. package/dist/core/rsc.d.ts +1 -1
  7. package/dist/core/rsc.js +1 -1
  8. package/dist/core/ssr.d.ts +1 -1
  9. package/dist/core/ssr.js +2 -2
  10. package/dist/{dist-DZUJDIM2.js → dist-yW9-EeG1.js} +1 -1
  11. package/dist/index-CLmWsR1c.d.ts +584 -0
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.js +4 -4
  14. package/dist/{picocolors-kt7Y18A3.js → picocolors-BRyoHAlU.js} +1 -1
  15. package/dist/plugin-BGmSmdwL.js +27 -0
  16. package/dist/{plugin-DBWiu_Dx.js → plugin-Cp12dr0Z.js} +408 -329
  17. package/dist/{plugin-V6VFxi_0.d.ts → plugin-K7i9F4Fd.d.ts} +6 -12
  18. package/dist/plugin.d.ts +2 -2
  19. package/dist/plugin.js +4 -4
  20. package/dist/plugins/cjs.js +1 -1
  21. package/dist/react/browser.d.ts +2 -2
  22. package/dist/react/rsc.js +1 -1
  23. package/dist/{rsc-BCFg12vs.js → rsc-Bhp6O2qz.js} +3 -3
  24. package/dist/rsc.d.ts +2 -2
  25. package/dist/rsc.js +2 -2
  26. package/dist/ssr.d.ts +2 -3
  27. package/dist/ssr.js +1 -1
  28. package/dist/transforms/index.d.ts +1 -1
  29. package/dist/transforms/index.js +1 -1
  30. package/dist/{transforms-D4jDIHgD.js → transforms-B2EJTNXG.js} +2 -2
  31. package/dist/utils/encryption-runtime.js +3 -3
  32. package/dist/utils/rpc.js +1 -1
  33. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-client.browser.development.js +129 -110
  34. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-client.browser.production.js +67 -55
  35. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-client.edge.development.js +127 -108
  36. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-client.edge.production.js +67 -55
  37. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-client.node.development.js +127 -108
  38. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-client.node.production.js +67 -55
  39. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-server.browser.development.js +625 -351
  40. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-server.browser.production.js +598 -314
  41. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-server.edge.development.js +628 -352
  42. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-server.edge.production.js +601 -315
  43. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-server.node.development.js +634 -356
  44. package/dist/vendor/react-server-dom/cjs/react-server-dom-webpack-server.node.production.js +607 -319
  45. package/dist/vendor/react-server-dom/package.json +3 -3
  46. package/package.json +10 -8
  47. package/dist/index-DJ0AhQ9B.d.ts +0 -90
  48. package/dist/plugin-B1AJWrMi.js +0 -24
  49. /package/dist/{browser-BmyjVnfA.d.ts → browser-s-WcB8A7.d.ts} +0 -0
  50. /package/dist/{chunk-BFhhoFQb.js → chunk-Dj_d7TT4.js} +0 -0
  51. /package/dist/{encryption-utils-BPYvebX4.js → encryption-utils-DdqSKS_O.js} +0 -0
  52. /package/dist/{index-DqoQPvhP.d.ts → index-now_lP2V.d.ts} +0 -0
  53. /package/dist/{rpc-DbBe389F.js → rpc-EIuXyQpO.js} +0 -0
  54. /package/dist/{shared-Chot7h9j.js → shared-CGK4coF3.js} +0 -0
  55. /package/dist/{shared-DEpnONZf.js → shared-rtJPs0Yj.js} +0 -0
@@ -1,16 +1,17 @@
1
- import { n as __toESM } from "./chunk-BFhhoFQb.js";
2
- import { t as createDebug } from "./dist-DZUJDIM2.js";
3
- import { t as vitePluginRscCore } from "./plugin-B1AJWrMi.js";
4
- import { t as cjsModuleRunnerPlugin } from "./cjs-DH9Oa3zy.js";
5
- import { i as toCssVirtual, n as parseIdQuery, r as parseReferenceValidationVirtual, t as parseCssVirtual } from "./shared-Chot7h9j.js";
6
- import { a as hasDirective, n as transformDirectiveProxyExport, o as transformWrapExport, s as findDirectives, t as transformServerActionServer } from "./transforms-D4jDIHgD.js";
7
- import { o as generateEncryptionKey, s as toBase64 } from "./encryption-utils-BPYvebX4.js";
8
- import { n as createRpcServer } from "./rpc-DbBe389F.js";
1
+ import { n as __toESM } from "./chunk-Dj_d7TT4.js";
2
+ import { t as createDebug } from "./dist-yW9-EeG1.js";
3
+ import { t as vitePluginRscCore } from "./plugin-BGmSmdwL.js";
4
+ import { t as cjsModuleRunnerPlugin } from "./cjs-D2v1gYgq.js";
5
+ import { i as toCssVirtual, n as parseIdQuery, r as parseReferenceValidationVirtual, t as parseCssVirtual } from "./shared-CGK4coF3.js";
6
+ import { a as hasDirective, n as transformDirectiveProxyExport, o as transformWrapExport, s as findDirectives, t as transformServerActionServer } from "./transforms-B2EJTNXG.js";
7
+ import { o as generateEncryptionKey, s as toBase64 } from "./encryption-utils-DdqSKS_O.js";
8
+ import { n as createRpcServer } from "./rpc-EIuXyQpO.js";
9
9
  import { createRequire } from "node:module";
10
10
  import assert from "node:assert";
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import { fileURLToPath, pathToFileURL } from "node:url";
14
+ import { exactRegex, prefixRegex } from "@rolldown/pluginutils";
14
15
  import * as esModuleLexer from "es-module-lexer";
15
16
  import MagicString from "magic-string";
16
17
  import { toNodeHandler } from "srvx/node";
@@ -29,19 +30,19 @@ const FS_PREFIX = `/@fs/`;
29
30
  function wrapId(id) {
30
31
  return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
31
32
  }
32
- function withTrailingSlash(path$1) {
33
- if (path$1[path$1.length - 1] !== "/") return `${path$1}/`;
34
- return path$1;
33
+ function withTrailingSlash(path) {
34
+ if (path[path.length - 1] !== "/") return `${path}/`;
35
+ return path;
35
36
  }
36
37
  const postfixRE = /[?#].*$/;
37
38
  function cleanUrl(url) {
38
39
  return url.replace(postfixRE, "");
39
40
  }
40
- function splitFileAndPostfix(path$1) {
41
- const file = cleanUrl(path$1);
41
+ function splitFileAndPostfix(path) {
42
+ const file = cleanUrl(path);
42
43
  return {
43
44
  file,
44
- postfix: path$1.slice(file.length)
45
+ postfix: path.slice(file.length)
45
46
  };
46
47
  }
47
48
  const windowsSlashRE = /\\/g;
@@ -176,14 +177,21 @@ function withRollupError(ctx, f) {
176
177
  };
177
178
  }
178
179
  function createVirtualPlugin(name, load) {
179
- name = "virtual:" + name;
180
+ const virtualId = "virtual:" + name;
181
+ const resolvedId = "\0" + virtualId;
180
182
  return {
181
183
  name: `rsc:virtual-${name}`,
182
- resolveId(source, _importer, _options) {
183
- return source === name ? "\0" + name : void 0;
184
+ resolveId: {
185
+ filter: { id: exactRegex(virtualId) },
186
+ handler(source) {
187
+ if (source === virtualId) return resolvedId;
188
+ }
184
189
  },
185
- load(id, options) {
186
- if (id === "\0" + name) return load.apply(this, [id, options]);
190
+ load: {
191
+ filter: { id: exactRegex(resolvedId) },
192
+ handler(id, options) {
193
+ if (id === resolvedId) return load.apply(this, [id, options]);
194
+ }
187
195
  }
188
196
  };
189
197
  }
@@ -244,11 +252,14 @@ function ensureEnvironmentImportsEntryFallback({ environments }) {
244
252
  function vitePluginImportEnvironment(manager) {
245
253
  return [{
246
254
  name: "rsc:import-environment",
247
- resolveId(source) {
248
- if (source === ENV_IMPORTS_MANIFEST_PLACEHOLDER) return {
249
- id: ENV_IMPORTS_MANIFEST_PLACEHOLDER,
250
- external: true
251
- };
255
+ resolveId: {
256
+ filter: { id: exactRegex(ENV_IMPORTS_MANIFEST_PLACEHOLDER) },
257
+ handler(source) {
258
+ if (source === ENV_IMPORTS_MANIFEST_PLACEHOLDER) return {
259
+ id: ENV_IMPORTS_MANIFEST_PLACEHOLDER,
260
+ external: true
261
+ };
262
+ }
252
263
  },
253
264
  buildStart() {
254
265
  if (this.environment.mode !== "build") return;
@@ -265,52 +276,55 @@ function vitePluginImportEnvironment(manager) {
265
276
  }
266
277
  }
267
278
  },
268
- transform: { async handler(code, id) {
269
- if (!code.includes("import.meta.viteRsc.import")) return;
270
- const { server } = manager;
271
- const s = new MagicString(code);
272
- for (const match of stripLiteral(code).matchAll(/import\.meta\.viteRsc\.import\s*(<[\s\S]*?>)?\s*\(([\s\S]*?)\)/dg)) {
273
- const [argStart, argEnd] = match.indices[2];
274
- const [specifier, options] = evalValue(`[${code.slice(argStart, argEnd).trim()}]`);
275
- const environmentName = options.environment;
276
- let resolvedId;
277
- if (this.environment.mode === "dev") {
278
- const targetEnv$1 = server.environments[environmentName];
279
- assert(targetEnv$1, `[vite-rsc] unknown environment '${environmentName}'`);
280
- const resolved = await targetEnv$1.pluginContainer.resolveId(specifier, id);
281
- assert(resolved, `[vite-rsc] failed to resolve '${specifier}' in environment '${environmentName}'`);
282
- resolvedId = resolved.id;
283
- } else {
284
- const targetEnvConfig = manager.config.environments[environmentName];
285
- assert(targetEnvConfig, `[vite-rsc] unknown environment '${environmentName}'`);
286
- const resolved = await this.resolve(specifier, id);
287
- assert(resolved, `[vite-rsc] failed to resolve '${specifier}' in environment '${environmentName}'`);
288
- resolvedId = resolved.id;
279
+ transform: {
280
+ filter: { code: "import.meta.viteRsc.import" },
281
+ async handler(code, id) {
282
+ if (!code.includes("import.meta.viteRsc.import")) return;
283
+ const { server } = manager;
284
+ const s = new MagicString(code);
285
+ for (const match of stripLiteral(code).matchAll(/import\.meta\.viteRsc\.import\s*(<[\s\S]*?>)?\s*\(([\s\S]*?)\)/dg)) {
286
+ const [argStart, argEnd] = match.indices[2];
287
+ const [specifier, options] = evalValue(`[${code.slice(argStart, argEnd).trim()}]`);
288
+ const environmentName = options.environment;
289
+ let resolvedId;
290
+ if (this.environment.mode === "dev") {
291
+ const targetEnv = server.environments[environmentName];
292
+ assert(targetEnv, `[vite-rsc] unknown environment '${environmentName}'`);
293
+ const resolved = await targetEnv.pluginContainer.resolveId(specifier, id);
294
+ assert(resolved, `[vite-rsc] failed to resolve '${specifier}' in environment '${environmentName}'`);
295
+ resolvedId = resolved.id;
296
+ } else {
297
+ const targetEnvConfig = manager.config.environments[environmentName];
298
+ assert(targetEnvConfig, `[vite-rsc] unknown environment '${environmentName}'`);
299
+ const resolved = await this.resolve(specifier, id);
300
+ assert(resolved, `[vite-rsc] failed to resolve '${specifier}' in environment '${environmentName}'`);
301
+ resolvedId = resolved.id;
302
+ }
303
+ const sourceEnv = this.environment.name;
304
+ const targetEnv = environmentName;
305
+ manager.environmentImportMetaMap[sourceEnv] ??= {};
306
+ manager.environmentImportMetaMap[sourceEnv][targetEnv] ??= {};
307
+ manager.environmentImportMetaMap[sourceEnv][targetEnv][resolvedId] = {
308
+ resolvedId,
309
+ targetEnv,
310
+ sourceEnv,
311
+ specifier
312
+ };
313
+ let replacement;
314
+ if (this.environment.mode === "dev") replacement = `globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(${JSON.stringify(environmentName)}, ${JSON.stringify(resolvedId)})`;
315
+ else {
316
+ const relativeId = manager.toRelativeId(resolvedId);
317
+ replacement = `(await import(${JSON.stringify(ENV_IMPORTS_MANIFEST_PLACEHOLDER)})).default[${JSON.stringify(relativeId)}]()`;
318
+ }
319
+ const [start, end] = match.indices[0];
320
+ s.overwrite(start, end, replacement);
289
321
  }
290
- const sourceEnv = this.environment.name;
291
- const targetEnv = environmentName;
292
- manager.environmentImportMetaMap[sourceEnv] ??= {};
293
- manager.environmentImportMetaMap[sourceEnv][targetEnv] ??= {};
294
- manager.environmentImportMetaMap[sourceEnv][targetEnv][resolvedId] = {
295
- resolvedId,
296
- targetEnv,
297
- sourceEnv,
298
- specifier
322
+ if (s.hasChanged()) return {
323
+ code: s.toString(),
324
+ map: s.generateMap({ hires: "boundary" })
299
325
  };
300
- let replacement;
301
- if (this.environment.mode === "dev") replacement = `globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(${JSON.stringify(environmentName)}, ${JSON.stringify(resolvedId)})`;
302
- else {
303
- const relativeId = manager.toRelativeId(resolvedId);
304
- replacement = `(await import(${JSON.stringify(ENV_IMPORTS_MANIFEST_PLACEHOLDER)})).default[${JSON.stringify(relativeId)}]()`;
305
- }
306
- const [start, end] = match.indices[0];
307
- s.overwrite(start, end, replacement);
308
326
  }
309
- if (s.hasChanged()) return {
310
- code: s.toString(),
311
- map: s.generateMap({ hires: "boundary" })
312
- };
313
- } },
327
+ },
314
328
  renderChunk(code, chunk) {
315
329
  if (code.includes(ENV_IMPORTS_MANIFEST_PLACEHOLDER)) {
316
330
  const replacement = normalizeRelativePath(path.relative(path.join(chunk.fileName, ".."), ENV_IMPORTS_MANIFEST_NAME));
@@ -363,10 +377,13 @@ function fromResolvedIdProxy(source) {
363
377
  function vitePluginResolvedIdProxy() {
364
378
  return {
365
379
  name: "rsc:resolved-id-proxy",
366
- resolveId: { handler(source) {
367
- const originalId = fromResolvedIdProxy(source);
368
- if (originalId !== void 0) return originalId;
369
- } }
380
+ resolveId: {
381
+ filter: { id: prefixRegex(RESOLVED_ID_PROXY_PREFIX) },
382
+ handler(source) {
383
+ const originalId = fromResolvedIdProxy(source);
384
+ if (originalId !== void 0) return originalId;
385
+ }
386
+ }
370
387
  };
371
388
  }
372
389
 
@@ -377,13 +394,13 @@ function scanBuildStripPlugin({ manager }) {
377
394
  name: "rsc:scan-strip",
378
395
  apply: "build",
379
396
  enforce: "post",
380
- async transform(code, _id, _options) {
397
+ transform: { async handler(code, _id, _options) {
381
398
  if (!manager.isScanBuild) return;
382
399
  return {
383
400
  code: await transformScanBuildStrip(code),
384
401
  map: { mappings: "" }
385
402
  };
386
- }
403
+ } }
387
404
  };
388
405
  }
389
406
  const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
@@ -409,6 +426,7 @@ function validateImportPlugin() {
409
426
  name: "rsc:validate-imports",
410
427
  resolveId: {
411
428
  order: "pre",
429
+ filter: { id: /^(client-only|server-only)$/ },
412
430
  async handler(source, _importer, options) {
413
431
  if ("scan" in options && options.scan) return;
414
432
  if (source === "client-only" || source === "server-only") {
@@ -423,12 +441,16 @@ function validateImportPlugin() {
423
441
  }
424
442
  }
425
443
  },
426
- load(id) {
427
- if (id.startsWith("\0virtual:vite-rsc/validate-imports/invalid/")) return `throw new Error("invalid import of '${id.slice(id.lastIndexOf("/") + 1)}'")`;
428
- if (id.startsWith("\0virtual:vite-rsc/validate-imports/")) return `export {}`;
444
+ load: {
445
+ filter: { id: prefixRegex("\0virtual:vite-rsc/validate-imports/") },
446
+ handler(id) {
447
+ if (id.startsWith("\0virtual:vite-rsc/validate-imports/invalid/")) return `throw new Error("invalid import of '${id.slice(id.lastIndexOf("/") + 1)}'")`;
448
+ if (id.startsWith("\0virtual:vite-rsc/validate-imports/")) return `export {}`;
449
+ }
429
450
  },
430
451
  transform: {
431
452
  order: "post",
453
+ filter: { id: prefixRegex("\0virtual:vite-rsc/validate-imports/invalid/") },
432
454
  async handler(_code, id) {
433
455
  if (this.environment.mode === "dev") {
434
456
  if (id.startsWith(`\0virtual:vite-rsc/validate-imports/invalid/`)) validateImportChain(getImportChainDev(this.environment, id), this.environment.name, this.environment.config.root);
@@ -445,11 +467,11 @@ function validateImportPlugin() {
445
467
  }
446
468
  function getImportChainDev(environment, id) {
447
469
  const chain = [];
448
- const recurse = (id$1) => {
449
- if (chain.includes(id$1)) return;
450
- const info = environment.moduleGraph.getModuleById(id$1);
470
+ const recurse = (id) => {
471
+ if (chain.includes(id)) return;
472
+ const info = environment.moduleGraph.getModuleById(id);
451
473
  if (!info) return;
452
- chain.push(id$1);
474
+ chain.push(id);
453
475
  const next = [...info.importers][0];
454
476
  if (next && next.id) recurse(next.id);
455
477
  };
@@ -458,11 +480,11 @@ function getImportChainDev(environment, id) {
458
480
  }
459
481
  function getImportChainBuild(ctx, id) {
460
482
  const chain = [];
461
- const recurse = (id$1) => {
462
- if (chain.includes(id$1)) return;
463
- const info = ctx.getModuleInfo(id$1);
483
+ const recurse = (id) => {
484
+ if (chain.includes(id)) return;
485
+ const info = ctx.getModuleInfo(id);
464
486
  if (!info) return;
465
- chain.push(id$1);
487
+ chain.push(id);
466
488
  const next = info.importers[0];
467
489
  if (next) recurse(next);
468
490
  };
@@ -474,7 +496,7 @@ function validateImportChain(chain, environmentName, root) {
474
496
  const id = chain[0];
475
497
  const source = id.slice(id.lastIndexOf("/") + 1);
476
498
  let result = `'${source}' cannot be imported in ${source === "server-only" ? "client" : "server"} build ('${environmentName}' environment):\n`;
477
- result += chain.slice(1, 6).map((id$1, i) => " ".repeat(i + 1) + `imported by ${path.relative(root, id$1).replaceAll("\0", "")}\n`).join("");
499
+ result += chain.slice(1, 6).map((id, i) => " ".repeat(i + 1) + `imported by ${path.relative(root, id).replaceAll("\0", "")}\n`).join("");
478
500
  if (chain.length > 6) result += " ".repeat(7) + "...\n";
479
501
  const error = new Error(result);
480
502
  if (chain[1]) Object.assign(error, { id: chain[1] });
@@ -550,6 +572,7 @@ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginMana
550
572
  name: "rsc:vite-client-raw-import",
551
573
  transform: {
552
574
  order: "post",
575
+ filter: { code: "__vite_rsc_raw_import__" },
553
576
  handler(code) {
554
577
  if (code.includes("__vite_rsc_raw_import__")) return code.replace("__vite_rsc_raw_import__", "import");
555
578
  }
@@ -562,19 +585,22 @@ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginMana
562
585
  {
563
586
  name: "rsc:reference-validation",
564
587
  apply: "serve",
565
- load: { handler(id, _options) {
566
- if (id.startsWith("\0virtual:vite-rsc/reference-validation?")) {
567
- const parsed = parseReferenceValidationVirtual(id);
568
- assert(parsed);
569
- if (parsed.type === "client") {
570
- if (Object.values(manager.clientReferenceMetaMap).find((meta) => meta.referenceKey === parsed.id)) return `export {}`;
571
- }
572
- if (parsed.type === "server") {
573
- if (Object.values(manager.serverReferenceMetaMap).find((meta) => meta.referenceKey === parsed.id)) return `export {}`;
588
+ load: {
589
+ filter: { id: prefixRegex("\0virtual:vite-rsc/reference-validation?") },
590
+ handler(id, _options) {
591
+ if (id.startsWith("\0virtual:vite-rsc/reference-validation?")) {
592
+ const parsed = parseReferenceValidationVirtual(id);
593
+ assert(parsed);
594
+ if (parsed.type === "client") {
595
+ if (Object.values(manager.clientReferenceMetaMap).find((meta) => meta.referenceKey === parsed.id)) return `export {}`;
596
+ }
597
+ if (parsed.type === "server") {
598
+ if (Object.values(manager.serverReferenceMetaMap).find((meta) => meta.referenceKey === parsed.id)) return `export {}`;
599
+ }
600
+ this.error(`[vite-rsc] invalid ${parsed.type} reference '${parsed.id}'`);
574
601
  }
575
- this.error(`[vite-rsc] invalid ${parsed.type} reference '${parsed.id}'`);
576
602
  }
577
- } }
603
+ }
578
604
  },
579
605
  scanBuildStripPlugin({ manager }),
580
606
  vitePluginResolvedIdProxy()
@@ -583,7 +609,7 @@ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginMana
583
609
  function vitePluginRsc(rscPluginOptions = {}) {
584
610
  const manager = new RscPluginManager();
585
611
  const buildApp = async (builder) => {
586
- const colors = await import("./picocolors-kt7Y18A3.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
612
+ const colors = await import("./picocolors-BRyoHAlU.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
587
613
  const logStep = (msg) => {
588
614
  builder.config.logger.info(colors.blue(msg));
589
615
  };
@@ -723,10 +749,10 @@ function vitePluginRsc(rscPluginOptions = {}) {
723
749
  } },
724
750
  configureServer(server) {
725
751
  globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async function(environmentName, id) {
726
- const environment$1 = server.environments[environmentName];
727
- if (!environment$1) throw new Error(`[vite-rsc] unknown environment '${environmentName}'`);
728
- if (!vite.isRunnableDevEnvironment(environment$1)) throw new Error(`[vite-rsc] environment '${environmentName}' is not runnable`);
729
- return environment$1.runner.import(id);
752
+ const environment = server.environments[environmentName];
753
+ if (!environment) throw new Error(`[vite-rsc] unknown environment '${environmentName}'`);
754
+ if (!vite.isRunnableDevEnvironment(environment)) throw new Error(`[vite-rsc] environment '${environmentName}' is not runnable`);
755
+ return environment.runner.import(id);
730
756
  };
731
757
  const oldSend = server.environments.client.hot.send;
732
758
  server.environments.client.hot.send = async function(...args) {
@@ -841,6 +867,7 @@ function vitePluginRsc(rscPluginOptions = {}) {
841
867
  name: "rsc:react-server-dom-webpack-alias",
842
868
  resolveId: {
843
869
  order: "pre",
870
+ filter: { id: prefixRegex(`${PKG_NAME}/vendor/react-server-dom/`) },
844
871
  async handler(source, importer, options) {
845
872
  if (hasReactServerDomWebpack && source.startsWith(`${PKG_NAME}/vendor/react-server-dom/`)) {
846
873
  const newSource = source.replace(`${PKG_NAME}/vendor/react-server-dom`, "react-server-dom-webpack");
@@ -854,40 +881,43 @@ function vitePluginRsc(rscPluginOptions = {}) {
854
881
  },
855
882
  {
856
883
  name: "rsc:load-environment-module",
857
- async transform(code) {
858
- if (!code.includes("import.meta.viteRsc.loadModule")) return;
859
- const { server } = manager;
860
- const s = new MagicString(code);
861
- for (const match of stripLiteral(code).matchAll(/import\.meta\.viteRsc\.loadModule\(([\s\S]*?)\)/dg)) {
862
- const [argStart, argEnd] = match.indices[1];
863
- const [environmentName, entryName] = evalValue(`[${code.slice(argStart, argEnd).trim()}]`);
864
- let replacement;
865
- if (this.environment.mode === "dev" && rscPluginOptions.loadModuleDevProxy) replacement = `import("virtual:vite-rsc/rpc-client").then((module) => module.createRpcClient(${JSON.stringify({
866
- environmentName,
867
- entryName
868
- })}))`;
869
- else if (this.environment.mode === "dev") {
870
- const environment = server.environments[environmentName];
871
- const source = getEntrySource(environment.config, entryName);
872
- const resolved = await environment.pluginContainer.resolveId(source);
873
- assert(resolved, `[vite-rsc] failed to resolve entry '${source}'`);
874
- replacement = `globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(${JSON.stringify(environmentName)}, ${JSON.stringify(resolved.id)})`;
875
- } else {
876
- const environment = manager.config.environments[environmentName];
877
- const targetName = entryName || getFallbackRollupEntry(environment.build.rollupOptions.input).name;
878
- replacement = JSON.stringify(`__vite_rsc_load_module_start__:` + JSON.stringify({
879
- fromEnv: this.environment.name,
880
- toEnv: environmentName,
881
- targetFileName: `${targetName}.js`
882
- }) + `:__vite_rsc_load_module_end__`);
884
+ transform: {
885
+ filter: { code: "import.meta.viteRsc.loadModule" },
886
+ async handler(code) {
887
+ if (!code.includes("import.meta.viteRsc.loadModule")) return;
888
+ const { server } = manager;
889
+ const s = new MagicString(code);
890
+ for (const match of stripLiteral(code).matchAll(/import\.meta\.viteRsc\.loadModule\(([\s\S]*?)\)/dg)) {
891
+ const [argStart, argEnd] = match.indices[1];
892
+ const [environmentName, entryName] = evalValue(`[${code.slice(argStart, argEnd).trim()}]`);
893
+ let replacement;
894
+ if (this.environment.mode === "dev" && rscPluginOptions.loadModuleDevProxy) replacement = `import("virtual:vite-rsc/rpc-client").then((module) => module.createRpcClient(${JSON.stringify({
895
+ environmentName,
896
+ entryName
897
+ })}))`;
898
+ else if (this.environment.mode === "dev") {
899
+ const environment = server.environments[environmentName];
900
+ const source = getEntrySource(environment.config, entryName);
901
+ const resolved = await environment.pluginContainer.resolveId(source);
902
+ assert(resolved, `[vite-rsc] failed to resolve entry '${source}'`);
903
+ replacement = `globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(${JSON.stringify(environmentName)}, ${JSON.stringify(resolved.id)})`;
904
+ } else {
905
+ const environment = manager.config.environments[environmentName];
906
+ const targetName = entryName || getFallbackRollupEntry(environment.build.rollupOptions.input).name;
907
+ replacement = JSON.stringify(`__vite_rsc_load_module_start__:` + JSON.stringify({
908
+ fromEnv: this.environment.name,
909
+ toEnv: environmentName,
910
+ targetFileName: `${targetName}.js`
911
+ }) + `:__vite_rsc_load_module_end__`);
912
+ }
913
+ const [start, end] = match.indices[0];
914
+ s.overwrite(start, end, replacement);
883
915
  }
884
- const [start, end] = match.indices[0];
885
- s.overwrite(start, end, replacement);
916
+ if (s.hasChanged()) return {
917
+ code: s.toString(),
918
+ map: s.generateMap({ hires: "boundary" })
919
+ };
886
920
  }
887
- if (s.hasChanged()) return {
888
- code: s.toString(),
889
- map: s.generateMap({ hires: "boundary" })
890
- };
891
921
  },
892
922
  renderChunk(code, chunk) {
893
923
  if (!code.includes("__vite_rsc_load_module")) return;
@@ -941,15 +971,20 @@ function vitePluginRsc(rscPluginOptions = {}) {
941
971
  },
942
972
  {
943
973
  name: "rsc:virtual:vite-rsc/rpc-client",
944
- resolveId(source) {
945
- if (source === "virtual:vite-rsc/rpc-client") return `\0${source}`;
974
+ resolveId: {
975
+ filter: { id: exactRegex("virtual:vite-rsc/rpc-client") },
976
+ handler(source) {
977
+ if (source === "virtual:vite-rsc/rpc-client") return `\0${source}`;
978
+ }
946
979
  },
947
- load(id) {
948
- if (id === "\0virtual:vite-rsc/rpc-client") {
949
- const { server } = manager;
950
- const origin = server.resolvedUrls?.local[0];
951
- assert(origin, "[vite-rsc] no server for loadModuleDevProxy");
952
- return `\
980
+ load: {
981
+ filter: { id: exactRegex("\0virtual:vite-rsc/rpc-client") },
982
+ handler(id) {
983
+ if (id === "\0virtual:vite-rsc/rpc-client") {
984
+ const { server } = manager;
985
+ const origin = server.resolvedUrls?.local[0];
986
+ assert(origin, "[vite-rsc] no server for loadModuleDevProxy");
987
+ return `\
953
988
  import * as __vite_rsc_rpc from "@vitejs/plugin-rsc/utils/rpc";
954
989
  export function createRpcClient(params) {
955
990
  const endpoint =
@@ -959,30 +994,37 @@ export function createRpcClient(params) {
959
994
  return __vite_rsc_rpc.createRpcClient({ endpoint });
960
995
  }
961
996
  `;
997
+ }
962
998
  }
963
999
  }
964
1000
  },
965
1001
  {
966
1002
  name: "rsc:virtual:vite-rsc/assets-manifest",
967
- resolveId(source) {
968
- if (source === "virtual:vite-rsc/assets-manifest") {
969
- if (this.environment.mode === "build") return {
970
- id: source,
971
- external: true
972
- };
973
- return `\0` + source;
1003
+ resolveId: {
1004
+ filter: { id: exactRegex("virtual:vite-rsc/assets-manifest") },
1005
+ handler(source) {
1006
+ if (source === "virtual:vite-rsc/assets-manifest") {
1007
+ if (this.environment.mode === "build") return {
1008
+ id: source,
1009
+ external: true
1010
+ };
1011
+ return `\0` + source;
1012
+ }
974
1013
  }
975
1014
  },
976
- load(id) {
977
- if (id === "\0virtual:vite-rsc/assets-manifest") {
978
- assert(this.environment.name !== "client");
979
- assert(this.environment.mode === "dev");
980
- const manifest = {
981
- bootstrapScriptContent: `import(${serializeValueWithRuntime(assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser, manager))})`,
982
- clientReferenceDeps: {},
983
- cssLinkPrecedence: rscPluginOptions.cssLinkPrecedence
984
- };
985
- return `export default ${JSON.stringify(manifest, null, 2)}`;
1015
+ load: {
1016
+ filter: { id: exactRegex("\0virtual:vite-rsc/assets-manifest") },
1017
+ handler(id) {
1018
+ if (id === "\0virtual:vite-rsc/assets-manifest") {
1019
+ assert(this.environment.name !== "client");
1020
+ assert(this.environment.mode === "dev");
1021
+ const manifest = {
1022
+ bootstrapScriptContent: `import(${serializeValueWithRuntime(assetsURL("@id/__x00__" + VIRTUAL_ENTRIES.browser, manager))})`,
1023
+ clientReferenceDeps: {},
1024
+ cssLinkPrecedence: rscPluginOptions.cssLinkPrecedence
1025
+ };
1026
+ return `export default ${JSON.stringify(manifest, null, 2)}`;
1027
+ }
986
1028
  }
987
1029
  },
988
1030
  generateBundle(_options, bundle) {
@@ -1050,25 +1092,28 @@ export default assetsManifest.bootstrapScriptContent;
1050
1092
  }),
1051
1093
  {
1052
1094
  name: "rsc:bootstrap-script-content",
1053
- async transform(code) {
1054
- if (!code.includes("loadBootstrapScriptContent") || !/import\s*\.\s*meta\s*\.\s*viteRsc\s*\.\s*loadBootstrapScriptContent/.test(code)) return;
1055
- assert(!rscPluginOptions.customClientEntry, `[vite-rsc] 'import.meta.viteRsc.loadBootstrapScriptContent' cannot be used with 'customClientEntry' option`);
1056
- assert(this.environment.name !== "client");
1057
- const output = new MagicString(code);
1058
- for (const match of stripLiteral(code).matchAll(/import\s*\.\s*meta\s*\.\s*viteRsc\s*\.\s*loadBootstrapScriptContent\(([\s\S]*?)\)/dg)) {
1059
- const [argStart, argEnd] = match.indices[1];
1060
- const argCode = code.slice(argStart, argEnd).trim();
1061
- assert(evalValue(argCode), `[vite-rsc] expected 'loadBootstrapScriptContent("index")' but got ${argCode}`);
1062
- let replacement = `Promise.resolve(__vite_rsc_assets_manifest.bootstrapScriptContent)`;
1063
- const [start, end] = match.indices[0];
1064
- output.overwrite(start, end, replacement);
1065
- }
1066
- if (output.hasChanged()) {
1067
- if (!code.includes("__vite_rsc_assets_manifest")) output.prepend(`import __vite_rsc_assets_manifest from "virtual:vite-rsc/assets-manifest";`);
1068
- return {
1069
- code: output.toString(),
1070
- map: output.generateMap({ hires: "boundary" })
1071
- };
1095
+ transform: {
1096
+ filter: { code: "loadBootstrapScriptContent" },
1097
+ async handler(code) {
1098
+ if (!code.includes("loadBootstrapScriptContent") || !/import\s*\.\s*meta\s*\.\s*viteRsc\s*\.\s*loadBootstrapScriptContent/.test(code)) return;
1099
+ assert(!rscPluginOptions.customClientEntry, `[vite-rsc] 'import.meta.viteRsc.loadBootstrapScriptContent' cannot be used with 'customClientEntry' option`);
1100
+ assert(this.environment.name !== "client");
1101
+ const output = new MagicString(code);
1102
+ for (const match of stripLiteral(code).matchAll(/import\s*\.\s*meta\s*\.\s*viteRsc\s*\.\s*loadBootstrapScriptContent\(([\s\S]*?)\)/dg)) {
1103
+ const [argStart, argEnd] = match.indices[1];
1104
+ const argCode = code.slice(argStart, argEnd).trim();
1105
+ assert(evalValue(argCode), `[vite-rsc] expected 'loadBootstrapScriptContent("index")' but got ${argCode}`);
1106
+ let replacement = `Promise.resolve(__vite_rsc_assets_manifest.bootstrapScriptContent)`;
1107
+ const [start, end] = match.indices[0];
1108
+ output.overwrite(start, end, replacement);
1109
+ }
1110
+ if (output.hasChanged()) {
1111
+ if (!code.includes("__vite_rsc_assets_manifest")) output.prepend(`import __vite_rsc_assets_manifest from "virtual:vite-rsc/assets-manifest";`);
1112
+ return {
1113
+ code: output.toString(),
1114
+ map: output.generateMap({ hires: "boundary" })
1115
+ };
1116
+ }
1072
1117
  }
1073
1118
  }
1074
1119
  },
@@ -1124,9 +1169,12 @@ import.meta.hot.on("rsc:update", () => {
1124
1169
  function globalAsyncLocalStoragePlugin() {
1125
1170
  return [{
1126
1171
  name: "rsc:inject-async-local-storage",
1127
- transform: { handler(code) {
1128
- if ((this.environment.name === "ssr" || this.environment.name === "rsc") && code.includes("typeof AsyncLocalStorage") && code.includes("new AsyncLocalStorage()") && !code.includes("__viteRscAsyncHooks")) return (this.environment.mode === "build" && !isRolldownVite ? `const __viteRscAsyncHooks = require("node:async_hooks");` : `import * as __viteRscAsyncHooks from "node:async_hooks";`) + `globalThis.AsyncLocalStorage = __viteRscAsyncHooks.AsyncLocalStorage;` + code;
1129
- } }
1172
+ transform: {
1173
+ filter: { code: "typeof AsyncLocalStorage" },
1174
+ handler(code) {
1175
+ if ((this.environment.name === "ssr" || this.environment.name === "rsc") && code.includes("typeof AsyncLocalStorage") && code.includes("new AsyncLocalStorage()") && !code.includes("__viteRscAsyncHooks")) return (this.environment.mode === "build" && !isRolldownVite ? `const __viteRscAsyncHooks = require("node:async_hooks");` : `import * as __viteRscAsyncHooks from "node:async_hooks";`) + `globalThis.AsyncLocalStorage = __viteRscAsyncHooks.AsyncLocalStorage;` + code;
1176
+ }
1177
+ }
1130
1178
  }];
1131
1179
  }
1132
1180
  function vitePluginUseClient(useClientPluginOptions, manager) {
@@ -1143,7 +1191,7 @@ function vitePluginUseClient(useClientPluginOptions, manager) {
1143
1191
  return [
1144
1192
  {
1145
1193
  name: "rsc:use-client",
1146
- async transform(code, id) {
1194
+ transform: { async handler(code, id) {
1147
1195
  if (this.environment.name !== serverEnvironmentName) return;
1148
1196
  if (!code.includes("use client")) {
1149
1197
  delete manager.clientReferenceMetaMap[id];
@@ -1206,87 +1254,96 @@ function vitePluginUseClient(useClientPluginOptions, manager) {
1206
1254
  code: output.toString(),
1207
1255
  map: { mappings: "" }
1208
1256
  };
1209
- }
1257
+ } }
1210
1258
  },
1211
1259
  {
1212
1260
  name: "rsc:use-client/build-references",
1213
- resolveId(source) {
1214
- if (source.startsWith("virtual:vite-rsc/client-references")) return "\0" + source;
1261
+ resolveId: {
1262
+ filter: { id: prefixRegex("virtual:vite-rsc/client-references") },
1263
+ handler(source) {
1264
+ if (source.startsWith("virtual:vite-rsc/client-references")) return "\0" + source;
1265
+ }
1215
1266
  },
1216
- load(id) {
1217
- if (id === "\0virtual:vite-rsc/client-references") {
1218
- if (this.environment.mode === "dev") return {
1219
- code: `export default {}`,
1220
- map: null
1221
- };
1222
- if (manager.isScanBuild) {
1223
- let code$1 = ``;
1224
- for (const meta of Object.values(manager.clientReferenceMetaMap)) code$1 += `import ${JSON.stringify(withResolvedIdProxy(meta.importId))};\n`;
1225
- return {
1226
- code: code$1,
1267
+ load: {
1268
+ filter: { id: prefixRegex("\0virtual:vite-rsc/client-references") },
1269
+ handler(id) {
1270
+ if (id === "\0virtual:vite-rsc/client-references") {
1271
+ if (this.environment.mode === "dev") return {
1272
+ code: `export default {}`,
1227
1273
  map: null
1228
1274
  };
1229
- }
1230
- let code = "";
1231
- manager.clientReferenceGroups = {};
1232
- for (const meta of Object.values(manager.clientReferenceMetaMap)) {
1233
- if (!meta.serverChunk) continue;
1234
- let name = useClientPluginOptions.clientChunks?.({
1235
- id: meta.importId,
1236
- normalizedId: manager.toRelativeId(meta.importId),
1237
- serverChunk: meta.serverChunk
1238
- }) ?? meta.serverChunk;
1239
- name = cleanUrl(name.replaceAll("..", "__"));
1240
- (manager.clientReferenceGroups[name] ??= []).push(meta);
1241
- meta.groupChunkId = `\0virtual:vite-rsc/client-references/group/${name}`;
1242
- }
1243
- debug("client-reference-groups", manager.clientReferenceGroups);
1244
- for (const [name, metas] of Object.entries(manager.clientReferenceGroups)) {
1245
- const groupVirtual = `virtual:vite-rsc/client-references/group/${name}`;
1246
- for (const meta of metas) code += `\
1275
+ if (manager.isScanBuild) {
1276
+ let code = ``;
1277
+ for (const meta of Object.values(manager.clientReferenceMetaMap)) code += `import ${JSON.stringify(withResolvedIdProxy(meta.importId))};\n`;
1278
+ return {
1279
+ code,
1280
+ map: null
1281
+ };
1282
+ }
1283
+ let code = "";
1284
+ manager.clientReferenceGroups = {};
1285
+ for (const meta of Object.values(manager.clientReferenceMetaMap)) {
1286
+ if (!meta.serverChunk) continue;
1287
+ let name = useClientPluginOptions.clientChunks?.({
1288
+ id: meta.importId,
1289
+ normalizedId: manager.toRelativeId(meta.importId),
1290
+ serverChunk: meta.serverChunk
1291
+ }) ?? meta.serverChunk;
1292
+ name = cleanUrl(name.replaceAll("..", "__"));
1293
+ (manager.clientReferenceGroups[name] ??= []).push(meta);
1294
+ meta.groupChunkId = `\0virtual:vite-rsc/client-references/group/${name}`;
1295
+ }
1296
+ debug("client-reference-groups", manager.clientReferenceGroups);
1297
+ for (const [name, metas] of Object.entries(manager.clientReferenceGroups)) {
1298
+ const groupVirtual = `virtual:vite-rsc/client-references/group/${name}`;
1299
+ for (const meta of metas) code += `\
1247
1300
  ${JSON.stringify(meta.referenceKey)}: async () => {
1248
1301
  const m = await import(${JSON.stringify(groupVirtual)});
1249
1302
  return m.export_${meta.referenceKey};
1250
1303
  },
1251
1304
  `;
1305
+ }
1306
+ code = `export default {${code}};\n`;
1307
+ return {
1308
+ code,
1309
+ map: null
1310
+ };
1252
1311
  }
1253
- code = `export default {${code}};\n`;
1254
- return {
1255
- code,
1256
- map: null
1257
- };
1258
- }
1259
- if (id.startsWith("\0virtual:vite-rsc/client-references/group/")) {
1260
- const name = id.slice(42);
1261
- const metas = manager.clientReferenceGroups[name];
1262
- assert(metas, `unknown client reference group: ${name}`);
1263
- let code = ``;
1264
- for (const meta of metas) {
1265
- const exports = meta.renderedExports.map((name$1) => `${name$1}: import_${meta.referenceKey}.${name$1},\n`).sort().join("");
1266
- code += `
1312
+ if (id.startsWith("\0virtual:vite-rsc/client-references/group/")) {
1313
+ const name = id.slice(42);
1314
+ const metas = manager.clientReferenceGroups[name];
1315
+ assert(metas, `unknown client reference group: ${name}`);
1316
+ let code = ``;
1317
+ for (const meta of metas) {
1318
+ const exports = meta.renderedExports.map((name) => `${name}: import_${meta.referenceKey}.${name},\n`).sort().join("");
1319
+ code += `
1267
1320
  import * as import_${meta.referenceKey} from ${JSON.stringify(withResolvedIdProxy(meta.importId))};
1268
1321
  export const export_${meta.referenceKey} = {${exports}};
1269
1322
  `;
1323
+ }
1324
+ return {
1325
+ code,
1326
+ map: null
1327
+ };
1270
1328
  }
1271
- return {
1272
- code,
1273
- map: null
1274
- };
1275
1329
  }
1276
1330
  }
1277
1331
  },
1278
1332
  {
1279
1333
  name: "rsc:virtual-client-in-server-package",
1280
- async load(id) {
1281
- if (id.startsWith("\0virtual:vite-rsc/client-in-server-package-proxy/")) {
1282
- assert.equal(this.environment.mode, "dev");
1283
- assert(this.environment.name !== serverEnvironmentName);
1284
- id = decodeURIComponent(id.slice(49));
1285
- return `
1334
+ load: {
1335
+ filter: { id: prefixRegex("\0virtual:vite-rsc/client-in-server-package-proxy/") },
1336
+ async handler(id) {
1337
+ if (id.startsWith("\0virtual:vite-rsc/client-in-server-package-proxy/")) {
1338
+ assert.equal(this.environment.mode, "dev");
1339
+ assert(this.environment.name !== serverEnvironmentName);
1340
+ id = decodeURIComponent(id.slice(49));
1341
+ return `
1286
1342
  export * from ${JSON.stringify(id)};
1287
1343
  import * as __all__ from ${JSON.stringify(id)};
1288
1344
  export default __all__.default;
1289
1345
  `;
1346
+ }
1290
1347
  }
1291
1348
  }
1292
1349
  },
@@ -1304,11 +1361,14 @@ function vitePluginUseClient(useClientPluginOptions, manager) {
1304
1361
  }
1305
1362
  }
1306
1363
  },
1307
- async load(id) {
1308
- if (id.startsWith("\0virtual:vite-rsc/client-package-proxy/")) {
1309
- assert(this.environment.mode === "dev");
1310
- const source = id.slice(39);
1311
- return `export {${Object.values(manager.clientReferenceMetaMap).find((v) => v.packageSource === source).exportNames.join(",")}} from ${JSON.stringify(source)};\n`;
1364
+ load: {
1365
+ filter: { id: prefixRegex("\0virtual:vite-rsc/client-package-proxy/") },
1366
+ async handler(id) {
1367
+ if (id.startsWith("\0virtual:vite-rsc/client-package-proxy/")) {
1368
+ assert(this.environment.mode === "dev");
1369
+ const source = id.slice(39);
1370
+ return `export {${Object.values(manager.clientReferenceMetaMap).find((v) => v.packageSource === source).exportNames.join(",")}} from ${JSON.stringify(source)};\n`;
1371
+ }
1312
1372
  }
1313
1373
  },
1314
1374
  generateBundle(_options, bundle) {
@@ -1392,16 +1452,22 @@ function vitePluginDefineEncryptionKey(useServerPluginOptions) {
1392
1452
  async configEnvironment(name, _config, env) {
1393
1453
  if (name === serverEnvironmentName && !env.isPreview) defineEncryptionKey = useServerPluginOptions.defineEncryptionKey ?? JSON.stringify(toBase64(await generateEncryptionKey()));
1394
1454
  },
1395
- resolveId(source) {
1396
- if (source === "virtual:vite-rsc/encryption-key") return {
1397
- id: "\0" + source,
1398
- moduleSideEffects: false
1399
- };
1455
+ resolveId: {
1456
+ filter: { id: exactRegex("virtual:vite-rsc/encryption-key") },
1457
+ handler(source) {
1458
+ if (source === "virtual:vite-rsc/encryption-key") return {
1459
+ id: "\0" + source,
1460
+ moduleSideEffects: false
1461
+ };
1462
+ }
1400
1463
  },
1401
- load(id) {
1402
- if (id === "\0virtual:vite-rsc/encryption-key") {
1403
- if (this.environment.mode === "build") return `export default () => ${KEY_PLACEHOLDER}`;
1404
- return `export default () => (${defineEncryptionKey})`;
1464
+ load: {
1465
+ filter: { id: exactRegex("\0virtual:vite-rsc/encryption-key") },
1466
+ handler(id) {
1467
+ if (id === "\0virtual:vite-rsc/encryption-key") {
1468
+ if (this.environment.mode === "build") return `export default () => ${KEY_PLACEHOLDER}`;
1469
+ return `export default () => (${defineEncryptionKey})`;
1470
+ }
1405
1471
  }
1406
1472
  },
1407
1473
  renderChunk(code, chunk) {
@@ -1425,7 +1491,7 @@ function vitePluginUseServer(useServerPluginOptions, manager) {
1425
1491
  const debug = createDebug("vite-rsc:use-server");
1426
1492
  return [{
1427
1493
  name: "rsc:use-server",
1428
- async transform(code, id) {
1494
+ transform: { async handler(code, id) {
1429
1495
  if (!code.includes("use server")) {
1430
1496
  delete manager.serverReferenceMetaMap[id];
1431
1497
  return;
@@ -1465,8 +1531,8 @@ function vitePluginUseServer(useServerPluginOptions, manager) {
1465
1531
  const importSource = resolvePackage(`${PKG_NAME}/react/rsc`);
1466
1532
  output.prepend(`import * as $$ReactServer from "${importSource}";\n`);
1467
1533
  if (enableEncryption) {
1468
- const importSource$1 = resolvePackage(`${PKG_NAME}/utils/encryption-runtime`);
1469
- output.prepend(`import * as __vite_rsc_encryption_runtime from ${JSON.stringify(importSource$1)};\n`);
1534
+ const importSource = resolvePackage(`${PKG_NAME}/utils/encryption-runtime`);
1535
+ output.prepend(`import * as __vite_rsc_encryption_runtime from ${JSON.stringify(importSource)};\n`);
1470
1536
  }
1471
1537
  return {
1472
1538
  code: output.toString(),
@@ -1498,7 +1564,7 @@ function vitePluginUseServer(useServerPluginOptions, manager) {
1498
1564
  map: output.generateMap({ hires: "boundary" })
1499
1565
  };
1500
1566
  }
1501
- }
1567
+ } }
1502
1568
  }, createVirtualPlugin("vite-rsc/server-references", function() {
1503
1569
  if (this.environment.mode === "dev") return {
1504
1570
  code: `export {}`,
@@ -1531,13 +1597,13 @@ var RuntimeAsset = class {
1531
1597
  };
1532
1598
  function serializeValueWithRuntime(value) {
1533
1599
  const replacements = [];
1534
- let result = JSON.stringify(value, (_key, value$1) => {
1535
- if (value$1 instanceof RuntimeAsset) {
1600
+ let result = JSON.stringify(value, (_key, value) => {
1601
+ if (value instanceof RuntimeAsset) {
1536
1602
  const placeholder = `__runtime_placeholder_${replacements.length}__`;
1537
- replacements.push([placeholder, value$1.runtime]);
1603
+ replacements.push([placeholder, value.runtime]);
1538
1604
  return placeholder;
1539
1605
  }
1540
- return value$1;
1606
+ return value;
1541
1607
  }, 2);
1542
1608
  for (const [placeholder, runtime] of replacements) result = result.replace(`"${placeholder}"`, runtime);
1543
1609
  return result;
@@ -1651,7 +1717,7 @@ function vitePluginRscCss(rscCssOptions = {}, manager) {
1651
1717
  return [
1652
1718
  {
1653
1719
  name: "rsc:rsc-css-export-transform",
1654
- async transform(code, id) {
1720
+ transform: { async handler(code, id) {
1655
1721
  if (this.environment.name !== "rsc") return;
1656
1722
  const filter = getRscCssTransformFilter({
1657
1723
  id,
@@ -1667,13 +1733,14 @@ function vitePluginRscCss(rscCssOptions = {}, manager) {
1667
1733
  code: result.output.toString(),
1668
1734
  map: result.output.generateMap({ hires: "boundary" })
1669
1735
  };
1670
- }
1736
+ } }
1671
1737
  },
1672
1738
  {
1673
1739
  name: "rsc:rsc-css-self-accept",
1674
1740
  apply: "serve",
1675
1741
  transform: {
1676
1742
  order: "post",
1743
+ filter: { id: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(\?|$)/ },
1677
1744
  handler(_code, id, _options) {
1678
1745
  if (this.environment.name === "client" && this.environment.mode === "dev" && isCSSRequest(id) && directRequestRE.test(id)) {
1679
1746
  const mod = this.environment.moduleGraph.getModuleById(id);
@@ -1684,19 +1751,25 @@ function vitePluginRscCss(rscCssOptions = {}, manager) {
1684
1751
  },
1685
1752
  {
1686
1753
  name: "rsc:css-virtual",
1687
- resolveId(source) {
1688
- if (source.startsWith("virtual:vite-rsc/css?")) return "\0" + source;
1754
+ resolveId: {
1755
+ filter: { id: prefixRegex("virtual:vite-rsc/css?") },
1756
+ handler(source) {
1757
+ if (source.startsWith("virtual:vite-rsc/css?")) return "\0" + source;
1758
+ }
1689
1759
  },
1690
- async load(id) {
1691
- const parsed = parseCssVirtual(id);
1692
- if (parsed?.type === "ssr") {
1693
- id = parsed.id;
1694
- const { server } = manager;
1695
- const mod = await server.environments.ssr.moduleGraph.getModuleByUrl(id);
1696
- if (!mod?.id || !mod?.file) return `export default []`;
1697
- const result = collectCss(server.environments.ssr, mod.id);
1698
- for (const file of [mod.file, ...result.visitedFiles]) this.addWatchFile(file);
1699
- return `export default ${serializeValueWithRuntime(result.hrefs.map((href) => assetsURL(href.slice(1), manager)))}`;
1760
+ load: {
1761
+ filter: { id: prefixRegex("\0virtual:vite-rsc/css?") },
1762
+ async handler(id) {
1763
+ const parsed = parseCssVirtual(id);
1764
+ if (parsed?.type === "ssr") {
1765
+ id = parsed.id;
1766
+ const { server } = manager;
1767
+ const mod = await server.environments.ssr.moduleGraph.getModuleByUrl(id);
1768
+ if (!mod?.id || !mod?.file) return `export default []`;
1769
+ const result = collectCss(server.environments.ssr, mod.id);
1770
+ for (const file of [mod.file, ...result.visitedFiles]) this.addWatchFile(file);
1771
+ return `export default ${serializeValueWithRuntime(result.hrefs.map((href) => assetsURL(href.slice(1), manager)))}`;
1772
+ }
1700
1773
  }
1701
1774
  }
1702
1775
  },
@@ -1715,73 +1788,79 @@ function vitePluginRscCss(rscCssOptions = {}, manager) {
1715
1788
  return original.apply(this, args);
1716
1789
  };
1717
1790
  },
1718
- async transform(code, id) {
1719
- if (!code.includes("import.meta.viteRsc.loadCss")) return;
1720
- assert(this.environment.name === "rsc");
1721
- const output = new MagicString(code);
1722
- let importAdded = false;
1723
- for (const match of stripLiteral(code).matchAll(/import\.meta\.viteRsc\.loadCss\(([\s\S]*?)\)/dg)) {
1724
- const [start, end] = match.indices[0];
1725
- const [argStart, argEnd] = match.indices[1];
1726
- const argCode = code.slice(argStart, argEnd).trim();
1727
- let importer = id;
1728
- if (argCode) {
1729
- const argValue = evalValue(argCode);
1730
- const resolved = await this.resolve(argValue, id);
1731
- if (resolved) importer = resolved.id;
1732
- else {
1733
- this.warn(`[vite-rsc] failed to transform 'import.meta.viteRsc.loadCss(${argCode})'`);
1734
- output.update(start, end, `null`);
1735
- continue;
1791
+ transform: {
1792
+ filter: { code: "import.meta.viteRsc.loadCss" },
1793
+ async handler(code, id) {
1794
+ if (!code.includes("import.meta.viteRsc.loadCss")) return;
1795
+ assert(this.environment.name === "rsc");
1796
+ const output = new MagicString(code);
1797
+ let importAdded = false;
1798
+ for (const match of stripLiteral(code).matchAll(/import\.meta\.viteRsc\.loadCss\(([\s\S]*?)\)/dg)) {
1799
+ const [start, end] = match.indices[0];
1800
+ const [argStart, argEnd] = match.indices[1];
1801
+ const argCode = code.slice(argStart, argEnd).trim();
1802
+ let importer = id;
1803
+ if (argCode) {
1804
+ const argValue = evalValue(argCode);
1805
+ const resolved = await this.resolve(argValue, id);
1806
+ if (resolved) importer = resolved.id;
1807
+ else {
1808
+ this.warn(`[vite-rsc] failed to transform 'import.meta.viteRsc.loadCss(${argCode})'`);
1809
+ output.update(start, end, `null`);
1810
+ continue;
1811
+ }
1736
1812
  }
1737
- }
1738
- const importId = toCssVirtual({
1739
- id: importer,
1740
- type: "rsc"
1741
- });
1742
- let replacement;
1743
- if (this.environment.mode === "dev") replacement = `__vite_rsc_react__.createElement(async () => {
1813
+ const importId = toCssVirtual({
1814
+ id: importer,
1815
+ type: "rsc"
1816
+ });
1817
+ let replacement;
1818
+ if (this.environment.mode === "dev") replacement = `__vite_rsc_react__.createElement(async () => {
1744
1819
  const __m = await import(${JSON.stringify(importId)});
1745
1820
  return __vite_rsc_react__.createElement(__m.Resources);
1746
1821
  })`;
1747
- else {
1748
- const hash = hashString(importId);
1749
- if (!importAdded && !code.includes(`__vite_rsc_importer_resources_${hash}`)) {
1750
- importAdded = true;
1751
- output.prepend(`import * as __vite_rsc_importer_resources_${hash} from ${JSON.stringify(importId)};`);
1822
+ else {
1823
+ const hash = hashString(importId);
1824
+ if (!importAdded && !code.includes(`__vite_rsc_importer_resources_${hash}`)) {
1825
+ importAdded = true;
1826
+ output.prepend(`import * as __vite_rsc_importer_resources_${hash} from ${JSON.stringify(importId)};`);
1827
+ }
1828
+ replacement = `__vite_rsc_react__.createElement(__vite_rsc_importer_resources_${hash}.Resources)`;
1752
1829
  }
1753
- replacement = `__vite_rsc_react__.createElement(__vite_rsc_importer_resources_${hash}.Resources)`;
1830
+ output.update(start, end, replacement);
1831
+ }
1832
+ if (output.hasChanged()) {
1833
+ if (!code.includes("__vite_rsc_react__")) output.prepend(`import __vite_rsc_react__ from "react";`);
1834
+ return {
1835
+ code: output.toString(),
1836
+ map: output.generateMap({ hires: "boundary" })
1837
+ };
1754
1838
  }
1755
- output.update(start, end, replacement);
1756
- }
1757
- if (output.hasChanged()) {
1758
- if (!code.includes("__vite_rsc_react__")) output.prepend(`import __vite_rsc_react__ from "react";`);
1759
- return {
1760
- code: output.toString(),
1761
- map: output.generateMap({ hires: "boundary" })
1762
- };
1763
1839
  }
1764
1840
  },
1765
- load(id) {
1766
- const { server } = manager;
1767
- const parsed = parseCssVirtual(id);
1768
- if (parsed?.type === "rsc") {
1769
- assert(this.environment.name === "rsc");
1770
- const importer = parsed.id;
1771
- if (this.environment.mode === "dev") {
1772
- const result = collectCss(server.environments.rsc, importer);
1773
- for (const file of [importer, ...result.visitedFiles]) this.addWatchFile(file);
1774
- return generateResourcesCode(serializeValueWithRuntime(assetsURLOfDeps({
1775
- css: result.hrefs.map((href) => href.slice(1)),
1776
- js: []
1777
- }, manager)), manager, { cssLinkPrecedence: rscCssOptions.cssLinkPrecedence });
1778
- } else {
1779
- const key = manager.toRelativeId(importer);
1780
- manager.serverResourcesMetaMap[importer] = { key };
1781
- return `
1841
+ load: {
1842
+ filter: { id: prefixRegex("\0virtual:vite-rsc/css?") },
1843
+ handler(id) {
1844
+ const { server } = manager;
1845
+ const parsed = parseCssVirtual(id);
1846
+ if (parsed?.type === "rsc") {
1847
+ assert(this.environment.name === "rsc");
1848
+ const importer = parsed.id;
1849
+ if (this.environment.mode === "dev") {
1850
+ const result = collectCss(server.environments.rsc, importer);
1851
+ for (const file of [importer, ...result.visitedFiles]) this.addWatchFile(file);
1852
+ return generateResourcesCode(serializeValueWithRuntime(assetsURLOfDeps({
1853
+ css: result.hrefs.map((href) => href.slice(1)),
1854
+ js: []
1855
+ }, manager)), manager, { cssLinkPrecedence: rscCssOptions.cssLinkPrecedence });
1856
+ } else {
1857
+ const key = manager.toRelativeId(importer);
1858
+ manager.serverResourcesMetaMap[importer] = { key };
1859
+ return `
1782
1860
  import __vite_rsc_assets_manifest__ from "virtual:vite-rsc/assets-manifest";
1783
1861
  ${generateResourcesCode(`__vite_rsc_assets_manifest__.serverResources[${JSON.stringify(key)}]`, manager, { cssLinkPrecedence: rscCssOptions.cssLinkPrecedence })}
1784
1862
  `;
1863
+ }
1785
1864
  }
1786
1865
  }
1787
1866
  }