@thexjs/core 1.3.2 → 1.3.3

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-MYYP67KQ.js";
12
+ } from "./chunk-LV4CJQYM.js";
13
13
 
14
14
  // src/adapter/bundle.ts
15
15
  import { mkdirSync, rmSync, writeFileSync } from "fs";
@@ -436,6 +436,13 @@ function registerServerFunctions(routePath, paramNames, fns) {
436
436
  ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
437
437
  }
438
438
  }
439
+ function snapshotActionRoutes() {
440
+ return ACTION_ROUTES.map((entry) => ({
441
+ routePath: entry.routePath,
442
+ paramNames: entry.paramNames,
443
+ fns: new Map(entry.fns)
444
+ }));
445
+ }
439
446
  function getServerFunctionHandler(csrfOptions) {
440
447
  return async (req) => {
441
448
  if (req.method !== "POST") return null;
@@ -450,7 +457,7 @@ function getServerFunctionHandler(csrfOptions) {
450
457
  const actionName = parts.pop();
451
458
  if (!actionName) return null;
452
459
  const concretePath = `/${parts.join("/")}`;
453
- for (const entry of ACTION_ROUTES) {
460
+ for (const entry of snapshotActionRoutes()) {
454
461
  const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
455
462
  if (params === null) continue;
456
463
  const fn = entry.fns.get(actionName);
package/dist/index.d.ts CHANGED
@@ -514,6 +514,8 @@ interface AppServeOptions {
514
514
  development: boolean;
515
515
  port: number;
516
516
  fetch: (req: Request) => Response | Promise<Response>;
517
+ /** Last-resort error boundary: called when the fetch handler throws. */
518
+ error?: (error: Error) => Response;
517
519
  }
518
520
  interface RevalidateOptions {
519
521
  revalidate?: number;
@@ -570,16 +572,19 @@ interface IslandEntry {
570
572
  name: string;
571
573
  id: string;
572
574
  }
575
+ interface IslandRegistry {
576
+ entries: IslandEntry[];
577
+ /** Per-request id counter, so island ids never cross request boundaries. */
578
+ nextId: number;
579
+ }
573
580
  declare function IslandProvider({ registry, children, }: {
574
- registry: {
575
- entries: IslandEntry[];
576
- };
581
+ registry: IslandRegistry;
577
582
  children?: ReactNode;
578
583
  }): react.JSX.Element;
579
584
  declare function Island({ name, client, children, }: {
580
585
  name: string;
581
586
  client?: IslandMode;
582
- children: ReactNode;
587
+ children?: ReactNode;
583
588
  }): react.JSX.Element;
584
589
 
585
590
  interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
package/dist/index.js CHANGED
@@ -34,7 +34,7 @@ import {
34
34
  verifyOrigin,
35
35
  withCsrfCookie,
36
36
  writeManifest
37
- } from "./chunk-MYYP67KQ.js";
37
+ } from "./chunk-LV4CJQYM.js";
38
38
 
39
39
  // src/build.ts
40
40
  import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
@@ -123,11 +123,18 @@ function renderListBlock(block) {
123
123
  var ALLOWED_LINK_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto"]);
124
124
  var LINK_SCHEME_RE = /^([a-z][a-z0-9+.-]*):/i;
125
125
  function decodeLinkUrl(url) {
126
- try {
127
- return decodeURIComponent(url);
128
- } catch {
129
- return url;
126
+ let prev = url;
127
+ for (let i = 0; i < 5; i++) {
128
+ let next;
129
+ try {
130
+ next = decodeURIComponent(prev);
131
+ } catch {
132
+ return prev;
133
+ }
134
+ if (next === prev) return next;
135
+ prev = next;
130
136
  }
137
+ return prev;
131
138
  }
132
139
  function stripUrlControlChars(url) {
133
140
  return url.replace(/[\t\n\r]/g, "");
@@ -169,7 +176,7 @@ function renderMarkdown(md) {
169
176
  import { createContext, useContext } from "react";
170
177
  import { jsx } from "react/jsx-runtime";
171
178
  function createIslandRegistry() {
172
- return { entries: [] };
179
+ return { entries: [], nextId: 0 };
173
180
  }
174
181
  var IslandContext = createContext(null);
175
182
  function IslandProvider({
@@ -178,18 +185,18 @@ function IslandProvider({
178
185
  }) {
179
186
  return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
180
187
  }
181
- var islandCounter = 0;
182
188
  function Island({
183
189
  name,
184
190
  client = "idle",
185
191
  children
186
192
  }) {
187
193
  const registry = useContext(IslandContext);
188
- const id = `x-island-${islandCounter++}`;
189
194
  if (registry) {
195
+ const id = `x-island-${registry.nextId++}`;
190
196
  registry.entries.push({ name, id });
197
+ return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
191
198
  }
192
- return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
199
+ return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": "x-island-0", "data-island-client": client, children });
193
200
  }
194
201
 
195
202
  // src/render.ts
@@ -475,22 +482,28 @@ ${liveReloadTag} </body>
475
482
  try {
476
483
  const { done, value } = await reader.read();
477
484
  if (done) {
478
- controller.enqueue(encoder.encode(`${rootFooter}
485
+ try {
486
+ controller.enqueue(encoder.encode(`${rootFooter}
479
487
  ${footer}`));
480
- controller.close();
488
+ controller.close();
489
+ } catch {
490
+ }
481
491
  return;
482
492
  }
483
493
  controller.enqueue(value);
484
494
  await pump();
485
495
  } catch (err) {
486
496
  console.error("[x] stream read error:", err);
487
- controller.enqueue(
488
- encoder.encode(
489
- `${rootFooter}<div style="color:red;padding:1em;margin:1rem">Render error: ${err instanceof Error ? err.message : "Unknown"}</div>
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>
490
501
  ${footer}`
491
- )
492
- );
493
- controller.close();
502
+ )
503
+ );
504
+ controller.close();
505
+ } catch {
506
+ }
494
507
  }
495
508
  }
496
509
  await pump();
@@ -752,7 +765,21 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
752
765
  " drainTimer.unref?.();",
753
766
  "}",
754
767
  'process.on("SIGTERM", () => shutdown("SIGTERM"));',
755
- 'process.on("SIGINT", () => shutdown("SIGINT"));'
768
+ 'process.on("SIGINT", () => shutdown("SIGINT"));',
769
+ "",
770
+ "// Request-level errors are caught inside createApp's fetch boundary;",
771
+ "// anything that still escapes (a throw outside the request lifecycle,",
772
+ "// a rejected promise from a background sweep) is routed to the error",
773
+ "// reporter so the box reports instead of dying.",
774
+ 'const { reportException } = await import("@thexjs/core");',
775
+ 'process.on("uncaughtException", (err) => {',
776
+ ' reportException(err, { phase: "api" });',
777
+ ' console.error("[x] uncaught exception:", err);',
778
+ "});",
779
+ 'process.on("unhandledRejection", (reason) => {',
780
+ ' reportException(reason, { phase: "api" });',
781
+ ' console.error("[x] unhandled rejection:", reason);',
782
+ "});"
756
783
  );
757
784
  return lines.join("\n");
758
785
  }
@@ -1304,6 +1331,83 @@ function applySecurityHeaders(res, options = {}) {
1304
1331
  return res;
1305
1332
  }
1306
1333
 
1334
+ // src/security/isr-cache.ts
1335
+ var IsrCache = class {
1336
+ entries = /* @__PURE__ */ new Map();
1337
+ inFlight = /* @__PURE__ */ new Map();
1338
+ maxEntries;
1339
+ constructor(maxEntries = 500) {
1340
+ this.maxEntries = maxEntries;
1341
+ }
1342
+ get(key) {
1343
+ const entry = this.entries.get(key);
1344
+ if (entry) {
1345
+ this.entries.delete(key);
1346
+ this.entries.set(key, entry);
1347
+ }
1348
+ return entry;
1349
+ }
1350
+ set(key, html) {
1351
+ this.entries.delete(key);
1352
+ this.entries.set(key, { html, timestamp: Date.now() });
1353
+ this.evict();
1354
+ }
1355
+ delete(key) {
1356
+ this.entries.delete(key);
1357
+ }
1358
+ clear() {
1359
+ this.entries.clear();
1360
+ }
1361
+ /** Deletes every entry whose pathname matches (query-blind purge). */
1362
+ deletePath(pathname) {
1363
+ let removed = 0;
1364
+ for (const key of this.entries.keys()) {
1365
+ const url = new URL(key, "http://localhost");
1366
+ if (url.pathname === pathname) {
1367
+ this.entries.delete(key);
1368
+ removed++;
1369
+ }
1370
+ }
1371
+ return removed;
1372
+ }
1373
+ get size() {
1374
+ return this.entries.size;
1375
+ }
1376
+ /**
1377
+ * Returns the cached HTML for `key`, or runs `compute` exactly once — even
1378
+ * when multiple callers miss concurrently — and caches the result. A
1379
+ * `Response` returned by `compute` (e.g. a loader redirect) is passed
1380
+ * through and never cached.
1381
+ */
1382
+ getOrCompute(key, compute) {
1383
+ const cached = this.get(key);
1384
+ if (cached) return Promise.resolve(cached.html);
1385
+ const existing = this.inFlight.get(key);
1386
+ if (existing) return existing;
1387
+ const promise = compute().then((result) => {
1388
+ if (typeof result === "string") {
1389
+ this.set(key, result);
1390
+ }
1391
+ return result;
1392
+ }).finally(() => {
1393
+ this.inFlight.delete(key);
1394
+ });
1395
+ this.inFlight.set(key, promise);
1396
+ return promise;
1397
+ }
1398
+ evict() {
1399
+ while (this.entries.size > this.maxEntries) {
1400
+ const oldestKey = this.entries.keys().next().value;
1401
+ if (oldestKey === void 0) break;
1402
+ this.entries.delete(oldestKey);
1403
+ }
1404
+ }
1405
+ };
1406
+ function isrCacheKey(requestUrl) {
1407
+ const url = new URL(requestUrl);
1408
+ return url.pathname + url.search;
1409
+ }
1410
+
1307
1411
  // src/security/rate-limit.ts
1308
1412
  function defaultKeyFn(req, server) {
1309
1413
  if (server?.requestIP) {
@@ -1488,7 +1592,7 @@ async function createApp(options) {
1488
1592
  let notFoundComponent = DefaultNotFound;
1489
1593
  let notFoundLayout;
1490
1594
  const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
1491
- const staticCache = /* @__PURE__ */ new Map();
1595
+ const staticCache = new IsrCache(500);
1492
1596
  let actionModules = /* @__PURE__ */ new Map();
1493
1597
  const islandBundleCache = /* @__PURE__ */ new Map();
1494
1598
  const islandFileCache = /* @__PURE__ */ new Map();
@@ -1588,33 +1692,33 @@ async function createApp(options) {
1588
1692
  try {
1589
1693
  const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
1590
1694
  const baseHandler = async (ctx) => {
1591
- const cacheKey = new URL(ctx.request.url).pathname;
1695
+ const cacheKey = isrCacheKey(ctx.request.url);
1592
1696
  if (mode === "server") {
1593
- let loaderData2 = {};
1697
+ let loaderData = {};
1594
1698
  if (loader) {
1595
1699
  const result = await loader(ctx);
1596
1700
  if (result instanceof Response) return result;
1597
- loaderData2 = result;
1701
+ loaderData = result;
1598
1702
  }
1599
- const registry2 = createIslandRegistry();
1600
- const content2 = createElement2(
1703
+ const registry = createIslandRegistry();
1704
+ const content = createElement2(
1601
1705
  IslandProvider,
1602
- { registry: registry2 },
1603
- wrapWithLayouts(Component, ctx.params, loaderData2, layoutModules)
1706
+ { registry },
1707
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1604
1708
  );
1605
- let scripts2 = islandScripts;
1606
- if (scripts2 === void 0) {
1607
- renderPage(content2, { stylesheet: stylesheetHref, liveReload: dev });
1608
- scripts2 = await resolveIslandScripts(
1709
+ let scripts = islandScripts;
1710
+ if (scripts === void 0) {
1711
+ renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1712
+ scripts = await resolveIslandScripts(
1609
1713
  route.filePath,
1610
1714
  layoutFilePaths,
1611
- registry2.entries
1715
+ registry.entries
1612
1716
  );
1613
1717
  }
1614
- const stream = await renderStreamingPage(content2, {
1718
+ const stream = await renderStreamingPage(content, {
1615
1719
  stylesheet: stylesheetHref,
1616
1720
  liveReload: dev,
1617
- islandScripts: scripts2
1721
+ islandScripts: scripts
1618
1722
  });
1619
1723
  return new Response(stream, {
1620
1724
  headers: { "Content-Type": "text/html; charset=utf-8" }
@@ -1631,36 +1735,52 @@ async function createApp(options) {
1631
1735
  }
1632
1736
  });
1633
1737
  }
1738
+ if (cached) staticCache.delete(cacheKey);
1634
1739
  }
1635
- let loaderData = {};
1636
- if (loader) {
1637
- const result = await loader(ctx);
1638
- if (result instanceof Response) return result;
1639
- loaderData = result;
1640
- }
1641
- const registry = createIslandRegistry();
1642
- const content = createElement2(
1643
- IslandProvider,
1644
- { registry },
1645
- wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1646
- );
1647
- let scripts = islandScripts;
1648
- if (scripts === void 0) {
1649
- renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1650
- scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
1651
- }
1652
- const html = renderPage(content, {
1653
- stylesheet: stylesheetHref,
1654
- liveReload: dev,
1655
- islandScripts: scripts
1656
- });
1740
+ const computeHtml = async () => {
1741
+ let loaderData = {};
1742
+ if (loader) {
1743
+ const result = await loader(ctx);
1744
+ if (result instanceof Response) return result;
1745
+ loaderData = result;
1746
+ }
1747
+ const registry = createIslandRegistry();
1748
+ const content = createElement2(
1749
+ IslandProvider,
1750
+ { registry },
1751
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1752
+ );
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, {
1763
+ stylesheet: stylesheetHref,
1764
+ liveReload: dev,
1765
+ islandScripts: scripts
1766
+ });
1767
+ };
1657
1768
  if (revalidateSeconds > 0) {
1658
- staticCache.set(cacheKey, { html, timestamp: Date.now() });
1769
+ const result = await staticCache.getOrCompute(cacheKey, computeHtml);
1770
+ if (result instanceof Response) return result;
1771
+ return new Response(result, {
1772
+ headers: {
1773
+ "Content-Type": "text/html; charset=utf-8",
1774
+ "X-Revalidated": "miss"
1775
+ }
1776
+ });
1659
1777
  }
1778
+ const html = await computeHtml();
1779
+ if (html instanceof Response) return html;
1660
1780
  return new Response(html, {
1661
1781
  headers: {
1662
1782
  "Content-Type": "text/html; charset=utf-8",
1663
- "X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
1783
+ "X-Revalidated": "none"
1664
1784
  }
1665
1785
  });
1666
1786
  };
@@ -1885,6 +2005,20 @@ async function createApp(options) {
1885
2005
  }
1886
2006
  }
1887
2007
  await buildHandlers();
2008
+ async function guardFetchErrors(inner, req, server) {
2009
+ try {
2010
+ return await inner(req, server);
2011
+ } catch (error) {
2012
+ const path = new URL(req.url).pathname;
2013
+ const phase = path.startsWith("/__x/actions/") ? "action" : path === "/__x/revalidate" ? "api" : "loader";
2014
+ reportException(error, { phase, route: path });
2015
+ const e = error instanceof Error ? error.message : String(error);
2016
+ return new Response(
2017
+ options.development ? `Internal Server Error: ${e}` : "Internal Server Error",
2018
+ { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8" } }
2019
+ );
2020
+ }
2021
+ }
1888
2022
  async function handleRevalidation(req) {
1889
2023
  if (new URL(req.url).pathname !== "/__x/revalidate") return null;
1890
2024
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
@@ -1892,10 +2026,15 @@ async function createApp(options) {
1892
2026
  if (!csrfResult.ok) {
1893
2027
  return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
1894
2028
  }
1895
- const body = await req.json();
2029
+ let body;
2030
+ try {
2031
+ body = await req.json();
2032
+ } catch {
2033
+ return new Response("Invalid JSON body", { status: 400 });
2034
+ }
1896
2035
  if (body.path) {
1897
- staticCache.delete(body.path);
1898
- return new Response(`Revalidated: ${body.path}`);
2036
+ const removed = staticCache.deletePath(new URL(body.path, "http://localhost").pathname);
2037
+ return new Response(`Revalidated: ${body.path} (${removed} cached variant(s))`);
1899
2038
  }
1900
2039
  staticCache.clear();
1901
2040
  return new Response("Revalidated all");
@@ -2035,14 +2174,22 @@ data: ${data}
2035
2174
  }
2036
2175
  return renderNotFound(req);
2037
2176
  };
2038
- const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2177
+ const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(devFetchInner, req, server));
2039
2178
  const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2040
2179
  const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
2041
2180
  return {
2042
2181
  routes: {},
2043
2182
  development: true,
2044
2183
  port: options.port ?? 3e3,
2045
- fetch: devFetch
2184
+ fetch: devFetch,
2185
+ // Last-resort boundary: `guardFetchErrors` catches exceptions raised
2186
+ // inside routing, but anything thrown by the request-stack wrappers
2187
+ // (logging/metrics/hardening) or by Bun itself still reaches the
2188
+ // process. Returning a 500 here keeps the server up.
2189
+ error: (error) => {
2190
+ reportException(error, { phase: "api" });
2191
+ return new Response("Internal Server Error", { status: 500 });
2192
+ }
2046
2193
  };
2047
2194
  }
2048
2195
  const prodFetchInner = async (req, server) => {
@@ -2083,14 +2230,18 @@ data: ${data}
2083
2230
  }
2084
2231
  return renderNotFound(req);
2085
2232
  };
2086
- const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2233
+ const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(prodFetchInner, req, server));
2087
2234
  const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2088
2235
  const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
2089
2236
  return {
2090
2237
  routes: {},
2091
2238
  development: false,
2092
2239
  port: options.port ?? 3e3,
2093
- fetch: prodFetch
2240
+ fetch: prodFetch,
2241
+ error: (error) => {
2242
+ reportException(error, { phase: "api" });
2243
+ return new Response("Internal Server Error", { status: 500 });
2244
+ }
2094
2245
  };
2095
2246
  }
2096
2247
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
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",