@rsc-kit/core 0.37.0 → 0.38.0

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.
package/dist/vite.js CHANGED
@@ -26,7 +26,7 @@ import { stampDisplayNames } from "./stableNames.js";
26
26
  import { REPORT_FILE, buildReport } from "./buildReport.js";
27
27
  import { contractPath, edgeGuarded, edgeMarker, edgeShells, edgeStatic } from "./edgeShells.js";
28
28
  import { EDGE, EDGE_HEADERS } from "./headers.js";
29
- import { claimDevServer, recordDevServerUrl, releaseDevServer, secondDevServerMessage, waitForDevServer } from "./devLock.js";
29
+ import { claimDevServer, recordDevServerUrl, releaseDevServer, secondDevServerMessage, startedAtATerminal, waitForDevServer } from "./devLock.js";
30
30
  import { devContentSecurityPolicy, normaliseContentSecurityPolicy, } from "./csp.js";
31
31
  import { MANIFEST_PATH, manifestWarning, webManifest } from "./webManifest.js";
32
32
  import { ASSET_BASE, allAppAssets, assetFile, appAssets, headTags, shareImageUrls, typeOf, } from "./appAssets.js";
@@ -241,6 +241,7 @@ let hotFile;
241
241
  let hostCallOptions;
242
242
  let packageDir;
243
243
  let backendPaths = [];
244
+ let subdomains = [];
244
245
  let hostGlobal;
245
246
  let interceptManifestFile;
246
247
  let packageAlias;
@@ -503,9 +504,18 @@ export function normaliseBackendPaths(paths, hostCallPath = DEFAULT_HOST_CALL_PA
503
504
  if (hostCallPath === path || hostCallPath.startsWith(path + "/")) {
504
505
  throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is the host-call endpoint (${hostCallPath}), which only the renderer calls. A proxy reading backendPaths would open it to browsers.`);
505
506
  }
506
- // A bracket is a dynamic segment to the client, which reads these as route patterns.
507
- if (/[?#*[\]]/.test(path)) {
508
- throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is a prefix, not a pattern: no query, fragment, wildcard or bracket.`);
507
+ if (/[?#*]/.test(path)) {
508
+ throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is a prefix, not a pattern: no query, fragment or wildcard.`);
509
+ }
510
+ // A whole segment in brackets is any one segment: '/login/[provider]' is
511
+ // /login/google and what is under it. Not the first one - '/[team]' would
512
+ // be every url - and not a catch-all, which a prefix already is.
513
+ const parts = path.slice(1).split("/");
514
+ if (parts.some((part) => /[[\]]/.test(part) && !/^\[[A-Za-z_]\w*\]$/.test(part))) {
515
+ throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} has a bracket that is not a whole segment. A dynamic segment is '[name]', as in '/login/[provider]'; a prefix already covers everything under it, so there is no '[...rest]'.`);
516
+ }
517
+ if (parts[0].startsWith("[")) {
518
+ throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} starts with a dynamic segment, which is every url of that depth and leaves none for this app. Start with a fixed segment, as in '/login/[provider]'.`);
509
519
  }
510
520
  if (!out.includes(path))
511
521
  out.push(path);
@@ -527,6 +537,97 @@ const DEFAULT_HOST_CALL_PATH = "/__rsc/host-call";
527
537
  export function backendPatterns(paths) {
528
538
  return paths.flatMap((path) => [path, `${path}/[...rest]`]);
529
539
  }
540
+ /**
541
+ * The ones that are plain prefixes, which is what a proxy in front reads from
542
+ * routes.json and the build report: "a path equal to one or under it". One
543
+ * with a dynamic segment is left out of that list rather than changing what
544
+ * the list means - the proxy hands the url on like any other, and the
545
+ * renderer, which reads them all, forwards it.
546
+ */
547
+ export function backendPrefixes(paths) {
548
+ return paths.filter((path) => !path.includes("["));
549
+ }
550
+ /** A backend path as the source of a RegExp: the prefix, at a segment boundary. */
551
+ export function backendPathSource(path) {
552
+ return ("^/" +
553
+ path
554
+ .slice(1)
555
+ .split("/")
556
+ .map((part) => (part.startsWith("[") ? "[^/]+" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))
557
+ .join("/") +
558
+ "(?:/|$)");
559
+ }
560
+ /**
561
+ * A page a dynamic backend path would take.
562
+ *
563
+ * A named prefix wins over every page, without asking one - that is what it
564
+ * is for, and why it costs a request nothing. With a dynamic segment the
565
+ * prefix can cover a page nobody meant it to: '/login/[provider]' is
566
+ * /login/forgot too. Said once, where the app starts, rather than checked on
567
+ * every request: the page would simply never render.
568
+ */
569
+ /** rscKit({ subdomains }), checked: labels a host can have, without a slash, once each. */
570
+ export function normaliseSubdomains(labels) {
571
+ if (labels === undefined)
572
+ return [];
573
+ if (!Array.isArray(labels))
574
+ throw new Error("[rsc-kit] subdomains: an array of directory names, as in ['merchant'].");
575
+ const out = [];
576
+ for (const label of labels) {
577
+ const name = typeof label === "string" ? label.replace(/^\/+|\/+$/g, "") : "";
578
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(name)) {
579
+ throw new Error(`[rsc-kit] subdomains: ${JSON.stringify(label)} is not a subdomain label. ` +
580
+ "Name a top-level directory of app/ the way its host spells it: lower-case letters, digits and hyphens, as in 'merchant'.");
581
+ }
582
+ if (name === "www")
583
+ throw new Error("[rsc-kit] subdomains: 'www' is the site's own host, never a subdomain of it.");
584
+ if (!out.includes(name))
585
+ out.push(name);
586
+ }
587
+ return out;
588
+ }
589
+ /**
590
+ * Why rscKit({ subdomains }) cannot be honoured, or null: a subdomain needs a
591
+ * site to be a subdomain of, and a directory to serve. Without either it
592
+ * would redirect visitors to a host that answers nothing.
593
+ */
594
+ export function subdomainProblem(routes, labels, hasSiteHost) {
595
+ if (labels.length === 0)
596
+ return null;
597
+ if (!hasSiteHost) {
598
+ return ("[rsc-kit] subdomains: a subdomain is one of the site's host, and the build does not know it. " +
599
+ "Pass it as rscKit({ hosts: [new URL(env.APP_URL).host] }).");
600
+ }
601
+ for (const label of labels) {
602
+ const served = routes.some((route) => {
603
+ const first = route.segments.find((segment) => segment.type !== "host");
604
+ return first?.type === "static" && first.value === label;
605
+ });
606
+ if (!served) {
607
+ return `[rsc-kit] subdomains: ${JSON.stringify(label)} has no page - add app/${label}/page.tsx, or a page under app/${label}/.`;
608
+ }
609
+ }
610
+ return null;
611
+ }
612
+ export function pageUnderBackendPath(routes, paths) {
613
+ for (const path of paths) {
614
+ if (!path.includes("["))
615
+ continue;
616
+ const parts = path.slice(1).split("/");
617
+ for (const route of routes) {
618
+ const segments = route.segments.filter((segment) => segment.type !== "host");
619
+ if (segments.length < parts.length)
620
+ continue;
621
+ const covered = parts.every((part, i) => part.startsWith("[") ? true : segments[i].type === "static" && segments[i].value === part);
622
+ if (covered) {
623
+ return (`[rsc-kit] backendPaths: ${JSON.stringify(path)} takes ${patternOf(segments)} (${route.component}), which would never render: ` +
624
+ "a backend path is sent to the backend before any page is asked. " +
625
+ "Name the backend's urls one by one, or give them a prefix of their own, as in '/auth/[provider]'.");
626
+ }
627
+ }
628
+ }
629
+ return null;
630
+ }
530
631
  function resolvePaths(options) {
531
632
  projectRoot = resolve(options.projectRoot || process.env.RSC_PROJECT_ROOT || process.cwd());
532
633
  sourceDir = resolve(options.sourceDir || process.env.RSC_SOURCE_DIR || join(projectRoot, "src"));
@@ -564,6 +665,7 @@ function resolvePaths(options) {
564
665
  hotFile = options.hotFile || process.env.RSC_HOT_FILE || "";
565
666
  hostCallOptions = options.hostCall;
566
667
  packageDir = resolve(options.packageDir || process.env.RSC_PACKAGE_DIR || thisDir());
668
+ subdomains = normaliseSubdomains(options.subdomains);
567
669
  backendPaths = normaliseBackendPaths(options.backendPaths, options.hostCall?.path ?? process.env.RSC_HOST_CALL_PATH ?? DEFAULT_HOST_CALL_PATH);
568
670
  hostGlobal = options.hostGlobal || process.env.RSC_HOST_GLOBAL || "rpc";
569
671
  interceptManifestFile = resolve(options.interceptManifestFile ||
@@ -932,7 +1034,7 @@ function routeManifest() {
932
1034
  ...revalidateOf([...layouts, name].map((n) => components.get(n).absPath)),
933
1035
  });
934
1036
  }
935
- const clash = samePageUrl(routes);
1037
+ const clash = samePageUrl(routes) ?? pageUnderBackendPath(routes, backendPaths) ?? subdomainProblem(routes, subdomains, siteHosts.length > 0);
936
1038
  if (clash)
937
1039
  throw new Error(clash);
938
1040
  // What the build decided, for a host that has to act on it afterwards —
@@ -949,8 +1051,9 @@ function routeManifest() {
949
1051
  headers: Object.keys(pageHeaders).length ? pageHeaders : undefined,
950
1052
  contentSecurityPolicy: devPolicy(),
951
1053
  // Always written, [] when none: a reader can tell "none" from a build
952
- // too old to say.
953
- backendPaths,
1054
+ // too old to say. Prefixes only - see backendPrefixes.
1055
+ backendPaths: backendPrefixes(backendPaths),
1056
+ subdomains: subdomains.length ? subdomains : undefined,
954
1057
  },
955
1058
  routes,
956
1059
  intercepts,
@@ -2441,7 +2544,11 @@ function renderRouteTypes(manifest) {
2441
2544
  " interface RegisterBackend {",
2442
2545
  backendPaths.length > 0
2443
2546
  ? " paths:\n" +
2444
- backendPaths.map((p) => " | " + JSON.stringify(p)).join("\n")
2547
+ backendPaths
2548
+ .map((p) => " | " +
2549
+ // A dynamic segment is any string there: `/login/${string}`.
2550
+ (p.includes("[") ? "`" + p.replace(/\[[^\]]+\]/g, "${string}") + "`" : JSON.stringify(p)))
2551
+ .join("\n")
2445
2552
  : " // No backendPaths named.\n paths: never",
2446
2553
  " }",
2447
2554
  // Regions: every section('name', …) the build read, and every @slot
@@ -3279,11 +3386,12 @@ const BACKEND_HEADERS = backendHeaders(typeof process === 'undefined' ? undefine
3279
3386
  * the same prefixes as the real one.
3280
3387
  */
3281
3388
  function backendPathConsts() {
3282
- return `const BACKEND_PATHS: string[] = ${JSON.stringify(backendPaths)}
3389
+ return `const BACKEND_PATHS: RegExp[] = ${JSON.stringify(backendPaths.map(backendPathSource))}.map((source) => new RegExp(source))
3283
3390
 
3284
- // A prefix at a segment boundary: '/auth' is '/auth' and what is under it, not '/authors'.
3391
+ // A prefix at a segment boundary: '/auth' is '/auth' and what is under it, not
3392
+ // '/authors'. '[name]' in one is any single segment.
3285
3393
  function onBackendPath(pathname: string): boolean {
3286
- return BACKEND_PATHS.some((prefix) => pathname === prefix || pathname.startsWith(prefix + '/'))
3394
+ return BACKEND_PATHS.some((prefix) => prefix.test(pathname))
3287
3395
  }
3288
3396
 
3289
3397
  // The backend's host-call endpoint, which only this server calls - straight to
@@ -7882,6 +7990,70 @@ export const SHUTDOWN_PLUGIN = `export default function rscKitShutdown() {
7882
7990
  process.once('SIGINT', stop)
7883
7991
  }
7884
7992
  `;
7993
+ /**
7994
+ * One dev-server restart at a time, and none lost.
7995
+ *
7996
+ * Vite answers a restart asked for while one is running with the running
7997
+ * one's promise. The route table that restart reads was already written, so
7998
+ * a second page added a moment after the first was a 404 until something
7999
+ * else restarted the server. A restart asked for while one runs becomes one
8000
+ * more, after it. On globalThis because a restart re-imports the config, and
8001
+ * this must outlive the plugin instance that started it.
8002
+ */
8003
+ const RESTARTS = Symbol.for("rsc-kit.dev-restarts");
8004
+ function restartOnce(server) {
8005
+ const holder = globalThis;
8006
+ const state = (holder[RESTARTS] ??= { running: false, again: false });
8007
+ if (state.running) {
8008
+ state.again = true;
8009
+ return;
8010
+ }
8011
+ state.running = true;
8012
+ void (async () => {
8013
+ try {
8014
+ do {
8015
+ state.again = false;
8016
+ await server.restart();
8017
+ } while (state.again);
8018
+ }
8019
+ finally {
8020
+ state.running = false;
8021
+ }
8022
+ })();
8023
+ }
8024
+ /**
8025
+ * What Vite starts on listen, started before a restarted server renders.
8026
+ *
8027
+ * Nitro's dev runner imports the ssr and rsc entries as soon as a restarted
8028
+ * server exists, which is before it listens - and two things Vite does only
8029
+ * on listen were therefore missing for whatever that import transformed.
8030
+ *
8031
+ * The client's buildStart, where vite:css registers its CSS-modules cache for
8032
+ * the new config: a stylesheet transformed first failed every request with
8033
+ * "cssModulesCache.get(config).get". And each environment's dependency
8034
+ * optimizer: resolved before it was initialised, react-dom/server came from
8035
+ * node_modules and the app's react from the optimized copy - two Reacts, and
8036
+ * every page failed with "resolveDispatcher().useEffect". Both lasted until
8037
+ * dev was restarted by hand. Both calls are idempotent, so Vite's own on
8038
+ * listen become no-ops.
8039
+ *
8040
+ * Its own plugin, ordered post, and not the first lines of the engine's
8041
+ * configureServer: waiting there let a transform run before plugin-rsc had
8042
+ * been handed the server ("reading 'environments'" of undefined).
8043
+ */
8044
+ function startedBeforeAnythingRenders() {
8045
+ return {
8046
+ name: "rsc-kit:started-before-anything-renders",
8047
+ apply: "serve",
8048
+ configureServer: {
8049
+ order: "post",
8050
+ async handler(server) {
8051
+ await server.environments?.client?.pluginContainer.buildStart();
8052
+ await Promise.all(Object.values(server.environments ?? {}).map((environment) => environment.depsOptimizer?.init()));
8053
+ },
8054
+ },
8055
+ };
8056
+ }
7885
8057
  /**
7886
8058
  * Where NODE_ENV=development came from, and what to do about it.
7887
8059
  *
@@ -8282,7 +8454,11 @@ export function rscKit(options = {}) {
8282
8454
  const lockDir = join(projectRoot, "node_modules", ".vite");
8283
8455
  const holder = claimDevServer(lockDir);
8284
8456
  if (holder) {
8285
- log(secondDevServerMessage(projectRoot, holder).replace(/^\[rsc-kit\] /, ""));
8457
+ const waits = !startedAtATerminal();
8458
+ log(secondDevServerMessage(projectRoot, holder, waits).replace(/^\[rsc-kit\] /, ""));
8459
+ // A person at a terminal is told and let go; see devLock.ts.
8460
+ if (!waits)
8461
+ process.exit(1);
8286
8462
  await waitForDevServer(lockDir);
8287
8463
  log("the other dev server stopped — starting this one");
8288
8464
  }
@@ -8427,6 +8603,8 @@ export function rscKit(options = {}) {
8427
8603
  __RSC_OFFLINE__: JSON.stringify(offline),
8428
8604
  // hostUrl()'s site: the host as named, port and all, without www.
8429
8605
  __RSC_SITE_HOST__: JSON.stringify(siteHostOf(rootMetadataBase(appDir), hostsOption)),
8606
+ // rscKit({ subdomains }): where Link, visit() and redirect() place a path.
8607
+ __RSC_SUBDOMAINS__: JSON.stringify(subdomains),
8430
8608
  },
8431
8609
  /*
8432
8610
  * This package's client modules are served as source, never
@@ -8792,7 +8970,7 @@ export function rscKit(options = {}) {
8792
8970
  if (!affectsRouting(file))
8793
8971
  return;
8794
8972
  server.config.logger.info(`[rsc-kit] route tree changed (${file.slice(sourceDir.length + 1)}) — restarting`);
8795
- void server.restart();
8973
+ restartOnce(server);
8796
8974
  };
8797
8975
  // Watched explicitly: the Vite root is the *out* directory, so the app's
8798
8976
  // source tree is outside it and nothing would report a file appearing.
@@ -8810,7 +8988,7 @@ export function rscKit(options = {}) {
8810
8988
  if (file !== hostActionsPath || hostFileOnDisk() === hostFileText)
8811
8989
  return;
8812
8990
  server.config.logger.info(`[rsc-kit] ${relative(projectRoot, file)} changed — restarting`);
8813
- void server.restart();
8991
+ restartOnce(server);
8814
8992
  };
8815
8993
  server.watcher.add(hostActionsPath);
8816
8994
  // The backend's own source, when the app says where it is: a function
@@ -8978,7 +9156,7 @@ export function rscKit(options = {}) {
8978
9156
  ...(buildCommands().length ? { commands: buildCommands().map((c) => c.name) } : {}),
8979
9157
  // The prefixes a proxy in front sends straight to the
8980
9158
  // backend: a path equal to one or under it. [] when none.
8981
- backendPaths,
9159
+ backendPaths: backendPrefixes(backendPaths),
8982
9160
  }, null, 2) + "\n");
8983
9161
  // The edge contract's marker: the pages an edge may answer from a
8984
9162
  // cached shell or whole, and the build both endpoints will say they
@@ -9088,6 +9266,7 @@ export function rscKit(options = {}) {
9088
9266
  clientImportsAudit(),
9089
9267
  serverOnlyInTheBrowser(),
9090
9268
  routesPlugin,
9269
+ startedBeforeAnythingRenders(),
9091
9270
  ];
9092
9271
  }
9093
9272
  /**