@thexjs/core 1.6.1 → 1.7.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/dist/index.d.ts +59 -3
- package/dist/index.js +132 -5
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ComponentType, ReactNode, CSSProperties, AnchorHTMLAttributes } from 'react';
|
|
3
3
|
|
|
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
|
+
|
|
4
54
|
type RouteMode = "static" | "server";
|
|
5
55
|
interface BuildOptions {
|
|
6
56
|
routesDir?: string;
|
|
@@ -631,6 +681,13 @@ declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProp
|
|
|
631
681
|
|
|
632
682
|
declare function DefaultNotFound(_props: RouteProps): react.JSX.Element;
|
|
633
683
|
|
|
684
|
+
/**
|
|
685
|
+
* Returns the client IP from a request, checking `X-Forwarded-For` first
|
|
686
|
+
* (for proxied/edge deployments), falling back to `X-Real-IP`, and finally
|
|
687
|
+
* to `null` if neither is present.
|
|
688
|
+
*/
|
|
689
|
+
declare function clientIpFromRequest(req: Request): string | null;
|
|
690
|
+
|
|
634
691
|
/**
|
|
635
692
|
* Structured, append-only audit logging for security-relevant events.
|
|
636
693
|
*
|
|
@@ -670,8 +727,7 @@ declare const noopAuditSink: AuditSink;
|
|
|
670
727
|
declare function createConsoleAuditSink(): AuditSink;
|
|
671
728
|
declare function setAuditSink(sink: AuditSink): void;
|
|
672
729
|
declare function getAuditSink(): AuditSink;
|
|
673
|
-
|
|
674
|
-
declare function clientIpFromRequest(req: Request): string | null;
|
|
730
|
+
|
|
675
731
|
/** Correlation id already assigned to the request by `withRequestLogging`, if any. */
|
|
676
732
|
declare function requestIdFromRequest(req: Request): string | undefined;
|
|
677
733
|
/**
|
|
@@ -955,4 +1011,4 @@ declare function resetServerFunctions(): void;
|
|
|
955
1011
|
declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
|
|
956
1012
|
declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
|
|
957
1013
|
|
|
958
|
-
export { type AuditEntry, type AuditEvent, type AuditSink, 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, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, 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, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
|
1014
|
+
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, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, 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, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withBackpressure, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
package/dist/index.js
CHANGED
|
@@ -56,6 +56,128 @@ import {
|
|
|
56
56
|
withRequestTracing
|
|
57
57
|
} from "./chunk-OIPCIXYR.js";
|
|
58
58
|
|
|
59
|
+
// src/backpressure.ts
|
|
60
|
+
var BackpressureSaturatedError = class extends Error {
|
|
61
|
+
retryAfterSeconds;
|
|
62
|
+
constructor(retryAfterSeconds) {
|
|
63
|
+
super("Backpressure queue is full");
|
|
64
|
+
this.name = "BackpressureSaturatedError";
|
|
65
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
function positiveInteger(value, name) {
|
|
69
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
70
|
+
throw new TypeError(`${name} must be a positive integer`);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function nonNegativeInteger(value, name) {
|
|
75
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
76
|
+
throw new TypeError(`${name} must be a non-negative integer`);
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
function abortReason(signal) {
|
|
81
|
+
if (signal.reason !== void 0) return signal.reason;
|
|
82
|
+
return new DOMException("The operation was aborted", "AbortError");
|
|
83
|
+
}
|
|
84
|
+
function createBackpressureController(options) {
|
|
85
|
+
const maxConcurrent = positiveInteger(options.maxConcurrent, "maxConcurrent");
|
|
86
|
+
const maxQueue = nonNegativeInteger(options.maxQueue ?? 0, "maxQueue");
|
|
87
|
+
const retryAfterSeconds = positiveInteger(options.retryAfterSeconds ?? 1, "retryAfterSeconds");
|
|
88
|
+
const queue = [];
|
|
89
|
+
let active = 0;
|
|
90
|
+
function detachAbort(waiter) {
|
|
91
|
+
if (waiter.signal && waiter.onAbort) {
|
|
92
|
+
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function makeLease() {
|
|
96
|
+
let released = false;
|
|
97
|
+
return {
|
|
98
|
+
release() {
|
|
99
|
+
if (released) return;
|
|
100
|
+
released = true;
|
|
101
|
+
active -= 1;
|
|
102
|
+
promote();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function promote() {
|
|
107
|
+
while (active < maxConcurrent && queue.length > 0) {
|
|
108
|
+
const waiter = queue.shift();
|
|
109
|
+
if (!waiter) return;
|
|
110
|
+
detachAbort(waiter);
|
|
111
|
+
if (waiter.signal?.aborted) {
|
|
112
|
+
waiter.reject(abortReason(waiter.signal));
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
active += 1;
|
|
116
|
+
waiter.resolve(makeLease());
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function acquire(signal) {
|
|
120
|
+
if (signal?.aborted) return Promise.reject(abortReason(signal));
|
|
121
|
+
if (active < maxConcurrent) {
|
|
122
|
+
active += 1;
|
|
123
|
+
return Promise.resolve(makeLease());
|
|
124
|
+
}
|
|
125
|
+
if (queue.length >= maxQueue) {
|
|
126
|
+
return Promise.reject(new BackpressureSaturatedError(retryAfterSeconds));
|
|
127
|
+
}
|
|
128
|
+
return new Promise((resolve2, reject) => {
|
|
129
|
+
const waiter = {
|
|
130
|
+
signal,
|
|
131
|
+
resolve: resolve2,
|
|
132
|
+
reject,
|
|
133
|
+
onAbort: void 0
|
|
134
|
+
};
|
|
135
|
+
if (signal) {
|
|
136
|
+
waiter.onAbort = () => {
|
|
137
|
+
const index = queue.indexOf(waiter);
|
|
138
|
+
if (index < 0) return;
|
|
139
|
+
queue.splice(index, 1);
|
|
140
|
+
detachAbort(waiter);
|
|
141
|
+
reject(abortReason(signal));
|
|
142
|
+
};
|
|
143
|
+
signal.addEventListener("abort", waiter.onAbort, { once: true });
|
|
144
|
+
}
|
|
145
|
+
queue.push(waiter);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
acquire,
|
|
150
|
+
snapshot() {
|
|
151
|
+
return { active, queued: queue.length, maxConcurrent, maxQueue };
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function withBackpressure(handler, options) {
|
|
156
|
+
const controller = createBackpressureController(options);
|
|
157
|
+
return async (req, server) => {
|
|
158
|
+
let lease;
|
|
159
|
+
try {
|
|
160
|
+
lease = await controller.acquire(req.signal);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (error instanceof BackpressureSaturatedError) {
|
|
163
|
+
return new Response("Service Unavailable", {
|
|
164
|
+
status: 503,
|
|
165
|
+
headers: {
|
|
166
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
167
|
+
"Retry-After": String(error.retryAfterSeconds)
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
return await handler(req, server);
|
|
175
|
+
} finally {
|
|
176
|
+
lease.release();
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
59
181
|
// src/build.ts
|
|
60
182
|
import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
|
|
61
183
|
import { join as join2, relative as relative2 } from "path";
|
|
@@ -2737,6 +2859,13 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
|
|
|
2737
2859
|
);
|
|
2738
2860
|
}
|
|
2739
2861
|
|
|
2862
|
+
// src/security/ip.ts
|
|
2863
|
+
function clientIpFromRequest(req) {
|
|
2864
|
+
const forwarded = req.headers.get("x-forwarded-for");
|
|
2865
|
+
if (forwarded) return forwarded.split(",")[0]?.trim() || null;
|
|
2866
|
+
return req.headers.get("x-real-ip");
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2740
2869
|
// src/observability/audit.ts
|
|
2741
2870
|
var noopAuditSink = {
|
|
2742
2871
|
write: () => {
|
|
@@ -2756,11 +2885,6 @@ function setAuditSink(sink) {
|
|
|
2756
2885
|
function getAuditSink() {
|
|
2757
2886
|
return activeSink;
|
|
2758
2887
|
}
|
|
2759
|
-
function clientIpFromRequest(req) {
|
|
2760
|
-
const forwarded = req.headers.get("x-forwarded-for");
|
|
2761
|
-
if (forwarded) return forwarded.split(",")[0]?.trim() || null;
|
|
2762
|
-
return req.headers.get("x-real-ip");
|
|
2763
|
-
}
|
|
2764
2888
|
function requestIdFromRequest(req) {
|
|
2765
2889
|
return req.headers.get("x-request-id") ?? void 0;
|
|
2766
2890
|
}
|
|
@@ -2850,6 +2974,7 @@ function installProcessCrashHandlers(options = {}) {
|
|
|
2850
2974
|
};
|
|
2851
2975
|
}
|
|
2852
2976
|
export {
|
|
2977
|
+
BackpressureSaturatedError,
|
|
2853
2978
|
CLIENT_NAV_SCRIPT,
|
|
2854
2979
|
DEFAULT_HISTOGRAM_BUCKETS_MS,
|
|
2855
2980
|
DEFAULT_MAX_BODY_SIZE,
|
|
@@ -2882,6 +3007,7 @@ export {
|
|
|
2882
3007
|
combineReporters,
|
|
2883
3008
|
composeMiddleware,
|
|
2884
3009
|
createApp,
|
|
3010
|
+
createBackpressureController,
|
|
2885
3011
|
createConsoleAuditSink,
|
|
2886
3012
|
createHealthCheckHandler,
|
|
2887
3013
|
createImageProxyHandler,
|
|
@@ -2941,6 +3067,7 @@ export {
|
|
|
2941
3067
|
traceRequestId,
|
|
2942
3068
|
verifyCsrfToken,
|
|
2943
3069
|
verifyOrigin,
|
|
3070
|
+
withBackpressure,
|
|
2944
3071
|
withCsrfCookie,
|
|
2945
3072
|
withRequestLogging,
|
|
2946
3073
|
withRequestMetrics,
|
package/package.json
CHANGED