@thexjs/core 1.3.3 → 1.3.5

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/adapter.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  scanNotFound,
10
10
  scanPages,
11
11
  scanRoutes
12
- } from "./chunk-LV4CJQYM.js";
12
+ } from "./chunk-PQ7ZVWEJ.js";
13
13
 
14
14
  // src/adapter/bundle.ts
15
15
  import { mkdirSync, rmSync, writeFileSync } from "fs";
@@ -540,17 +540,36 @@ function resolveIsland(name: string) {
540
540
 
541
541
  // Islands whose render is non-deterministic (e.g. \`useState(() => ...)\` with
542
542
  // Math.random) can't be hydrated against their SSR output. React recovers by
543
- // re-rendering client-side, so the island is still fully interactive -- the
544
- // mismatch is benign, so swallow the recovery so it doesn't spam the console
545
- // or cascade into React's event system.
546
- function onRecoverableError() {}
543
+ // re-rendering client-side, so the island is still fully interactive. The
544
+ // mismatch is NOT silently swallowed: it is reported to the server so real
545
+ // rendering bugs are observable in production instead of hidden.
546
+ function reportHydrationMismatch(error, name) {
547
+ try {
548
+ console.error("[x] hydration mismatch on island '" + name + "':", error);
549
+ } catch (_) {}
550
+ try {
551
+ var message = error instanceof Error ? error.message : String(error);
552
+ navigator.sendBeacon(
553
+ "/__x/hydration-mismatch",
554
+ new Blob([JSON.stringify({ error: message, island: name, url: location.href })], {
555
+ type: "application/json",
556
+ }),
557
+ );
558
+ } catch (_) {
559
+ // sendBeacon is best-effort; a failing beacon must not break hydration.
560
+ }
561
+ }
547
562
 
548
563
  document.querySelectorAll("[data-island]").forEach((el) => {
549
564
  const name = el.getAttribute("data-island");
550
565
  if (!name) return;
551
566
  const Component = resolveIsland(name);
552
567
  if (!Component) return;
553
- hydrateRoot(el, React.createElement(Component), { onRecoverableError });
568
+ hydrateRoot(el, React.createElement(Component), {
569
+ onRecoverableError(error) {
570
+ reportHydrationMismatch(error, name);
571
+ },
572
+ });
554
573
  });
555
574
  `;
556
575
  }
package/dist/index.d.ts CHANGED
@@ -201,6 +201,8 @@ interface ErrorContext {
201
201
  route?: string;
202
202
  requestId?: string;
203
203
  phase: "ssr" | "action" | "api" | "loader";
204
+ /** Free-form discriminator, e.g. `hydration-mismatch`, for filtering. */
205
+ tag?: string;
204
206
  }
205
207
  interface ErrorReporter {
206
208
  captureException(error: unknown, context: ErrorContext): void;
@@ -634,6 +636,19 @@ interface RenderOptions {
634
636
  clientNav?: boolean;
635
637
  /** Inject live-reload script (development mode). */
636
638
  liveReload?: boolean;
639
+ /**
640
+ * Called when the SSR stream fails mid-flight. Pass this through to
641
+ * `renderStreamingPage` so the app can report the failure via its error
642
+ * reporter/metrics instead of shipping a partial page silently.
643
+ */
644
+ onRenderError?: (error: unknown) => void;
645
+ /**
646
+ * Single-render island resolution. When set, the page renders exactly once
647
+ * and this callback is awaited to resolve the island script list from the
648
+ * islands that pass actually produced (the caller holds the registry). Used
649
+ * to eliminate the two-pass discovery render.
650
+ */
651
+ resolveIslandScripts?: () => Promise<string[]>;
637
652
  }
638
653
  interface LoaderArgs {
639
654
  params: Record<string, string>;
package/dist/index.js CHANGED
@@ -34,7 +34,7 @@ import {
34
34
  verifyOrigin,
35
35
  withCsrfCookie,
36
36
  writeManifest
37
- } from "./chunk-LV4CJQYM.js";
37
+ } from "./chunk-PQ7ZVWEJ.js";
38
38
 
39
39
  // src/build.ts
40
40
  import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
@@ -411,29 +411,24 @@ function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptT
411
411
  </html>`;
412
412
  }
413
413
  function renderPage(node, options = {}) {
414
- const { islandScripts, islandProps } = options;
415
- const title = options.title ?? "x app";
416
414
  const body = renderToString(node);
417
- const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
418
- const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
419
- const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
420
- return htmlShell(
421
- title,
422
- buildHeadExtras(options.stylesheet),
423
- propsScript,
424
- islandScriptsHtml,
425
- body,
426
- buildNavScriptTag(options.clientNav),
427
- buildLiveReloadTag(options.liveReload)
428
- );
415
+ return buildShellHtml(body, options, options.islandScripts ?? []);
429
416
  }
430
417
  function renderStaticPage(node, options = {}) {
431
- const { islandScripts, islandProps } = options;
432
- const title = options.title ?? "x app";
433
418
  const body = renderToStaticMarkup(node);
419
+ return buildShellHtml(body, options, options.islandScripts ?? []);
420
+ }
421
+ async function renderPageOnce(node, options = {}) {
422
+ const body = renderToString(node);
423
+ const scripts = options.resolveIslandScripts ? await options.resolveIslandScripts() : options.islandScripts ?? [];
424
+ return buildShellHtml(body, options, scripts);
425
+ }
426
+ function buildShellHtml(body, options, islandScripts) {
427
+ const { islandProps } = options;
428
+ const title = options.title ?? "x app";
434
429
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
435
430
  const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
436
- const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
431
+ const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
437
432
  return htmlShell(
438
433
  title,
439
434
  buildHeadExtras(options.stylesheet),
@@ -444,18 +439,64 @@ function renderStaticPage(node, options = {}) {
444
439
  buildLiveReloadTag(options.liveReload)
445
440
  );
446
441
  }
442
+ function pumpStreamingResponse(source, options) {
443
+ const { header, footer, onRenderError, onCancel } = options;
444
+ const reader = source.getReader();
445
+ let headerSent = false;
446
+ let ended = false;
447
+ async function readAhead(controller) {
448
+ if (!headerSent) {
449
+ headerSent = true;
450
+ controller.enqueue(header);
451
+ }
452
+ while (true) {
453
+ const { done, value } = await reader.read();
454
+ if (done) {
455
+ if (!ended) {
456
+ const footerBytes = typeof footer === "function" ? await footer() : footer;
457
+ ended = true;
458
+ try {
459
+ controller.enqueue(footerBytes);
460
+ } catch {
461
+ }
462
+ controller.close();
463
+ }
464
+ return;
465
+ }
466
+ controller.enqueue(value);
467
+ if (controller.desiredSize !== null && controller.desiredSize <= 0) return;
468
+ }
469
+ }
470
+ return new ReadableStream({
471
+ async pull(controller) {
472
+ try {
473
+ await readAhead(controller);
474
+ } catch (err) {
475
+ if (!ended) {
476
+ ended = true;
477
+ onRenderError?.(err);
478
+ }
479
+ try {
480
+ controller.error(err);
481
+ } catch {
482
+ }
483
+ }
484
+ },
485
+ cancel(reason) {
486
+ reader.cancel(reason).catch(() => {
487
+ });
488
+ onCancel?.(reason);
489
+ }
490
+ });
491
+ }
447
492
  async function renderStreamingPage(node, options = {}) {
448
493
  const { islandScripts, islandProps } = options;
449
494
  const title = escapeHtml2(options.title ?? "x app");
450
495
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
451
496
  const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
452
- const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
453
497
  const navScriptTag = buildNavScriptTag(options.clientNav);
454
498
  const liveReloadTag = buildLiveReloadTag(options.liveReload);
455
499
  const headExtras = buildHeadExtras(options.stylesheet);
456
- const rootFooter = `${propsScript ? ` ${propsScript}
457
- ` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
458
- ` : ""}`;
459
500
  const footer = `</div>${navScriptTag}
460
501
  ${liveReloadTag} </body>
461
502
  </html>`;
@@ -474,40 +515,21 @@ ${liveReloadTag} </body>
474
515
  </head>
475
516
  <body>
476
517
  <div id="root">`;
477
- return new ReadableStream({
478
- async start(controller) {
479
- controller.enqueue(encoder.encode(header));
480
- const reader = reactStream.getReader();
481
- async function pump() {
482
- try {
483
- const { done, value } = await reader.read();
484
- if (done) {
485
- try {
486
- controller.enqueue(encoder.encode(`${rootFooter}
487
- ${footer}`));
488
- controller.close();
489
- } catch {
490
- }
491
- return;
492
- }
493
- controller.enqueue(value);
494
- await pump();
495
- } catch (err) {
496
- console.error("[x] stream read error:", err);
497
- try {
498
- controller.enqueue(
499
- encoder.encode(
500
- `${rootFooter}<div style="color:red;padding:1em;margin:1rem">Render error: ${err instanceof Error ? err.message : "Unknown"}</div>
501
- ${footer}`
502
- )
503
- );
504
- controller.close();
505
- } catch {
506
- }
507
- }
508
- }
509
- await pump();
510
- }
518
+ return pumpStreamingResponse(reactStream, {
519
+ header: encoder.encode(header),
520
+ // Lazy footer: the island script list may only be knowable after the
521
+ // render completed (single-render mode), so resolve it right before the
522
+ // closing tags are emitted rather than up front.
523
+ footer: async () => {
524
+ const scripts = islandScripts ?? await options.resolveIslandScripts?.() ?? [];
525
+ const islandScriptsHtml = scripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
526
+ const rootFooter = `${propsScript ? ` ${propsScript}
527
+ ` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
528
+ ` : ""}`;
529
+ return encoder.encode(`${rootFooter}
530
+ ${footer}`);
531
+ },
532
+ ...options.onRenderError ? { onRenderError: options.onRenderError } : {}
511
533
  });
512
534
  }
513
535
 
@@ -1706,19 +1728,21 @@ async function createApp(options) {
1706
1728
  { registry },
1707
1729
  wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1708
1730
  );
1709
- let scripts = islandScripts;
1710
- if (scripts === void 0) {
1711
- renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1712
- scripts = await resolveIslandScripts(
1713
- route.filePath,
1714
- layoutFilePaths,
1715
- registry.entries
1716
- );
1717
- }
1718
1731
  const stream = await renderStreamingPage(content, {
1719
1732
  stylesheet: stylesheetHref,
1720
1733
  liveReload: dev,
1721
- islandScripts: scripts
1734
+ ...islandScripts === void 0 ? {
1735
+ // Single-render mode: islands register into `registry`
1736
+ // during the one render that produces the HTML, and the
1737
+ // script list is resolved from that same pass in the lazy
1738
+ // footer — no separate discovery render, so non-deterministic
1739
+ // components can't diverge between two passes.
1740
+ resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
1741
+ } : { islandScripts },
1742
+ onRenderError: (error) => {
1743
+ reportException(error, { route: route.routePath, phase: "ssr" });
1744
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1745
+ }
1722
1746
  });
1723
1747
  return new Response(stream, {
1724
1748
  headers: { "Content-Type": "text/html; charset=utf-8" }
@@ -1750,19 +1774,12 @@ async function createApp(options) {
1750
1774
  { registry },
1751
1775
  wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1752
1776
  );
1753
- let scripts = islandScripts;
1754
- if (scripts === void 0) {
1755
- renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1756
- scripts = await resolveIslandScripts(
1757
- route.filePath,
1758
- layoutFilePaths,
1759
- registry.entries
1760
- );
1761
- }
1762
- return renderPage(content, {
1777
+ return renderPageOnce(content, {
1763
1778
  stylesheet: stylesheetHref,
1764
1779
  liveReload: dev,
1765
- islandScripts: scripts
1780
+ ...islandScripts === void 0 ? {
1781
+ resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
1782
+ } : { islandScripts }
1766
1783
  });
1767
1784
  };
1768
1785
  if (revalidateSeconds > 0) {
@@ -2039,6 +2056,34 @@ async function createApp(options) {
2039
2056
  staticCache.clear();
2040
2057
  return new Response("Revalidated all");
2041
2058
  }
2059
+ async function handleHydrationMismatch(req) {
2060
+ if (new URL(req.url).pathname !== "/__x/hydration-mismatch") return null;
2061
+ if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
2062
+ const origin = req.headers.get("origin");
2063
+ const referer = req.headers.get("referer");
2064
+ const selfOrigin = `${new URL(req.url).protocol}//${new URL(req.url).host}`;
2065
+ const attempt = origin ?? referer;
2066
+ if (attempt && !attempt.startsWith(selfOrigin)) {
2067
+ return new Response("Forbidden", { status: 403 });
2068
+ }
2069
+ let body;
2070
+ try {
2071
+ const text = await req.text();
2072
+ if (text.length > 2048) return new Response("Payload too large", { status: 413 });
2073
+ body = JSON.parse(text);
2074
+ } catch {
2075
+ return new Response("Invalid JSON body", { status: 400 });
2076
+ }
2077
+ const error = new Error(body.error ?? "hydration mismatch");
2078
+ const routeFromUrl = body.url ? new URL(body.url).pathname : "/";
2079
+ reportException(error, {
2080
+ route: routeFromUrl,
2081
+ phase: "ssr",
2082
+ tag: "hydration-mismatch"
2083
+ });
2084
+ metricsReporter?.incr("x_http_hydration_mismatch", 1, { island: body.island ?? "unknown" });
2085
+ return new Response(null, { status: 204 });
2086
+ }
2042
2087
  if (options.development) {
2043
2088
  let notifyClients2 = function() {
2044
2089
  for (const send of sseClients) {
@@ -2153,6 +2198,8 @@ data: ${data}
2153
2198
  }
2154
2199
  const revalidationResult = await handleRevalidation(req);
2155
2200
  if (revalidationResult !== null) return revalidationResult;
2201
+ const mismatchResult = await handleHydrationMismatch(req);
2202
+ if (mismatchResult !== null) return mismatchResult;
2156
2203
  const serverFnResult = await serverFnHandler(req);
2157
2204
  if (serverFnResult !== null) return serverFnResult;
2158
2205
  const staticAsset = await serveStaticAsset(publicDir, req);
@@ -2209,6 +2256,8 @@ data: ${data}
2209
2256
  }
2210
2257
  const revalidationResult = await handleRevalidation(req);
2211
2258
  if (revalidationResult !== null) return revalidationResult;
2259
+ const mismatchResult = await handleHydrationMismatch(req);
2260
+ if (mismatchResult !== null) return mismatchResult;
2212
2261
  const serverFnResult = await serverFnHandler(req);
2213
2262
  if (serverFnResult !== null) return serverFnResult;
2214
2263
  const staticAsset = await serveStaticAsset(publicDir, req);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.3.3",
3
+ "version": "1.3.5",
4
4
  "description": "Full-stack React framework core (router, SSR/SSG renderer, islands, server functions) for the x framework, built on Bun.",
5
5
  "keywords": [
6
6
  "react",