@rsc-kit/core 0.42.1 → 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));
@@ -2205,7 +2227,24 @@ export function smallStylesheetReader(assetsDir, setting) {
2205
2227
  }
2206
2228
  };
2207
2229
  }
2208
- 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 = []) {
2209
2248
  // A missing bundle used to be a silent `return`, and under Nitro it was the
2210
2249
  // normal case: the path was assumed to be <outDir>/dist/rsc/index.js, Nitro
2211
2250
  // builds the rsc environment somewhere else entirely, and so every Nitro app
@@ -2217,7 +2256,7 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir, knownActions
2217
2256
  throw new Error("[rsc-kit] The build produced no rsc bundle to prerender from.\n" +
2218
2257
  "Prerendering renders the app, so it needs the bundle the build just wrote.");
2219
2258
  }
2220
- 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([
2221
2260
  import("./prerender.js"),
2222
2261
  import("./files.js"),
2223
2262
  import("./apiPrerender.js"),
@@ -2434,9 +2473,8 @@ ${legend(counted)}
2434
2473
  throw new Error(refusal.message);
2435
2474
  if (failed > 0) {
2436
2475
  throw new Error(`[rsc-kit] ${failed} route${failed === 1 ? "" : "s"} failed to render.\n` +
2437
- "Prerendering runs your app: whatever those pages need at render time has to be\n" +
2438
- "reachable from the build. Give it that, or mark the read with `await connection()`\n" +
2439
- "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")));
2440
2478
  }
2441
2479
  // The urls whose answer cannot change until the next build. The service
2442
2480
  // worker serves these from its cache first rather than asking the network
@@ -2868,50 +2906,6 @@ function formType(sig) {
2868
2906
  const literal = (name) => (name.includes("${") ? "`" + name + "`" : JSON.stringify(name));
2869
2907
  return "FormFields<" + [...new Set(names)].map(literal).join(" | ") + ">";
2870
2908
  }
2871
- /**
2872
- * A form posted to a backend action. React hands the action a FormData; on
2873
- * the wire to the backend it is JSON, and JSON.stringify of a FormData is {} -
2874
- * so a form posting straight to a backend action used to send nothing. Its
2875
- * fields become one object, typed by the first parameter where the backend
2876
- * described it: numbers and booleans coerced, a repeated name a list.
2877
- */
2878
- const FORM_ARGS = `function formArgs(args: unknown[], schemas: (Record<string, any> | null)[]): unknown[] {
2879
- // The form is the last argument, and it fills the parameter it lands on: the
2880
- // first when the action takes nothing before it, the one after the team when
2881
- // that was bound with stub.bind(null, team).
2882
- const at = args.length - 1
2883
-
2884
- if (at < 0 || !(args[at] instanceof FormData)) return args
2885
-
2886
- const form = args[at] as FormData
2887
- const schema = schemas[at] ?? null
2888
- const props: Record<string, any> = schema?.properties ?? {}
2889
- const coerce = (type: unknown, v: string): unknown =>
2890
- type === 'integer' || type === 'number' ? (v === '' ? null : Number(v))
2891
- : type === 'boolean' ? v === 'on' || v === 'true' || v === '1'
2892
- : v
2893
- const out: Record<string, unknown> = {}
2894
-
2895
- for (const key of new Set(form.keys())) {
2896
- // React's own fields for a form action, not the form's.
2897
- if (key.startsWith('$ACTION_')) continue
2898
-
2899
- const values = form.getAll(key).filter((v): v is string => typeof v === 'string')
2900
- const prop = props[key]
2901
-
2902
- out[key] = prop?.type === 'array' || (!prop && values.length > 1)
2903
- ? values.map((v) => coerce(prop?.items?.type, v))
2904
- : coerce(prop?.type, values[0] ?? '')
2905
- }
2906
-
2907
- // An unchecked checkbox sends nothing: false, not missing.
2908
- for (const [key, prop] of Object.entries(props)) {
2909
- if (!(key in out) && prop?.type === 'boolean') out[key] = false
2910
- }
2911
-
2912
- return [...args.slice(0, at), out]
2913
- }
2914
- `;
2915
2909
  /**
2916
2910
  * One class's "use server" module: each host function a plain async call. An
2917
2911
  * __invoke is the default export, and a method JavaScript reserves the name
@@ -2922,10 +2916,9 @@ function renderHostActions(module) {
2922
2916
  const exportsOf = hostActions[module] ?? {};
2923
2917
  const taken = new Set(Object.keys(exportsOf));
2924
2918
  const renamed = [];
2925
- // Type-only, so the module stays what "use server" allows: functions.
2926
- lines.push('import type { Redirected } from "@rsc-kit/core/errors";');
2927
- lines.push('import type { FormFields } from "@rsc-kit/core/form";', "");
2928
- 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;
2929
2922
  for (const [exported, target] of Object.entries(exportsOf)) {
2930
2923
  const sig = hostTypes[target];
2931
2924
  // The default's own name is the module's - send-invite, sendInvite - so a
@@ -2970,8 +2963,42 @@ function renderHostActions(module) {
2970
2963
  }
2971
2964
  if (renamed.length > 0)
2972
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, "");
2973
2974
  return lines.join("\n");
2974
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";
2975
3002
  /** Ambient declaration for the host global, written beside the app's source. */
2976
3003
  function renderHostGlobalTypes() {
2977
3004
  return [
@@ -3013,6 +3040,11 @@ function renderHostSignatures() {
3013
3040
  for (const name of typed) {
3014
3041
  const sig = hostTypes[name];
3015
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("*/", "* /") + " */");
3016
3048
  out.push("declare function " + hostGlobal + "<T = " + (sig.result ? tsOf(sig.result) : "void") + ">(name: " +
3017
3049
  JSON.stringify(name) + (params ? ", " + params : "") + "): Promise<T>;");
3018
3050
  }
@@ -3422,36 +3454,46 @@ function rootMetadataBase(appDir) {
3422
3454
  return match ? match[1] : null;
3423
3455
  }
3424
3456
  /**
3425
- * Whether a route file exports this name, in any of the ways TypeScript
3426
- * 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
3427
3459
  * `generateMetadata: GenerateMetadata` - or a list, `export { x as name }` or
3428
3460
  * `export { name } from`. Only the function form was read once, and a page
3429
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.
3430
3466
  */
3431
- function exportsName(src, name) {
3432
- if (new RegExp(`export\\s+(?:async\\s+)?function\\s*\\*?\\s*${name}\\b`).test(src))
3433
- return true;
3434
- if (new RegExp(`export\\s+(?:const|let|var)\\s+${name}\\b`).test(src))
3435
- return true;
3436
- // A list exports the name after `as`, or the name itself; `export type {}`
3437
- // and a `type` entry export no value.
3438
- for (const [list, names] of Array.from(src.matchAll(/export\s+(type\s+)?\{([^}]*)\}/g), (m) => [m[1], m[2]])) {
3439
- 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")
3440
3471
  continue;
3441
- for (const raw of names.split(",")) {
3442
- const entry = raw.trim();
3443
- if (!entry.startsWith("type ") && entry.split(/\s+as\s+/).pop() === name)
3444
- return true;
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)
3478
+ continue;
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
+ }
3445
3486
  }
3446
3487
  }
3447
- return false;
3488
+ return names;
3448
3489
  }
3449
3490
  function metadataExports(absPath) {
3450
3491
  const src = readFileSync(absPath, "utf-8");
3492
+ const names = exportedNames(absPath);
3451
3493
  return {
3452
- static: exportsName(src, "metadata"),
3453
- generate: exportsName(src, "generateMetadata"),
3454
- viewport: exportsName(src, "viewport"),
3494
+ static: names.has("metadata"),
3495
+ generate: names.has("generateMetadata"),
3496
+ viewport: names.has("viewport"),
3455
3497
  writes: {
3456
3498
  charset: /\bcharSet\s*=/.test(src),
3457
3499
  viewport: /name\s*=\s*["']viewport["']/.test(src),
@@ -3497,7 +3539,7 @@ export function revalidateOf(files) {
3497
3539
  function topLevel(file) {
3498
3540
  const src = readFileSync(file, "utf-8");
3499
3541
  const ext = file.slice(file.lastIndexOf(".") + 1);
3500
- const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : "js";
3542
+ const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : ext === "mts" ? "ts" : "js";
3501
3543
  return { body: parseAst(src, { lang }).body, src };
3502
3544
  }
3503
3545
  function exportedDeclarations(body) {
@@ -3839,14 +3881,13 @@ function instrumentationFile() {
3839
3881
  // exists - a namespace import's missing member is a bundler warning on
3840
3882
  // every build (IMPORT_IS_UNDEFINED), which is the app being told off for
3841
3883
  // a file written exactly as documented.
3842
- const source = readFileSync(file, "utf-8");
3843
- 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);
3844
3885
  return {
3845
3886
  file,
3846
- hasRegister: exports("register"),
3847
- hasShutdown: exports("shutdown"),
3848
- hasOnRequest: exports("onRequest"),
3849
- hasOnRequestHeaders: exports("onRequestHeaders"),
3887
+ hasRegister: names.has("register"),
3888
+ hasShutdown: names.has("shutdown"),
3889
+ hasOnRequest: names.has("onRequest"),
3890
+ hasOnRequestHeaders: names.has("onRequestHeaders"),
3850
3891
  };
3851
3892
  }
3852
3893
  return null;
@@ -3978,6 +4019,7 @@ import { cachingOf, finishCacheable, keptBodyOf } from ${JSON.stringify(join(pac
3978
4019
  import { inlineHashes, newNonce, policyHeaderName, policyValue } from ${JSON.stringify(join(packageDir, "csp"))}
3979
4020
  import { createRscHandler, notFoundRouteOf, pageSaidNotFound, queryAndParams } from ${JSON.stringify(join(packageDir, "host"))}
3980
4021
  import { backendHeaders, httpHostCalls } from ${JSON.stringify(join(packageDir, "hostCalls"))}
4022
+ import { answerAtBuild, awaitingBuildAnswer, buildAnswerer, buildBudget, onBuildAnswer } from ${JSON.stringify(join(packageDir, "buildScope"))}
3981
4023
  import { backendVersions, installBackendVersionSource } from ${JSON.stringify(join(packageDir, "changed"))}
3982
4024
  import { RefreshOn } from ${JSON.stringify(join(packageDir, "js/refreshOn"))}
3983
4025
  import { prerenderedBeside } from ${JSON.stringify(join(packageDir, "files"))}
@@ -4533,7 +4575,9 @@ function applyHost() {
4533
4575
  // that reaches is a question about the render it is inside.
4534
4576
  //
4535
4577
  ;(globalThis as Record<string, unknown>)[HOST_GLOBAL] = (...args: unknown[]) => {
4536
- 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)
4537
4581
 
4538
4582
  // An optional call was here, and it answered every rpc() with undefined
4539
4583
  // when no host was installed. undefined is a value: the component renders
@@ -6302,6 +6346,12 @@ export async function resolveMetadata(
6302
6346
  return merged
6303
6347
  }
6304
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
+
6305
6355
  // Buffered render (worker: rsc / rscWithoutCallbacks — used at prerender time).
6306
6356
  export async function handleRsc(
6307
6357
  component: string,
@@ -6328,19 +6378,22 @@ export async function handleRsc(
6328
6378
  let usedDynamicApis = false
6329
6379
  const hostCalls: string[] = []
6330
6380
 
6331
- const probe = (...args: unknown[]) => {
6381
+ const needsVisitor = (said: string, build = false): Promise<never> => {
6332
6382
  usedDynamicApis = true
6333
6383
 
6334
- // The name it was called with, so the build can say rpc("getUser") rather
6335
- // than "this page reached for the host" and leave you to find which call.
6336
- const name = typeof args[0] === 'string' ? args[0] : null
6337
- const said = name ? 'rpc(' + JSON.stringify(name) + ')' : 'rpc()'
6338
-
6339
6384
  if (!hostCalls.includes(said)) hostCalls.push(said)
6340
6385
 
6341
- 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>(() => {})
6342
6392
  }
6343
6393
 
6394
+ const probe = (...args: unknown[]): Promise<unknown> =>
6395
+ buildAnswerer() ? answerAtBuild(args, (said) => needsVisitor(said, true)) : needsVisitor(hostCallName(args))
6396
+
6344
6397
  // Not a generic arrow function: this file is generated as .tsx, where <T>
6345
6398
  // parses as JSX and the build fails on a tag it cannot close.
6346
6399
  const runWith = canReachHost
@@ -6365,6 +6418,7 @@ export async function handleRsc(
6365
6418
  rscPayload,
6366
6419
  clientChunks: {},
6367
6420
  usedDynamicApis,
6421
+ dynamicBecause: hostCalls,
6368
6422
  // Client reference rows name the components the browser has to run. Shipping
6369
6423
  // no runtime would leave them as inert markup, so the host refuses — and
6370
6424
  // says which components forced the decision, since they are usually in a
@@ -6526,15 +6580,9 @@ export async function handleRscPprShell(
6526
6580
  budgetMs = PPR_SHELL_TIMEOUT_MS,
6527
6581
  // Whether this build can answer host calls.
6528
6582
  //
6529
- // False is the old and still the usual answer: the stub suspends, and a page
6530
- // reaching for its host becomes a shell rather than freezing data fetched
6531
- // once at build time.
6532
- //
6533
- // A host that opened a callback socket for the build says true, and then the
6534
- // call is made and its answer stored. That is the only way a page whose data
6535
- // lives in the host can be static at all, since a host call is its only route
6536
- // to that data — and
6537
- // 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.
6538
6586
  //
6539
6587
  // Asked of the caller rather than read from whatever host happens to be
6540
6588
  // installed, because those are different statements: a test that installed
@@ -6545,7 +6593,7 @@ export async function handleRscPprShell(
6545
6593
  // stored - but the caller no longer has to hold a slot for a render that
6546
6594
  // is doing nothing but watching a clock.
6547
6595
  onQuiet?: () => void,
6548
- ): 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 }> {
6549
6597
  // Deliberately no middleware here. The probe is asking whether the content is
6550
6598
  // the same for everyone, which is a question about the page. Whether a
6551
6599
  // particular caller may see it is a question about the request, and there is
@@ -6556,14 +6604,25 @@ export async function handleRscPprShell(
6556
6604
  await instrumented()
6557
6605
  applyHost()
6558
6606
 
6559
- const probe = (..._args: unknown[]) => {
6607
+ const hostCalls: string[] = []
6608
+
6609
+ const needsVisitor = (said: string): Promise<unknown> => {
6560
6610
  usedDynamicApis = true
6561
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
+
6562
6616
  // Never resolves: the awaiting component suspends and React renders its
6563
6617
  // Suspense fallback into the shell instead of the real content.
6564
6618
  return new Promise<unknown>(() => {})
6565
6619
  }
6566
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
+
6567
6626
  let shellHtml = ''
6568
6627
  let completed = false
6569
6628
  let error: string | undefined
@@ -6571,7 +6630,7 @@ export async function handleRscPprShell(
6571
6630
 
6572
6631
  // The budget, declared before the error handler that consults it.
6573
6632
  const controller = new AbortController()
6574
- const budget = setTimeout(() => controller.abort(), budgetMs)
6633
+ const budget = buildBudget(budgetMs, () => controller.abort())
6575
6634
 
6576
6635
  // Quiet is a stretch with no Flight row: what is left is awaiting something,
6577
6636
  // and whether that something ever answers is what the budget decides. A
@@ -6582,11 +6641,17 @@ export async function handleRscPprShell(
6582
6641
  if (!onQuiet) return
6583
6642
  clearTimeout(quietTimer)
6584
6643
  quietTimer = setTimeout(() => {
6644
+ // Waiting for the backend is not quiet: its answer is work to come.
6645
+ if (awaitingBuildAnswer()) return
6646
+
6585
6647
  const told = onQuiet
6586
6648
  onQuiet = undefined
6587
6649
  told?.()
6588
6650
  }, PPR_QUIET_MS)
6589
6651
  }
6652
+ const stopListening = onBuildAnswer(() => {
6653
+ if (!awaitingBuildAnswer()) stir()
6654
+ })
6590
6655
  const watchForQuiet = (stream: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> => {
6591
6656
  if (!onQuiet) return stream
6592
6657
 
@@ -6713,7 +6778,8 @@ export async function handleRscPprShell(
6713
6778
  })
6714
6779
 
6715
6780
  await produce
6716
- clearTimeout(budget)
6781
+ budget.stop()
6782
+ stopListening()
6717
6783
  clearTimeout(quietTimer)
6718
6784
 
6719
6785
  // timedOut used to mean the stopwatch ran out. It now means React has
@@ -6725,6 +6791,7 @@ export async function handleRscPprShell(
6725
6791
  clientChunks: {},
6726
6792
  timedOut: postponed !== null,
6727
6793
  usedDynamicApis,
6794
+ dynamicBecause: hostCalls,
6728
6795
  error,
6729
6796
  postponed,
6730
6797
  renderFailure,
@@ -7517,7 +7584,10 @@ function validateLoadingBoundaries() {
7517
7584
  const pageDir = dirname(c.absPath);
7518
7585
  const source = readFileSync(c.absPath, "utf-8");
7519
7586
  let reason = null;
7520
- 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)) {
7521
7591
  reason = `its default export awaits ${hostGlobal}()`;
7522
7592
  }
7523
7593
  else {
@@ -9258,9 +9328,23 @@ export function rscKit(options = {}) {
9258
9328
  // the stub was not there to import. Any event: the file appears on a
9259
9329
  // first action, changes on the next, and goes when the last is removed.
9260
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;
9261
9334
  const hostActionsChanged = (file) => {
9262
- if (file !== hostActionsPath || hostFileOnDisk() === hostFileText)
9335
+ if (file !== hostActionsPath)
9263
9336
  return;
9337
+ const now = hostFileOnDisk();
9338
+ if (now === servedManifest)
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
+ }
9264
9348
  server.config.logger.info(`[rsc-kit] ${relative(projectRoot, file)} changed — restarting`);
9265
9349
  restartOnce(server);
9266
9350
  };