@rsc-kit/core 0.14.0 → 0.15.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
@@ -18,7 +18,7 @@ import { createHash } from 'node:crypto';
18
18
  import { createRequire } from 'node:module';
19
19
  import { dirname, join, relative, resolve } from 'node:path';
20
20
  import { fileURLToPath, pathToFileURL } from 'node:url';
21
- import rsc from '@vitejs/plugin-rsc';
21
+ import rsc, { getPluginApi } from '@vitejs/plugin-rsc';
22
22
  import { loadEnv } from 'vite';
23
23
  import { REPORT_FILE, buildReport } from './buildReport.js';
24
24
  import { MANIFEST_PATH, manifestWarning, webManifest } from './webManifest.js';
@@ -1009,7 +1009,37 @@ function resolveRscBundle(dir) {
1009
1009
  }
1010
1010
  return null;
1011
1011
  }
1012
- async function prerenderAfterBundles(bundle, staticDir, assetsDir) {
1012
+ /**
1013
+ * Every server action the bundle registered, from the plugin's own table.
1014
+ *
1015
+ * Only the app's: the engine registers a few of its own and they are not the
1016
+ * project's to be warned about.
1017
+ */
1018
+ function knownActionsOf(config, root) {
1019
+ const api = getPluginApi(config);
1020
+ const metaMap = api?.manager?.serverReferences?.metaMap;
1021
+ if (!metaMap)
1022
+ return [];
1023
+ const out = [];
1024
+ for (const meta of metaMap.values()) {
1025
+ if (meta.importId.includes('/node_modules/'))
1026
+ continue;
1027
+ const file = relative(root, meta.importId.split('?')[0] ?? meta.importId);
1028
+ for (const name of meta.exportNames) {
1029
+ out.push({ id: `${meta.referenceKey}#${name}`, name, file });
1030
+ }
1031
+ }
1032
+ return out;
1033
+ }
1034
+ async function auditActions(engine, known) {
1035
+ const audit = engine
1036
+ .auditActions;
1037
+ if (!audit || known.length === 0)
1038
+ return [];
1039
+ const byId = new Map(known.map((k) => [k.id, k]));
1040
+ return (await audit(known.map((k) => k.id))).map((a) => ({ ...byId.get(a.id), client: a.client, query: a.query }));
1041
+ }
1042
+ async function prerenderAfterBundles(bundle, staticDir, assetsDir, knownActions = []) {
1013
1043
  // A missing bundle used to be a silent `return`, and under Nitro it was the
1014
1044
  // normal case: the path was assumed to be <outDir>/dist/rsc/index.js, Nitro
1015
1045
  // builds the rsc environment somewhere else entirely, and so every Nitro app
@@ -1022,7 +1052,7 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir) {
1022
1052
  'Prerendering renders the app, so it needs the bundle the build just wrote. ' +
1023
1053
  'Build with prerender: false to render every page on demand instead.');
1024
1054
  }
1025
- const [{ prerender, summary, legend, notes, clientJsSize, pathKey: pathKeyOf }, { writeTo }, { prerenderApiRoutes },] = await Promise.all([
1055
+ const [{ prerender, NotPrerenderable, summary, legend, notes, clientJsSize, pathKey: pathKeyOf }, { writeTo }, { prerenderApiRoutes },] = await Promise.all([
1026
1056
  import('./prerender.js'),
1027
1057
  import('./files.js'),
1028
1058
  import('./apiPrerender.js'),
@@ -1032,36 +1062,56 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir) {
1032
1062
  // Nothing warns — the page loads, with content from the previous build.
1033
1063
  rmSync(staticDir, { recursive: true, force: true });
1034
1064
  const engine = (await import(pathToFileURL(bundle).href));
1035
- const mark = { frozen: '○', shell: '◐', blocked: 'ƒ', error: '✗' };
1065
+ const mark = { frozen: '○', shell: '◐', blocked: '✗', error: '✗' };
1036
1066
  let failed = 0;
1037
1067
  // Weighed from the page the prerenderer just wrote, so the column is what
1038
1068
  // that page actually loads rather than a total every route is charged for.
1039
1069
  const weigh = weighClientJs(assetsDir);
1040
1070
  const sized = new Map();
1041
1071
  const pending = [];
1042
- const results = await prerender({
1043
- engine,
1044
- write: writeTo(staticDir),
1045
- onResult: (r) => {
1046
- if (r.type === 'error')
1047
- failed++;
1048
- const key = pathKeyOf(r.url);
1049
- const file = [`${key}.html`, `${key}.ppr.html`]
1050
- .map((name) => join(staticDir, name))
1051
- .find((path) => existsSync(path));
1052
- const bytes = file ? weigh(readFileSync(file, 'utf-8')) : null;
1053
- if (bytes !== null)
1054
- sized.set(r.url, bytes);
1055
- pending.push({
1056
- line: ` ${mark[r.type] ?? ' '} ${r.url}`,
1057
- bytes,
1058
- extra: [
1059
- ...(r.reason ? [` ${r.reason}`] : []),
1060
- ...(r.warning ? [` ⚠ ${r.warning}`] : []),
1061
- ],
1062
- });
1063
- },
1064
- });
1072
+ // Every result as it lands, so a refusal still has the whole table.
1073
+ //
1074
+ // prerender() throws NotPrerenderable when a page blocked above every
1075
+ // boundary, and it used to throw past everything below: no table printed,
1076
+ // no report written. The terminal got the advice; the report on disk was
1077
+ // the previous build's, and an agent reading it through the MCP server was
1078
+ // told the routes were fine, as of some minutes ago. A build that refuses
1079
+ // is the build an agent most needs written down.
1080
+ const collected = [];
1081
+ let refusal = null;
1082
+ let results;
1083
+ try {
1084
+ results = await prerender({
1085
+ engine,
1086
+ write: writeTo(staticDir),
1087
+ onResult: (r) => {
1088
+ collected.push(r);
1089
+ if (r.type === 'error' || r.type === 'blocked')
1090
+ failed++;
1091
+ const key = pathKeyOf(r.url);
1092
+ const file = [`${key}.html`, `${key}.ppr.html`]
1093
+ .map((name) => join(staticDir, name))
1094
+ .find((path) => existsSync(path));
1095
+ const bytes = file ? weigh(readFileSync(file, 'utf-8')) : null;
1096
+ if (bytes !== null)
1097
+ sized.set(r.url, bytes);
1098
+ pending.push({
1099
+ line: ` ${mark[r.type] ?? ' '} ${r.url}`,
1100
+ bytes,
1101
+ extra: [
1102
+ ...(r.reason ? [` ${r.reason}`] : []),
1103
+ ...(r.warning ? [` ⚠ ${r.warning}`] : []),
1104
+ ],
1105
+ });
1106
+ },
1107
+ });
1108
+ }
1109
+ catch (error) {
1110
+ if (!(error instanceof NotPrerenderable))
1111
+ throw error;
1112
+ refusal = error;
1113
+ results = collected;
1114
+ }
1065
1115
  // After the pages, sharing their output. An api route is a url the build
1066
1116
  // either answered or could not, which is the same question the table above
1067
1117
  // is already answering — a second list under its own heading would be two
@@ -1085,6 +1135,21 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir) {
1085
1135
  console.log(line);
1086
1136
  }
1087
1137
  const count = (type) => results.filter((r) => r.type === type).length;
1138
+ // The actions, after the routes. Which ones a client built is a mark on the
1139
+ // loaded function, so the bundle is asked; the answer is the one fact about
1140
+ // an action nothing else in the app states — whether anything checks who
1141
+ // calls it.
1142
+ const audited = await auditActions(engine, knownActions);
1143
+ const bare = audited.filter((a) => !a.client);
1144
+ if (bare.length > 0) {
1145
+ const byFile = new Map();
1146
+ for (const a of bare)
1147
+ byFile.set(a.file, [...(byFile.get(a.file) ?? []), a.name]);
1148
+ console.log(`\n \u26a0 ${bare.length} ${bare.length === 1 ? 'action runs' : 'actions run'} no middleware: ` +
1149
+ [...byFile].map(([file, names]) => `${names.join(', ')} (${file})`).join('; '));
1150
+ console.log(' Nothing checks who calls them. Fine for a public one; otherwise build it\n' +
1151
+ ' from an action client, so the check cannot be forgotten.');
1152
+ }
1088
1153
  // Written from the rows that were just printed rather than recomputed: the
1089
1154
  // report and the terminal must not be able to disagree about what happened.
1090
1155
  writeFileSync(join(outDir, REPORT_FILE), buildReport(results.map((r) => ({
@@ -1094,13 +1159,16 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir) {
1094
1159
  reason: r.reason,
1095
1160
  warning: r.warning ?? null,
1096
1161
  clientJs: sized.get(r.url) ?? null,
1097
- })), apis.map((a) => ({ url: a.url, name: a.name, type: a.type, reason: a.reason }))));
1162
+ })), apis.map((a) => ({ url: a.url, name: a.name, type: a.type, reason: a.reason })), audited));
1098
1163
  const note = notes(results);
1099
1164
  const counted = [...results, ...apis];
1100
1165
  console.log(`
1101
1166
  ${legend(counted)}
1102
1167
 
1103
1168
  ${summary(counted)}${note ? `\n\n${note}` : ''}`);
1169
+ // The table and the report are on disk. Now the refusal, in its own words.
1170
+ if (refusal)
1171
+ throw new Error(refusal.message);
1104
1172
  if (failed > 0) {
1105
1173
  throw new Error(`[rsc-kit] ${failed} route${failed === 1 ? '' : 's'} failed to render.\n` +
1106
1174
  'Prerendering runs your app: whatever those pages need at render time has to be\n' +
@@ -1241,6 +1309,19 @@ function patternOf(segments) {
1241
1309
  function renderRouteTypes(manifest) {
1242
1310
  const patterns = [...new Set(manifest.routes.map((route) => patternOf(route.segments)))].sort();
1243
1311
  const apis = [...new Set((manifest.apis ?? []).map((route) => patternOf(route.segments)))].sort();
1312
+ // Each pattern to the page module that answers it, as a type-only import
1313
+ // from the generated file's own directory. SearchExportOf reads the page's
1314
+ // `searchParams` export, or undefined when there is none, so nothing here
1315
+ // has to look inside the file - the typechecker already has every page
1316
+ // open. One line per route, and a page without a schema costs nothing.
1317
+ const search = new Map();
1318
+ for (const route of manifest.routes) {
1319
+ const pattern = patternOf(route.segments);
1320
+ if (search.has(pattern))
1321
+ continue;
1322
+ const target = relative(typesDir, join(sourceDir, route.component)).replace(/\\/g, '/');
1323
+ search.set(pattern, target.startsWith('.') ? target : './' + target);
1324
+ }
1244
1325
  return [
1245
1326
  '// @generated — do not edit. Written by the RSC build from the route tree.',
1246
1327
  '//',
@@ -1258,6 +1339,11 @@ function renderRouteTypes(manifest) {
1258
1339
  patterns.length > 0
1259
1340
  ? ' routes:\n' + patterns.map((p) => ' | ' + JSON.stringify(p)).join('\n')
1260
1341
  : ' // No routes found under the source directory.\n routes: never',
1342
+ // The searchParams schema each page exports, read off the module's type.
1343
+ // This is what types Link's `search` prop and href() per route.
1344
+ ' search: {',
1345
+ ...[...search].sort().map(([pattern, target]) => ' ' + JSON.stringify(pattern) + ': SearchExportOf<typeof import(' + JSON.stringify(target) + ')>'),
1346
+ ' }',
1261
1347
  ' }',
1262
1348
  // Api routes are a separate union, so Link refuses an api url and apiUrl()
1263
1349
  // refuses a page. Linking to an api route navigates the browser away to a
@@ -1679,6 +1765,7 @@ import { httpHostCalls } from ${JSON.stringify(join(packageDir, 'hostCalls'))}
1679
1765
  import { prerenderedBeside } from ${JSON.stringify(join(packageDir, 'files'))}
1680
1766
  import { renderToReadableStream, decodeReply, loadServerAction } from '@vitejs/plugin-rsc/rsc'
1681
1767
  import { isQuery, queryCacheControl, isQueryValidationError } from ${JSON.stringify(join(packageDir, 'query'))}
1768
+ import { isActionValidationError, isClientBuilt } from ${JSON.stringify(join(packageDir, 'action'))}
1682
1769
  import { Suspense, createElement, Fragment } from 'react'
1683
1770
  import { AsyncLocalStorage } from 'node:async_hooks'
1684
1771
  ${imports.join('\n')}
@@ -1872,6 +1959,31 @@ export function manifest(): any {
1872
1959
  return ${JSON.stringify(routeManifest())}
1873
1960
  }
1874
1961
 
1962
+ /**
1963
+ * For each server action id, whether a client built it. The build asks after
1964
+ * the bundle exists, because the answer is a mark on the loaded function and
1965
+ * nothing static could tell a wrapped export from a bare one.
1966
+ */
1967
+ export async function auditActions(ids: string[]): Promise<{ id: string; client: boolean; query: boolean }[]> {
1968
+ const out: { id: string; client: boolean; query: boolean }[] = []
1969
+
1970
+ for (const id of ids) {
1971
+ let fn: unknown = null
1972
+
1973
+ try {
1974
+ fn = await loadServerAction(id)
1975
+ } catch {
1976
+ continue
1977
+ }
1978
+
1979
+ if (typeof fn !== 'function') continue
1980
+
1981
+ out.push({ id, client: isClientBuilt(fn), query: isQuery(fn) })
1982
+ }
1983
+
1984
+ return out
1985
+ }
1986
+
1875
1987
  /**
1876
1988
  * The param sets a route declares, or null when it declares none.
1877
1989
  *
@@ -2914,7 +3026,20 @@ export async function handleAction(
2914
3026
  )
2915
3027
  }
2916
3028
 
2917
- const result = await (action as (...a: unknown[]) => unknown)(...args)
3029
+ // A plain "use server" function that threw fieldErrors() gets the same
3030
+ // treatment createActionClient gives its handlers: the throw becomes the
3031
+ // returned { validationErrors } that <Form> reads. Left thrown, React
3032
+ // serialises the rejection opaquely — production strips the message — and the
3033
+ // fields it named never reach the browser.
3034
+ let result: unknown
3035
+
3036
+ try {
3037
+ result = await (action as (...a: unknown[]) => unknown)(...args)
3038
+ } catch (error) {
3039
+ if (!isActionValidationError(error)) throw error
3040
+
3041
+ result = { validationErrors: error.errors }
3042
+ }
2918
3043
 
2919
3044
  // Read after the action has run: what it invalidated is only known once its
2920
3045
  // host calls have been made. Rendering here rather than telling the browser
@@ -4043,7 +4168,7 @@ export function rscKit(options = {}) {
4043
4168
  const staticDir = clientOut
4044
4169
  ? join(dirname(clientOut), 'server', NITRO_STATIC_DIR)
4045
4170
  : join(outDir, NITRO_STATIC_DIR);
4046
- const { frozen, results } = await prerenderAfterBundles(bundle, staticDir, clientOut ?? publicAssetsDir);
4171
+ const { frozen, results } = await prerenderAfterBundles(bundle, staticDir, clientOut ?? publicAssetsDir, builder ? knownActionsOf(builder.config, projectRoot) : []);
4047
4172
  // Manifest first. The service worker precaches whatever it finds in this
4048
4173
  // directory, so writing it afterwards leaves it out of the list — and an
4049
4174
  // installed app whose manifest is the one file that needs the network is