@rsc-kit/core 0.30.52 → 0.30.54

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
@@ -35,7 +35,7 @@ import { automaticSitemap, METADATA_ROUTES, ROOT_FILES, rootFileType, } from "./
35
35
  import { ownHosts } from "./hostRouting.js";
36
36
  import { unrollBarrelImports } from "./barrelImports.js";
37
37
  import { hasUseSsr, serverRendererMessage, SERVER_RENDERER, ssrProxyModule, UseSsrError, withoutSsrDirective } from "./useSsr.js";
38
- import { httpHostCalls } from "./hostCalls.js";
38
+ import { backendHeaders, httpHostCalls } from "./hostCalls.js";
39
39
  import { BARE_COMMANDS_ENVIRONMENT, BARE_COMMANDS_MODULE_ID, COMMANDS_MODULE_ID, bareCommandsModule, commandFiles, commandsEntry, commandsEntrySource, commandsModule, compileEntryWithCommands } from "./commandFiles.js";
40
40
  import { clientPackages, importsServerRenderer, packageDir as installedPackageDir, packageEntryInGraph, polyfillsToTrace, traceableByName } from "./clientPackages.js";
41
41
  // Resolved once per rscKit() call. One build runs in one process, so these are
@@ -446,7 +446,7 @@ export function normalisePageHeaders(raw) {
446
446
  * slash. Refused rather than corrected where a mistake would silently send the
447
447
  * whole app, or its own endpoints, to the backend.
448
448
  */
449
- export function normaliseBackendPaths(paths) {
449
+ export function normaliseBackendPaths(paths, hostCallPath = DEFAULT_HOST_CALL_PATH) {
450
450
  const out = [];
451
451
  for (const raw of paths ?? []) {
452
452
  const given = typeof raw === "string" ? raw.trim() : "";
@@ -461,6 +461,12 @@ export function normaliseBackendPaths(paths) {
461
461
  if (path === "/_rsc" || path.startsWith("/_rsc/")) {
462
462
  throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is this package's own endpoint, which the renderer answers.`);
463
463
  }
464
+ // A proxy routes these prefixes to the backend from outside, and the
465
+ // host-call endpoint is for the renderer alone: named here, a proxy
466
+ // reading the list would open it to every browser.
467
+ if (hostCallPath === path || hostCallPath.startsWith(path + "/")) {
468
+ 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.`);
469
+ }
464
470
  // A bracket is a dynamic segment to the client, which reads these as route patterns.
465
471
  if (/[?#*[\]]/.test(path)) {
466
472
  throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is a prefix, not a pattern: no query, fragment, wildcard or bracket.`);
@@ -470,6 +476,8 @@ export function normaliseBackendPaths(paths) {
470
476
  }
471
477
  return out;
472
478
  }
479
+ /** Where host calls go on the backend, unless `hostCall.path` or RSC_HOST_CALL_PATH says. */
480
+ const DEFAULT_HOST_CALL_PATH = "/__rsc/host-call";
473
481
  /**
474
482
  * The prefixes a backend owns, as the route patterns the browser already reads
475
483
  * for a route.ts: the prefix, and everything under it.
@@ -520,7 +528,7 @@ function resolvePaths(options) {
520
528
  hotFile = options.hotFile || process.env.RSC_HOT_FILE || "";
521
529
  hostCallOptions = options.hostCall;
522
530
  packageDir = resolve(options.packageDir || process.env.RSC_PACKAGE_DIR || thisDir());
523
- backendPaths = normaliseBackendPaths(options.backendPaths);
531
+ backendPaths = normaliseBackendPaths(options.backendPaths, options.hostCall?.path ?? process.env.RSC_HOST_CALL_PATH ?? DEFAULT_HOST_CALL_PATH);
524
532
  hostGlobal = options.hostGlobal || process.env.RSC_HOST_GLOBAL || "rpc";
525
533
  interceptManifestFile = resolve(options.interceptManifestFile ||
526
534
  process.env.RSC_INTERCEPT_MANIFEST ||
@@ -880,6 +888,9 @@ function routeManifest() {
880
888
  identify,
881
889
  refreshOn: usesRefreshOn() || undefined,
882
890
  headers: Object.keys(pageHeaders).length ? pageHeaders : undefined,
891
+ // Always written, [] when none: a reader can tell "none" from a build
892
+ // too old to say.
893
+ backendPaths,
883
894
  },
884
895
  routes,
885
896
  intercepts,
@@ -3115,6 +3126,11 @@ function fallbackOrigin(): string {
3115
3126
  }
3116
3127
  const FALLBACK_MARKER = 'x-rsc-renderer-fallback'
3117
3128
  const PROXIED_MARKER = 'x-rsc-proxied-by-backend'
3129
+
3130
+ // RSC_BACKEND_HEADERS, read once at startup: on every url handed to the
3131
+ // backend, as on every host call, and on nothing sent anywhere else. Malformed
3132
+ // stops the server here rather than sending requests without them.
3133
+ const BACKEND_HEADERS = backendHeaders(typeof process === 'undefined' ? undefined : process.env.RSC_BACKEND_HEADERS)
3118
3134
  `;
3119
3135
  /**
3120
3136
  * The urls the app said belong to the backend, tested before any page is
@@ -3128,10 +3144,22 @@ function backendPathConsts() {
3128
3144
  function onBackendPath(pathname: string): boolean {
3129
3145
  return BACKEND_PATHS.some((prefix) => pathname === prefix || pathname.startsWith(prefix + '/'))
3130
3146
  }
3147
+
3148
+ // The backend's host-call endpoint, which only this server calls - straight to
3149
+ // the backend, never through here. A browser asking for it here was handed on
3150
+ // like any url nothing owns, so the secret was all that stood in front of it.
3151
+ function isHostCallPath(pathname: string): boolean {
3152
+ const path = (typeof process !== 'undefined' && process.env.RSC_HOST_CALL_PATH) || ${JSON.stringify(hostCallOptions?.path ?? DEFAULT_HOST_CALL_PATH)}
3153
+ const asked = pathname.replace(/\\/+$/, '')
3154
+
3155
+ return asked === path || asked.startsWith(path + '/')
3156
+ }
3131
3157
  `;
3132
3158
  }
3133
3159
  /** With no backend configured: this app's not-found page, or a test's backend. */
3134
- const NO_FALLBACK_BODY = ` // The app named this prefix as the backend's: no page is asked about it, so one
3160
+ const NO_FALLBACK_BODY = ` if (isHostCallPath(new URL(request.url).pathname)) return await notFound(request)
3161
+
3162
+ // The app named this prefix as the backend's: no page is asked about it, so one
3135
3163
  // that matches (a dynamic root route) cannot answer for it.
3136
3164
  const toBackend = onBackendPath(new URL(request.url).pathname)
3137
3165
  const answer = toBackend ? null : await devHandler(request)
@@ -3144,6 +3172,8 @@ const NO_FALLBACK_BODY = ` // The app named this prefix as the backend's: no pa
3144
3172
  `;
3145
3173
  const FALLBACK_BODY = ` const FALLBACK_ORIGIN = fallbackOrigin()
3146
3174
 
3175
+ if (isHostCallPath(new URL(request.url).pathname)) return await notFound(request)
3176
+
3147
3177
  // The app named this prefix as the backend's (rscKit({ backendPaths })): no
3148
3178
  // page is asked about it. A dynamic root route such as [team]/[app] matches
3149
3179
  // /gitlab/connect, renders, says notFound() - and a page that said that is not
@@ -3198,6 +3228,10 @@ const FALLBACK_BODY = ` const FALLBACK_ORIGIN = fallbackOrigin()
3198
3228
  headers.delete('host')
3199
3229
  headers.set(FALLBACK_MARKER, '1')
3200
3230
 
3231
+ // Set over whatever the visitor sent under the same name: the value is the
3232
+ // deployment's, never the browser's.
3233
+ for (const [name, value] of Object.entries(BACKEND_HEADERS)) headers.set(name, value)
3234
+
3201
3235
  // What the browser actually asked for. Without these the backend generates
3202
3236
  // absolute urls — url(), route(), redirects, form actions — against its own
3203
3237
  // origin rather than this one, and a redirect walks the browser off this
@@ -3332,7 +3366,7 @@ function installHostCallsOnce(): void {
3332
3366
 
3333
3367
  const path = process.env.RSC_HOST_CALL_PATH ?? '/__rsc/host-call'
3334
3368
 
3335
- installHostFn(httpHostCalls({ endpoint: origin.replace(/\\/$/, '') + path, secret }))
3369
+ installHostFn(httpHostCalls({ endpoint: origin.replace(/\\/$/, '') + path, secret, headers: backendHeaders(process.env.RSC_BACKEND_HEADERS) }))
3336
3370
  }
3337
3371
 
3338
3372
  `;
@@ -3483,7 +3517,7 @@ import { cancelledByConsumer } from ${JSON.stringify(join(packageDir, "js/fallba
3483
3517
  import { withoutPayloadKey } from ${JSON.stringify(join(packageDir, "js/payloadKey"))}
3484
3518
  import { cachingOf, finishCacheable } from ${JSON.stringify(join(packageDir, "pageCache"))}
3485
3519
  import { createRscHandler, notFoundRouteOf, pageSaidNotFound, queryAndParams } from ${JSON.stringify(join(packageDir, "host"))}
3486
- import { httpHostCalls } from ${JSON.stringify(join(packageDir, "hostCalls"))}
3520
+ import { backendHeaders, httpHostCalls } from ${JSON.stringify(join(packageDir, "hostCalls"))}
3487
3521
  import { backendVersions, installBackendVersionSource } from ${JSON.stringify(join(packageDir, "changed"))}
3488
3522
  import { RefreshOn } from ${JSON.stringify(join(packageDir, "js/refreshOn"))}
3489
3523
  import { prerenderedBeside } from ${JSON.stringify(join(packageDir, "files"))}
@@ -6445,7 +6479,7 @@ import { parseRedirectDigest } from ${JSON.stringify(redirectDigestModule)}
6445
6479
  import { isNotFoundDigest } from ${JSON.stringify(notFoundModule)}
6446
6480
  import { EARLY_CLICKS } from ${JSON.stringify(earlyClicks)}
6447
6481
  import { searchSnapshotContext } from ${JSON.stringify(join(packageDir, "js/useSearchParams"))}
6448
- import { createElement as h, use } from 'react'
6482
+ import { createElement as h } from 'react'
6449
6483
  ${webManifestOptions ? `import { INSTALL_CAPTURE } from ${JSON.stringify(installCapture)}` : ""}
6450
6484
 
6451
6485
  // What runs ahead of the runtime: held taps, and - in an app that can be
@@ -6470,9 +6504,15 @@ const DEV_ORIGIN = ${JSON.stringify(devOrigin)}
6470
6504
  *
6471
6505
  * One component for the first render, the prerender and the resume: a shell
6472
6506
  * and its holes must be the same tree.
6507
+ *
6508
+ * It returns the promise rather than calling use() on it - React renders a
6509
+ * promise as what it resolves to. A hook here would be this module's React,
6510
+ * and in dev, on a start with an empty dependency cache, that is not the copy
6511
+ * React DOM renders with: every page answered 500 with "Invalid hook call"
6512
+ * until the server was restarted on a warm cache.
6473
6513
  */
6474
6514
  function Decoded({ from }: { from: { stream: ReadableStream; decoded?: Promise<unknown> } }) {
6475
- return use((from.decoded ??= createFromReadableStream(from.stream)) as Promise<any>)
6515
+ return (from.decoded ??= createFromReadableStream(from.stream)) as any
6476
6516
  }
6477
6517
 
6478
6518
  function decodedBy(stream: ReadableStream): unknown {
@@ -7502,6 +7542,16 @@ function clientImportsAudit() {
7502
7542
  },
7503
7543
  };
7504
7544
  }
7545
+ /** Whether the app's Nitro exports `nitro/services`: the release candidate on. */
7546
+ function nitroHasPublicServices(root) {
7547
+ try {
7548
+ createRequire(join(root, "package.json")).resolve("nitro/services");
7549
+ return true;
7550
+ }
7551
+ catch {
7552
+ return false;
7553
+ }
7554
+ }
7505
7555
  /**
7506
7556
  * A Nitro runtime plugin, so instrumentation.ts runs when the server starts.
7507
7557
  *
@@ -7513,15 +7563,30 @@ function clientImportsAudit() {
7513
7563
  * it. Not on a Worker: there is no startup, and the first request is the
7514
7564
  * first chance to read a binding.
7515
7565
  */
7516
- const STARTUP_PLUGIN = `import { viteServices } from "#nitro/virtual/vite-services"
7566
+ /**
7567
+ * How the plugin reaches the ssr service. Nitro's release candidate made
7568
+ * `nitro/services` public and removed the virtual module the betas had, so an
7569
+ * app is answered with whichever its own Nitro has: a build importing the
7570
+ * other failed to resolve it, and the app could not build at all.
7571
+ */
7572
+ function startupPlugin(publicServices) {
7573
+ return (publicServices
7574
+ ? `import { fetchService } from "nitro/services"
7517
7575
 
7576
+ const ssr = { fetch: (request) => fetchService('ssr', request) }
7577
+ `
7578
+ : `import { viteServices } from "#nitro/virtual/vite-services"
7579
+
7580
+ const ssr = viteServices.ssr
7581
+ `) + STARTUP_PLUGIN;
7582
+ }
7583
+ const STARTUP_PLUGIN = `
7518
7584
  export default function rscKitStartup() {
7519
7585
  if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') return
7520
7586
 
7521
7587
  // The ssr service is the one Nitro's renderer asks; its fetch imports the
7522
7588
  // rsc entry and hands the request on. The rsc service's own export is the
7523
7589
  // handler function, not a { fetch }, so it cannot be probed directly.
7524
- const ssr = viteServices.ssr
7525
7590
  if (!ssr) return
7526
7591
 
7527
7592
  // Two ways to fail, one outcome. register() rejecting is reported by the
@@ -7925,7 +7990,7 @@ export function rscKit(options = {}) {
7925
7990
  }
7926
7991
  if (!instrumentationFile())
7927
7992
  return;
7928
- nitro.options.virtual["#rsc-kit/startup"] = STARTUP_PLUGIN;
7993
+ nitro.options.virtual["#rsc-kit/startup"] = startupPlugin(nitroHasPublicServices(projectRoot));
7929
7994
  nitro.options.plugins = [...(nitro.options.plugins ?? []), "#rsc-kit/startup"];
7930
7995
  },
7931
7996
  },
@@ -8338,7 +8403,11 @@ export function rscKit(options = {}) {
8338
8403
  try {
8339
8404
  const entry = await env.runner.import(join(genDir, "entry.rsc.tsx"));
8340
8405
  const install = entry.installHostFn;
8341
- install?.(httpHostCalls({ endpoint, secret }));
8406
+ install?.(httpHostCalls({
8407
+ endpoint,
8408
+ secret,
8409
+ headers: backendHeaders(fromEnv.RSC_BACKEND_HEADERS),
8410
+ }));
8342
8411
  }
8343
8412
  catch (error) {
8344
8413
  // Reported rather than thrown: the dev server is still useful for
@@ -8568,6 +8637,9 @@ export function rscKit(options = {}) {
8568
8637
  output: "server",
8569
8638
  ...compileStep(projectRoot),
8570
8639
  ...(buildCommands().length ? { commands: buildCommands().map((c) => c.name) } : {}),
8640
+ // The prefixes a proxy in front sends straight to the
8641
+ // backend: a path equal to one or under it. [] when none.
8642
+ backendPaths,
8571
8643
  }, null, 2) + "\n");
8572
8644
  // The edge contract's marker: the pages an edge may answer from a
8573
8645
  // cached shell or whole, and the build both endpoints will say they