@thexjs/core 1.9.0 → 1.10.1

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/README.md CHANGED
@@ -40,23 +40,22 @@ Run it via the CLI: `x dev` (or `bun run dev` if that's wired up in your `packag
40
40
 
41
41
  Given a `pagesDir`, `scanPages` walks the directory and maps files to routes:
42
42
 
43
- | File | Route |
44
- |---|---|
45
- | `src/pages/index.tsx` | `/` |
46
- | `src/pages/about.tsx` | `/about` |
47
- | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
- | `src/pages/blog/[...rest].tsx` | `/blog/*` (catch-all) |
49
- | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
- | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
- | `src/pages/_404.tsx` | Custom not-found page |
52
- | `src/api/users.ts` | API route at `/api/users` (via `apiDir`) |
43
+ | File | Route |
44
+ | ------------------------------ | ------------------------------------------------------------- |
45
+ | `src/pages/index.tsx` | `/` |
46
+ | `src/pages/about.tsx` | `/about` |
47
+ | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
+ | `src/pages/blog/[...rest].tsx` | `/blog/*` (catch-all) |
49
+ | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
+ | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
+ | `src/pages/_404.tsx` | Custom not-found page |
52
+ | `src/api/users.ts` | API route at `/api/users` (via `apiDir`) |
53
53
 
54
54
  Files and directories prefixed with `_` or `.` are never treated as routes.
55
55
 
56
56
  ### Route resolution order
57
57
 
58
58
  When several routes could match one URL, the most specific one wins:
59
-
60
59
  1. **Static (literal) routes beat dynamic ones** — `/users/new` is served by
61
60
  `pages/users/new.tsx`, never by `pages/users/[id].tsx`.
62
61
  2. **Single-segment params beat catch-alls** — `[slug].tsx` matches
@@ -128,7 +127,7 @@ import { Island } from "@thexjs/core";
128
127
 
129
128
  <Island name="LikeButton" client="visible">
130
129
  <LikeButton />
131
- </Island>
130
+ </Island>;
132
131
  ```
133
132
 
134
133
  `client` accepts `"idle" | "visible" | "load"`, controlling when the island hydrates on the client. Everything outside an `<Island>` stays static/server-rendered HTML with no client JS shipped.
@@ -204,6 +203,8 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
204
203
 
205
204
  `build()` writes prerendered `static` pages (and copies `public/`) to `<outDir>/client`; that output is a plain static site, deployable anywhere (Vercel, Netlify, any CDN). Any page left in the default `server` mode requires a running Bun process (`x start`) and **is not included in the static output**. It needs a Bun-capable host (Fly.io, a VPS, Docker, etc.), not a static host or a Node-only serverless platform.
206
205
 
206
+ A single Bun process serves every request for a given server-mode app — there's no per-request isolation. `requestTimeoutMs` bounds how long any one request can take before it's given up on (504), so a hung handler can't stall the process forever, but it doesn't free up CPU mid-flight. For real isolation under load, run at least two replicas behind a load balancer in production.
207
+
207
208
  ## Enterprise readiness: security & observability
208
209
 
209
210
  `createApp` accepts optional `security` and `observability` config, all on by sane defaults:
@@ -214,6 +215,12 @@ import { createApp, createSentryReporter } from "@thexjs/core";
214
215
  const app = createApp({
215
216
  pagesDir: "./src/pages",
216
217
  actionsDir: "./src/actions",
218
+ // Opt in once you know your app has no legitimately-long requests (or has
219
+ // raised the budget on those routes specifically): a handler that hangs
220
+ // past this gets a 504 instead of stalling every other request. Unset by
221
+ // default. See "Deployment note" below for the single-process caveat this
222
+ // only partially covers.
223
+ requestTimeoutMs: 30_000,
217
224
  security: {
218
225
  // Origin/Referer verification on /__x/actions/* is always on; add explicit
219
226
  // cross-subdomain origins here, or requireToken for double-submit CSRF cookies.
@@ -241,32 +248,32 @@ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser. `@thexjs/env`'s
241
248
 
242
249
  ## Exports reference
243
250
 
244
- | Export | Purpose |
245
- |---|---|
246
- | `defineConfig`, `createApp`, `CreateAppOptions`, `RouteProps`, `RevalidateOptions` | App setup / dev & runtime server |
247
- | `build`, `BuildOptions`, `RouteMode` | Static/server build step |
248
- | `renderPage`, `renderStaticPage`, `renderStreamingPage`, `LoaderArgs`, `LoaderReturn` | Lower-level render functions |
249
- | `scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`, `findLayoutChain`, `findMiddlewareChain`, `generateManifestSource`, `writeManifest` | Routing internals |
250
- | `Island`, `IslandProvider`, `IslandMode`, `IslandEntry` | Selective hydration |
251
- | `Image`, `ImageProps`, `buildSrcSet`, `SRCSET_WIDTHS`, `setImageRemoteHosts` | Optimized image component & srcset builder |
252
- | `Link`, `LinkProps` | Client-side navigation link component |
253
- | `createImageProxyHandler`, `ImageProxyOptions` | Remote image proxy handler for `_next/image`-style rewriting |
254
- | `scanContent`, `renderMarkdown`, `escapeHtml`, `ContentEntry`, `Frontmatter` | Markdown content collections |
255
- | `composeMiddleware`, `MiddlewareContext`, `MiddlewareFn`, `MiddlewareNext` | Middleware |
256
- | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
257
- | `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
258
- | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
259
- | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
260
- | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
261
- | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitStore`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
262
- | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
263
- | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
264
- | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
265
- | `setTracer`, `getTracer`, `runWithRequestSpan`, `tracePhase`, `tracePhaseSync`, `withRequestTracing`, `traceRequestId`, `dbTraceAttributes`, `TracerLike`, `TraceSpan` | Tracing / OpenTelemetry spans |
266
- | `createInMemoryMetrics`, `createOtlpMetricsReporter`, `withRequestMetrics`, `noopMetrics`, `MetricsReporter`, `CounterSeries`, `HistogramSeries` | Metrics collection (Prometheus/OTLP) |
267
- | `audit`, `setAuditSink`, `clientIpFromRequest`, `requestIdFromRequest`, `AuditSink`, `AuditEntry` | Audit logging |
268
- | `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
251
+ | Export | Purpose |
252
+ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
253
+ | `defineConfig`, `createApp`, `CreateAppOptions`, `RouteProps`, `RevalidateOptions` | App setup / dev & runtime server |
254
+ | `build`, `BuildOptions`, `RouteMode` | Static/server build step |
255
+ | `renderPage`, `renderStaticPage`, `renderStreamingPage`, `LoaderArgs`, `LoaderReturn` | Lower-level render functions |
256
+ | `scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`, `findLayoutChain`, `findMiddlewareChain`, `generateManifestSource`, `writeManifest` | Routing internals |
257
+ | `Island`, `IslandProvider`, `IslandMode`, `IslandEntry` | Selective hydration |
258
+ | `Image`, `ImageProps`, `buildSrcSet`, `SRCSET_WIDTHS`, `setImageRemoteHosts` | Optimized image component & srcset builder |
259
+ | `Link`, `LinkProps` | Client-side navigation link component |
260
+ | `createImageProxyHandler`, `ImageProxyOptions` | Remote image proxy handler, served at `/_x/image?url=...` |
261
+ | `scanContent`, `renderMarkdown`, `escapeHtml`, `ContentEntry`, `Frontmatter` | Markdown content collections |
262
+ | `composeMiddleware`, `MiddlewareContext`, `MiddlewareFn`, `MiddlewareNext` | Middleware |
263
+ | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
264
+ | `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
265
+ | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
266
+ | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
267
+ | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
268
+ | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitStore`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
269
+ | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
270
+ | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
271
+ | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
272
+ | `setTracer`, `getTracer`, `runWithRequestSpan`, `tracePhase`, `tracePhaseSync`, `withRequestTracing`, `traceRequestId`, `dbTraceAttributes`, `TracerLike`, `TraceSpan` | Tracing / OpenTelemetry spans |
273
+ | `createInMemoryMetrics`, `createOtlpMetricsReporter`, `withRequestMetrics`, `noopMetrics`, `MetricsReporter`, `CounterSeries`, `HistogramSeries` | Metrics collection (Prometheus/OTLP) |
274
+ | `audit`, `setAuditSink`, `clientIpFromRequest`, `requestIdFromRequest`, `AuditSink`, `AuditEntry` | Audit logging |
275
+ | `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
269
276
 
270
277
  ## License
271
278
 
272
- MIT
279
+ MIT
package/dist/adapter.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as BackpressureOptions } from './backpressure-05lHLY5O.js';
1
+ import { BackpressureOptions } from './index.js';
2
2
 
3
3
  /**
4
4
  * The scratch directory that holds the transient (transpiled module / entry
@@ -170,4 +170,5 @@ declare function allModuleRefs(manifest: BuildManifest): CompiledModuleRef[];
170
170
  */
171
171
  declare function transpileModules(refs: CompiledModuleRef[]): Promise<void>;
172
172
 
173
- export { type AdapterOptions, type BuildManifest, type CompiledModuleRef, ModuleRegistry, type ResolvedAction, type ResolvedRoute, adapterScratchDir, allModuleRefs, bundleRenderFunction, generateAdapterEntry, resolveBuildManifest, serializeRuntimeOptions, transpileModules };
173
+ export { ModuleRegistry, adapterScratchDir, allModuleRefs, bundleRenderFunction, generateAdapterEntry, resolveBuildManifest, serializeRuntimeOptions, transpileModules };
174
+ export type { AdapterOptions, BuildManifest, CompiledModuleRef, ResolvedAction, ResolvedRoute };
@@ -48,4 +48,5 @@ type BackpressureHandler<TServer = unknown> = (req: Request, server?: TServer) =
48
48
  */
49
49
  declare function withBackpressure<TServer = unknown>(handler: BackpressureHandler<TServer>, options: BackpressureOptions): BackpressureHandler<TServer>;
50
50
 
51
- export { type BackpressureOptions as B, type BackpressureController as a, type BackpressureHandler as b, type BackpressureLease as c, BackpressureSaturatedError as d, type BackpressureSnapshot as e, createBackpressureController as f, withBackpressure as w };
51
+ export { BackpressureSaturatedError as d, createBackpressureController as f, withBackpressure as w };
52
+ export type { BackpressureOptions as B, BackpressureController as a, BackpressureHandler as b, BackpressureLease as c, BackpressureSnapshot as e };
package/dist/data.d.ts CHANGED
@@ -80,4 +80,5 @@ interface SQLiteOptions {
80
80
  }
81
81
  declare function connectSQLite(options?: SQLiteOptions): Database;
82
82
 
83
- export { type MigrationOptions, type MigrationResult, type PostgresMigrationResult, type PostgresOptions, type SQLiteOptions, connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
83
+ export { connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
84
+ export type { MigrationOptions, MigrationResult, PostgresMigrationResult, PostgresOptions, SQLiteOptions };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as BackpressureOptions } from './backpressure-05lHLY5O.js';
2
- export { a as BackpressureController, b as BackpressureHandler, c as BackpressureLease, d as BackpressureSaturatedError, e as BackpressureSnapshot, f as createBackpressureController, w as withBackpressure } from './backpressure-05lHLY5O.js';
1
+ import { B as BackpressureOptions } from './backpressure-Bf3iE2Fv.js';
2
+ export { a as BackpressureController, b as BackpressureHandler, c as BackpressureLease, d as BackpressureSaturatedError, e as BackpressureSnapshot, f as createBackpressureController, w as withBackpressure } from './backpressure-Bf3iE2Fv.js';
3
3
  import * as react from 'react';
4
4
  import { ComponentType, ReactNode, CSSProperties, AnchorHTMLAttributes } from 'react';
5
5
 
@@ -476,6 +476,20 @@ interface CreateAppOptions$1 {
476
476
  * crossed. Default: 1 MiB.
477
477
  */
478
478
  maxBodySize?: number;
479
+ /**
480
+ * Maximum time, in milliseconds, a single request may take before the
481
+ * server gives up waiting and responds with 504 Gateway Timeout. Enforced
482
+ * around the whole dispatch (routing, loaders, actions, API handlers) — a
483
+ * handler that hangs past this budget can no longer stall every other
484
+ * request in the process indefinitely. The handler keeps running after the
485
+ * timeout fires (JS can't forcibly cancel synchronous work), so this bounds
486
+ * how long a *caller* waits, not CPU usage.
487
+ *
488
+ * Default: unset (no timeout). Opt in deliberately: a timeout that's too
489
+ * low will cut off legitimately slow routes (large SSR pages, streaming
490
+ * responses, long-running server actions) with a hard 504.
491
+ */
492
+ requestTimeoutMs?: number;
479
493
  /**
480
494
  * Maximum entries in the per-route island bundle caches (both the
481
495
  * route→script-list mapping and the URL→bundled-JS file cache). Entries are
@@ -1105,4 +1119,5 @@ declare function resetServerFunctions(): void;
1105
1119
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
1106
1120
  declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
1107
1121
 
1108
- export { type AuditEntry, type AuditEvent, type AuditSink, BackpressureOptions, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, OTEL_ERROR_STATUS_CODE, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, type TraceSpan, type TracerLike, type TrustedProxyOptions, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
1122
+ export { BackpressureOptions, CLIENT_NAV_SCRIPT, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, Image, Island, IslandProvider, Link, OTEL_ERROR_STATUS_CODE, PUBLIC_ENV_PREFIX, REDACTED, RequestBodyTooLargeError, SRCSET_WIDTHS, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
1123
+ export type { AuditEntry, AuditEvent, AuditSink, BuildOptions, ContentEntry, CounterSeries, CreateAppOptions, CsrfOptions, CsrfResult, ErrorContext, ErrorReporter, Frontmatter, HealthCheck, HealthCheckOptions, HistogramSeries, ImageProps, ImageProxyOptions, InMemoryMetricsOptions, InMemoryMetricsReporter, IslandEntry, IslandMode, LayoutEntry, LinkProps, LoaderArgs, LoaderReturn, LogFields, Logger, MetricLabels, MetricsReporter, MetricsSnapshot, MiddlewareContext, MiddlewareEntry, MiddlewareFn, MiddlewareNext, NotFoundEntry, OtelMeterLike, OtelTracerLike, ProcessCrashHandlerOptions, RateLimitOptions, RateLimitResult, RateLimitStore, ReadinessResult, RevalidateOptions, RouteEntry, RouteMode, RouteProps, SecurityHeadersOptions, SentryLike, TraceSpan, TracerLike, TrustedProxyOptions };
package/dist/index.js CHANGED
@@ -1615,19 +1615,37 @@ async function rateLimitMiddleware(limiter, req, server) {
1615
1615
  }
1616
1616
  function createBunRedisClient(options) {
1617
1617
  return async () => {
1618
- const require2 = import.meta.require;
1619
- const mod = require2("bun:redis");
1620
- const instance = options.url ? new mod.RedisClient({ url: options.url }) : new mod.RedisClient();
1618
+ const BunRedis = globalThis.Bun.RedisClient;
1619
+ const instance = options.url ? new BunRedis(options.url) : new BunRedis();
1621
1620
  await instance.connect();
1622
- return instance;
1621
+ return {
1622
+ sendCommand: (command, ...args) => instance.send(command, args)
1623
+ };
1623
1624
  };
1624
1625
  }
1625
1626
  function createRedisRateLimitStore(options = {}) {
1626
1627
  return createRedisRateLimitStoreFromClient(createBunRedisClient(options));
1627
1628
  }
1629
+ var INCR_WITH_WINDOW_SCRIPT = `local c = redis.call('INCR', KEYS[1])
1630
+ if redis.call('PTTL', KEYS[1]) == -1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
1631
+ return { c, redis.call('PTTL', KEYS[1]) }`;
1632
+ async function incrWithoutScript(c, redisKey, ttlSeconds) {
1633
+ const count = Number(await c.sendCommand("INCR", redisKey));
1634
+ let pttl = Number(await c.sendCommand("PTTL", redisKey));
1635
+ if (pttl === -1) {
1636
+ await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
1637
+ pttl = Number(await c.sendCommand("PTTL", redisKey));
1638
+ }
1639
+ return [count, pttl];
1640
+ }
1641
+ function isScriptingDenied(err) {
1642
+ const message = err instanceof Error ? err.message : String(err);
1643
+ return /NOSCRIPT|unknown command|NOPERM|scripting is disabled|not allowed/i.test(message);
1644
+ }
1628
1645
  function createRedisRateLimitStoreFromClient(clientFactory) {
1629
1646
  let client = null;
1630
1647
  let connecting = null;
1648
+ let scriptingDenied = false;
1631
1649
  function getClient() {
1632
1650
  if (client) return Promise.resolve(client);
1633
1651
  if (!connecting) {
@@ -1649,12 +1667,26 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
1649
1667
  const c = await getClient();
1650
1668
  const redisKey = `x:ratelimit:${key}`;
1651
1669
  const ttlSeconds = Math.max(1, Math.ceil(windowMs / 1e3));
1652
- const count = Number(await c.sendCommand("INCR", redisKey));
1653
- if (count === 1) {
1654
- await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
1670
+ let reply;
1671
+ if (scriptingDenied) {
1672
+ reply = await incrWithoutScript(c, redisKey, ttlSeconds);
1673
+ } else {
1674
+ try {
1675
+ reply = await c.sendCommand(
1676
+ "EVAL",
1677
+ INCR_WITH_WINDOW_SCRIPT,
1678
+ "1",
1679
+ redisKey,
1680
+ String(ttlSeconds)
1681
+ );
1682
+ } catch (err) {
1683
+ if (!isScriptingDenied(err)) throw err;
1684
+ scriptingDenied = true;
1685
+ reply = await incrWithoutScript(c, redisKey, ttlSeconds);
1686
+ }
1655
1687
  }
1656
- const pttl = Number(await c.sendCommand("PTTL", redisKey));
1657
- const remainingMs = pttl > 0 ? pttl : 0;
1688
+ const count = Number(reply[0]);
1689
+ const remainingMs = Math.max(Number(reply[1]), 0);
1658
1690
  return { count, resetAt: Date.now() + remainingMs };
1659
1691
  }
1660
1692
  };
@@ -1801,6 +1833,7 @@ async function createApp(options) {
1801
1833
  const metricsReporter = options.observability?.metrics;
1802
1834
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1803
1835
  const maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
1836
+ const requestTimeoutMs = options.requestTimeoutMs;
1804
1837
  const securityHeadersOptions = options.security?.headers;
1805
1838
  const loggingEnabled = options.observability?.logging ?? true;
1806
1839
  const imageProxyHandler = createImageProxyHandler(options.images);
@@ -2248,6 +2281,31 @@ async function createApp(options) {
2248
2281
  );
2249
2282
  }
2250
2283
  }
2284
+ const withRequestTimeout = (inner) => async (req, server) => {
2285
+ if (!requestTimeoutMs) return inner(req, server);
2286
+ let timer;
2287
+ const timeout = new Promise((resolve2) => {
2288
+ timer = setTimeout(() => {
2289
+ const path = new URL(req.url).pathname;
2290
+ reportException(new Error(`Request timed out after ${requestTimeoutMs}ms`), {
2291
+ phase: "api",
2292
+ route: path
2293
+ });
2294
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "timeout" });
2295
+ resolve2(
2296
+ new Response("Gateway Timeout", {
2297
+ status: 504,
2298
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
2299
+ })
2300
+ );
2301
+ }, requestTimeoutMs);
2302
+ });
2303
+ try {
2304
+ return await Promise.race([inner(req, server), timeout]);
2305
+ } finally {
2306
+ clearTimeout(timer);
2307
+ }
2308
+ };
2251
2309
  async function handleRevalidation(req) {
2252
2310
  if (new URL(req.url).pathname !== "/__x/revalidate") return null;
2253
2311
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
@@ -2446,7 +2504,9 @@ data: ${data}
2446
2504
  }
2447
2505
  return renderNotFound(req);
2448
2506
  };
2449
- const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(devFetchInner), req, server));
2507
+ const devFetchHardened = async (req, server) => withResponseHardening(
2508
+ await guardFetchErrors(withRequestTimeout(withBodySizeLimit(devFetchInner)), req, server)
2509
+ );
2450
2510
  const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2451
2511
  const devFetchTraced = withRequestTracing(devFetchBase);
2452
2512
  const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchTraced) : devFetchTraced;
@@ -2505,7 +2565,9 @@ data: ${data}
2505
2565
  }
2506
2566
  return renderNotFound(req);
2507
2567
  };
2508
- const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
2568
+ const prodFetchHardened = async (req, server) => withResponseHardening(
2569
+ await guardFetchErrors(withRequestTimeout(withBodySizeLimit(prodFetchInner)), req, server)
2570
+ );
2509
2571
  const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2510
2572
  const prodFetchTraced = withRequestTracing(prodFetchBase);
2511
2573
  const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.9.0",
3
+ "version": "1.10.1",
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",
@@ -52,8 +52,8 @@
52
52
  "react-dom": "^19.0.0"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/react": "^19.0.0",
56
- "@types/react-dom": "^19.2.5",
57
- "tsup": "^8.3.0"
55
+ "@types/react": "^19.3.0",
56
+ "@types/react-dom": "^19.3.0",
57
+ "tsup": "^9.0.0"
58
58
  }
59
59
  }