@thexjs/core 1.8.4 → 1.10.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/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,3 +1,5 @@
1
+ import { BackpressureOptions } from './index.js';
2
+
1
3
  /**
2
4
  * The scratch directory that holds the transient (transpiled module / entry
3
5
  * source) files the bundler reads before inlining everything into
@@ -39,6 +41,8 @@ interface AdapterOptions {
39
41
  images?: {
40
42
  remoteHosts?: string[];
41
43
  };
44
+ /** Optional per-process request admission/backpressure. */
45
+ backpressure?: BackpressureOptions | false;
42
46
  /** Client build output dir. Server-mode routes' island bundles are emitted
43
47
  * into `<islandsDir>/_islands/` here so adapters can ship them as static
44
48
  * assets. Undefined skips island bundling (server HTML ships no island
@@ -96,16 +100,18 @@ interface BuildManifest {
96
100
  observability?: AdapterOptions["observability"];
97
101
  /** Remote image proxy options serialized for the generated entry. */
98
102
  images?: AdapterOptions["images"];
103
+ /** Backpressure options serialized for the generated entry. */
104
+ backpressure?: AdapterOptions["backpressure"];
99
105
  }
100
106
 
101
107
  /**
102
- * Serializes runtime config (security / observability / images) into the
103
- * generated entry. Only JSON-serializable values can cross the build
104
- * boundary -- a `security.errorReporter` or `observability.logger` callback
105
- * in `x.config.ts` must not silently vanish, or the deployed function would
106
- * drift from `x start`. Fail the build loudly with the offending keys.
108
+ * Serializes runtime config (security / observability / images / backpressure)
109
+ * into the generated entry. Only JSON-serializable values can cross the build
110
+ * boundary -- a callback in runtime config must not silently vanish, or the
111
+ * deployed function would drift from `x start`. Fail the build loudly with
112
+ * the offending keys.
107
113
  */
108
- declare function serializeRuntimeOptions(label: string, options: Record<string, unknown> | undefined): string;
114
+ declare function serializeRuntimeOptions(label: string, options: object | undefined): string;
109
115
  /**
110
116
  * Emits the source for the adapter render-function entry module.
111
117
  *
@@ -121,7 +127,8 @@ declare function serializeRuntimeOptions(label: string, options: Record<string,
121
127
  * function behaves exactly like the `x start` production server -- health
122
128
  * checks, rate limiting, revalidation, server actions, SSR with
123
129
  * loaders/layouts/middleware, API routes, security headers, the 404 page,
124
- * request logging -- all of it, with no drift between the two.
130
+ * request logging, and configured request backpressure -- all of it, with no
131
+ * drift between the two.
125
132
  *
126
133
  * The returned module exports a `handler` function; the platform adapter
127
134
  * decides its signature (e.g. a Node `(req, res)` bridge for Vercel).
@@ -163,4 +170,5 @@ declare function allModuleRefs(manifest: BuildManifest): CompiledModuleRef[];
163
170
  */
164
171
  declare function transpileModules(refs: CompiledModuleRef[]): Promise<void>;
165
172
 
166
- 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 };
package/dist/adapter.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  scanNotFound,
10
10
  scanPages,
11
11
  scanRoutes
12
- } from "./chunk-VGTN4YI5.js";
12
+ } from "./chunk-ME4ES2PD.js";
13
13
  import "./chunk-OXV2QTWV.js";
14
14
 
15
15
  // src/adapter/bundle.ts
@@ -76,10 +76,12 @@ function generateAdapterEntry(manifest, entryDir) {
76
76
  const securityOpts = serializeRuntimeOptions("security", manifest.security);
77
77
  const observabilityOpts = serializeRuntimeOptions("observability", manifest.observability);
78
78
  const imagesOpts = serializeRuntimeOptions("images", manifest.images);
79
+ const backpressureOpts = manifest.backpressure === void 0 ? "undefined" : manifest.backpressure === false ? "false" : serializeRuntimeOptions("backpressure", manifest.backpressure);
79
80
  lines.push(
80
81
  `const __x_security = ${securityOpts};`,
81
82
  `const __x_observability = ${observabilityOpts};`,
82
83
  `const __x_images = ${imagesOpts};`,
84
+ `const __x_backpressure = ${backpressureOpts};`,
83
85
  ""
84
86
  );
85
87
  const refs = /* @__PURE__ */ new Map();
@@ -148,6 +150,7 @@ function generateAdapterEntry(manifest, entryDir) {
148
150
  " ...(Object.keys(__x_security).length > 0 ? { security: __x_security } : {}),",
149
151
  " ...(Object.keys(__x_observability).length > 0 ? { observability: __x_observability } : {}),",
150
152
  " ...(Object.keys(__x_images).length > 0 ? { images: __x_images } : {}),",
153
+ " ...(__x_backpressure !== undefined ? { backpressure: __x_backpressure } : {}),",
151
154
  " preloaded: {",
152
155
  " routes: __x_preloadedRoutes,",
153
156
  ...manifest.notFound ? [` notFoundComponent: ${manifest.notFound.identifier}.default ?? undefined,`] : [],
@@ -304,7 +307,8 @@ async function resolveBuildManifest(options, scratchDir) {
304
307
  ...existsSync(join2(projectRoot, "public", "styles.css")) ? { stylesheetHref: "/styles.css" } : {},
305
308
  security: options.security,
306
309
  observability: options.observability,
307
- images: options.images
310
+ images: options.images,
311
+ backpressure: options.backpressure
308
312
  };
309
313
  }
310
314
  function allModuleRefs(manifest) {
@@ -0,0 +1,52 @@
1
+ interface BackpressureOptions {
2
+ /** Maximum number of requests allowed to execute concurrently in this process. */
3
+ maxConcurrent: number;
4
+ /** Maximum number of additional requests allowed to wait for a slot. Default: 0. */
5
+ maxQueue?: number;
6
+ /** Retry-After value used by `withBackpressure` when the queue is full. Default: 1 second. */
7
+ retryAfterSeconds?: number;
8
+ }
9
+ interface BackpressureSnapshot {
10
+ active: number;
11
+ queued: number;
12
+ maxConcurrent: number;
13
+ maxQueue: number;
14
+ }
15
+ interface BackpressureLease {
16
+ /** Releases one active slot. Safe to call more than once. */
17
+ release(): void;
18
+ }
19
+ interface BackpressureController {
20
+ /**
21
+ * Waits for an execution slot. Rejects with `BackpressureSaturatedError`
22
+ * when the queue is full, or with the request's abort reason while queued.
23
+ */
24
+ acquire(signal?: AbortSignal): Promise<BackpressureLease>;
25
+ snapshot(): BackpressureSnapshot;
26
+ }
27
+ declare class BackpressureSaturatedError extends Error {
28
+ readonly retryAfterSeconds: number;
29
+ constructor(retryAfterSeconds: number);
30
+ }
31
+ /**
32
+ * Creates one in-process admission controller.
33
+ *
34
+ * This is deliberately separate from rate limiting: rate limiting controls
35
+ * request frequency per identity/window, while this controller bounds the
36
+ * amount of work that may be active or waiting inside one process at a time.
37
+ * Queued requests are promoted FIFO as active leases are released.
38
+ */
39
+ declare function createBackpressureController(options: BackpressureOptions): BackpressureController;
40
+ type BackpressureHandler<TServer = unknown> = (req: Request, server?: TServer) => Response | Promise<Response>;
41
+ /**
42
+ * Wraps a request handler with bounded per-process admission.
43
+ *
44
+ * Saturation is reported as 503 Service Unavailable (not 429): the caller is
45
+ * not being rate-limited; this process has no execution/queue capacity left.
46
+ * Requests aborted while waiting are removed from the queue and their abort
47
+ * reason is re-thrown without invoking the wrapped handler.
48
+ */
49
+ declare function withBackpressure<TServer = unknown>(handler: BackpressureHandler<TServer>, options: BackpressureOptions): BackpressureHandler<TServer>;
50
+
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 };
@@ -60,7 +60,12 @@ var SAFE_ENV_KEYS = /* @__PURE__ */ new Set([
60
60
  "PATH",
61
61
  "TMPDIR",
62
62
  "TEMP",
63
- "TMP"
63
+ "TMP",
64
+ // Vercel injects this at build time as a cache-busting salt for
65
+ // content-addressed output (a Unix timestamp, e.g. "1783933175"). It is not
66
+ // a secret, but its short numeric value routinely appears inside bundled
67
+ // code, so the value scan would otherwise fail every Vercel build.
68
+ "VERCEL_HASH_SALT"
64
69
  ]);
65
70
  var SENSITIVE_KEY_PATTERNS = [
66
71
  /SECRET/i,
@@ -386,10 +391,7 @@ export function href<T extends keyof RouteMap & string>(
386
391
  const isNamedToken = (key: string) => new RegExp(\`(^|/):\${key}(?=/|$)\`).test(path);
387
392
  for (const [key, value] of Object.entries(params)) {
388
393
  if (!isNamedToken(key)) {
389
- const encoded = String(value)
390
- .split("/")
391
- .map(encodeURIComponent)
392
- .join("/");
394
+ const encoded = String(value).split("/").map(encodeURIComponent).join("/");
393
395
  result = result.replace(/\\*/, encoded);
394
396
  }
395
397
  }
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,56 +1,8 @@
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';
1
3
  import * as react from 'react';
2
4
  import { ComponentType, ReactNode, CSSProperties, AnchorHTMLAttributes } from 'react';
3
5
 
4
- interface BackpressureOptions {
5
- /** Maximum number of requests allowed to execute concurrently in this process. */
6
- maxConcurrent: number;
7
- /** Maximum number of additional requests allowed to wait for a slot. Default: 0. */
8
- maxQueue?: number;
9
- /** Retry-After value used by `withBackpressure` when the queue is full. Default: 1 second. */
10
- retryAfterSeconds?: number;
11
- }
12
- interface BackpressureSnapshot {
13
- active: number;
14
- queued: number;
15
- maxConcurrent: number;
16
- maxQueue: number;
17
- }
18
- interface BackpressureLease {
19
- /** Releases one active slot. Safe to call more than once. */
20
- release(): void;
21
- }
22
- interface BackpressureController {
23
- /**
24
- * Waits for an execution slot. Rejects with `BackpressureSaturatedError`
25
- * when the queue is full, or with the request's abort reason while queued.
26
- */
27
- acquire(signal?: AbortSignal): Promise<BackpressureLease>;
28
- snapshot(): BackpressureSnapshot;
29
- }
30
- declare class BackpressureSaturatedError extends Error {
31
- readonly retryAfterSeconds: number;
32
- constructor(retryAfterSeconds: number);
33
- }
34
- /**
35
- * Creates one in-process admission controller.
36
- *
37
- * This is deliberately separate from rate limiting: rate limiting controls
38
- * request frequency per identity/window, while this controller bounds the
39
- * amount of work that may be active or waiting inside one process at a time.
40
- * Queued requests are promoted FIFO as active leases are released.
41
- */
42
- declare function createBackpressureController(options: BackpressureOptions): BackpressureController;
43
- type BackpressureHandler<TServer = unknown> = (req: Request, server?: TServer) => Response | Promise<Response>;
44
- /**
45
- * Wraps a request handler with bounded per-process admission.
46
- *
47
- * Saturation is reported as 503 Service Unavailable (not 429): the caller is
48
- * not being rate-limited; this process has no execution/queue capacity left.
49
- * Requests aborted while waiting are removed from the queue and their abort
50
- * reason is re-thrown without invoking the wrapped handler.
51
- */
52
- declare function withBackpressure<TServer = unknown>(handler: BackpressureHandler<TServer>, options: BackpressureOptions): BackpressureHandler<TServer>;
53
-
54
6
  type RouteMode = "static" | "server";
55
7
  interface BuildOptions {
56
8
  routesDir?: string;
@@ -63,50 +15,15 @@ interface BuildOptions {
63
15
  /**
64
16
  * Absolute path to the project's x.config.ts/js/mjs, if any. When set, the
65
17
  * generated production server entry re-imports it at startup and forwards
66
- * its `security`/`observability` fields into `createApp()` — those fields
67
- * can hold live values (rate-limit key functions, error reporters, health
68
- * checks) that can't be serialized into the generated file directly.
18
+ * its runtime `security`/`observability`/`images`/`backpressure` fields into
19
+ * `createApp()` — those fields can hold live values (rate-limit key
20
+ * functions, error reporters, health checks) that can't be serialized into
21
+ * the generated file directly.
69
22
  */
70
23
  configPath?: string;
71
24
  }
72
25
  declare function build(options: BuildOptions): Promise<void>;
73
26
 
74
- /**
75
- * Inline client-side navigation script.
76
- *
77
- * Embedded directly into every rendered page as a <script> tag (see render.ts).
78
- * Intercepts same-origin <a> clicks, fetches the destination page, and swaps
79
- * the #root element's content in place. Includes hover-prefetch and popstate
80
- * (back/forward) support.
81
- *
82
- * Opt-out attributes on <a> / <Link />:
83
- * - data-no-nav — skip client navigation (full page load)
84
- * - data-no-prefetch — skip hover prefetch (navigation still works)
85
- */
86
- declare global {
87
- interface Window {
88
- __xIslandRoots?: Array<{
89
- unmount(): void;
90
- }>;
91
- }
92
- }
93
- declare const CLIENT_NAV_SCRIPT: string;
94
-
95
- interface Frontmatter {
96
- title?: string;
97
- [key: string]: unknown;
98
- }
99
- interface ContentEntry {
100
- filePath: string;
101
- routePath: string;
102
- slug: string;
103
- frontmatter: Frontmatter;
104
- body: string;
105
- }
106
- declare function scanContent(rootDir: string): ContentEntry[];
107
- declare function escapeHtml(s: string): string;
108
- declare function renderMarkdown(md: string): string;
109
-
110
27
  interface ImageProxyOptions {
111
28
  /** Hostnames allowed to be proxied, e.g. ["stardance.hackclub.com"]. Required — an empty/missing list disables the route (404). */
112
29
  remoteHosts?: string[];
@@ -504,7 +421,7 @@ interface RouteProps {
504
421
  params: Record<string, string>;
505
422
  loaderData?: Record<string, unknown>;
506
423
  }
507
- interface CreateAppOptions {
424
+ interface CreateAppOptions$1 {
508
425
  /** Primary route directory (legacy — mixes pages, api, layouts together). */
509
426
  routesDir?: string;
510
427
  /** Separate directory for page routes (preferred over routesDir when set). */
@@ -559,6 +476,20 @@ interface CreateAppOptions {
559
476
  * crossed. Default: 1 MiB.
560
477
  */
561
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;
562
493
  /**
563
494
  * Maximum entries in the per-route island bundle caches (both the
564
495
  * route→script-list mapping and the URL→bundled-JS file cache). Entries are
@@ -611,9 +542,73 @@ interface AppServeOptions {
611
542
  interface RevalidateOptions {
612
543
  revalidate?: number;
613
544
  }
545
+
546
+ /** Public application options, including opt-in per-process backpressure. */
547
+ interface CreateAppOptions extends CreateAppOptions$1 {
548
+ /**
549
+ * Bounds requests admitted into the application request pipeline for this
550
+ * process. `undefined`/`false` keeps the existing unbounded behavior.
551
+ *
552
+ * Liveness/readiness probes, an enabled built-in `/metrics` endpoint, and
553
+ * the development live-reload stream bypass admission so overload cannot
554
+ * make the process look dead or consume a permanent slot with the dev SSE
555
+ * connection.
556
+ */
557
+ backpressure?: BackpressureOptions | false;
558
+ }
559
+ /** Type-safe config helper for x.config.ts. */
614
560
  declare function defineConfig(config: CreateAppOptions): CreateAppOptions;
561
+ /**
562
+ * Creates the normal application and, when configured, places one bounded
563
+ * admission gate in front of its request pipeline.
564
+ *
565
+ * The controller is per `createApp()` call/process. Saturation returns 503 +
566
+ * Retry-After. A client that disconnects while queued is removed without
567
+ * entering the application pipeline or being turned into a false 500.
568
+ *
569
+ * Rate limiting remains the existing inner createApp policy. The two controls
570
+ * keep distinct semantics (429 policy vs 503 process capacity), but if the
571
+ * process is already saturated the outer admission gate can return 503 before
572
+ * the request reaches the inner rate limiter.
573
+ */
615
574
  declare function createApp(options: CreateAppOptions): Promise<AppServeOptions>;
616
575
 
576
+ /**
577
+ * Inline client-side navigation script.
578
+ *
579
+ * Embedded directly into every rendered page as a <script> tag (see render.ts).
580
+ * Intercepts same-origin <a> clicks, fetches the destination page, and swaps
581
+ * the #root element's content in place. Includes hover-prefetch and popstate
582
+ * (back/forward) support.
583
+ *
584
+ * Opt-out attributes on <a> / <Link />:
585
+ * - data-no-nav — skip client navigation (full page load)
586
+ * - data-no-prefetch — skip hover prefetch (navigation still works)
587
+ */
588
+ declare global {
589
+ interface Window {
590
+ __xIslandRoots?: Array<{
591
+ unmount(): void;
592
+ }>;
593
+ }
594
+ }
595
+ declare const CLIENT_NAV_SCRIPT: string;
596
+
597
+ interface Frontmatter {
598
+ title?: string;
599
+ [key: string]: unknown;
600
+ }
601
+ interface ContentEntry {
602
+ filePath: string;
603
+ routePath: string;
604
+ slug: string;
605
+ frontmatter: Frontmatter;
606
+ body: string;
607
+ }
608
+ declare function scanContent(rootDir: string): ContentEntry[];
609
+ declare function escapeHtml(s: string): string;
610
+ declare function renderMarkdown(md: string): string;
611
+
617
612
  declare function renderErrorOverlay(error: unknown): string;
618
613
 
619
614
  interface ImageProps {
@@ -1124,4 +1119,5 @@ declare function resetServerFunctions(): void;
1124
1119
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
1125
1120
  declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
1126
1121
 
1127
- export { type AuditEntry, type AuditEvent, type AuditSink, type BackpressureController, type BackpressureHandler, type BackpressureLease, type BackpressureOptions, BackpressureSaturatedError, type BackpressureSnapshot, 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, createBackpressureController, 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, withBackpressure, 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 };