@rsc-kit/core 0.32.0 → 0.34.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,47 @@ 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
+ /**
2280
+ * The host hostUrl() puts a subdomain in front of: the first rscKit({ hosts })
2281
+ * entry, or a literal metadataBase's, as written - a port kept, for
2282
+ * localhost:8000 - with www. taken off. Null when neither names one.
2283
+ */
2284
+ export function siteHostOf(metadataBase, hosts) {
2285
+ let host = hosts[0]?.trim().toLowerCase() || null;
2286
+ if (!host && metadataBase) {
2287
+ try {
2288
+ host = new URL(String(metadataBase)).host;
2289
+ }
2290
+ catch {
2291
+ host = null;
2292
+ }
2293
+ }
2294
+ return host?.replace(/^www\./, "") || null;
2295
+ }
2296
+ export function samePageUrl(routes) {
2297
+ const seen = new Map();
2298
+ for (const route of routes) {
2299
+ const key = route.segments
2300
+ .map((segment) => (segment.type === "static" ? `s:${segment.value}` : segment.type))
2301
+ .join("/");
2302
+ const first = seen.get(key);
2303
+ if (first) {
2304
+ const url = patternOf(route.segments.filter((segment) => segment.type !== "host"));
2305
+ return (`[rsc-kit] ${first} and ${route.component} are both the page at ${url}. ` +
2306
+ "A route group - a (name) directory - adds nothing to the url, so the two cannot be told apart. " +
2307
+ "Keep one, or give the other a directory that is part of the url.");
2308
+ }
2309
+ seen.set(key, route.component);
2310
+ }
2311
+ return null;
2312
+ }
2268
2313
  /** `/posts/[slug]` — the pattern, in the shape the app writes its links in. */
2269
2314
  function patternOf(segments) {
2270
2315
  if (segments.length === 0)
@@ -2812,6 +2857,8 @@ function openApiPlugin() {
2812
2857
  }
2813
2858
  /** Files beside the root layout served at the root as they are: robots.txt, a hand-written sitemap.xml, humans.txt. */
2814
2859
  let rootFiles = [];
2860
+ /** Shadowed root files already warned about, so a dev restart does not repeat them. */
2861
+ const saidShadowed = new Set();
2815
2862
  const METADATA_ROUTE_ID = "virtual:rsc-kit/metadata-route/";
2816
2863
  /**
2817
2864
  * robots.ts, sitemap.ts, llms.ts beside the root layout, each registered as
@@ -3094,21 +3141,59 @@ function metadataExports(absPath) {
3094
3141
  export function revalidateOf(files) {
3095
3142
  let smallest;
3096
3143
  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);
3144
+ const declared = exportedConst(file, "revalidate");
3099
3145
  if (!declared)
3100
3146
  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()}`);
3147
+ const value = unwrapTypes(declared.init);
3148
+ if (value?.type !== "Literal" || typeof value.value !== "number" || !Number.isInteger(value.value) || value.value < 0) {
3149
+ throw new Error(`${file}: export const revalidate must be a number of seconds the build can read, like 60. Found: ${declared.source}`);
3104
3150
  }
3105
- smallest = Math.min(smallest ?? Infinity, Number(value));
3151
+ smallest = Math.min(smallest ?? Infinity, value.value);
3106
3152
  }
3107
3153
  return smallest ? { revalidate: smallest } : {};
3108
3154
  }
3155
+ /**
3156
+ * A module's top-level statements, parsed - not its text. A regex over the
3157
+ * source matched `export const revalidate = 60` written as prose in a page's
3158
+ * JSX, in a comment, in a string, and failed the build on a page that
3159
+ * declared nothing.
3160
+ */
3161
+ function topLevel(file) {
3162
+ const src = readFileSync(file, "utf-8");
3163
+ const ext = file.slice(file.lastIndexOf(".") + 1);
3164
+ const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : "js";
3165
+ return { body: parseAst(src, { lang }).body, src };
3166
+ }
3167
+ function exportedDeclarations(body) {
3168
+ return body.filter((node) => node.type === "ExportNamedDeclaration" && node.declaration).map((node) => node.declaration);
3169
+ }
3170
+ /** `export const <name> = …`: its initialiser, and the text of it for a message. */
3171
+ function exportedConst(file, name) {
3172
+ const { body, src } = topLevel(file);
3173
+ for (const declaration of exportedDeclarations(body)) {
3174
+ if (declaration.type !== "VariableDeclaration")
3175
+ continue;
3176
+ for (const declarator of declaration.declarations) {
3177
+ if (declarator.id?.type === "Identifier" && declarator.id.name === name) {
3178
+ const init = declarator.init ?? null;
3179
+ return { init, source: init ? src.slice(init.start, init.end) : "nothing" };
3180
+ }
3181
+ }
3182
+ }
3183
+ return null;
3184
+ }
3185
+ /** `60 as const`, `60 satisfies number`, `(60)`: the value under them. */
3186
+ function unwrapTypes(node) {
3187
+ while (node && ["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "ParenthesizedExpression"].includes(node.type)) {
3188
+ node = node.expression;
3189
+ }
3190
+ return node;
3191
+ }
3109
3192
  function hasStaticParams(absPath) {
3110
- const src = readFileSync(absPath, "utf-8");
3111
- return /export\s+((async\s+)?function\s+generateStaticParams|const\s+generateStaticParams)/.test(src);
3193
+ return exportedDeclarations(topLevel(absPath).body).some((declaration) => declaration.type === "FunctionDeclaration"
3194
+ ? declaration.id?.name === "generateStaticParams"
3195
+ : declaration.type === "VariableDeclaration" &&
3196
+ declaration.declarations.some((d) => d.id?.type === "Identifier" && d.id.name === "generateStaticParams"));
3112
3197
  }
3113
3198
  /**
3114
3199
  * Which url schemas a page exports.
@@ -3566,6 +3651,8 @@ import { isActionValidationError, isActionRefusal, isClientBuilt, turnedAwayStat
3566
3651
  import { forgetCached } from ${JSON.stringify(join(packageDir, "cache"))}
3567
3652
  import { noteFallback as noteCaughtRead } from ${JSON.stringify(join(packageDir, "request"))}
3568
3653
  import { isOutdatedOptimizedDep, outdatedDepResponse } from ${JSON.stringify(join(packageDir, "devReload"))}
3654
+ import { devActionErrorResponse, isActionCall } from ${JSON.stringify(join(packageDir, "devActionError"))}
3655
+ import { sayUnroutedHost } from ${JSON.stringify(join(packageDir, "hostRouting"))}
3569
3656
  import { paramsFor, segmentNames, sharedDepth } from ${JSON.stringify(join(packageDir, "routing"))}
3570
3657
  import { Suspense, createElement, Fragment } from 'react'
3571
3658
  import { AsyncLocalStorage } from 'node:async_hooks'
@@ -6311,6 +6398,15 @@ async function served(request: Request): Promise<Response> {
6311
6398
  // is over already; the page is asked to load again.
6312
6399
  if (import.meta.env.DEV && isOutdatedOptimizedDep(error)) return outdatedDepResponse(request)
6313
6400
 
6401
+ // A failed action, in development: its error and the backend's frames,
6402
+ // for the browser's overlay. Left to the server's generic 500 the page
6403
+ // said nothing, and the cause was in the terminal. Still printed there.
6404
+ if (import.meta.env.DEV && isActionCall(request)) {
6405
+ console.error(error)
6406
+
6407
+ return devActionErrorResponse(error)
6408
+ }
6409
+
6314
6410
  throw error
6315
6411
  }
6316
6412
  }
@@ -6353,6 +6449,7 @@ async function serve(request: Request): Promise<Response> {
6353
6449
  } as never,
6354
6450
  ${NITRO_HANDLER_OPTIONS}${NITRO_PRERENDERED} maxActionBody: ${maxActionBody === undefined ? "undefined" : String(maxActionBody)},
6355
6451
  trustedOrigins: ${JSON.stringify(trustedOrigins ?? [])},
6452
+ onUnroutedHost: import.meta.env.DEV ? sayUnroutedHost : undefined,
6356
6453
  })
6357
6454
 
6358
6455
  ${fallbackOrigin === false ? NO_FALLBACK_BODY : FALLBACK_BODY}}
@@ -6846,6 +6943,7 @@ function generateEntryBrowser() {
6846
6943
  : null;
6847
6944
  const refreshModule = join(packageDir, "js/navigate");
6848
6945
  const chunkPreload = join(packageDir, "js/chunkPreload");
6946
+ const devErrorOverlay = join(packageDir, "js/devErrorOverlay");
6849
6947
  return `// GENERATED by rscKit() — do not edit.
6850
6948
  import { createViteRscApp } from ${JSON.stringify(clientBootstrap)}
6851
6949
  import { refresh } from ${JSON.stringify(refreshModule)}
@@ -6861,6 +6959,13 @@ if (import.meta.env.PROD) {
6861
6959
  setChunkLoader((id) => references[id]?.())
6862
6960
  }
6863
6961
 
6962
+ // A failed server action, on the page as Vite's error overlay - development
6963
+ // only, and loaded only there: removed from a production build with the
6964
+ // branch it is in.
6965
+ if (import.meta.env.DEV) {
6966
+ void import(${JSON.stringify(devErrorOverlay)}).then((overlay) => overlay.installDevActionErrors())
6967
+ }
6968
+
6864
6969
  createViteRscApp(document, ${JSON.stringify(interceptManifest())}, ${JSON.stringify({
6865
6970
  staticPayloads: staticPayloads || null,
6866
6971
  routes: routesForClient,
@@ -8110,6 +8215,16 @@ export function rscKit(options = {}) {
8110
8215
  discover(appDir);
8111
8216
  registerMetadataRoutes(appDir);
8112
8217
  registerOpenApiRoutes();
8218
+ // A file in public/ answered in place of the app's own - Laravel's
8219
+ // empty favicon.ico and robots.txt. Once per message: this hook runs
8220
+ // again on every dev restart.
8221
+ for (const shadowed of shadowedRootFiles(appDir, join(projectRoot, "public"))) {
8222
+ const message = shadowedRootFileMessage(shadowed, projectRoot);
8223
+ if (!saidShadowed.has(message)) {
8224
+ saidShadowed.add(message);
8225
+ console.warn(message);
8226
+ }
8227
+ }
8113
8228
  siteHosts = ownHosts(rootMetadataBase(appDir), hostsOption);
8114
8229
  // Silent when it worked. The names were printed on every dev start and
8115
8230
  // every build — thirty of them for a middling app, above the output that
@@ -8216,6 +8331,8 @@ export function rscKit(options = {}) {
8216
8331
  define: {
8217
8332
  "process.env.NODE_ENV": JSON.stringify((builtNodeEnv = env.mode === "development" ? "development" : "production")),
8218
8333
  __RSC_OFFLINE__: JSON.stringify(offline),
8334
+ // hostUrl()'s site: the host as named, port and all, without www.
8335
+ __RSC_SITE_HOST__: JSON.stringify(siteHostOf(rootMetadataBase(appDir), hostsOption)),
8219
8336
  },
8220
8337
  /*
8221
8338
  * This package's client modules are served as source, never