@rsc-kit/core 0.42.0 → 0.43.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
@@ -21,6 +21,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
21
21
  import { fileURLToPath, pathToFileURL } from "node:url";
22
22
  import rsc, { getPluginApi } from "@vitejs/plugin-rsc";
23
23
  import { loadEnv, parseAst } from "vite";
24
+ import { hostSourceMap, withoutSources } from "./hostSources.js";
24
25
  import { formInputs } from "./hostInputs.js";
25
26
  import { stampDisplayNames } from "./stableNames.js";
26
27
  import { REPORT_FILE, buildReport } from "./buildReport.js";
@@ -310,6 +311,10 @@ let hostDefs = {};
310
311
  * sent a check - a backend that has never heard of one would run the call.
311
312
  */
312
313
  let hostValidates = [];
314
+ /** Where the backend wrote each function, when it says. */
315
+ let hostSources = {};
316
+ /** The command a build asks what rpc() answers; see hostManifest.calls. */
317
+ let hostCallsCommand = null;
313
318
  /**
314
319
  * The manifest commands run in this process, by project and command.
315
320
  *
@@ -447,7 +452,7 @@ function fileHostManifest(root) {
447
452
  throw new Error("[rsc-kit] rsc-host-actions.json is the old manifest. The backend now writes " +
448
453
  HOST_FILE + " - { actions, functions } - so update the adapter and run its manifest command.");
449
454
  }
450
- return { actions: {}, functions: null, types: {}, defs: {}, validates: [] };
455
+ return { actions: {}, functions: null, types: {}, defs: {}, validates: [], sources: {}, calls: null };
451
456
  }
452
457
  let parsed;
453
458
  try {
@@ -468,13 +473,21 @@ function fileHostManifest(root) {
468
473
  if (validates !== undefined && (!Array.isArray(validates) || validates.some((n) => typeof n !== "string"))) {
469
474
  throw new Error(`[rsc-kit] ${HOST_FILE}: "validates" must be an array of function names.`);
470
475
  }
476
+ const calls = parsed?.calls;
477
+ if (calls !== undefined && (!Array.isArray(calls) || calls.length === 0 || calls.some((a) => typeof a !== "string"))) {
478
+ throw new Error(`[rsc-kit] ${HOST_FILE}: "calls" must be the arguments that make the manifest command answer calls.`);
479
+ }
471
480
  return {
481
+ calls: calls ?? null,
472
482
  types: isMap(parsed?.types) ? parsed.types : {},
473
483
  defs: isMap(parsed?.defs) ? parsed.defs : {},
474
484
  actions,
475
485
  // The reserved guard call is the engine's to make, not the app's.
476
486
  functions: functions ? functions.filter((n) => !n.startsWith("__rsc.")).sort() : null,
477
487
  validates: validates ?? [],
488
+ // Only what a position can be read from. The editor's, and nothing the
489
+ // app does: a malformed one is a name with nowhere to go, not a failure.
490
+ sources: Object.fromEntries(Object.entries(isMap(parsed?.sources) ? parsed.sources : {}).filter(([, at]) => isMap(at) && typeof at.file === "string" && at.file !== "" && Number.isInteger(at.line) && at.line > 0)),
478
491
  };
479
492
  }
480
493
  /**
@@ -848,13 +861,22 @@ function loadHostManifest(options, before = false) {
848
861
  // checked when it lands.
849
862
  if (!before || !options.hostManifest)
850
863
  throw error;
851
- manifest = { actions: {}, functions: null, types: {}, defs: {}, validates: [] };
864
+ manifest = { actions: {}, functions: null, types: {}, defs: {}, validates: [], sources: {}, calls: null };
852
865
  }
853
866
  hostActions = options.hostActions ? checkHostActions(options.hostActions, "rscKit({ hostActions })") : manifest.actions;
854
867
  hostFunctions = manifest.functions;
855
868
  hostTypes = manifest.types;
856
869
  hostDefs = manifest.defs;
857
870
  hostValidates = manifest.validates;
871
+ hostSources = manifest.sources;
872
+ hostCallsCommand = buildCallsCommand(options.hostManifest, manifest.calls);
873
+ }
874
+ /** @internal What answers rpc() during a build, or null when nothing does. */
875
+ export function buildCallsCommand(spec, declared) {
876
+ if (!spec || spec.calls === false)
877
+ return null;
878
+ const command = spec.calls ?? (declared ? [...spec.command, ...declared] : null);
879
+ return command?.length ? { command, cwd: spec.cwd ? resolve(projectRoot, spec.cwd) : projectRoot } : null;
858
880
  }
859
881
  /** Run the backend's manifest command, once per process; see the option. */
860
882
  function runHostManifest(options, isBuild, again = false) {
@@ -1231,7 +1253,7 @@ function writeHostBindings(manifest) {
1231
1253
  // The global is installed at runtime, so nothing in app source declares it
1232
1254
  // and a typecheck cannot see it. Written whether or not there are actions:
1233
1255
  // server components call it directly too.
1234
- writeGenerated(join(typesDir, "rsc-env.d.ts"), renderHostGlobalTypes());
1256
+ writeHostGlobalTypes();
1235
1257
  // The urls this build found, so a link to a page that does not exist fails
1236
1258
  // the typecheck instead of the browser.
1237
1259
  writeGenerated(join(typesDir, "rsc-routes.d.ts"), renderRouteTypes(manifest));
@@ -1603,6 +1625,57 @@ const MATCH = { ignoreVary: true }
1603
1625
  // of one page, asked for at several depths, fetch its document once.
1604
1626
  const documentsInFlight = new Set()
1605
1627
 
1628
+ // Whether the site moved off this origin - www to the bare domain, an old
1629
+ // domain to a new one - asked when a request failed. The failure is what a
1630
+ // cross-origin redirect looks like from here: a payload fetch follows it to a
1631
+ // host that sends no CORS headers, and rejects exactly as it would offline.
1632
+ // So the url is asked again without following redirects, and a redirect where
1633
+ // a request just failed is the answer. Offline, the probe fails too.
1634
+ //
1635
+ // Asked rather than assumed, because this worker cannot update itself out of
1636
+ // it: the browser refuses a worker script behind a redirect, so once
1637
+ // /sw.js redirects, nothing replaces this worker. It served the old origin's
1638
+ // stored home page from its cache, the boot that followed failed, and the
1639
+ // visitor was shown the offline page on every visit - never the redirect.
1640
+ function moved(request) {
1641
+ return fetch(request.url, { redirect: 'manual', cache: 'no-store', credentials: 'omit' }).then(
1642
+ (response) => response.type === 'opaqueredirect',
1643
+ () => false,
1644
+ )
1645
+ }
1646
+
1647
+ // What the development worker does: the caches go, the worker unregisters,
1648
+ // and each page it controlled is loaded again, uncontrolled, so the
1649
+ // navigation reaches the redirect. Once, however many requests noticed.
1650
+ let leaving = null
1651
+
1652
+ function leave() {
1653
+ leaving ??= (async () => {
1654
+ const keys = await caches.keys()
1655
+ await Promise.all(keys.filter((k) => k.startsWith('rsc-kit-')).map((k) => caches.delete(k)))
1656
+ const pages = await self.clients.matchAll({ type: 'window' })
1657
+ await self.registration.unregister()
1658
+ for (const page of pages) page.navigate(page.url).catch(() => {})
1659
+ })()
1660
+
1661
+ return leaving
1662
+ }
1663
+
1664
+ /** True, and on its way out, when the failed request's url now redirects. */
1665
+ async function leftForMove(event, request) {
1666
+ if (!(await moved(request))) return false
1667
+
1668
+ const going = leave()
1669
+
1670
+ // The event may be over already - a stored page answered from the cache
1671
+ // while its refresh failed behind it - and then there is nothing to extend.
1672
+ try {
1673
+ event.waitUntil(going)
1674
+ } catch {}
1675
+
1676
+ return true
1677
+ }
1678
+
1606
1679
  self.addEventListener('fetch', (event) => {
1607
1680
  const request = event.request
1608
1681
  const url = new URL(request.url)
@@ -1648,6 +1721,7 @@ self.addEventListener('fetch', (event) => {
1648
1721
  return response
1649
1722
  })
1650
1723
  .catch(async (error) => {
1724
+ if (await leftForMove(event, request)) return Response.error()
1651
1725
  if (hit) return hit
1652
1726
 
1653
1727
  // Stored by the build but never visited from this browser, so
@@ -1718,6 +1792,10 @@ self.addEventListener('fetch', (event) => {
1718
1792
  return response
1719
1793
  })
1720
1794
  .catch(async () => {
1795
+ // Before the cache: a copy from the origin the site left is what kept
1796
+ // the visitor there.
1797
+ if (await leftForMove(event, request)) return Response.error()
1798
+
1721
1799
  const hit = await own(keyFor(request), MATCH)
1722
1800
 
1723
1801
  if (hit) return hit
@@ -2149,7 +2227,24 @@ export function smallStylesheetReader(assetsDir, setting) {
2149
2227
  }
2150
2228
  };
2151
2229
  }
2152
- async function prerenderAfterBundles(bundle, staticDir, assetsDir, knownActions = []) {
2230
+ async function prerenderAfterBundles(...args) {
2231
+ if (!hostCallsCommand)
2232
+ return prerenderBundles(...args);
2233
+ const [{ buildProcess }, { installBuildAnswerer }] = await Promise.all([
2234
+ import("./buildProcess.js"),
2235
+ import("./buildScope.js"),
2236
+ ]);
2237
+ const backend = buildProcess(hostCallsCommand);
2238
+ const uninstall = installBuildAnswerer(backend);
2239
+ try {
2240
+ return await prerenderBundles(...args);
2241
+ }
2242
+ finally {
2243
+ uninstall();
2244
+ backend.close();
2245
+ }
2246
+ }
2247
+ async function prerenderBundles(bundle, staticDir, assetsDir, knownActions = []) {
2153
2248
  // A missing bundle used to be a silent `return`, and under Nitro it was the
2154
2249
  // normal case: the path was assumed to be <outDir>/dist/rsc/index.js, Nitro
2155
2250
  // builds the rsc environment somewhere else entirely, and so every Nitro app
@@ -2161,7 +2256,7 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir, knownActions
2161
2256
  throw new Error("[rsc-kit] The build produced no rsc bundle to prerender from.\n" +
2162
2257
  "Prerendering renders the app, so it needs the bundle the build just wrote.");
2163
2258
  }
2164
- const [{ prerender, NotPrerenderable, summary, legend, notes, clientJsSize, pathKey: pathKeyOf, }, { writeTo }, { prerenderApiRoutes },] = await Promise.all([
2259
+ const [{ prerender, NotPrerenderable, renderFailureAdvice, summary, legend, notes, clientJsSize, pathKey: pathKeyOf, }, { writeTo }, { prerenderApiRoutes },] = await Promise.all([
2165
2260
  import("./prerender.js"),
2166
2261
  import("./files.js"),
2167
2262
  import("./apiPrerender.js"),
@@ -2378,9 +2473,8 @@ ${legend(counted)}
2378
2473
  throw new Error(refusal.message);
2379
2474
  if (failed > 0) {
2380
2475
  throw new Error(`[rsc-kit] ${failed} route${failed === 1 ? "" : "s"} failed to render.\n` +
2381
- "Prerendering runs your app: whatever those pages need at render time has to be\n" +
2382
- "reachable from the build. Give it that, or mark the read with `await connection()`\n" +
2383
- "so the page renders per request and the rest of it is still stored.");
2476
+ "\n" +
2477
+ renderFailureAdvice(results.filter((r) => r.type === "error" || r.type === "blocked")));
2384
2478
  }
2385
2479
  // The urls whose answer cannot change until the next build. The service
2386
2480
  // worker serves these from its cache first rather than asking the network
@@ -2812,50 +2906,6 @@ function formType(sig) {
2812
2906
  const literal = (name) => (name.includes("${") ? "`" + name + "`" : JSON.stringify(name));
2813
2907
  return "FormFields<" + [...new Set(names)].map(literal).join(" | ") + ">";
2814
2908
  }
2815
- /**
2816
- * A form posted to a backend action. React hands the action a FormData; on
2817
- * the wire to the backend it is JSON, and JSON.stringify of a FormData is {} -
2818
- * so a form posting straight to a backend action used to send nothing. Its
2819
- * fields become one object, typed by the first parameter where the backend
2820
- * described it: numbers and booleans coerced, a repeated name a list.
2821
- */
2822
- const FORM_ARGS = `function formArgs(args: unknown[], schemas: (Record<string, any> | null)[]): unknown[] {
2823
- // The form is the last argument, and it fills the parameter it lands on: the
2824
- // first when the action takes nothing before it, the one after the team when
2825
- // that was bound with stub.bind(null, team).
2826
- const at = args.length - 1
2827
-
2828
- if (at < 0 || !(args[at] instanceof FormData)) return args
2829
-
2830
- const form = args[at] as FormData
2831
- const schema = schemas[at] ?? null
2832
- const props: Record<string, any> = schema?.properties ?? {}
2833
- const coerce = (type: unknown, v: string): unknown =>
2834
- type === 'integer' || type === 'number' ? (v === '' ? null : Number(v))
2835
- : type === 'boolean' ? v === 'on' || v === 'true' || v === '1'
2836
- : v
2837
- const out: Record<string, unknown> = {}
2838
-
2839
- for (const key of new Set(form.keys())) {
2840
- // React's own fields for a form action, not the form's.
2841
- if (key.startsWith('$ACTION_')) continue
2842
-
2843
- const values = form.getAll(key).filter((v): v is string => typeof v === 'string')
2844
- const prop = props[key]
2845
-
2846
- out[key] = prop?.type === 'array' || (!prop && values.length > 1)
2847
- ? values.map((v) => coerce(prop?.items?.type, v))
2848
- : coerce(prop?.type, values[0] ?? '')
2849
- }
2850
-
2851
- // An unchecked checkbox sends nothing: false, not missing.
2852
- for (const [key, prop] of Object.entries(props)) {
2853
- if (!(key in out) && prop?.type === 'boolean') out[key] = false
2854
- }
2855
-
2856
- return [...args.slice(0, at), out]
2857
- }
2858
- `;
2859
2909
  /**
2860
2910
  * One class's "use server" module: each host function a plain async call. An
2861
2911
  * __invoke is the default export, and a method JavaScript reserves the name
@@ -2866,10 +2916,9 @@ function renderHostActions(module) {
2866
2916
  const exportsOf = hostActions[module] ?? {};
2867
2917
  const taken = new Set(Object.keys(exportsOf));
2868
2918
  const renamed = [];
2869
- // Type-only, so the module stays what "use server" allows: functions.
2870
- lines.push('import type { Redirected } from "@rsc-kit/core/errors";');
2871
- lines.push('import type { FormFields } from "@rsc-kit/core/form";', "");
2872
- lines.push(FORM_ARGS);
2919
+ // The imports are written last, when it is known which types the stubs
2920
+ // name: an unused one fails an app that typechecks with noUnusedLocals.
2921
+ const importsAt = lines.length;
2873
2922
  for (const [exported, target] of Object.entries(exportsOf)) {
2874
2923
  const sig = hostTypes[target];
2875
2924
  // The default's own name is the module's - send-invite, sendInvite - so a
@@ -2914,8 +2963,42 @@ function renderHostActions(module) {
2914
2963
  }
2915
2964
  if (renamed.length > 0)
2916
2965
  lines.push("export { " + renamed.join(", ") + " };", "");
2966
+ const stubs = lines.slice(importsAt).join("\n");
2967
+ // Imported, not exported: what "use server" allows out is functions.
2968
+ const imports = ['import { formArgs } from "@rsc-kit/core/internal/form-args";'];
2969
+ if (/\| Redirected>/.test(stubs))
2970
+ imports.push('import type { Redirected } from "@rsc-kit/core/errors";');
2971
+ if (stubs.includes("form: FormFields<"))
2972
+ imports.push('import type { FormFields } from "@rsc-kit/core/form";');
2973
+ lines.splice(importsAt, 0, ...imports, "");
2917
2974
  return lines.join("\n");
2918
2975
  }
2976
+ /**
2977
+ * The declaration, and the map that takes the editor past it.
2978
+ *
2979
+ * A .d.ts.map is how an editor opens the source of a declaration, and nothing
2980
+ * in it says the source is TypeScript: each rpc() overload maps to its line in
2981
+ * the backend's own file, so going to the definition of the call opens the PHP
2982
+ * or Go function rather than this declaration of it. The map alone moves when
2983
+ * the backend's lines do, so the declaration does not change under the app's
2984
+ * typecheck - or in a diff - because a comment was added in PHP.
2985
+ */
2986
+ function writeHostGlobalTypes() {
2987
+ const path = join(typesDir, HOST_TYPES_FILE);
2988
+ const types = renderHostGlobalTypes();
2989
+ const map = hostSourceMap(types, HOST_TYPES_FILE, hostGlobal, (name) => {
2990
+ const at = hostSources[name];
2991
+ return at && { file: relative(typesDir, resolve(projectRoot, at.file)).replaceAll("\\", "/"), line: at.line };
2992
+ });
2993
+ if (map === null) {
2994
+ rmSync(path + ".map", { force: true });
2995
+ writeGenerated(path, types);
2996
+ return;
2997
+ }
2998
+ writeGenerated(path + ".map", map);
2999
+ writeGenerated(path, types + "//# sourceMappingURL=" + HOST_TYPES_FILE + ".map\n");
3000
+ }
3001
+ const HOST_TYPES_FILE = "rsc-env.d.ts";
2919
3002
  /** Ambient declaration for the host global, written beside the app's source. */
2920
3003
  function renderHostGlobalTypes() {
2921
3004
  return [
@@ -2957,6 +3040,11 @@ function renderHostSignatures() {
2957
3040
  for (const name of typed) {
2958
3041
  const sig = hostTypes[name];
2959
3042
  const params = tsParams(sig);
3043
+ const at = hostSources[name];
3044
+ // What hovering the call shows. Without the line, which the map has: it
3045
+ // moves with every edit above it, and this file would with it.
3046
+ if (at)
3047
+ out.push("/** " + [at.name, at.file].filter(Boolean).join(" in ").replaceAll("*/", "* /") + " */");
2960
3048
  out.push("declare function " + hostGlobal + "<T = " + (sig.result ? tsOf(sig.result) : "void") + ">(name: " +
2961
3049
  JSON.stringify(name) + (params ? ", " + params : "") + "): Promise<T>;");
2962
3050
  }
@@ -3366,36 +3454,46 @@ function rootMetadataBase(appDir) {
3366
3454
  return match ? match[1] : null;
3367
3455
  }
3368
3456
  /**
3369
- * Whether a route file exports this name, in any of the ways TypeScript
3370
- * spells it: a function, a const - which is how the metadata guide writes
3457
+ * The values a file exports by name, in any of the ways TypeScript spells it:
3458
+ * a function, a const - which is how the metadata guide writes
3371
3459
  * `generateMetadata: GenerateMetadata` - or a list, `export { x as name }` or
3372
3460
  * `export { name } from`. Only the function form was read once, and a page
3373
3461
  * exporting the guide's own const was titled by its layout, silently.
3462
+ *
3463
+ * Parsed, not matched: a comment saying "export const viewport changes it" -
3464
+ * the one every new app's root layout carried - read as an export, and the
3465
+ * entry's import of it was a bundler warning on every build.
3374
3466
  */
3375
- function exportsName(src, name) {
3376
- if (new RegExp(`export\\s+(?:async\\s+)?function\\s*\\*?\\s*${name}\\b`).test(src))
3377
- return true;
3378
- if (new RegExp(`export\\s+(?:const|let|var)\\s+${name}\\b`).test(src))
3379
- return true;
3380
- // A list exports the name after `as`, or the name itself; `export type {}`
3381
- // and a `type` entry export no value.
3382
- for (const [list, names] of Array.from(src.matchAll(/export\s+(type\s+)?\{([^}]*)\}/g), (m) => [m[1], m[2]])) {
3383
- if (list)
3467
+ function exportedNames(file) {
3468
+ const names = new Set();
3469
+ for (const node of topLevel(file).body) {
3470
+ if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type")
3471
+ continue;
3472
+ for (const specifier of (node.specifiers ?? [])) {
3473
+ if (specifier.exportKind !== "type")
3474
+ names.add(specifier.exported.name ?? specifier.exported.value);
3475
+ }
3476
+ const declaration = node.declaration;
3477
+ if (!declaration || declaration.declare)
3384
3478
  continue;
3385
- for (const raw of names.split(",")) {
3386
- const entry = raw.trim();
3387
- if (!entry.startsWith("type ") && entry.split(/\s+as\s+/).pop() === name)
3388
- return true;
3479
+ if (declaration.type === "FunctionDeclaration")
3480
+ names.add(declaration.id.name);
3481
+ if (declaration.type === "VariableDeclaration") {
3482
+ for (const declarator of declaration.declarations) {
3483
+ if (declarator.id?.type === "Identifier")
3484
+ names.add(declarator.id.name);
3485
+ }
3389
3486
  }
3390
3487
  }
3391
- return false;
3488
+ return names;
3392
3489
  }
3393
3490
  function metadataExports(absPath) {
3394
3491
  const src = readFileSync(absPath, "utf-8");
3492
+ const names = exportedNames(absPath);
3395
3493
  return {
3396
- static: exportsName(src, "metadata"),
3397
- generate: exportsName(src, "generateMetadata"),
3398
- viewport: exportsName(src, "viewport"),
3494
+ static: names.has("metadata"),
3495
+ generate: names.has("generateMetadata"),
3496
+ viewport: names.has("viewport"),
3399
3497
  writes: {
3400
3498
  charset: /\bcharSet\s*=/.test(src),
3401
3499
  viewport: /name\s*=\s*["']viewport["']/.test(src),
@@ -3441,7 +3539,7 @@ export function revalidateOf(files) {
3441
3539
  function topLevel(file) {
3442
3540
  const src = readFileSync(file, "utf-8");
3443
3541
  const ext = file.slice(file.lastIndexOf(".") + 1);
3444
- const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : "js";
3542
+ const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : ext === "mts" ? "ts" : "js";
3445
3543
  return { body: parseAst(src, { lang }).body, src };
3446
3544
  }
3447
3545
  function exportedDeclarations(body) {
@@ -3783,14 +3881,13 @@ function instrumentationFile() {
3783
3881
  // exists - a namespace import's missing member is a bundler warning on
3784
3882
  // every build (IMPORT_IS_UNDEFINED), which is the app being told off for
3785
3883
  // a file written exactly as documented.
3786
- const source = readFileSync(file, "utf-8");
3787
- const exports = (name) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${name}\\b|const\\s+${name}\\b|let\\s+${name}\\b|\\{[^}]*\\b${name}\\b[^}]*\\})`).test(source);
3884
+ const names = exportedNames(file);
3788
3885
  return {
3789
3886
  file,
3790
- hasRegister: exports("register"),
3791
- hasShutdown: exports("shutdown"),
3792
- hasOnRequest: exports("onRequest"),
3793
- hasOnRequestHeaders: exports("onRequestHeaders"),
3887
+ hasRegister: names.has("register"),
3888
+ hasShutdown: names.has("shutdown"),
3889
+ hasOnRequest: names.has("onRequest"),
3890
+ hasOnRequestHeaders: names.has("onRequestHeaders"),
3794
3891
  };
3795
3892
  }
3796
3893
  return null;
@@ -3922,6 +4019,7 @@ import { cachingOf, finishCacheable, keptBodyOf } from ${JSON.stringify(join(pac
3922
4019
  import { inlineHashes, newNonce, policyHeaderName, policyValue } from ${JSON.stringify(join(packageDir, "csp"))}
3923
4020
  import { createRscHandler, notFoundRouteOf, pageSaidNotFound, queryAndParams } from ${JSON.stringify(join(packageDir, "host"))}
3924
4021
  import { backendHeaders, httpHostCalls } from ${JSON.stringify(join(packageDir, "hostCalls"))}
4022
+ import { answerAtBuild, awaitingBuildAnswer, buildAnswerer, buildBudget, onBuildAnswer } from ${JSON.stringify(join(packageDir, "buildScope"))}
3925
4023
  import { backendVersions, installBackendVersionSource } from ${JSON.stringify(join(packageDir, "changed"))}
3926
4024
  import { RefreshOn } from ${JSON.stringify(join(packageDir, "js/refreshOn"))}
3927
4025
  import { prerenderedBeside } from ${JSON.stringify(join(packageDir, "files"))}
@@ -4477,7 +4575,9 @@ function applyHost() {
4477
4575
  // that reaches is a question about the render it is inside.
4478
4576
  //
4479
4577
  ;(globalThis as Record<string, unknown>)[HOST_GLOBAL] = (...args: unknown[]) => {
4480
- const fn = probeHost.getStore() ?? currentHost
4578
+ // A build's answers before the installed host: nothing in a build is for
4579
+ // anyone, and a host installed there would answer as though it were.
4580
+ const fn = probeHost.getStore() ?? (buildAnswerer() ? (...a: unknown[]) => answerAtBuild(a) : currentHost)
4481
4581
 
4482
4582
  // An optional call was here, and it answered every rpc() with undefined
4483
4583
  // when no host was installed. undefined is a value: the component renders
@@ -6246,6 +6346,12 @@ export async function resolveMetadata(
6246
6346
  return merged
6247
6347
  }
6248
6348
 
6349
+ // The name a host call was made with, so the build can say rpc("getUser")
6350
+ // rather than "this page reached for the host" and leave you to find which.
6351
+ function hostCallName(args: unknown[]): string {
6352
+ return typeof args[0] === 'string' ? 'rpc(' + JSON.stringify(args[0]) + ')' : 'rpc()'
6353
+ }
6354
+
6249
6355
  // Buffered render (worker: rsc / rscWithoutCallbacks — used at prerender time).
6250
6356
  export async function handleRsc(
6251
6357
  component: string,
@@ -6272,19 +6378,22 @@ export async function handleRsc(
6272
6378
  let usedDynamicApis = false
6273
6379
  const hostCalls: string[] = []
6274
6380
 
6275
- const probe = (...args: unknown[]) => {
6381
+ const needsVisitor = (said: string, build = false): Promise<never> => {
6276
6382
  usedDynamicApis = true
6277
6383
 
6278
- // The name it was called with, so the build can say rpc("getUser") rather
6279
- // than "this page reached for the host" and leave you to find which call.
6280
- const name = typeof args[0] === 'string' ? args[0] : null
6281
- const said = name ? 'rpc(' + JSON.stringify(name) + ')' : 'rpc()'
6282
-
6283
6384
  if (!hostCalls.includes(said)) hostCalls.push(said)
6284
6385
 
6285
- return new Promise<never>(() => {})
6386
+ // This render is read to its end, and one that waits for ever has none. A
6387
+ // call the backend says needs a visitor only now - the shell probe found
6388
+ // none, so it was not made there - fails instead: the page is not stored.
6389
+ return build
6390
+ ? Promise.reject(new Error(said + ' needs a visitor, and a build has none'))
6391
+ : new Promise<never>(() => {})
6286
6392
  }
6287
6393
 
6394
+ const probe = (...args: unknown[]): Promise<unknown> =>
6395
+ buildAnswerer() ? answerAtBuild(args, (said) => needsVisitor(said, true)) : needsVisitor(hostCallName(args))
6396
+
6288
6397
  // Not a generic arrow function: this file is generated as .tsx, where <T>
6289
6398
  // parses as JSX and the build fails on a tag it cannot close.
6290
6399
  const runWith = canReachHost
@@ -6309,6 +6418,7 @@ export async function handleRsc(
6309
6418
  rscPayload,
6310
6419
  clientChunks: {},
6311
6420
  usedDynamicApis,
6421
+ dynamicBecause: hostCalls,
6312
6422
  // Client reference rows name the components the browser has to run. Shipping
6313
6423
  // no runtime would leave them as inert markup, so the host refuses — and
6314
6424
  // says which components forced the decision, since they are usually in a
@@ -6470,15 +6580,9 @@ export async function handleRscPprShell(
6470
6580
  budgetMs = PPR_SHELL_TIMEOUT_MS,
6471
6581
  // Whether this build can answer host calls.
6472
6582
  //
6473
- // False is the old and still the usual answer: the stub suspends, and a page
6474
- // reaching for its host becomes a shell rather than freezing data fetched
6475
- // once at build time.
6476
- //
6477
- // A host that opened a callback socket for the build says true, and then the
6478
- // call is made and its answer stored. That is the only way a page whose data
6479
- // lives in the host can be static at all, since a host call is its only route
6480
- // to that data — and
6481
- // connection() is how such a page opts back out.
6583
+ // False at build: the call is answered by the backend's build process, where
6584
+ // there is one, and suspends where there is not. connection() is how a page
6585
+ // whose answer should not be stored opts out of the first.
6482
6586
  //
6483
6587
  // Asked of the caller rather than read from whatever host happens to be
6484
6588
  // installed, because those are different statements: a test that installed
@@ -6489,7 +6593,7 @@ export async function handleRscPprShell(
6489
6593
  // stored - but the caller no longer has to hold a slot for a render that
6490
6594
  // is doing nothing but watching a clock.
6491
6595
  onQuiet?: () => void,
6492
- ): Promise<{ shellHtml: string; clientChunks: unknown; timedOut: boolean; usedDynamicApis: boolean; error?: string }> {
6596
+ ): Promise<{ shellHtml: string; clientChunks: unknown; timedOut: boolean; usedDynamicApis: boolean; dynamicBecause: string[]; error?: string }> {
6493
6597
  // Deliberately no middleware here. The probe is asking whether the content is
6494
6598
  // the same for everyone, which is a question about the page. Whether a
6495
6599
  // particular caller may see it is a question about the request, and there is
@@ -6500,14 +6604,25 @@ export async function handleRscPprShell(
6500
6604
  await instrumented()
6501
6605
  applyHost()
6502
6606
 
6503
- const probe = (..._args: unknown[]) => {
6607
+ const hostCalls: string[] = []
6608
+
6609
+ const needsVisitor = (said: string): Promise<unknown> => {
6504
6610
  usedDynamicApis = true
6505
6611
 
6612
+ // Named, as the whole-page render names them: without it a page waiting
6613
+ // on rpc() was reported as one whose data was merely slow.
6614
+ if (!hostCalls.includes(said)) hostCalls.push(said)
6615
+
6506
6616
  // Never resolves: the awaiting component suspends and React renders its
6507
6617
  // Suspense fallback into the shell instead of the real content.
6508
6618
  return new Promise<unknown>(() => {})
6509
6619
  }
6510
6620
 
6621
+ // Asked of the backend when the build has one to ask: what is the same for
6622
+ // everyone is answered, and what read the visitor is a hole.
6623
+ const probe = (...args: unknown[]): Promise<unknown> =>
6624
+ buildAnswerer() ? answerAtBuild(args, needsVisitor) : needsVisitor(hostCallName(args))
6625
+
6511
6626
  let shellHtml = ''
6512
6627
  let completed = false
6513
6628
  let error: string | undefined
@@ -6515,7 +6630,7 @@ export async function handleRscPprShell(
6515
6630
 
6516
6631
  // The budget, declared before the error handler that consults it.
6517
6632
  const controller = new AbortController()
6518
- const budget = setTimeout(() => controller.abort(), budgetMs)
6633
+ const budget = buildBudget(budgetMs, () => controller.abort())
6519
6634
 
6520
6635
  // Quiet is a stretch with no Flight row: what is left is awaiting something,
6521
6636
  // and whether that something ever answers is what the budget decides. A
@@ -6526,11 +6641,17 @@ export async function handleRscPprShell(
6526
6641
  if (!onQuiet) return
6527
6642
  clearTimeout(quietTimer)
6528
6643
  quietTimer = setTimeout(() => {
6644
+ // Waiting for the backend is not quiet: its answer is work to come.
6645
+ if (awaitingBuildAnswer()) return
6646
+
6529
6647
  const told = onQuiet
6530
6648
  onQuiet = undefined
6531
6649
  told?.()
6532
6650
  }, PPR_QUIET_MS)
6533
6651
  }
6652
+ const stopListening = onBuildAnswer(() => {
6653
+ if (!awaitingBuildAnswer()) stir()
6654
+ })
6534
6655
  const watchForQuiet = (stream: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> => {
6535
6656
  if (!onQuiet) return stream
6536
6657
 
@@ -6657,7 +6778,8 @@ export async function handleRscPprShell(
6657
6778
  })
6658
6779
 
6659
6780
  await produce
6660
- clearTimeout(budget)
6781
+ budget.stop()
6782
+ stopListening()
6661
6783
  clearTimeout(quietTimer)
6662
6784
 
6663
6785
  // timedOut used to mean the stopwatch ran out. It now means React has
@@ -6669,6 +6791,7 @@ export async function handleRscPprShell(
6669
6791
  clientChunks: {},
6670
6792
  timedOut: postponed !== null,
6671
6793
  usedDynamicApis,
6794
+ dynamicBecause: hostCalls,
6672
6795
  error,
6673
6796
  postponed,
6674
6797
  renderFailure,
@@ -7461,7 +7584,10 @@ function validateLoadingBoundaries() {
7461
7584
  const pageDir = dirname(c.absPath);
7462
7585
  const source = readFileSync(c.absPath, "utf-8");
7463
7586
  let reason = null;
7464
- if (pageBlocksOnHostCall(source)) {
7587
+ // Only a guess, and wrong where the build asks the backend: the page waits
7588
+ // for an answer that is stored with it. One that needs a visitor is refused
7589
+ // by its own render, which names the call.
7590
+ if (!hostCallsCommand && pageBlocksOnHostCall(source)) {
7465
7591
  reason = `its default export awaits ${hostGlobal}()`;
7466
7592
  }
7467
7593
  else {
@@ -9202,9 +9328,23 @@ export function rscKit(options = {}) {
9202
9328
  // the stub was not there to import. Any event: the file appears on a
9203
9329
  // first action, changes on the next, and goes when the last is removed.
9204
9330
  const hostActionsPath = join(projectRoot, HOST_FILE);
9331
+ // What this server was started from, rather than what was last read:
9332
+ // the watch below reads the file itself, before this hears of it.
9333
+ let servedManifest = hostFileText;
9205
9334
  const hostActionsChanged = (file) => {
9206
- if (file !== hostActionsPath || hostFileOnDisk() === hostFileText)
9335
+ if (file !== hostActionsPath)
9336
+ return;
9337
+ const now = hostFileOnDisk();
9338
+ if (now === servedManifest)
9207
9339
  return;
9340
+ const moved = withoutSources(now) === withoutSources(servedManifest);
9341
+ servedManifest = now;
9342
+ // Only where the functions are: nothing the server renders with.
9343
+ if (moved) {
9344
+ loadHostManifest(options);
9345
+ writeHostGlobalTypes();
9346
+ return;
9347
+ }
9208
9348
  server.config.logger.info(`[rsc-kit] ${relative(projectRoot, file)} changed — restarting`);
9209
9349
  restartOnce(server);
9210
9350
  };