@rsc-kit/core 0.31.3 → 0.33.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
@@ -36,6 +36,7 @@ import { serverImportsOfClientPackages } from "./clientImports.js";
36
36
  import { automaticSitemap, METADATA_ROUTES, ROOT_FILES, rootFileType, } from "./metadataRoutes.js";
37
37
  import { ownHosts } from "./hostRouting.js";
38
38
  import { unrollBarrelImports } from "./barrelImports.js";
39
+ import { shadowedRootFileMessage, shadowedRootFiles } from "./shadowedRootFiles.js";
39
40
  import { hasUseSsr, serverRendererMessage, SERVER_RENDERER, ssrProxyModule, UseSsrError, withoutSsrDirective } from "./useSsr.js";
40
41
  import { backendHeaders, httpHostCalls } from "./hostCalls.js";
41
42
  import { BARE_COMMANDS_ENVIRONMENT, BARE_COMMANDS_MODULE_ID, COMMANDS_MODULE_ID, bareCommandsModule, commandFiles, commandsEntry, commandsEntrySource, commandsModule, compileEntryWithCommands } from "./commandFiles.js";
@@ -912,6 +913,9 @@ function routeManifest() {
912
913
  ...revalidateOf([...layouts, name].map((n) => components.get(n).absPath)),
913
914
  });
914
915
  }
916
+ const clash = samePageUrl(routes);
917
+ if (clash)
918
+ throw new Error(clash);
915
919
  // What the build decided, for a host that has to act on it afterwards —
916
920
  // writing the site out, and knowing which filename the client will ask for.
917
921
  return {
@@ -2265,6 +2269,30 @@ async function exportAfterPrerender(results, staticDir, assetsDir) {
2265
2269
  throw new Error(`[rsc-kit] ${error.message}`);
2266
2270
  }
2267
2271
  }
2272
+ /**
2273
+ * Two pages at one url. A route group adds nothing to the url, so
2274
+ * (home)/page.tsx and (preview)/(home)/page.tsx are both / - and the first
2275
+ * found answered while the other was never reached, with nothing said. A
2276
+ * parameter's name does not tell two urls apart either: [id] and [slug] in
2277
+ * one place match the same requests.
2278
+ */
2279
+ export function samePageUrl(routes) {
2280
+ const seen = new Map();
2281
+ for (const route of routes) {
2282
+ const key = route.segments
2283
+ .map((segment) => (segment.type === "static" ? `s:${segment.value}` : segment.type))
2284
+ .join("/");
2285
+ const first = seen.get(key);
2286
+ if (first) {
2287
+ const url = patternOf(route.segments.filter((segment) => segment.type !== "host"));
2288
+ return (`[rsc-kit] ${first} and ${route.component} are both the page at ${url}. ` +
2289
+ "A route group - a (name) directory - adds nothing to the url, so the two cannot be told apart. " +
2290
+ "Keep one, or give the other a directory that is part of the url.");
2291
+ }
2292
+ seen.set(key, route.component);
2293
+ }
2294
+ return null;
2295
+ }
2268
2296
  /** `/posts/[slug]` — the pattern, in the shape the app writes its links in. */
2269
2297
  function patternOf(segments) {
2270
2298
  if (segments.length === 0)
@@ -2812,6 +2840,8 @@ function openApiPlugin() {
2812
2840
  }
2813
2841
  /** Files beside the root layout served at the root as they are: robots.txt, a hand-written sitemap.xml, humans.txt. */
2814
2842
  let rootFiles = [];
2843
+ /** Shadowed root files already warned about, so a dev restart does not repeat them. */
2844
+ const saidShadowed = new Set();
2815
2845
  const METADATA_ROUTE_ID = "virtual:rsc-kit/metadata-route/";
2816
2846
  /**
2817
2847
  * robots.ts, sitemap.ts, llms.ts beside the root layout, each registered as
@@ -3094,21 +3124,59 @@ function metadataExports(absPath) {
3094
3124
  export function revalidateOf(files) {
3095
3125
  let smallest;
3096
3126
  for (const file of files) {
3097
- const src = readFileSync(file, "utf-8");
3098
- const declared = /export\s+const\s+revalidate\s*(?::[^=]+)?=\s*([^;\n]+)/.exec(src);
3127
+ const declared = exportedConst(file, "revalidate");
3099
3128
  if (!declared)
3100
3129
  continue;
3101
- const value = declared[1].trim().replace(/_/g, "");
3102
- if (!/^\d+$/.test(value)) {
3103
- throw new Error(`${file}: export const revalidate must be a number of seconds the build can read, like 60. Found: ${declared[1].trim()}`);
3130
+ const value = unwrapTypes(declared.init);
3131
+ if (value?.type !== "Literal" || typeof value.value !== "number" || !Number.isInteger(value.value) || value.value < 0) {
3132
+ throw new Error(`${file}: export const revalidate must be a number of seconds the build can read, like 60. Found: ${declared.source}`);
3104
3133
  }
3105
- smallest = Math.min(smallest ?? Infinity, Number(value));
3134
+ smallest = Math.min(smallest ?? Infinity, value.value);
3106
3135
  }
3107
3136
  return smallest ? { revalidate: smallest } : {};
3108
3137
  }
3138
+ /**
3139
+ * A module's top-level statements, parsed - not its text. A regex over the
3140
+ * source matched `export const revalidate = 60` written as prose in a page's
3141
+ * JSX, in a comment, in a string, and failed the build on a page that
3142
+ * declared nothing.
3143
+ */
3144
+ function topLevel(file) {
3145
+ const src = readFileSync(file, "utf-8");
3146
+ const ext = file.slice(file.lastIndexOf(".") + 1);
3147
+ const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : "js";
3148
+ return { body: parseAst(src, { lang }).body, src };
3149
+ }
3150
+ function exportedDeclarations(body) {
3151
+ return body.filter((node) => node.type === "ExportNamedDeclaration" && node.declaration).map((node) => node.declaration);
3152
+ }
3153
+ /** `export const <name> = …`: its initialiser, and the text of it for a message. */
3154
+ function exportedConst(file, name) {
3155
+ const { body, src } = topLevel(file);
3156
+ for (const declaration of exportedDeclarations(body)) {
3157
+ if (declaration.type !== "VariableDeclaration")
3158
+ continue;
3159
+ for (const declarator of declaration.declarations) {
3160
+ if (declarator.id?.type === "Identifier" && declarator.id.name === name) {
3161
+ const init = declarator.init ?? null;
3162
+ return { init, source: init ? src.slice(init.start, init.end) : "nothing" };
3163
+ }
3164
+ }
3165
+ }
3166
+ return null;
3167
+ }
3168
+ /** `60 as const`, `60 satisfies number`, `(60)`: the value under them. */
3169
+ function unwrapTypes(node) {
3170
+ while (node && ["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "ParenthesizedExpression"].includes(node.type)) {
3171
+ node = node.expression;
3172
+ }
3173
+ return node;
3174
+ }
3109
3175
  function hasStaticParams(absPath) {
3110
- const src = readFileSync(absPath, "utf-8");
3111
- return /export\s+((async\s+)?function\s+generateStaticParams|const\s+generateStaticParams)/.test(src);
3176
+ return exportedDeclarations(topLevel(absPath).body).some((declaration) => declaration.type === "FunctionDeclaration"
3177
+ ? declaration.id?.name === "generateStaticParams"
3178
+ : declaration.type === "VariableDeclaration" &&
3179
+ declaration.declarations.some((d) => d.id?.type === "Identifier" && d.id.name === "generateStaticParams"));
3112
3180
  }
3113
3181
  /**
3114
3182
  * Which url schemas a page exports.
@@ -3566,6 +3634,8 @@ import { isActionValidationError, isActionRefusal, isClientBuilt, turnedAwayStat
3566
3634
  import { forgetCached } from ${JSON.stringify(join(packageDir, "cache"))}
3567
3635
  import { noteFallback as noteCaughtRead } from ${JSON.stringify(join(packageDir, "request"))}
3568
3636
  import { isOutdatedOptimizedDep, outdatedDepResponse } from ${JSON.stringify(join(packageDir, "devReload"))}
3637
+ import { devActionErrorResponse, isActionCall } from ${JSON.stringify(join(packageDir, "devActionError"))}
3638
+ import { sayUnroutedHost } from ${JSON.stringify(join(packageDir, "hostRouting"))}
3569
3639
  import { paramsFor, segmentNames, sharedDepth } from ${JSON.stringify(join(packageDir, "routing"))}
3570
3640
  import { Suspense, createElement, Fragment } from 'react'
3571
3641
  import { AsyncLocalStorage } from 'node:async_hooks'
@@ -6311,6 +6381,15 @@ async function served(request: Request): Promise<Response> {
6311
6381
  // is over already; the page is asked to load again.
6312
6382
  if (import.meta.env.DEV && isOutdatedOptimizedDep(error)) return outdatedDepResponse(request)
6313
6383
 
6384
+ // A failed action, in development: its error and the backend's frames,
6385
+ // for the browser's overlay. Left to the server's generic 500 the page
6386
+ // said nothing, and the cause was in the terminal. Still printed there.
6387
+ if (import.meta.env.DEV && isActionCall(request)) {
6388
+ console.error(error)
6389
+
6390
+ return devActionErrorResponse(error)
6391
+ }
6392
+
6314
6393
  throw error
6315
6394
  }
6316
6395
  }
@@ -6353,6 +6432,7 @@ async function serve(request: Request): Promise<Response> {
6353
6432
  } as never,
6354
6433
  ${NITRO_HANDLER_OPTIONS}${NITRO_PRERENDERED} maxActionBody: ${maxActionBody === undefined ? "undefined" : String(maxActionBody)},
6355
6434
  trustedOrigins: ${JSON.stringify(trustedOrigins ?? [])},
6435
+ onUnroutedHost: import.meta.env.DEV ? sayUnroutedHost : undefined,
6356
6436
  })
6357
6437
 
6358
6438
  ${fallbackOrigin === false ? NO_FALLBACK_BODY : FALLBACK_BODY}}
@@ -6539,6 +6619,7 @@ import { isNotFoundDigest } from ${JSON.stringify(notFoundModule)}
6539
6619
  import { EARLY_CLICKS } from ${JSON.stringify(earlyClicks)}
6540
6620
  import { READ_BLOCKS } from ${JSON.stringify(inlineFlightModule)}
6541
6621
  import { searchSnapshotContext } from ${JSON.stringify(join(packageDir, "js/useSearchParams"))}
6622
+ import { nonceContext } from ${JSON.stringify(join(packageDir, "js/useNonce"))}
6542
6623
  import { createElement as h } from 'react'
6543
6624
  ${webManifestOptions ? `import { INSTALL_CAPTURE } from ${JSON.stringify(installCapture)}` : ""}
6544
6625
 
@@ -6596,8 +6677,15 @@ function decodedBy(stream: ReadableStream): unknown {
6596
6677
  * its holes resumed per request must be the same tree, or React cannot line
6597
6678
  * them up.
6598
6679
  */
6599
- function withSearch(root: unknown, search: string | null | undefined): unknown {
6600
- return h(searchSnapshotContext().Provider, { value: search ?? null }, root as any)
6680
+ function withSearch(root: unknown, search: string | null | undefined, nonce?: string): unknown {
6681
+ // And the response's nonce, for useNonce(): undefined where the HTML may
6682
+ // be stored, which is allowed by hash instead. Always wrapped, for the
6683
+ // same reason.
6684
+ return h(
6685
+ searchSnapshotContext().Provider,
6686
+ { value: search ?? null },
6687
+ h(nonceContext().Provider, { value: nonce }, root as any),
6688
+ )
6601
6689
  }
6602
6690
 
6603
6691
  export async function handleSsr(
@@ -6614,7 +6702,7 @@ export async function handleSsr(
6614
6702
  // Declared here so the runtime knows before its first chunk arrives.
6615
6703
  inline = false,
6616
6704
  ): Promise<ReadableStream> {
6617
- const root = withSearch(decodedBy(rscStream), search)
6705
+ const root = withSearch(decodedBy(rscStream), search, nonce)
6618
6706
 
6619
6707
  // Without the bootstrap the page ships no client runtime at all: no React,
6620
6708
  // no Flight client, no router. HTML only. A page with nothing interactive on
@@ -6779,7 +6867,7 @@ export async function handleSsrResume(
6779
6867
  ): Promise<ReadableStream> {
6780
6868
  // The same tree the shell was prerendered with, now holding this
6781
6869
  // request's query: the holes are filled per request.
6782
- const root = withSearch(decodedBy(rscStream), search)
6870
+ const root = withSearch(decodedBy(rscStream), search, nonce)
6783
6871
 
6784
6872
  const html = await resume(root as any, postponed as any, {
6785
6873
  nonce: nonce ? { script: nonce, style: nonce } : undefined,
@@ -6838,6 +6926,7 @@ function generateEntryBrowser() {
6838
6926
  : null;
6839
6927
  const refreshModule = join(packageDir, "js/navigate");
6840
6928
  const chunkPreload = join(packageDir, "js/chunkPreload");
6929
+ const devErrorOverlay = join(packageDir, "js/devErrorOverlay");
6841
6930
  return `// GENERATED by rscKit() — do not edit.
6842
6931
  import { createViteRscApp } from ${JSON.stringify(clientBootstrap)}
6843
6932
  import { refresh } from ${JSON.stringify(refreshModule)}
@@ -6853,6 +6942,13 @@ if (import.meta.env.PROD) {
6853
6942
  setChunkLoader((id) => references[id]?.())
6854
6943
  }
6855
6944
 
6945
+ // A failed server action, on the page as Vite's error overlay - development
6946
+ // only, and loaded only there: removed from a production build with the
6947
+ // branch it is in.
6948
+ if (import.meta.env.DEV) {
6949
+ void import(${JSON.stringify(devErrorOverlay)}).then((overlay) => overlay.installDevActionErrors())
6950
+ }
6951
+
6856
6952
  createViteRscApp(document, ${JSON.stringify(interceptManifest())}, ${JSON.stringify({
6857
6953
  staticPayloads: staticPayloads || null,
6858
6954
  routes: routesForClient,
@@ -8102,6 +8198,16 @@ export function rscKit(options = {}) {
8102
8198
  discover(appDir);
8103
8199
  registerMetadataRoutes(appDir);
8104
8200
  registerOpenApiRoutes();
8201
+ // A file in public/ answered in place of the app's own - Laravel's
8202
+ // empty favicon.ico and robots.txt. Once per message: this hook runs
8203
+ // again on every dev restart.
8204
+ for (const shadowed of shadowedRootFiles(appDir, join(projectRoot, "public"))) {
8205
+ const message = shadowedRootFileMessage(shadowed, projectRoot);
8206
+ if (!saidShadowed.has(message)) {
8207
+ saidShadowed.add(message);
8208
+ console.warn(message);
8209
+ }
8210
+ }
8105
8211
  siteHosts = ownHosts(rootMetadataBase(appDir), hostsOption);
8106
8212
  // Silent when it worked. The names were printed on every dev start and
8107
8213
  // every build — thirty of them for a middling app, above the output that