@thexjs/core 0.1.7 → 1.1.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
@@ -1,14 +1,14 @@
1
1
  # @thexjs/core
2
2
 
3
- The rendering/routing engine behind **x** — a full-stack React framework built on [Bun](https://bun.sh). This package provides file-based routing, SSR/SSG rendering, islands, server functions, a content layer, and a lightweight data layer (SQLite/Postgres).
3
+ The rendering/routing engine behind **x**, a full-stack React framework built on [Bun](https://bun.sh). This package provides file-based routing, SSR/SSG rendering, islands, server functions, a content layer, and a lightweight data layer (SQLite/Postgres).
4
4
 
5
- You typically don't install this directly — [`@thexjs/cli`](https://www.npmjs.com/package/@thexjs/cli) depends on it and drives `x dev` / `x build` / `x start` for you. Install it explicitly only if you're calling the APIs below directly (e.g. a custom server entry).
5
+ You typically don't install this directly. [`@thexjs/cli`](https://www.npmjs.com/package/@thexjs/cli) depends on it and drives `x dev` / `x build` / `x start` for you. Install it explicitly only if you're calling the APIs below directly (e.g. a custom server entry).
6
6
 
7
7
  ```sh
8
8
  bun add @thexjs/core
9
9
  ```
10
10
 
11
- > Requires the Bun runtime — this package uses `Bun.serve`, `Bun.file`, `bun:sqlite`, and `Bun.sql` internally.
11
+ > Requires the Bun runtime. This package uses `Bun.serve`, `Bun.file`, `bun:sqlite`, and `Bun.sql` internally.
12
12
 
13
13
  ## Quick start
14
14
 
@@ -45,10 +45,11 @@ Given a `pagesDir`, `scanPages` walks the directory and maps files to routes:
45
45
  | `src/pages/index.tsx` | `/` |
46
46
  | `src/pages/about.tsx` | `/about` |
47
47
  | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
- | `src/pages/api/users.ts` | API route at `/api/users` |
48
+ | `src/pages/blog/[...rest].tsx` | `/blog/*` (catch-all) |
49
49
  | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
50
  | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
51
  | `src/pages/_404.tsx` | Custom not-found page |
52
+ | `src/api/users.ts` | API route at `/api/users` (via `apiDir`) |
52
53
 
53
54
  Files and directories prefixed with `_` or `.` are never treated as routes.
54
55
 
@@ -62,8 +63,8 @@ Every page defaults to **server-rendered (SSR)**. Opt into build-time prerenderi
62
63
  export const mode: "static" | "server" = "static";
63
64
  ```
64
65
 
65
- - **`static`** — rendered once at `x build` time to a `.html` file. Best for marketing pages, docs, blog posts — anything that doesn't need per-request data. No page in your app defaults to this; you must set it explicitly, or the build step will silently ship an empty/server-only route with no prerendered HTML.
66
- - **`server`** (default) — rendered per-request via `renderPage` / `renderStreamingPage` when running under `x start` (or `x dev`). Requires a live Bun server; **not deployable to static hosts** (see Deployment below).
66
+ - **`static`**: rendered once at `x build` time to a `.html` file. Best for marketing pages, docs, blog posts, anything that doesn't need per-request data. No page in your app defaults to this; you must set it explicitly, or the build step will silently ship an empty/server-only route with no prerendered HTML.
67
+ - **`server`** (default): rendered per-request via `renderPage` / `renderStreamingPage` when running under `x start` (or `x dev`). Requires a live Bun server; **not deployable to static hosts** (see Deployment below).
67
68
 
68
69
  ## Loaders
69
70
 
@@ -76,8 +77,9 @@ export async function loader({ params }: { params: Record<string, string> }) {
76
77
  return { user: await getUser(params.id) };
77
78
  }
78
79
 
79
- export default function UserPage({ loaderData }: RouteProps<typeof loader>) {
80
- return <p>{loaderData.user.name}</p>;
80
+ export default function UserPage({ loaderData }: RouteProps) {
81
+ const { user } = loaderData as { user: { name: string } };
82
+ return <p>{user.name}</p>;
81
83
  }
82
84
  ```
83
85
 
@@ -85,16 +87,20 @@ export default function UserPage({ loaderData }: RouteProps<typeof loader>) {
85
87
 
86
88
  ## Server functions / actions
87
89
 
88
- Files under an `actionsDir` (or a page's colocated `actions` export) register callable server functions:
90
+ Files under an `actionsDir` register callable server functions. Each named export (or an `export const actions = { ... }` map) becomes a function callable from a client island:
89
91
 
90
92
  ```ts
91
- // src/pages/contact/_actions.ts
93
+ // src/actions/contact.ts
92
94
  export async function submitContact(data: { email: string; message: string }) {
93
95
  // runs on the server, callable from a client island
94
96
  }
97
+
98
+ export const actions = {
99
+ ping: async () => ({ pong: true }),
100
+ };
95
101
  ```
96
102
 
97
- `registerServerFunctions`, `generateServerFunctionClient`, and `getServerFunctionHandler` are the lower-level primitives the router wires up automatically — most apps won't call these directly.
103
+ `registerServerFunctions`, `generateServerFunctionClient`, and `getServerFunctionHandler` are the lower-level primitives the router wires up automatically. Most apps won't call these directly.
98
104
 
99
105
  ## Islands (selective hydration)
100
106
 
@@ -103,7 +109,7 @@ Wrap any interactive piece of a static/server-rendered page in `<Island>` to shi
103
109
  ```tsx
104
110
  import { Island } from "@thexjs/core";
105
111
 
106
- <Island name="like-button" client="visible">
112
+ <Island name="LikeButton" client="visible">
107
113
  <LikeButton />
108
114
  </Island>
109
115
  ```
@@ -123,17 +129,17 @@ const html = renderMarkdown(posts[0].body);
123
129
 
124
130
  ## Data layer
125
131
 
126
- Thin, typed wrappers over Bun's built-in SQLite and Postgres clients, plus a minimal migration runner:
132
+ Thin, typed wrappers over Bun's built-in SQLite and Postgres clients, plus a minimal migration runner. Import from the `@thexjs/core/data` subpath:
127
133
 
128
134
  ```ts
129
- import { connectSQLite, runSQLiteMigrations } from "@thexjs/core";
135
+ import { connectSQLite, runSQLiteMigrations } from "@thexjs/core/data";
130
136
 
131
- const db = connectSQLite({ filename: "./data/dev.db" });
137
+ const db = connectSQLite({ path: "./data/dev.db" });
132
138
  await runSQLiteMigrations(db, "./data/migrations");
133
139
  ```
134
140
 
135
141
  ```ts
136
- import { connectPostgres, runPostgresMigrations } from "@thexjs/core";
142
+ import { connectPostgres, runPostgresMigrations } from "@thexjs/core/data";
137
143
 
138
144
  const sql = connectPostgres({ url: process.env.DATABASE_URL! });
139
145
  await runPostgresMigrations(sql, "./data/migrations");
@@ -143,12 +149,14 @@ await runPostgresMigrations(sql, "./data/migrations");
143
149
 
144
150
  ```ts
145
151
  // src/pages/dashboard/_middleware.ts
146
- import type { MiddlewareFn } from "@thexjs/core";
152
+ import type { MiddlewareContext, MiddlewareNext } from "@thexjs/core";
147
153
 
148
- export const middleware: MiddlewareFn = async (ctx, next) => {
149
- if (!ctx.session) return new Response("Unauthorized", { status: 401 });
154
+ export async function middleware(ctx: MiddlewareContext, next: MiddlewareNext) {
155
+ if (!ctx.request.headers.get("authorization")) {
156
+ return new Response("Unauthorized", { status: 401 });
157
+ }
150
158
  return next();
151
- };
159
+ }
152
160
  ```
153
161
 
154
162
  `composeMiddleware` chains multiple middleware functions together; `findMiddlewareChain` resolves which ones apply to a given route based on directory nesting.
@@ -170,7 +178,7 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
170
178
 
171
179
  ## Deployment note
172
180
 
173
- `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.
181
+ `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.
174
182
 
175
183
  ## Enterprise readiness: security & observability
176
184
 
@@ -205,7 +213,7 @@ const app = createApp({
205
213
  });
206
214
  ```
207
215
 
208
- Only variables prefixed `THEXJS_PUBLIC_` may reach the browser — `@thexjs/env`'s `createEnv` defaults `clientPrefix` to that, and the build step throws an `EnvLeakageError` if any client bundle references a server-only `process.env`/`Bun.env`/`import.meta.env` variable, so a secret like `STRIPE_SECRET_KEY` can never round-trip into shipped JS.
216
+ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser. `@thexjs/env`'s `createEnv` defaults `clientPrefix` to that, and the build step throws an `EnvLeakageError` if any client bundle references a server-only `process.env`/`Bun.env`/`import.meta.env` variable, so a secret like `STRIPE_SECRET_KEY` can never round-trip into shipped JS.
209
217
 
210
218
  ## Exports reference
211
219
 
@@ -223,7 +231,7 @@ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser — `@thexjs/env`
223
231
  | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
224
232
  | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
225
233
  | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
226
- | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult` | Rate limiting |
234
+ | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitServer`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
227
235
  | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
228
236
  | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
229
237
  | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
package/dist/data.d.ts CHANGED
@@ -7,9 +7,20 @@ interface SQLiteOptions {
7
7
  }
8
8
  declare function connectSQLite(options?: SQLiteOptions): Database;
9
9
 
10
+ /** A Postgres client scoped to a single transaction (auto-commit/rollback). */
11
+ interface PostgresTransactionClient {
12
+ unsafe(query: string, params?: unknown[]): Promise<unknown>;
13
+ (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
14
+ }
10
15
  interface PostgresClient {
11
- unsafe(query: string): Promise<unknown>;
16
+ unsafe(query: string, params?: unknown[]): Promise<unknown>;
12
17
  (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
18
+ /**
19
+ * Runs `fn` inside a transaction. The callback receives a transaction-scoped
20
+ * client; when it resolves the transaction commits, when it throws it rolls
21
+ * back — so a group of statements either all apply or none do.
22
+ */
23
+ begin<T>(fn: (tx: PostgresTransactionClient) => Promise<T>): Promise<T>;
13
24
  }
14
25
  type PostgresSslMode = "disable" | "prefer" | "require" | "verify-ca" | "verify-full";
15
26
  interface PostgresOptions {
package/dist/data.js CHANGED
@@ -84,7 +84,10 @@ function connectPostgres(options = {}) {
84
84
  return new Proxy(sql, {
85
85
  get(target, prop, receiver) {
86
86
  if (prop === "unsafe") {
87
- return (query) => run(() => client.unsafe(query));
87
+ return (query, params) => run(() => client.unsafe(query, params));
88
+ }
89
+ if (prop === "begin") {
90
+ return (fn) => run(() => client.begin(async (tx) => fn(tx)));
88
91
  }
89
92
  const value = Reflect.get(target, prop, receiver);
90
93
  return typeof value === "function" ? value.bind(target) : value;
@@ -119,8 +122,10 @@ function runSQLiteMigrations(db, migrationsDir) {
119
122
  continue;
120
123
  }
121
124
  const sql = readFileSync(join(migrationsDir, file), "utf-8");
122
- db.run(sql);
123
- db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
125
+ db.transaction(() => {
126
+ db.run(sql);
127
+ db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
128
+ })();
124
129
  console.log(`[x] migration applied: ${file}`);
125
130
  result.applied.push(file);
126
131
  }
@@ -146,8 +151,10 @@ async function runPostgresMigrations(client, migrationsDir) {
146
151
  continue;
147
152
  }
148
153
  const raw = readFileSync(join(migrationsDir, file), "utf-8");
149
- await client.unsafe(raw);
150
- await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
154
+ await client.begin(async (tx) => {
155
+ await tx.unsafe(raw);
156
+ await tx.unsafe("INSERT INTO _x_migrations (name) VALUES ($1)", [file]);
157
+ });
151
158
  console.log(`[x] migration applied: ${file}`);
152
159
  result.applied.push(file);
153
160
  }
package/dist/index.d.ts CHANGED
@@ -234,11 +234,26 @@ interface RateLimitOptions {
234
234
  limit?: number;
235
235
  /** Window size in milliseconds. Default: 60_000 (1 minute). */
236
236
  windowMs?: number;
237
- /** Derives the rate-limit bucket key from a request. Default: client IP from standard headers. */
238
- keyFn?: (req: Request) => string;
237
+ /**
238
+ * Derives the rate-limit bucket key from a request. Default: the client IP
239
+ * from the underlying socket (Bun `server.requestIP`), falling back to the
240
+ * `x-forwarded-for` / `x-real-ip` headers. `server` is provided when the
241
+ * limiter is wired into `Bun.serve`.
242
+ */
243
+ keyFn?: (req: Request, server?: RateLimitServer) => string;
239
244
  /** Optional shared store (e.g. Redis) for multi-instance deployments. */
240
245
  store?: RateLimitStore;
241
246
  }
247
+ /**
248
+ * The subset of Bun's `Bun.serve` server handle the rate limiter needs to
249
+ * resolve the real client IP from the socket. Passed through from
250
+ * `Bun.serve`'s `fetch(request, server)` second argument.
251
+ */
252
+ interface RateLimitServer {
253
+ requestIP?: (req: Request) => {
254
+ address: string;
255
+ } | null;
256
+ }
242
257
  interface RateLimitResult {
243
258
  ok: boolean;
244
259
  limit: number;
@@ -262,7 +277,7 @@ interface Bucket {
262
277
  }
263
278
  /** Creates an independent rate limiter with its own bucket store. */
264
279
  declare function createRateLimiter(options?: RateLimitOptions): {
265
- check: (req: Request) => Promise<RateLimitResult>;
280
+ check: (req: Request, server?: RateLimitServer) => Promise<RateLimitResult>;
266
281
  sweep: () => void;
267
282
  buckets: Map<string, Bucket>;
268
283
  dispose: () => void;
@@ -271,12 +286,12 @@ declare function createRateLimiter(options?: RateLimitOptions): {
271
286
  * Convenience middleware-style handler: returns a 429 Response when the
272
287
  * limit is exceeded, or null when the request should proceed.
273
288
  */
274
- declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request): Promise<Response | null>;
289
+ declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request, server?: RateLimitServer): Promise<Response | null>;
275
290
  /**
276
291
  * Shared rate-limit store backed by Redis, so limits are enforced across
277
- * multiple server instances. Uses Bun's built-in `bun:redis` (no npm
278
- * dependency) and connects lazily on first use. Pass the result as
279
- * `store` in `createRateLimiter`/`security.rateLimit`.
292
+ * multiple server instances. Connects lazily on first use and keeps retrying
293
+ * after a failed connection attempt. Pass the result as `store` in
294
+ * `createRateLimiter`/`security.rateLimit`.
280
295
  */
281
296
  declare function createRedisRateLimitStore(options?: {
282
297
  url?: string;
@@ -501,7 +516,9 @@ declare const logger: Logger;
501
516
  /**
502
517
  * Wraps a fetch handler so every request is logged as one structured JSON
503
518
  * line with `timestamp`, `requestId`, `route`, `status`, and `durationMs`.
519
+ * A second argument (Bun.serve's `server` handle) is forwarded untouched so
520
+ * downstream middleware like the rate limiter can resolve the client IP.
504
521
  */
505
- declare function withRequestLogging(handler: (req: Request) => Response | Promise<Response>): (req: Request) => Promise<Response>;
522
+ declare function withRequestLogging<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
506
523
 
507
524
  export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CreateAppOptions, type CsrfOptions, type CsrfResult, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type ImageProxyOptions, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelTracerLike, PUBLIC_ENV_PREFIX, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, build, buildSecurityHeaders, checkCsrf, combineReporters, composeMiddleware, createApp, createHealthCheckHandler, createImageProxyHandler, createOtelReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, defineConfig, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getErrorReporter, getServerFunctionHandler, logger, noopReporter, rateLimitMiddleware, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, resetServerFunctions, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setErrorReporter, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, writeManifest };
package/dist/index.js CHANGED
@@ -611,19 +611,49 @@ function parseYamlLines(raw) {
611
611
  function escapeHtml2(s) {
612
612
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
613
613
  }
614
+ function renderListBlock(block) {
615
+ const lines = block.split("\n");
616
+ const isUl = lines.every((l) => /^\s*[-*]\s+/.test(l));
617
+ const isOl = lines.every((l) => /^\s*\d+\.\s+/.test(l));
618
+ if (!isUl && !isOl) return block;
619
+ const tag = isUl ? "ul" : "ol";
620
+ const items = lines.map((l) => `<li>${l.replace(/^\s*[-*]\s+/, "").replace(/^\s*\d+\.\s+/, "")}</li>`).join("");
621
+ return `<${tag}>${items}</${tag}>`;
622
+ }
623
+ var ALLOWED_LINK_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto"]);
624
+ var LINK_SCHEME_RE = /^([a-z][a-z0-9+.-]*):/i;
625
+ function decodeLinkUrl(url) {
626
+ try {
627
+ return decodeURIComponent(url);
628
+ } catch {
629
+ return url;
630
+ }
631
+ }
632
+ function isSafeLinkUrl(url) {
633
+ const scheme = LINK_SCHEME_RE.exec(decodeLinkUrl(url.trim()))?.[1]?.toLowerCase();
634
+ return scheme === void 0 || ALLOWED_LINK_SCHEMES.has(scheme);
635
+ }
614
636
  function renderMarkdown(md) {
615
637
  const inlineCodes = [];
616
- let html = md.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(
617
- /`{3}(\w*)\n([\s\S]*?)`{3}/gm,
618
- (_m, _lang, code) => `<pre><code>${escapeHtml2(code.trim())}</code></pre>`
619
- ).replace(/`([^`]+)`/g, (_m, code) => {
638
+ const fences = [];
639
+ let html = escapeHtml2(md).replace(/`{3}(\w*)\n([\s\S]*?)`{3}/gm, (_m, _lang, code) => {
640
+ fences.push(`<pre><code>${code.trim()}</code></pre>`);
641
+ return `__X_FENCE_${fences.length - 1}__`;
642
+ });
643
+ html = html.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(/`([^`]+)`/g, (_m, code) => {
620
644
  inlineCodes.push(code);
621
645
  return `__X_CODE_${inlineCodes.length - 1}__`;
622
- }).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>').replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
646
+ }).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
647
+ /\[([^\]]+)\]\(([^)]+)\)/g,
648
+ (_m, text, href) => isSafeLinkUrl(href) ? `<a href="${href}">${text}</a>` : text
649
+ ).replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
650
+ html = html.replace(/__X_FENCE_(\d+)__/g, (_m, i) => fences[Number.parseInt(i)] ?? "");
623
651
  const blocks = html.split(/\n\n+/);
624
652
  html = blocks.map((b) => {
625
653
  const t = b.trim();
626
654
  if (!t) return "";
655
+ const listBlock = renderListBlock(t);
656
+ if (listBlock !== t) return listBlock;
627
657
  if (t.startsWith("<h") || t.startsWith("<pre") || t.startsWith("<ul") || t.startsWith("<ol"))
628
658
  return t;
629
659
  return `<p>${t}</p>`;
@@ -1303,12 +1333,12 @@ var logger = {
1303
1333
  error: (message, fields) => write("error", message, fields)
1304
1334
  };
1305
1335
  function withRequestLogging(handler) {
1306
- return async (req) => {
1336
+ return async (req, server) => {
1307
1337
  const start = performance.now();
1308
1338
  const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
1309
1339
  const route = new URL(req.url).pathname;
1310
1340
  try {
1311
- const res = await handler(req);
1341
+ const res = await handler(req, server);
1312
1342
  const isStream = res.headers.get("content-type")?.includes("text/event-stream");
1313
1343
  console.log(
1314
1344
  `[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
@@ -1371,11 +1401,14 @@ function applySecurityHeaders(res, options = {}) {
1371
1401
  }
1372
1402
 
1373
1403
  // src/security/rate-limit.ts
1374
- function defaultKeyFn(req) {
1375
- const headers = req.headers;
1376
- const forwarded = headers.get("x-forwarded-for");
1404
+ function defaultKeyFn(req, server) {
1405
+ if (server?.requestIP) {
1406
+ const ip = server.requestIP(req);
1407
+ if (ip) return ip.address;
1408
+ }
1409
+ const forwarded = req.headers.get("x-forwarded-for");
1377
1410
  if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
1378
- return headers.get("x-real-ip") ?? "unknown";
1411
+ return req.headers.get("x-real-ip") ?? "unknown";
1379
1412
  }
1380
1413
  function createRateLimiter(options = {}) {
1381
1414
  const limit = options.limit ?? 60;
@@ -1383,8 +1416,8 @@ function createRateLimiter(options = {}) {
1383
1416
  const keyFn = options.keyFn ?? defaultKeyFn;
1384
1417
  const store = options.store;
1385
1418
  const buckets = /* @__PURE__ */ new Map();
1386
- async function check(req) {
1387
- const key = keyFn(req);
1419
+ async function check(req, server) {
1420
+ const key = keyFn(req, server);
1388
1421
  if (store) {
1389
1422
  const { count, resetAt } = await store.incr(key, windowMs);
1390
1423
  return { ok: count <= limit, limit, remaining: Math.max(0, limit - count), resetAt };
@@ -1409,33 +1442,39 @@ function createRateLimiter(options = {}) {
1409
1442
  timer.unref?.();
1410
1443
  return { check, sweep, buckets, dispose: () => clearInterval(timer) };
1411
1444
  }
1412
- async function rateLimitMiddleware(limiter, req) {
1413
- const result = await limiter.check(req);
1445
+ async function rateLimitMiddleware(limiter, req, server) {
1446
+ const result = await limiter.check(req, server);
1414
1447
  if (result.ok) return null;
1415
1448
  const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
1416
1449
  return new Response("Too Many Requests", {
1417
1450
  status: 429,
1418
1451
  headers: {
1452
+ "Content-Type": "text/plain; charset=utf-8",
1419
1453
  "Retry-After": String(retryAfterSeconds),
1420
1454
  "X-RateLimit-Limit": String(result.limit),
1421
1455
  "X-RateLimit-Remaining": String(result.remaining)
1422
1456
  }
1423
1457
  });
1424
1458
  }
1425
- function createRedisRateLimitStore(options = {}) {
1426
- let client = null;
1427
- let connecting = null;
1428
- async function connect() {
1459
+ function createBunRedisClient(options) {
1460
+ return async () => {
1429
1461
  const require2 = import.meta.require;
1430
1462
  const mod = require2("bun:redis");
1431
1463
  const instance = options.url ? new mod.RedisClient({ url: options.url }) : new mod.RedisClient();
1432
1464
  await instance.connect();
1433
1465
  return instance;
1434
- }
1466
+ };
1467
+ }
1468
+ function createRedisRateLimitStore(options = {}) {
1469
+ return createRedisRateLimitStoreFromClient(createBunRedisClient(options));
1470
+ }
1471
+ function createRedisRateLimitStoreFromClient(clientFactory) {
1472
+ let client = null;
1473
+ let connecting = null;
1435
1474
  function getClient() {
1436
1475
  if (client) return Promise.resolve(client);
1437
1476
  if (!connecting) {
1438
- connecting = connect().then(
1477
+ connecting = clientFactory().then(
1439
1478
  (c) => {
1440
1479
  client = c;
1441
1480
  return c;
@@ -1989,12 +2028,12 @@ async function createApp(options) {
1989
2028
  } catch {
1990
2029
  console.warn("[x] file watching not available on this platform");
1991
2030
  }
1992
- const devFetchInner = async (req) => {
2031
+ const devFetchInner = async (req, server) => {
1993
2032
  const url = new URL(req.url).pathname;
1994
2033
  const healthResult = await healthHandler(req);
1995
2034
  if (healthResult !== null) return healthResult;
1996
2035
  if (rateLimiter) {
1997
- const limited = await rateLimitMiddleware(rateLimiter, req);
2036
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
1998
2037
  if (limited !== null) return limited;
1999
2038
  }
2000
2039
  if (url === "/__x/reload") {
@@ -2055,7 +2094,7 @@ data: ${data}
2055
2094
  }
2056
2095
  return renderNotFound(req);
2057
2096
  };
2058
- const devFetchHardened = async (req) => withResponseHardening(await devFetchInner(req));
2097
+ const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2059
2098
  const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2060
2099
  return {
2061
2100
  routes: {},
@@ -2064,12 +2103,12 @@ data: ${data}
2064
2103
  fetch: devFetch
2065
2104
  };
2066
2105
  }
2067
- const prodFetchInner = async (req) => {
2106
+ const prodFetchInner = async (req, server) => {
2068
2107
  const url = new URL(req.url).pathname;
2069
2108
  const healthResult = await healthHandler(req);
2070
2109
  if (healthResult !== null) return healthResult;
2071
2110
  if (rateLimiter) {
2072
- const limited = await rateLimitMiddleware(rateLimiter, req);
2111
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
2073
2112
  if (limited !== null) return limited;
2074
2113
  }
2075
2114
  const revalidationResult = await handleRevalidation(req);
@@ -2095,7 +2134,7 @@ data: ${data}
2095
2134
  }
2096
2135
  return renderNotFound(req);
2097
2136
  };
2098
- const prodFetchHardened = async (req) => withResponseHardening(await prodFetchInner(req));
2137
+ const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2099
2138
  const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2100
2139
  return {
2101
2140
  routes: {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "0.1.7",
3
+ "version": "1.1.0",
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",