barejs 0.2.4 → 0.2.6
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 +80 -33
- package/dist/edge.js +70 -0
- package/dist/index.js +200 -189
- package/dist/node.js +200 -189
- package/dist/types/client/index.d.ts +100 -0
- package/dist/types/core/bare.d.ts +68 -25
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/core/router.d.ts +27 -2
- package/dist/types/core/ws-match.d.ts +34 -2
- package/dist/types/edge.d.ts +99 -0
- package/dist/types/index.d.ts +6 -5
- package/dist/types/runtime/types.d.ts +15 -0
- package/dist/types/security/validators.d.ts +46 -1
- package/dist/types/utils/tracing.d.ts +25 -0
- package/llms.txt +13 -6
- package/package.json +7 -3
- package/src/client/index.ts +399 -6
- package/src/core/bare.ts +366 -46
- package/src/core/context.ts +10 -3
- package/src/core/radix.ts +54 -31
- package/src/core/router.ts +37 -4
- package/src/core/ws-match.ts +17 -2
- package/src/edge.ts +494 -0
- package/src/index.ts +16 -5
- package/src/runtime/bun.ts +39 -7
- package/src/runtime/node.ts +37 -4
- package/src/runtime/types.ts +16 -0
- package/src/runtime/uws.ts +60 -12
- package/src/security/auth.ts +7 -5
- package/src/security/validators.ts +240 -38
- package/src/utils/openapi.ts +39 -9
- package/src/utils/tracing.ts +86 -0
package/README.md
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
<br />
|
|
3
3
|
<h1>Bare<span style="color: #F7DF1E;">JS</span></h1>
|
|
4
|
-
<p><strong>The batteries-included web framework for Bun, Node.js, and
|
|
5
|
-
<p><i>Built-in TypeBox, Zod & JSON Schema validation, end-to-end RPC client
|
|
4
|
+
<p><strong>The batteries-included web framework for Bun, Node.js, Deno, and Edge, engineered for minimal overhead.</strong></p>
|
|
5
|
+
<p><i>Built-in Standard Schema v1 (Valibot, ArkType, Zod 4), TypeBox, Zod & JSON Schema validation, end-to-end <code>bareTreaty</code> RPC & typed WebSocket client, OpenAPI 3.1, WebSockets, SSE, Streaming Uploads, JSON-RPC 2.0, Native TLS, Cron, Resilience, and Zero-Trust Security — powered by a JIT-compiled O(1) radix router and LIFO context pooling.</i></p>
|
|
6
6
|
|
|
7
7
|
<p>
|
|
8
8
|
<a href="https://www.npmjs.com/package/barejs"><img src="https://img.shields.io/npm/v/barejs?style=for-the-badge&logo=npm&color=CB3837" alt="NPM Version"></a>
|
|
9
9
|
<a href="https://github.com/xarhang/bareJS/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/xarhang/bareJS/ci.yml?branch=main&label=CI&style=for-the-badge&logo=github" alt="CI"></a>
|
|
10
|
-
<a href="https://github.
|
|
11
|
-
<a href="https://bun.sh"><img src="https://img.shields.io/badge/Bun-%3E%3D1.1.0-black?style=for-the-badge&logo=bun" alt="Bun"></a>
|
|
12
|
-
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node.js-%3E%3D20.0.0-339933?style=for-the-badge&logo=nodedotjs" alt="Node.js"></a>
|
|
13
|
-
<a href="https://deno.com"><img src="https://img.shields.io/badge/Deno-%3E%3D2.0-000000?style=for-the-badge&logo=deno" alt="Deno"></a>
|
|
10
|
+
<a href="https://xarhang.github.io/bareJS/"><img src="https://img.shields.io/badge/Docs-GitHub_Pages-f5b942?style=for-the-badge&logo=readthedocs&logoColor=black" alt="Docs"></a>
|
|
14
11
|
<a href="https://github.com/xarhang/bareJS/blob/main/LICENSE"><img src="https://img.shields.io/github/license/xarhang/bareJS?style=for-the-badge&color=blue" alt="License"></a>
|
|
15
12
|
</p>
|
|
13
|
+
<p>
|
|
14
|
+
<a href="https://http-arena.com/frameworks/barejs/"><img src="https://img.shields.io/endpoint?url=https://http-arena.com/badge/barejs/h1.json&style=for-the-badge" alt="HTTP Arena H/1.1"></a>
|
|
15
|
+
<a href="https://http-arena.com/#type=emerging,flagship&tuned=0&lang=TS"><img src="https://img.shields.io/endpoint?url=https://http-arena.com/badge/barejs/h1-ts.json&style=for-the-badge" alt="HTTP Arena H/1.1 (TS)"></a>
|
|
16
|
+
<a href="https://http-arena.com/frameworks/barejs/"><img src="https://img.shields.io/endpoint?url=https://http-arena.com/badge/barejs/h3.json&style=for-the-badge" alt="HTTP Arena H/3"></a>
|
|
17
|
+
</p>
|
|
16
18
|
</div>
|
|
17
19
|
|
|
18
20
|
---
|
|
@@ -38,16 +40,33 @@ app.listen(3000);
|
|
|
38
40
|
## Why BareJS?
|
|
39
41
|
|
|
40
42
|
- **O(1) JIT Router, Bun Native Routes & Pooling:** Compiles static routes into an inline `switch` fast-path and dynamic routes into a radix jump-table (`:params`, `*` wildcards, `BareRouter` sub-app mounting) with a lazy LIFO `Context` pool (`0..65536`) and dev-mode Use-After-Free Proxy guard. On Bun, `app.listen()` also offloads eligible middleware-free routes to `Bun.serve({ routes })` (with pure-static `Response` and `isTrulyZeroArg` fast-paths in `NODE_ENV=production`) while keeping full `fetch()` fallback parity.
|
|
41
|
-
- **Unified Schema Validation:** Declarative `body`, `query`, `params`, `headers`, and `response` schemas with **TypeBox**, **Zod**, or **Native JSON Schema** — including auto-coercion, `stripUnknown` Mass-Assignment protection, `413` `maxBodySize` guards, and automatic secret-field stripping.
|
|
42
|
-
- **End-to-End Type Safety:** `bareClient(app)`
|
|
43
|
-
- **Batteries Included:** Auto-generated **OpenAPI 3.1** (with automatic `bearerAuth`/`basicAuth` security schemes) + Scalar UI (`app.docs`), **JSON-RPC 2.0** (`app.rpc`), **WebSockets** (`app.ws`), **SSE** (`ctx.sse`), **Streaming Uploads** (`ctx.upload` / `ctx.uploadStream`), **Compression** (`compress` — `zstd`/`br`/`gzip`), **Static Files** (`staticFile` with ETag/`304`/Range `206`/`spa: true`), `app.derive`, `app.cron`, `app.useLog({ format: 'json' })`, `onRequest`/`onResponse` hooks, `app.listenCluster()`, and `healthcheck`.
|
|
44
|
-
- **Zero-Trust Security & Resilience:** Built-in `bareAuth` (HS256/RS256/ES256/JWKS + `revokeToken`), `basicAuth`, `hasRole`, `Hash` (Argon2id/bcrypt/scrypt), HMAC-signed cookies, `trustProxy` CIDR/IP allowlist, `cors`, `csrf`, `rateLimit`, `idempotency`, `circuitBreaker`, `createSingleflight`, `timeout`, `redisStore`, and `app.onDrain`.
|
|
45
|
-
- **Multi-Runtime &
|
|
43
|
+
- **Unified Schema Validation:** Declarative `body`, `query`, `params`, `headers`, and `response` schemas with **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect — sync & async fail-closed), **TypeBox**, **Zod**, or **Native JSON Schema** — including auto-coercion, `stripUnknown` Mass-Assignment protection, `413` `maxBodySize` guards, and automatic secret-field stripping.
|
|
44
|
+
- **End-to-End Type Safety:** `bareClient(app)` (with non-throwing `client.safe.*` and typed `client.ws()`) and chained Proxy **`bareTreaty(app | url)`** (`api.users({ id: 42 }).get()` & `.subscribe()`) provide compile-time route, param, query, body, and response inference over HTTP/WS or zero-network in-memory calls.
|
|
45
|
+
- **Batteries Included:** Auto-generated **OpenAPI 3.1** (with automatic `bearerAuth`/`basicAuth` security schemes) + Scalar UI (`app.docs`), **JSON-RPC 2.0** (`app.rpc`), **WebSockets** (`app.ws`), **SSE** (`ctx.sse`), **Streaming Uploads** (`ctx.upload` / `ctx.uploadStream`), **Compression** (`compress` — `zstd`/`br`/`gzip`), **Static Files** (`staticFile` with ETag/`304`/Range `206`/`spa: true`), `app.derive`, `app.cron`, `app.useLog({ format: 'json' })`, `onRequest`/`onResponse` hooks, native `tls`, `app.listenCluster()`, and `healthcheck`.
|
|
46
|
+
- **Zero-Trust Security & Resilience:** Built-in `bareAuth` (HS256/RS256/ES256/JWKS + `revokeToken`), `basicAuth`, `hasRole`, `Hash` (Argon2id/bcrypt/scrypt), HMAC-signed cookies, CRLF header/cookie/redirect injection protection, `trustProxy` CIDR/IP allowlist, `cors`, `csrf`, `rateLimit`, `idempotency`, `circuitBreaker`, `createSingleflight`, `timeout`, `redisStore`, and `app.onDrain`.
|
|
47
|
+
- **Multi-Runtime & Edge Interop:** Zero-dep native drivers for **Bun** (`Bun.serve({ routes })`), **Node.js >= 20** (`barejs/node` with built-in RFC 6455 WebSockets & `scrypt`, plus optional `uWebSockets.js` auto-detection with streaming backpressure, `uWS.SSLApp` TLS & WS pub/sub), **Deno >= 2.0** (`Deno.upgradeWebSocket`), and **Edge Workers** (`barejs/edge` — zero `node:*` imports for Cloudflare Workers, Vercel Edge & Deno Deploy). Standard `Request`/`Response` (`ctx.req`) works directly with **Better-Auth**, **Auth0**, **Clerk**, **GraphQL Yoga**, **Sentry**, and **OpenTelemetry**.
|
|
46
48
|
|
|
47
49
|
---
|
|
48
50
|
|
|
49
51
|
## Installation & Quick Start
|
|
50
52
|
|
|
53
|
+
### Official Starter CLI ([`create-barejs`](https://github.com/xarhang/create-barejs))
|
|
54
|
+
|
|
55
|
+
Scaffold a production-ready project (with JSON logging, `securityHeaders()`, `healthcheck()`, and OpenAPI 3.1 + Scalar `/docs`) in one command:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# Interactive (prompts for Bun, Node.js, Node.js + uWebSockets.js, or Deno)
|
|
59
|
+
bun create barejs my-app
|
|
60
|
+
|
|
61
|
+
# Or choose a runtime directly:
|
|
62
|
+
bun create barejs my-bun-app --bun
|
|
63
|
+
bun create barejs my-node-app --node
|
|
64
|
+
bun create barejs my-uws-app --node-uws
|
|
65
|
+
bun create barejs my-deno-app --deno
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Manual Installation
|
|
69
|
+
|
|
51
70
|
<details open>
|
|
52
71
|
<summary><strong>Bun (>= 1.1.0)</strong></summary>
|
|
53
72
|
|
|
@@ -102,36 +121,62 @@ Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostnam
|
|
|
102
121
|
|
|
103
122
|
</details>
|
|
104
123
|
|
|
124
|
+
<details>
|
|
125
|
+
<summary><strong>Edge Workers (Cloudflare Workers / Vercel Edge / Deno Deploy)</strong></summary>
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
import { BareJS, cors, securityHeaders } from 'barejs/edge';
|
|
129
|
+
|
|
130
|
+
// Zero node:* imports (~195 KB bundle)
|
|
131
|
+
const app = new BareJS<{ API_KEY: string }>()
|
|
132
|
+
.use(securityHeaders())
|
|
133
|
+
.use(cors({ origin: '*' }))
|
|
134
|
+
.get('/ping', () => 'pong')
|
|
135
|
+
.get('/users/:id', (ctx) => ({ id: ctx.params.id, hasKey: Boolean(ctx.env.API_KEY) }));
|
|
136
|
+
|
|
137
|
+
export default app;
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
</details>
|
|
141
|
+
|
|
105
142
|
---
|
|
106
143
|
|
|
107
144
|
## Runtime Support
|
|
108
145
|
|
|
109
|
-
| Feature | Bun (`barejs`) | Node.js >= 20 (`barejs/node`) | Deno (`app.fetch`) |
|
|
110
|
-
| :--- | :---: | :---: | :---: |
|
|
111
|
-
| **Router, Validation
|
|
112
|
-
| **Security Middlewares (`cors`, `csrf`, `rateLimit`, `bareAuth`, `idempotency`)** | ✅ | ✅ | ✅ |
|
|
113
|
-
| **Streaming (`ctx.sse`, `ctx.upload`, `ctx.uploadStream`)** | ✅ | ✅ | ✅ |
|
|
114
|
-
| **Static Files (`staticFile`)
|
|
115
|
-
| **Compression (`compress` — `gzip` / `br` / `zstd`)** | ✅ | ✅ (`gzip` / `br`, + `zstd` on Node >= 22.15) | ✅ (`gzip` / `br`) |
|
|
116
|
-
| **WebSockets (`app.ws`)** | ✅ Native | ✅ Native (RFC 6455) · Optional `ws` | ✅ Native (`Deno.upgradeWebSocket`) |
|
|
117
|
-
| **Password Hashing (`Hash`)** | ✅ Native (`Argon2id` / `bcrypt`) | ✅ Native (`scrypt`) · Optional `Argon2id` | ✅ Native (`scrypt`) · Optional `Argon2id` |
|
|
146
|
+
| Feature | Bun (`barejs`) | Node.js >= 20 (`barejs/node`) | Deno (`app.fetch`) | Edge (`barejs/edge`) |
|
|
147
|
+
| :--- | :---: | :---: | :---: | :---: |
|
|
148
|
+
| **Router, Validation (Standard Schema / TypeBox / Zod), `bareClient`/`bareTreaty`** | ✅ | ✅ | ✅ | ✅ |
|
|
149
|
+
| **Security Middlewares (`cors`, `csrf`, `rateLimit`, `bareAuth`, `idempotency`)** | ✅ | ✅ | ✅ | ✅ (Web Crypto) |
|
|
150
|
+
| **Streaming (`ctx.sse`, `ctx.upload`, `ctx.uploadStream`)** | ✅ | ✅ | ✅ | ✅ (`ctx.sse`) |
|
|
151
|
+
| **Static Files (`staticFile`) & Native `tls`** | ✅ | ✅ (`uWS.SSLApp` / `https`) | ✅ | — (Edge CDN) |
|
|
152
|
+
| **Compression (`compress` — `gzip` / `br` / `zstd`)** | ✅ | ✅ (`gzip` / `br`, + `zstd` on Node >= 22.15) | ✅ (`gzip` / `br`) | — (Edge CDN) |
|
|
153
|
+
| **WebSockets (`app.ws`)** | ✅ Native | ✅ Native (RFC 6455) · `uWS` · Optional `ws` | ✅ Native (`Deno.upgradeWebSocket`) | — |
|
|
154
|
+
| **Password Hashing (`Hash`)** | ✅ Native (`Argon2id` / `bcrypt`) | ✅ Native (`scrypt`) · Optional `Argon2id` | ✅ Native (`scrypt`) · Optional `Argon2id` | — |
|
|
118
155
|
|
|
119
156
|
---
|
|
120
157
|
|
|
121
158
|
## Benchmarks (Bun)
|
|
122
159
|
|
|
160
|
+
<p>
|
|
161
|
+
<a href="https://http-arena.com/frameworks/barejs/"><img src="https://img.shields.io/endpoint?url=https://http-arena.com/badge/barejs/h2.json&style=flat-square" alt="HTTP Arena H/2"></a>
|
|
162
|
+
<a href="https://http-arena.com/frameworks/barejs/"><img src="https://img.shields.io/endpoint?url=https://http-arena.com/badge/barejs/ws.json&style=flat-square" alt="HTTP Arena WebSocket"></a>
|
|
163
|
+
<a href="https://http-arena.com/frameworks/barejs/"><img src="https://img.shields.io/endpoint?url=https://http-arena.com/badge/barejs/db.json&style=flat-square" alt="HTTP Arena Database"></a>
|
|
164
|
+
<a href="https://web-frameworks-benchmark.vercel.app/result?l=javascript"><img src="https://img.shields.io/badge/Web_Frameworks-Benchmarked-10b981?style=flat-square&logo=vercel&logoColor=white" alt="Web Frameworks Benchmark"></a>
|
|
165
|
+
<a href="https://github.com/xarhang/bareJS/actions/workflows/bench.yml"><img src="https://img.shields.io/github/actions/workflow/status/xarhang/bareJS/bench.yml?branch=main&label=CI_Benchmarks&style=flat-square&logo=github" alt="CI Benchmarks"></a>
|
|
166
|
+
</p>
|
|
167
|
+
|
|
123
168
|
Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitata) (`benchmarks/fair-suite.ts`). Bold values indicate a **mean** latency more than 10% faster than the runner-up; differences under ~10% vary between GitHub Actions runs and are left unbolded (treated as ties). These micro-benchmarks measure framework overhead rather than end-to-end network HTTP throughput, and do not represent Node.js or Deno latency.
|
|
124
169
|
|
|
125
170
|
<!-- MARKER: MULTI_BENCH_SUMMARY_START -->
|
|
126
171
|
|
|
127
172
|
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
128
173
|
| :--- | :---: | :---: | :---: |
|
|
129
|
-
| **1. 100 Routes + Dynamic Params** | **`1.
|
|
130
|
-
| **2. 10 Middlewares + Deep Path** | **`1.
|
|
131
|
-
| **3. POST JSON + Schema Validation** | **`
|
|
132
|
-
| **4. Async Handler + Query Parsing** |
|
|
174
|
+
| **1. 100 Routes + Dynamic Params** | **`1.28 µs`**<br><sub>`p99: 7.01 µs`</sub> | `1.91 µs`<br><sub>`p99: 8.83 µs`</sub> | `3.90 µs`<br><sub>`p99: 15.79 µs`</sub> |
|
|
175
|
+
| **2. 10 Middlewares + Deep Path** | **`1.19 µs`**<br><sub>`p99: 6.78 µs`</sub> | `1.99 µs`<br><sub>`p99: 8.04 µs`</sub> | `3.97 µs`<br><sub>`p99: 14.68 µs`</sub> |
|
|
176
|
+
| **3. POST JSON + Schema Validation** | **`3.54 µs`**<br><sub>`p99: 12.64 µs`</sub> | `4.61 µs`<br><sub>`p99: 14.65 µs`</sub> | `4.63 µs`<br><sub>`p99: 15.63 µs`</sub> |
|
|
177
|
+
| **4. Async Handler + Query Parsing** | **`1.88 µs`**<br><sub>`p99: 8.83 µs`</sub> | `2.21 µs`<br><sub>`p99: 9.09 µs`</sub> | `3.15 µs`<br><sub>`p99: 12.65 µs`</sub> |
|
|
133
178
|
|
|
134
|
-
> Last Updated: 2026-11-
|
|
179
|
+
> Last Updated: 2026-11-30 (github action — `linux`, AMD EPYC 7763 64-Core Processor, Bun `1.4.5`, Elysia `1.4.21`, Hono `4.11.4`)
|
|
135
180
|
|
|
136
181
|
<!-- MARKER: MULTI_BENCH_SUMMARY_END -->
|
|
137
182
|
|
|
@@ -145,21 +190,23 @@ BareJS is a complete, zero-boilerplate backend platform—every module below shi
|
|
|
145
190
|
|
|
146
191
|
| Category | Built-In Capabilities |
|
|
147
192
|
| :--- | :--- |
|
|
148
|
-
| **Core & Routing** | $O(1)$ static `switch` fast-path + radix jump-table (`:params`, `*` wildcards), `
|
|
149
|
-
| **Validation & Serialization** | Unified `RouteSchemas` (`body`, `query`, `params`, `headers`, `response`, `maxBodySize`) supporting **TypeBox** (`Type`/`t`), **Zod** (`Z`/`z`), and **Native JSON Schema** (`native()`), automatic
|
|
150
|
-
| **Type-Safe RPC & Docs** |
|
|
151
|
-
| **Zero-Trust Security** | `bareAuth()` (constant-time HS256 JWT + asymmetric RS256/ES256/JWKS + `revokeToken()`/`isRevoked`), `basicAuth()`, `hasRole()`, `Hash` (Argon2id/bcrypt on Bun; zero-dep `scrypt` fallback on Node/Deno), HMAC-SHA256 signed `HttpOnly` cookies, `cors()`, `csrf()`, `securityHeaders()`, `rateLimit()` (flood-resistant), `trustProxy(
|
|
193
|
+
| **Core & Routing** | $O(1)$ static `switch` fast-path + radix jump-table (`:params`, `*` wildcards), Bun native `routes` fast-path, optional Node.js **`uWebSockets.js`** driver (`engine: 'uws'`), native **`tls`** option (Bun, `uWS.SSLApp`, Node `https`), zero-Node **`barejs/edge`** entrypoint (Cloudflare Workers, Vercel Edge, Deno Deploy), `app.listenCluster()` multi-core clustering, `BareRouter` sub-app mounting, lazy bounded LIFO `Context` pool (`0..65536`), `app.onRequest()`/`app.onResponse()` hooks, `app.request()` test helper |
|
|
194
|
+
| **Validation & Serialization** | Unified `RouteSchemas` (`body`, `query`, `params`, `headers`, `response`, `maxBodySize`) supporting **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect — async fail-closed), **TypeBox** (`Type`/`t`), **Zod** (`Z`/`z`), and **Native JSON Schema** (`native()`), automatic coercion, `413` streaming body limit, `stripUnknown` Mass-Assignment protection, recursive response secret-field stripping |
|
|
195
|
+
| **Type-Safe RPC & Docs** | `bareClient(app \| url)` (with non-throwing `client.safe` Result union & typed `client.ws()`), chained proxy **`bareTreaty(app \| url)`** (`api.users({ id: 42 }).get()` & `.subscribe()` WebSocket in-memory or network), automatic **OpenAPI 3.1** spec (`/docs/json`) + Scalar UI (`/docs`), **JSON-RPC 2.0** (`app.rpc()`) |
|
|
196
|
+
| **Zero-Trust Security** | `bareAuth()` (constant-time HS256 JWT + asymmetric RS256/ES256/JWKS + `revokeToken()`/`isRevoked`), `basicAuth()`, `hasRole()`, `Hash` (Argon2id/bcrypt on Bun; zero-dep `scrypt` fallback on Node/Deno), HMAC-SHA256 signed `HttpOnly` cookies, `cors()`, `csrf()`, `securityHeaders()`, `rateLimit()` (flood-resistant), `trustProxy(boolean \| string[])` CIDR allowlist |
|
|
152
197
|
| **Resilience & State** | `idempotency()` (`409 IDEMPOTENT_IN_FLIGHT` + `X-Idempotent-Replayed`, caller-scoped), `createSingleflight()` cache-stampede coalescing, `circuitBreaker()` (`503 Retry-After`), `timeout()` (`408`), pluggable `redisStore()` (`Bun.redis` / `ioredis`), overlap-safe `app.cron()` |
|
|
153
|
-
| **Real-Time, Files & Ops** | Parameterized WebSockets (`app.ws('/ws/:room')`), Server-Sent Events (`ctx.sse()`), `ctx.upload()` & $O(\text{chunk})$ streaming `ctx.uploadStream()`, `staticFile()` (ETag, `304`, Range `206`, LRU metadata cache), `compress()` (`zstd`/`br`/`gzip`), `
|
|
198
|
+
| **Real-Time, Files & Ops** | Parameterized WebSockets (`app.ws('/ws/:room')` with pub/sub on Bun & `uWebSockets.js`), Server-Sent Events (`ctx.sse()`), `ctx.upload()` & $O(\text{chunk})$ streaming `ctx.uploadStream()`, `staticFile()` (ETag, `304`, Range `206`, SPA fallback, LRU metadata cache), `compress()` (`zstd`/`br`/`gzip`), `useLog({ format: 'json' })` + `logger()`, `healthcheck()` (`/health` + `/ready`), `app.onDrain()` + IPC `DRAIN_REQUEST` |
|
|
154
199
|
| **External Integrations** | Web Standard `ctx.req`/`Response` works out of the box with **Better-Auth**, **GraphQL Yoga**, **Auth0** (JWKS), **Clerk**, **Sentry**, and **OpenTelemetry** — see [docs/integrations.md](./docs/integrations.md) |
|
|
155
200
|
|
|
156
201
|
---
|
|
157
202
|
|
|
158
203
|
## Documentation
|
|
159
204
|
|
|
160
|
-
- **[
|
|
205
|
+
- **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs, code examples, and live CI benchmark dashboard.
|
|
206
|
+
- **[`create-barejs` Starter CLI](https://github.com/xarhang/create-barejs)** — Official multi-runtime project scaffolding (`bun create barejs my-app --bun|--node|--node-uws|--deno`).
|
|
207
|
+
- **[Comprehensive Guide](./docs/guide.md)** — Scaffolding, validation & auto-coercion, cookies & uploads, security suite, `app.derive()`, `app.macro()`, WebSockets, SSE, JSON-RPC 2.0, OpenAPI 3.1, `listenCluster()`, `uWebSockets.js`, native `tls`, `barejs/edge`, and `bareClient`/`bareTreaty`.
|
|
161
208
|
- **[External Integrations](./docs/integrations.md)** — Ready-to-use recipes for Better-Auth, GraphQL Yoga, Auth0, Clerk, Sentry, and OpenTelemetry.
|
|
162
|
-
- **[API & Configuration Reference](./docs/reference.md)** — Complete `Context` (`ctx`) API
|
|
209
|
+
- **[API & Configuration Reference](./docs/reference.md)** — Complete `Context` (`ctx`) & `BareJS` API tables, `poolSize`, `bare.config.ts`, and `NODE_ENV` settings.
|
|
163
210
|
- **[Benchmarks](./BENCHMARKS.md)** — Full 7-scenario results and reproduction instructions.
|
|
164
211
|
- **[Security Policy](./SECURITY.md)** — Vulnerability reporting and security hardening guidelines.
|
|
165
212
|
- **[Changelog](./CHANGELOG.md)** — Release history and migration notes.
|
|
@@ -169,7 +216,7 @@ BareJS is a complete, zero-boilerplate backend platform—every module below shi
|
|
|
169
216
|
|
|
170
217
|
## Status, Contributing & License
|
|
171
218
|
|
|
172
|
-
- **Status:** Active `0.
|
|
219
|
+
- **Status:** Active `0.2.x` development (**489 tests / 6,789 assertions**). Verified in [CI](./.github/workflows/ci.yml) across **Bun** (`bun test`), **Node.js 20 & 22** (`vitest run` + `tests/node-smoke.mjs`; Node 20 skips `production-db.test.ts` which requires `node:sqlite`), and **Deno 2** (`deno test` + `tests/deno-smoke.ts`; skips `playwright.test.ts` and `production-db.test.ts`).
|
|
173
220
|
- **Security:** See [SECURITY.md](./SECURITY.md) for reporting vulnerabilities.
|
|
174
221
|
- **Contributing:** See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup and release workflows.
|
|
175
222
|
- **License:** [MIT](./LICENSE) — Maintained by [xarhang](https://github.com/xarhang).
|
package/dist/edge.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import*as p from"@sinclair/typebox/compiler";import{z as QR}from"zod";var m=QR,W=(R,f=400)=>Response.json(R,{status:f,headers:{"Content-Type":"application/json"}});var gR=(R)=>{let f=c(R),_=async(Z,$)=>{try{let T=Z instanceof Object&&"req"in Z,u=T?await Z.jsonBody():await Z.json(),G=f(u);if(!G.ok)return W({status:"error",code:G.error?.code||"TYPE_MISMATCH",message:G.error?.message||"Validation failed",...G.error?.path?{field:G.error.path}:{}});if(T)Z.body=G.data;return $?$():void 0}catch(T){if(T?.status===413)return W({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return W({status:"error",message:"Invalid JSON payload"})}};return _.__schema=R,_};var h=(R)=>Boolean(R&&typeof R==="object"&&"~standard"in R&&R["~standard"]&&typeof R["~standard"].validate==="function"),x=(R)=>{if(!R||typeof R!=="object")return{ok:!1,error:{message:"Invalid validator result"}};if(Array.isArray(R.issues))return{ok:!1,error:R.issues.map((f)=>({message:f?.message||"Validation failed",...f?.path?{path:f.path.map((_)=>typeof _==="object"&&_!==null&&("key"in _)?_.key:_)}:{}}))};if("value"in R)return{ok:!0,data:R.value};return{ok:!1,error:{message:"Invalid validator result"}}},XR=(R)=>{let f=async(_,Z)=>{try{let $=_ instanceof Object&&"req"in _,T=$?await _.jsonBody():await _.json(),u=await R["~standard"].validate(T),G=x(u);if(!G.ok)return W({status:"error",code:"VALIDATION_FAILED",errors:G.error});if($)_.body=G.data;return Z?Z():void 0}catch($){if($?.status===413)return W({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return W({status:"error",message:"Invalid JSON payload"})}};return f.__schema=R,f};var r=(R,f)=>{if(f===void 0)return!0;if(Array.isArray(f))return f.some((_)=>r(R,_));if(f==="array")return Array.isArray(R);if(f==="integer")return typeof R==="number"&&Number.isInteger(R);if(f==="number")return typeof R==="number"&&Number.isFinite(R);if(f==="object")return R!==null&&typeof R==="object"&&!Array.isArray(R);if(f==="null")return R===null;return typeof R===f},y=(R,f)=>{if(R===f)return!0;if(typeof R!=="object"||typeof f!=="object"||R===null||f===null)return!1;if(Array.isArray(R)!==Array.isArray(f))return!1;if(Array.isArray(R)){if(R.length!==f.length)return!1;for(let Z=0;Z<R.length;Z++)if(!y(R[Z],f[Z]))return!1;return!0}let _=Object.keys(R);if(_.length!==Object.keys(f).length)return!1;for(let Z=0;Z<_.length;Z++){let $=_[Z];if(!Object.hasOwn(f,$)||!y(R[$],f[$]))return!1}return!0},P=(R,f,_,Z)=>{if(!f||typeof f!=="object")return{ok:!0};if(Object.hasOwn(f,"const")&&!y(R,f.const))return{ok:!1,error:{message:`Value at '${_||"root"}' must equal ${JSON.stringify(f.const)}`,path:_}};if(Array.isArray(f.enum)&&!f.enum.some(($)=>y($,R)))return{ok:!1,error:{message:`Value at '${_||"root"}' must be one of enum values`,path:_}};if(f.not&&typeof f.not==="object"&&P(R,f.not,_,!1).ok)return{ok:!1,error:{message:`Value at '${_||"root"}' must not match the 'not' schema`,path:_}};if(Array.isArray(f.allOf))for(let $=0;$<f.allOf.length;$++){let T=P(R,f.allOf[$],_,!1);if(!T.ok)return T}if(Array.isArray(f.anyOf)){let $=!1;for(let T=0;T<f.anyOf.length;T++)if(P(R,f.anyOf[T],_,!1).ok){$=!0;break}if(!$)return{ok:!1,error:{message:`Value at '${_||"root"}' failed anyOf constraint`,path:_}}}if(Array.isArray(f.oneOf)){let $=0;for(let T=0;T<f.oneOf.length;T++)if(P(R,f.oneOf[T],_,!1).ok)$++;if($!==1)return{ok:!1,error:{message:`Value at '${_||"root"}' must match exactly one schema in oneOf`,path:_}}}if(!r(R,f.type))return{ok:!1,error:{message:_?`Field '${_}' must be of type ${f.type}`:`Expected type ${f.type}`,path:_}};if(typeof R==="number"){if(typeof f.minimum==="number"&&R<f.minimum)return{ok:!1,error:{message:`Field '${_}' must be >= ${f.minimum}`,path:_}};if(typeof f.maximum==="number"&&R>f.maximum)return{ok:!1,error:{message:`Field '${_}' must be <= ${f.maximum}`,path:_}};if(typeof f.multipleOf==="number"&&f.multipleOf>0){let $=R/f.multipleOf;if(Math.abs($-Math.round($))>0.000000001*Math.max(1,Math.abs($)))return{ok:!1,error:{message:`Field '${_}' must be a multiple of ${f.multipleOf}`,path:_}}}if(typeof f.exclusiveMinimum==="number"&&R<=f.exclusiveMinimum)return{ok:!1,error:{message:`Field '${_}' must be > ${f.exclusiveMinimum}`,path:_}};if(typeof f.exclusiveMaximum==="number"&&R>=f.exclusiveMaximum)return{ok:!1,error:{message:`Field '${_}' must be < ${f.exclusiveMaximum}`,path:_}}}if(typeof R==="string"){if(typeof f.minLength==="number"&&R.length<f.minLength)return{ok:!1,error:{message:`Field '${_}' length must be >= ${f.minLength}`,path:_}};if(typeof f.maxLength==="number"&&R.length>f.maxLength)return{ok:!1,error:{message:`Field '${_}' length must be <= ${f.maxLength}`,path:_}};if(typeof f.pattern==="string")try{if(!new RegExp(f.pattern).test(R))return{ok:!1,error:{message:`Field '${_}' does not match pattern`,path:_}}}catch{}}if(Array.isArray(R)){if(typeof f.minItems==="number"&&R.length<f.minItems)return{ok:!1,error:{message:`Field '${_}' must have at least ${f.minItems} items`,path:_}};if(typeof f.maxItems==="number"&&R.length>f.maxItems)return{ok:!1,error:{message:`Field '${_}' must have at most ${f.maxItems} items`,path:_}};if(f.uniqueItems===!0){for(let $=1;$<R.length;$++)for(let T=0;T<$;T++)if(y(R[$],R[T]))return{ok:!1,error:{message:`Field '${_}' must have unique items`,path:_}}}if(Array.isArray(f.items)){let $=Math.min(R.length,f.items.length);for(let T=0;T<$;T++){let u=P(R[T],f.items[T],_?`${_}[${T}]`:`[${T}]`,!1);if(!u.ok)return u}}else if(f.items&&typeof f.items==="object")for(let $=0;$<R.length;$++){let T=P(R[$],f.items,_?`${_}[${$}]`:`[${$}]`,!1);if(!T.ok)return T}}if(R!==null&&typeof R==="object"&&!Array.isArray(R)){let $=f.properties&&typeof f.properties==="object"?f.properties:null,T=Array.isArray(f.required)?f.required:null,u=T?new Set(T):null;if(typeof f.minProperties==="number"||typeof f.maxProperties==="number"){let Q=Object.keys(R).length;if(typeof f.minProperties==="number"&&Q<f.minProperties)return{ok:!1,error:{message:`Object at '${_||"root"}' must have at least ${f.minProperties} properties`,path:_}};if(typeof f.maxProperties==="number"&&Q>f.maxProperties)return{ok:!1,error:{message:`Object at '${_||"root"}' must have at most ${f.maxProperties} properties`,path:_}}}if(T)for(let Q=0;Q<T.length;Q++){let Y=T[Q];if(!Object.hasOwn(R,Y)||R[Y]===void 0){let E=$?.[Y]?.type;return{ok:!1,error:{message:E?`Field '${Y}' must be of type ${E}`:`Missing required field '${Y}'`,path:_?`${_}.${Y}`:Y}}}}if($){let Q=Object.keys($);for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if(!(Object.hasOwn(R,E)&&R[E]!==void 0)){if(Z&&!u)return{ok:!1,error:{message:`Field '${E}' must be of type ${$[E]?.type}`,path:_?`${_}.${E}`:E}};continue}let g=_?`${_}.${E}`:E,B=P(R[E],$[E],g,!1);if(!B.ok)return B}}let G=new Set;if(f.patternProperties&&typeof f.patternProperties==="object"){let Q=Object.keys(R);for(let[Y,E]of Object.entries(f.patternProperties)){let X;try{X=new RegExp(Y)}catch{continue}for(let g=0;g<Q.length;g++){let B=Q[g];if(!X.test(B))continue;G.add(B);let M=P(R[B],E,_?`${_}.${B}`:B,!1);if(!M.ok)return M}}}if(f.dependentRequired&&typeof f.dependentRequired==="object")for(let[Q,Y]of Object.entries(f.dependentRequired)){if(!Object.hasOwn(R,Q)||!Array.isArray(Y))continue;for(let E of Y)if(!Object.hasOwn(R,E))return{ok:!1,error:{message:`Field '${E}' is required when '${Q}' is present`,path:_?`${_}.${E}`:E}}}if(f.additionalProperties===!1){let Q=Object.keys(R);for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if((!$||!Object.hasOwn($,E))&&!G.has(E))return{ok:!1,error:{code:"ADDITIONAL_PROPERTIES",message:`Unknown field '${E}' is not allowed`,path:_?`${_}.${E}`:E}}}}else if(f.additionalProperties&&typeof f.additionalProperties==="object"){let Q=Object.keys(R);for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if((!$||!Object.hasOwn($,E))&&!G.has(E)){let X=P(R[E],f.additionalProperties,_?`${_}.${E}`:E,!1);if(!X.ok)return X}}}}return{ok:!0}},c=(R)=>{let f=Boolean(R?.anyOf||R?.oneOf||R?.allOf),_=!f&&!Array.isArray(R?.required)&&Boolean(R?.properties),Z=!R?.type||R.type==="object";return($)=>{if(!R||typeof R!=="object")return!$||typeof $!=="object"||Array.isArray($)?{ok:!1,error:{message:"Invalid JSON object payload"}}:{ok:!0,data:$};if(Z&&(!$||typeof $!=="object"||Array.isArray($))&&!f)return{ok:!1,error:{message:"Invalid JSON object payload"}};let T=P($,R,"",_);return T.ok?{ok:!0,data:$}:T}},q=(R)=>{if(R&&"_def"in R)return(f)=>{let _=R.safeParse(f);return _.success?{ok:!0,data:_.data}:{ok:!1,error:_.error.flatten()}};if(h(R)){let f=R["~standard"].validate;return(_)=>{let Z=f(_);if(Z&&typeof Z.then==="function")return Z.then(($)=>x($),()=>({ok:!1,error:{message:"Validation failed"}}));return x(Z)}}try{let f=p.TypeCompiler.Compile(R);return(_)=>{if(f.Check(_))return{ok:!0,data:_};let Z=f.Errors(_).First();return{ok:!1,error:{message:Z?.message||"Invalid input",path:Z?.path}}}}catch{return c(R)}},t=(R,f,_,Z,$)=>{if(!R)return null;let T=`ar_${Z}_${$}`,u=`j_${Z}_${$}`,G=`ai_${Z}_${$}`;if(R.type==="array"&&R.items){let E=t(R.items,G,`${T}[${u}] = `,Z+1,$+1);if(E===null)return null;return`if (Array.isArray(${f})) {
|
|
2
|
+
const ${T} = new Array(${f}.length);
|
|
3
|
+
for (let ${u} = 0; ${u} < ${f}.length; ${u}++) {
|
|
4
|
+
const ${G} = ${f}[${u}];
|
|
5
|
+
${E}
|
|
6
|
+
}
|
|
7
|
+
${_}${T};
|
|
8
|
+
} else {
|
|
9
|
+
${_}${f};
|
|
10
|
+
}`}let Q=`ao_${Z}_${$}`,Y=d(R,G,Q,Z+1);if(Y===null)return null;return`if (Array.isArray(${f})) {
|
|
11
|
+
const ${T} = new Array(${f}.length);
|
|
12
|
+
for (let ${u} = 0; ${u} < ${f}.length; ${u}++) {
|
|
13
|
+
const ${G} = ${f}[${u}];
|
|
14
|
+
if (${G} && typeof ${G} === 'object' && !Array.isArray(${G})) {
|
|
15
|
+
const ${Q} = {};
|
|
16
|
+
${Y} ${T}[${u}] = ${Q};
|
|
17
|
+
} else {
|
|
18
|
+
${T}[${u}] = ${G};
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
${_}${T};
|
|
22
|
+
} else {
|
|
23
|
+
${_}${f};
|
|
24
|
+
}`},d=(R,f,_,Z=0)=>{let $=R?.properties;if(!$||typeof $!=="object")return null;let T="",u=0;for(let[G,Q]of Object.entries($)){if(G==="__proto__"||G==="constructor"||G==="prototype")continue;let Y=JSON.stringify(G),E=`v_${Z}_${u++}`,X=`d_${Z}_${u}`;if(T+=`const ${E} = Object.hasOwn(${f}, ${Y}) ? ${f}[${Y}] : undefined;
|
|
25
|
+
`,Q?.type==="array"&&Q?.items){let B=t(Q.items,E,`${_}[${Y}] = `,Z,u);if(B!==null){T+=`if (${E} !== undefined) {
|
|
26
|
+
${B}
|
|
27
|
+
}
|
|
28
|
+
`;continue}}let g=d(Q,E,X,Z+1);if(g!==null)T+=`if (${E} !== undefined) {
|
|
29
|
+
`,T+=` if (${E} && typeof ${E} === 'object' && !Array.isArray(${E})) {
|
|
30
|
+
`,T+=` const ${X} = {};
|
|
31
|
+
${g} ${_}[${Y}] = ${X};
|
|
32
|
+
`,T+=` } else {
|
|
33
|
+
${_}[${Y}] = ${E};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
`;else T+=`if (${E} !== undefined) ${_}[${Y}] = ${E};
|
|
37
|
+
`}return T},v=(R)=>{if(!R||typeof R!=="object")return!1;if(Array.isArray(R.anyOf)||Array.isArray(R.oneOf)||Array.isArray(R.allOf))return!0;if(R.additionalProperties&&typeof R.additionalProperties==="object")return!0;if(R.patternProperties&&typeof R.patternProperties==="object")return!0;if(Array.isArray(R.items))return!0;if(R.type==="array"&&R.items)return v(R.items);if(R.properties&&typeof R.properties==="object"){for(let f of Object.values(R.properties))if(v(f))return!0}return!1},s=(R,f)=>{let _=!1;if(R?.properties&&typeof R.properties==="object")Object.assign(f,R.properties),_=!0;if(Array.isArray(R?.allOf)){for(let Z of R.allOf)if(s(Z,f))_=!0}return _},N=(R,f)=>{if(!f||typeof f!=="object"||R===null||typeof R!=="object")return R;if(Array.isArray(R)){if(Array.isArray(f.items))return R.map((u,G)=>f.items[G]?N(u,f.items[G]):u);if(f.items&&typeof f.items==="object")return R.map((u)=>N(u,f.items));return R}let _=f.anyOf||f.oneOf;if(Array.isArray(_)&&_.length>0){let u=null;for(let G of _)if(G&&typeof G==="object"&&q(G)(R).ok){u=G;break}if(u){if(f.properties&&typeof f.properties==="object"){let G={...f.properties,...u.properties||{}},Q={};for(let[Y,E]of Object.entries(G)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;if(Object.hasOwn(R,Y)&&R[Y]!==void 0)Q[Y]=N(R[Y],E)}return Q}return N(R,u)}if(!f.properties)return R}if(Array.isArray(f.allOf)){let u={};if(s(f,u)){let G={};for(let[Q,Y]of Object.entries(u)){if(Q==="__proto__"||Q==="constructor"||Q==="prototype")continue;if(Object.hasOwn(R,Q)&&R[Q]!==void 0)G[Q]=N(R[Q],Y)}return G}}let Z=Boolean(f.properties&&typeof f.properties==="object"),$=Boolean(f.patternProperties&&typeof f.patternProperties==="object"),T=Boolean(f.additionalProperties&&typeof f.additionalProperties==="object");if(Z||$||T){let u={},G=Z?f.properties:null;if(G)for(let[Q,Y]of Object.entries(G)){if(Q==="__proto__"||Q==="constructor"||Q==="prototype")continue;if(Object.hasOwn(R,Q)&&R[Q]!==void 0)u[Q]=N(R[Q],Y)}if($||T){let Q=$?Object.entries(f.patternProperties).map(([Y,E])=>({re:new RegExp(Y),sub:E})):[];for(let Y of Object.keys(R)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;if(R[Y]===void 0||G&&Object.hasOwn(G,Y))continue;let E=!1;for(let X=0;X<Q.length;X++)if(Q[X].re.test(Y)){u[Y]=N(R[Y],Q[X].sub),E=!0;break}if(!E&&T)u[Y]=N(R[Y],f.additionalProperties)}}return u}return R},k=(R)=>{if(!R||"_def"in R||h(R))return null;if(v(R))return(_)=>N(_,R);if(R.type==="array"&&R.items){if(R.items.type==="array")return(Z)=>N(Z,R);let _=d(R.items,"item","outItem");if(_===null)return(Z)=>N(Z,R);return new Function(`return function(arr) {
|
|
38
|
+
if (!Array.isArray(arr)) return arr;
|
|
39
|
+
const len = arr.length;
|
|
40
|
+
const out = new Array(len);
|
|
41
|
+
for (let i = 0; i < len; i++) {
|
|
42
|
+
const item = arr[i];
|
|
43
|
+
if (item && typeof item === 'object' && !Array.isArray(item)) {
|
|
44
|
+
const outItem = {};
|
|
45
|
+
${_}
|
|
46
|
+
out[i] = outItem;
|
|
47
|
+
} else {
|
|
48
|
+
out[i] = item;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}`)()}let f=d(R,"o","out");if(f===null)return(_)=>N(_,R);return new Function(`return function(o) {
|
|
53
|
+
if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
|
|
54
|
+
const out = {};
|
|
55
|
+
${f}
|
|
56
|
+
return out;
|
|
57
|
+
}`)()},GR=/^[1-5]\d\d$/,o=(R)=>{if(!R||typeof R!=="object"||Array.isArray(R))return!1;if("~standard"in R||"_def"in R||typeof R.parse==="function"||"type"in R||"properties"in R||"anyOf"in R||"oneOf"in R||"allOf"in R||"$ref"in R||Symbol.for("TypeBox.Kind")in R)return!1;let f=Object.keys(R);if(f.length===0)return!1;for(let _=0;_<f.length;_++)if(!GR.test(f[_]))return!1;return!0},e=(R)=>{if(o(R)){let $=new Map;for(let[T,u]of Object.entries(R)){let G=Number(T);if(Number.isInteger(G)&&G>=100&&G<=599)$.set(G,e(u))}return(T,u)=>{let G=u??(T instanceof Response?T.status:200),Q=$.get(G);return Q?Q(T,G):T}}let f=q(R),_=k(R),Z=($)=>{if(!$.ok)return W({status:"error",code:"RESPONSE_VALIDATION_FAILED",error:$.error},500);return $.data};return($)=>{if($ instanceof Response)return $;let T=_?_($):$,u=f(T);if(u&&typeof u.then==="function")return u.then(Z);return Z(u)}},YR=(R)=>{let f=R;while(f?._def){let _=f._def.typeName;if(_==="ZodOptional"||_==="ZodDefault"||_==="ZodNullable")f=f._def.innerType;else if(_==="ZodEffects")f=f._def.schema;else break}return f?.type||f?._def?.typeName},ER=/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/,l=(R,f)=>{let _=f;while(_?._def?.typeName==="ZodEffects")_=_._def.schema;let Z=_?.properties||(_?._def?.shape?typeof _._def.shape==="function"?_._def.shape():_._def.shape:null);if(!Z)return R;let $={...R};for(let[T,u]of Object.entries(Z)){if(!Object.hasOwn($,T))continue;let G=$[T];if(typeof G!=="string")continue;let Q=YR(u);if(Q==="number"||Q==="integer"||Q==="ZodNumber"){if(/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(G)){let Y=Number(G);if(Number.isFinite(Y))$[T]=Y}}else if(Q==="boolean"||Q==="ZodBoolean"){if(G==="true")$[T]=!0;else if(G==="false")$[T]=!1}}return $},a=(R)=>{let f=R.body?q(R.body):null,_=R.query?q(R.query):null,Z=R.params?q(R.params):null,$=R.headers?q(R.headers):null,T=R.stripUnknown&&R.body?k(R.body):null,u=R.stripUnknown&&R.query?k(R.query):null,G=R.stripUnknown&&R.params?k(R.params):null,Q=R.response?e(R.response):null,Y=R.maxBodySize??1048576,E=[],X=new Set;{let D=R.query;while(D?._def?.schema)D=D._def.schema;let S=D?.properties||(D?._def?.shape?typeof D._def.shape==="function"?D._def.shape():D._def.shape:null),U=(F)=>{let L=F;while(L?._def){let C=L._def.typeName;if(C==="ZodOptional"||C==="ZodDefault"||C==="ZodNullable")L=L._def.innerType;else if(C==="ZodEffects")L=L._def.schema;else break}return L};if(S)for(let[F,L]of Object.entries(S)){let C=U(L);if(!(C?.type==="array"||C?._def?.typeName==="ZodArray"))continue;E.push(F);let A=U(C.items??C._def?.type),j=A?.type??A?._def?.typeName;if(j==="number"||j==="integer"||j==="ZodNumber")X.add(F)}}let g=Boolean(Z||_||$),B=(D)=>{let S=()=>{if(!$)return;let F={};D.req.headers.forEach((J,A)=>{let j=A.toLowerCase();if(j!=="__proto__"&&j!=="constructor"&&j!=="prototype")F[j]=J});let L=$(F);if(L&&typeof L.then==="function")return L.then((J)=>J.ok?void 0:W({status:"error",code:"HEADERS_INVALID",error:J.error}));let C=L;if(!C.ok)return W({status:"error",code:"HEADERS_INVALID",error:C.error});return},U=()=>{if(!_)return S();let F=l(D.query,R.query);for(let J of E){let A=D.queryAll(J);if(A.length>0)F[J]=A.map((j)=>X.has(J)&&ER.test(j)?Number(j):j)}let L=_(F);if(L&&typeof L.then==="function")return L.then((J)=>{if(!J.ok)return W({status:"error",code:"QUERY_INVALID",error:J.error});return D._query=u?u(J.data):J.data,S()});let C=L;if(!C.ok)return W({status:"error",code:"QUERY_INVALID",error:C.error});return D._query=u?u(C.data):C.data,S()};if(Z){let F=l(D.params,R.params),L=Z(F);if(L&&typeof L.then==="function")return L.then((J)=>{if(!J.ok)return W({status:"error",code:"PARAMS_INVALID",error:J.error});return D.params=G?G(J.data):J.data,U()});let C=L;if(!C.ok)return W({status:"error",code:"PARAMS_INVALID",error:C.error});D.params=G?G(C.data):C.data}return U()};if(!f){let D=(S,U)=>{if(g){let F=B(S);if(F&&typeof F.then==="function")return F.then((L)=>L?L:U?U():void 0);if(F)return F}return U?U():void 0};if(D.__routeSchemas=R,Q)D.__responseFilter=Q;return D}let M=Boolean(R.body&&"_def"in R.body),z=(D,S,U)=>{if(!S.ok)return W({status:"error",code:"VALIDATION_FAILED",error:S.error});return D.body=T?T(S.data):S.data,U?U():void 0},I=(D,S,U)=>{let F;try{F=f(S)}catch{if(M)return R.body.safeParseAsync(S).then((L)=>{if(!L.success)return W({status:"error",code:"VALIDATION_FAILED",error:L.error.flatten()});return D.body=T?T(L.data):L.data,U?U():void 0});F={ok:!1,error:{message:"Validation failed"}}}if(F&&typeof F.then==="function")return F.then((L)=>z(D,L,U));return z(D,F,U)},H=(D,S)=>{let U;try{U=D.jsonBodySyncOrAsync(Y)}catch(F){if(F?.status===413)return W({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return W({status:"error",message:"Malformed JSON payload"})}if(U&&typeof U.then==="function")return U.then((F)=>I(D,F,S),(F)=>{if(F?.status===413)return W({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return W({status:"error",message:"Malformed JSON payload"})});return I(D,U,S)},K=(D,S)=>{if(g){let U=B(D);if(U&&typeof U.then==="function")return U.then((F)=>F?F:H(D,S));if(U)return U}return H(D,S)};if(K.__schema=R.body,K.__routeSchemas=R,Q)K.__responseFilter=Q;return K};class b{prefix;groupMiddleware;routes=[];constructor(R="",f=[]){this.prefix=R;this.groupMiddleware=f}_add(R,f,_){let Z=(this.prefix+"/"+f).replace(/\/+/g,"/");if(Z.endsWith("/"))Z=Z.slice(0,-1);let $=[];for(let T=0;T<_.length;T++){let u=_[T];if(typeof u==="function")$.push(u);else if(u&&typeof u==="object")$.push(a(u))}return this.routes.push({method:R.toUpperCase(),path:Z||"",handlers:[...this.groupMiddleware,...$]}),this._onRouteMutate?.(),this}get=(R,...f)=>this._add("GET",R,f);post=(R,...f)=>this._add("POST",R,f);put=(R,...f)=>this._add("PUT",R,f);patch=(R,...f)=>this._add("PATCH",R,f);delete=(R,...f)=>this._add("DELETE",R,f);options=(R,...f)=>this._add("OPTIONS",R,f);head=(R,...f)=>this._add("HEAD",R,f);all=(R,...f)=>{for(let _ of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this._add(_,R,f);return this};group=(R,...f)=>{let _=f.pop(),Z=f,$=(this.prefix+"/"+R).replace(/\/+/g,"/"),T=new b($,[...this.groupMiddleware,...Z]);return _(T),this.routes.push(...T.routes),this._onRouteMutate?.(),this};_mountRouter(R,f){let _=(this.prefix+"/"+R).replace(/\/+/g,"/").replace(/\/$/,"");for(let Z of f.routes){let $=(_+"/"+Z.path).replace(/\/+/g,"/");if($.endsWith("/"))$=$.slice(0,-1);this.routes.push({method:Z.method,path:$||"",handlers:[...this.groupMiddleware,...Z.handlers]})}this._onRouteMutate?.()}route(R,f){return this._mountRouter(R,f),this}use(R,...f){if(typeof R==="string"){let Z=[],$=[];for(let T=0;T<f.length;T++){let u=f[T];if(u instanceof b||u&&u.routes)$.push(u);else if(typeof u==="function")Z.push(u)}if($.length===0)throw new TypeError(`BareRouter.use("${R}", ...) requires a BareRouter instance`);for(let T=0;T<$.length;T++){let u=this.routes.length;if(this._mountRouter(R,$[T]),Z.length>0)for(let G=u;G<this.routes.length;G++)this.routes[G].handlers=[...this.groupMiddleware,...Z,...this.routes[G].handlers.slice(this.groupMiddleware.length)]}return this._onRouteMutate?.(),this}let _=[R,...f];for(let Z=0;Z<_.length;Z++){let $=_[Z];if($ instanceof b||$&&$.routes)this._mountRouter("",$);else if($&&typeof $.install==="function")$.install(this);else if(typeof $==="function")this.groupMiddleware.push($)}return this._onRouteMutate?.(),this}}import{Type as sR,Type as eR}from"@sinclair/typebox";var RR=(R,f,_)=>{let Z=f;if(_?.params){let G=_.params;Z=Z.replace(/:([a-zA-Z0-9_]+)(?=\/|\?|$)/g,(Q,Y)=>Object.hasOwn(G,Y)&&G[Y]!==void 0?encodeURIComponent(String(G[Y])):Q)}let $=R.endsWith("/")?R.slice(0,-1):R,T=Z.startsWith("/")?Z:`/${Z}`,u=`${$}${T}`;if(_?.query){let G=new URLSearchParams;for(let[Y,E]of Object.entries(_.query))if(E!==void 0)G.set(Y,String(E));let Q=G.toString();if(Q)u+=(u.includes("?")?"&":"?")+Q}return u},fR=(R)=>{if(typeof R==="string"){let f=R.trim();if(f.startsWith("{")&&f.endsWith("}")||f.startsWith("[")&&f.endsWith("]"))try{return JSON.parse(f)}catch{return R}}return R},_R=(R)=>{if(typeof R==="string"||R instanceof ArrayBuffer||ArrayBuffer.isView(R))return R;return JSON.stringify(R)},MR=(R,f,_)=>{let Z=new Set,$=new Set,T=new Set,u=1,G=new URL(f),Q=R?.wsRoutes,Y=null,E={};if(Q&&Q.size>0){let g=Q.get(G.pathname);if(g)Y=g;else{let B=G.pathname.split("/").filter(Boolean);for(let[M,z]of Q.entries()){let I=M.split("/").filter(Boolean);if(I.length!==B.length)continue;let H={},K=!0;for(let D=0;D<I.length;D++)if(I[D].startsWith(":"))H[I[D].slice(1)]=decodeURIComponent(B[D]);else if(I[D]!==B[D]){K=!1;break}if(K){Y=z,E=H;break}}}}let X={data:Y?{...Y,params:E}:{params:E},send(g){if(u!==1)return;let B=fR(g);for(let M of Z)M(B)},close(g=1000,B=""){if(u===3)return;u=3;for(let M of T)M(g,B)}};return queueMicrotask(async()=>{if(u!==1)return;if(Y?.__validateUpgrade)try{let g=await Y.__validateUpgrade(f,_);if(!g?.ok){X.close(1008,g?.code||"WS_UPGRADE_INVALID");return}if(g.query!==void 0)X.data.query=g.query;if(g.headers!==void 0)X.data.headers=g.headers}catch{X.close(1008,"WS_UPGRADE_INVALID");return}if(u!==1)return;Y?.open?.(X);for(let g of $)g()}),{get readyState(){return u},send(g){if(u!==1)throw new Error("WebSocket is closed");Y?.message?.(X,_R(g))},onMessage(g){return Z.add(g),()=>Z.delete(g)},onOpen(g){return $.add(g),()=>$.delete(g)},onClose(g){return T.add(g),()=>T.delete(g)},close(g=1000,B=""){if(u===3)return;u=3,Y?.close?.(X,g,B);for(let M of T)M(g,B)}}},BR=(R)=>{let f=R.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:"),_=new WebSocket(f),Z=new Set,$=new Set,T=new Set;return _.onmessage=(u)=>{let G=fR(u.data);for(let Q of Z)Q(G)},_.onopen=()=>{for(let u of $)u()},_.onclose=(u)=>{for(let G of T)G(u.code,u.reason)},{get readyState(){return _.readyState},send(u){_.send(_R(u))},onMessage(u){return Z.add(u),()=>Z.delete(u)},onOpen(u){return $.add(u),()=>$.delete(u)},onClose(u){return T.add(u),()=>T.delete(u)},close(u,G){_.close(u,G)}}},IR=new Set(["get","post","put","patch","delete"]),$R=(R,f={})=>{let _=typeof R==="object"&&R!==null&&typeof R.fetch==="function",Z=_?"http://localhost":R,$=f.fetch??(_?(X,g)=>R.fetch(new Request(String(X),g)):fetch),T=f.headers??{},u=async(X,g,B)=>{let M=RR(Z,g,B),z=new Headers;for(let[D,S]of Object.entries(T))z.set(D,S);if(B?.headers)for(let[D,S]of Object.entries(B.headers))z.set(D,S);let I={method:X,headers:z};if(B?.body!==void 0&&X!=="GET"&&X!=="HEAD"){let D=B.body;if(typeof D==="string"||D instanceof FormData||D instanceof URLSearchParams||D instanceof Blob||D instanceof ArrayBuffer||ArrayBuffer.isView(D)||typeof ReadableStream!=="undefined"&&D instanceof ReadableStream){if(D instanceof FormData)z.delete("content-type");I.body=D}else{if(!z.has("content-type"))z.set("Content-Type","application/json");I.body=JSON.stringify(D)}}let H=await $(M,I),K=null;if(H.status!==204&&H.status!==205&&H.status!==304){let D=(H.headers.get("content-type")||"").toLowerCase();if(D.includes("application/json")||D.includes("+json")){let S=await H.text();if(S)try{K=JSON.parse(S)}catch{K=S}else K=null}else K=await H.text()}if(!H.ok)return{ok:!1,data:null,error:K,status:H.status,headers:H.headers};return{ok:!0,data:K,error:null,status:H.status,headers:H.headers}},G=async(X,g,B)=>{let M=await u(X,g,B);if(!M.ok){let z=new Error(`HTTP ${M.status}`);throw z.status=M.status,z.data=M.error,z}return M.data},Q=(X,g)=>{let B=RR(Z,X,g),M={...T,...g?.headers||{}};return _?MR(R,B,M):BR(B)},Y=(X)=>{return new Proxy((B)=>{if(typeof B==="string"||typeof B==="number")return Y([...X,encodeURIComponent(String(B))]);let M=[...X];for(let z of Object.values(B))M.push(encodeURIComponent(String(z)));return Y(M)},{get(B,M){if(typeof M==="symbol")return;if(M==="then"||M==="catch"||M==="finally")return;if(IR.has(M)){let z=M.toUpperCase(),I="/"+X.join("/");return(H)=>u(z,I,H)}if(M==="subscribe"){let z="/"+X.join("/");return(I)=>Q(z,I)}return Y([...X,M])}})};return{get:(X,g)=>G("GET",X,g),post:(X,g)=>G("POST",X,g),put:(X,g)=>G("PUT",X,g),patch:(X,g)=>G("PATCH",X,g),delete:(X,g)=>G("DELETE",X,g),safe:{get:(X,g)=>u("GET",X,g),post:(X,g)=>u("POST",X,g),put:(X,g)=>u("PUT",X,g),patch:(X,g)=>u("PATCH",X,g),delete:(X,g)=>u("DELETE",X,g)},treaty:Y([]),ws:Q}},DR=(R,f={})=>$R(R,f).treaty;var O=(R)=>{let f=R.get("Vary");if(!f)R.set("Vary","Origin");else if(!f.toLowerCase().split(",").some((_)=>_.trim()==="origin"))R.set("Vary",`${f}, Origin`)},zR=(R={})=>{let f=R.origin??"*",_=R.methods||"GET,POST,PUT,PATCH,DELETE,OPTIONS",Z=Array.isArray(R.allowedHeaders)?R.allowedHeaders.join(", "):R.allowedHeaders||"Content-Type, Authorization",$=Array.isArray(R.exposedHeaders)?R.exposedHeaders.join(", "):R.exposedHeaders,T=R.credentials===!0,u=(E)=>{let X=E._headers?.vary;if(!X)E.setHeader("Vary","Origin");else if(!X.toLowerCase().split(",").map((g)=>g.trim()).includes("origin"))E.setHeader("Vary",`${X}, Origin`)};if(typeof f==="string"){if(f===""){let M=(z,I)=>{if(z.req.method==="OPTIONS")return new Response(null,{status:204,headers:{Vary:"Origin"}});z.setHeader("Vary","Origin");let H=I?.();if(H&&typeof H.then==="function")return H.then((K)=>{if(K instanceof Response)O(K.headers);else u(z);return K});if(H instanceof Response)O(H.headers);else u(z);return H};return M.__isCors=!0,M}let E=T&&f!=="*",X={"Access-Control-Allow-Origin":f,"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z};if(f!=="*")X.Vary="Origin";if(E)X["Access-Control-Allow-Credentials"]="true";let g={status:204,headers:X},B=(M,z)=>{if(M.req.method==="OPTIONS")return new Response(null,g);if(M.setHeader("Access-Control-Allow-Origin",f),M.setHeader("Access-Control-Allow-Methods",_),f!=="*")M.setHeader("Vary","Origin");if(E)M.setHeader("Access-Control-Allow-Credentials","true");if($)M.setHeader("Access-Control-Expose-Headers",$);let I=z?.();if(I&&typeof I.then==="function")return I.then((H)=>{if(H instanceof Response){if(H.headers.set("Access-Control-Allow-Origin",f),H.headers.set("Access-Control-Allow-Methods",_),f!=="*")O(H.headers);if(E)H.headers.set("Access-Control-Allow-Credentials","true");if($)H.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")u(M);return H});if(I instanceof Response){if(I.headers.set("Access-Control-Allow-Origin",f),I.headers.set("Access-Control-Allow-Methods",_),f!=="*")O(I.headers);if(E)I.headers.set("Access-Control-Allow-Credentials","true");if($)I.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")u(M);return I};return B.__isCors=!0,B}let G=Array.isArray(f)?new Set(f):null,Q=(E)=>{if(!E)return null;if(G)return G.has(E)?E:null;return f(E)?E:null},Y=(E,X)=>{let g=Q(E.req.headers.get("origin"));if(E.req.method==="OPTIONS"){let M={"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z,Vary:"Origin"};if(g)M["Access-Control-Allow-Origin"]=g;if(T&&g)M["Access-Control-Allow-Credentials"]="true";return new Response(null,{status:204,headers:M})}if(E.setHeader("Vary","Origin"),E.setHeader("Access-Control-Allow-Methods",_),g){if(E.setHeader("Access-Control-Allow-Origin",g),T)E.setHeader("Access-Control-Allow-Credentials","true")}if($)E.setHeader("Access-Control-Expose-Headers",$);let B=X?.();if(B&&typeof B.then==="function")return B.then((M)=>{if(M instanceof Response){if(O(M.headers),M.headers.set("Access-Control-Allow-Methods",_),g){if(M.headers.set("Access-Control-Allow-Origin",g),T)M.headers.set("Access-Control-Allow-Credentials","true")}if($)M.headers.set("Access-Control-Expose-Headers",$)}else u(E);return M});if(B instanceof Response){if(O(B.headers),B.headers.set("Access-Control-Allow-Methods",_),g){if(B.headers.set("Access-Control-Allow-Origin",g),T)B.headers.set("Access-Control-Allow-Credentials","true")}if($)B.headers.set("Access-Control-Expose-Headers",$)}else u(E);return B};return Y.__isCors=!0,Y};var HR=(R={})=>{let f=[];if(R.noSniff!==!1)f.push(["X-Content-Type-Options","nosniff"]);if(R.frameOptions!==!1)f.push(["X-Frame-Options",R.frameOptions??"DENY"]);if(R.referrerPolicy!==!1)f.push(["Referrer-Policy",R.referrerPolicy??"strict-origin-when-cross-origin"]);if(R.hsts!==!1)f.push(["Strict-Transport-Security",R.hsts??"max-age=31536000; includeSubDomains"]);if(R.contentSecurityPolicy)f.push(["Content-Security-Policy",R.contentSecurityPolicy]);f.push(["X-XSS-Protection","0"]);let _=f.length,Z=Object.freeze((()=>{let $={};for(let T=0;T<_;T++){let u=f[T];$[u[0].toLowerCase()]=u[1]}return $})());return($,T)=>{if(!$._headers)$._headers=Z;else $._headers={...$._headers,...Z};let u=T?.();if(u&&typeof u.then==="function")return u.then((G)=>{if(G instanceof Response)for(let Q=0;Q<_;Q++){let Y=f[Q];if(!G.headers.has(Y[0]))G.headers.set(Y[0],Y[1])}return G});if(u instanceof Response)for(let G=0;G<_;G++){let Q=f[G];if(!u.headers.has(Q[0]))u.headers.set(Q[0],Q[1])}return u}};var LR=(R={})=>{let f=R.windowMs??60000,_=R.max??100,Z=R.message??"Too many requests, please try again later.",$=Math.max(1,R.maxEntries??1e4),T=R.keyGenerator??((Y)=>Y.ip),u=R.store,G=(Y,E,X,g,B)=>{let M=Math.max(0,_-E),z=String(Math.ceil(X/1000));if(Y.setHeader("X-RateLimit-Limit",String(_)),Y.setHeader("X-RateLimit-Remaining",String(M)),Y.setHeader("X-RateLimit-Reset",z),E>_){let I=Math.max(1,Math.ceil((X-g)/1000));return Response.json({status:"error",code:"RATE_LIMITED",message:Z},{status:429,headers:{"Retry-After":String(I),"X-RateLimit-Limit":String(_),"X-RateLimit-Remaining":"0","X-RateLimit-Reset":z}})}return B?.()};if(u)return async(Y,E)=>{let X=Date.now(),g=T(Y),{count:B,resetAt:M}=await u.increment(g,f);return G(Y,B,M,X,E)};let Q=new Map;return(Y,E)=>{let X=Date.now(),g=T(Y),B=Q.get(g);if(!B||X>=B.resetAt){if(Q.size>=$)for(let[z,I]of Q){if(X>=I.resetAt)Q.delete(z);if(Q.size<$)break}let M=g;if(Q.size>=$&&!Q.has(g)){M="\x00__overflow__";let z=Q.get(M);if(z&&X<z.resetAt)return z.count++,G(Y,z.count,z.resetAt,X,E)}B={count:1,resetAt:X+f},Q.delete(M),Q.set(M,B)}else B.count++,Q.delete(g),Q.set(g,B);return G(Y,B.count,B.resetAt,X,E)}};var FR=(R=1e4,f={})=>{let _=f.status??408,Z=f.message??"Request Timeout",$=Number.isFinite(R)?Math.min(Math.max(R,0),2147483647):2147483647,T=async(u,G)=>{let Q;try{let Y=Promise.resolve(G()),E=new Promise((X)=>{Q=setTimeout(()=>{u._detached=!0,Y.catch(()=>{}),X(Response.json({status:"error",code:"REQUEST_TIMEOUT",message:Z},{status:_}))},$)});return await Promise.race([Y,E])}finally{if(Q!==void 0)clearTimeout(Q)}};return T.__timeout={ms:$,status:_,message:Z},T};var SR=(R={})=>{let f=R.failureThreshold??5,_=R.resetTimeoutMs??30000,Z=R.isFailure??((M,z)=>Boolean(z)||M instanceof Response&&(M.status>=500||M.status===408)),$="CLOSED",T=0,u=0,G=!1,Q=0,Y=0,E=0,X=(M)=>{if($!==M){let z=$;$=M,Q++;try{R.onStateChange?.(z,M)}catch{}}},g=async(M)=>{if($==="OPEN"){let D=Date.now()-u;if(D<_){let S=Math.max(1,Math.ceil((_-D)/1000));return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":String(S)}})}X("HALF_OPEN")}let z=!1;if($==="HALF_OPEN"){if(G)return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":"1"}});G=!0,z=!0}let I=Q,H,K=z?++Y:0;if(z)E=K,H=setTimeout(()=>{if(E===K&&I===Q)G=!1,E=0,u=Date.now(),X("OPEN")},Math.min(Math.max(_,1),2147483647));try{let D=await M();if(I!==Q)return D;if(Z(D)){if(T++,z||T>=f)u=Date.now(),X("OPEN")}else if(T=0,z)X("CLOSED");return D}catch(D){if(I===Q&&Z(void 0,D)){if(T++,z||T>=f)u=Date.now(),X("OPEN")}throw D}finally{if(H!==void 0)clearTimeout(H);if(z&&E===K)G=!1,E=0}},B=(M,z)=>g(()=>z?z():void 0);return B.__circuitBreaker=g,B};var UR=(R,f={})=>{let _=f.prefix??"barejs:",Z=typeof R.send==="function",$=(X)=>Z?R.send("GET",[X]):R.get(X),T=(X)=>Z?R.send("DEL",[X]):R.del(X),u=(X)=>Z?R.send("INCR",[X]):R.incr(X),G=async(X,g,B)=>{if(Z){await R.send("SET",[X,g,"PX",String(B)]);return}try{await R.set(X,g,"PX",B)}catch{if(await R.set(X,g),typeof R.pexpire==="function")await R.pexpire(X,B);else if(typeof R.expire==="function")await R.expire(X,Math.max(1,Math.ceil(B/1000)))}},Q=async(X,g)=>{if(Z)await R.send("PEXPIRE",[X,String(g)]);else if(typeof R.pexpire==="function")await R.pexpire(X,g);else if(typeof R.expire==="function")await R.expire(X,Math.max(1,Math.ceil(g/1000)))},Y=new Map,E='if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';return{async increment(X,g){let B=`${_}rl:${X}`,M=Number(await u(B));if(M===1)await Q(B,g);let z=g,I=null;if(Z)I=Number(await R.send("PTTL",[B]));else if(typeof R.pttl==="function")I=Number(await R.pttl(B));else if(typeof R.ttl==="function"){let H=Number(await R.ttl(B));I=H<0?H:H*1000}if(I===-1)await Q(B,g);else if(I!==null&&Number.isFinite(I)&&I>0)z=I;return{count:M,resetAt:Date.now()+z}},async get(X){let g=await $(`${_}idem:${X}`);if(!g)return;try{let B=JSON.parse(typeof g==="string"?g:String(g));if(typeof B.rawBodyBase64==="string"){let M=Buffer.from(B.rawBodyBase64,"base64");return{status:B.status,rawBody:M.buffer.slice(M.byteOffset,M.byteOffset+M.byteLength),contentType:B.contentType,headers:B.headers,expiresAt:B.expiresAt}}return B}catch{return}},async set(X,g,B){let M={status:g.status,expiresAt:g.expiresAt};if(g.rawBody!==void 0){if(M.rawBodyBase64=Buffer.from(g.rawBody).toString("base64"),M.contentType=g.contentType,g.headers)M.headers=g.headers}else M.body=g.body;await G(`${_}idem:${X}`,JSON.stringify(M),B)},async acquireToken(X,g=30000){let B=`${_}idem:lock:${X}`,M=crypto.randomUUID();if(Z){let I=await R.send("SET",[B,M,"PX",String(g),"NX"]);return I==="OK"||I===!0?M:null}let z=await R.set(B,M,"PX",g,"NX");return z==="OK"||z===!0||z===1?M:null},async acquire(X,g=30000){let B=await this.acquireToken(X,g);if(!B)return!1;let M=Y.get(X);if(!M)M=[],Y.set(X,M);return M.push(B),!0},async release(X,g){let B=`${_}idem:lock:${X}`,M=g;if(M===void 0){let I=Y.get(X);if(M=I?.pop(),I&&I.length===0)Y.delete(X)}if(!M)return;if(Z)try{await R.send("EVAL",['if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',"1",B,M]);return}catch{}else if(typeof R.eval==="function")try{await R.eval('if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',1,B,M);return}catch{}if(await $(B)===M)await T(B)},async revoke(X,g){await G(`${_}rev:${X}`,"1",g)},async isRevoked(X){let g=await $(`${_}rev:${X}`);return g!==null&&g!==void 0}}};var CR=(R={})=>{let f=R.path??"/health",_=R.readyPath,Z=R.checks,$=Date.now(),T=async()=>{let u={},G=!0;if(Z){let Y=Object.entries(Z);await Promise.all(Y.map(async([E,X])=>{try{let g=await X();if(u[E]=g?"ok":"fail",!g)G=!1}catch{u[E]="fail",G=!1}}))}let Q={status:G?"ok":"degraded",uptimeMs:Date.now()-$,timestamp:new Date().toISOString()};if(R.version)Q.version=R.version;if(Z)Q.checks=u;return Response.json(Q,{status:G?200:503})};return{install(u){if(u.get(f,T),_&&_!==f)u.get(_,T)}}};var KR=(R)=>{let f=R.indexOf("/",8);if(f===-1)return"/";let _=R.indexOf("?",f);return _===-1?R.slice(f):R.slice(f,_)},JR=(R={})=>{let f=R.format??"pretty",_=R.requestId??!0,Z=R.skip,$=R.onLog;return(T,u)=>{let G=KR(T.req.url);if(Z?.(T,G))return u?.();let Q=_?T.requestId:void 0;if(Q)T.setHeader("x-request-id",Q);let Y={timestamp:new Date().toISOString(),method:T.req.method,path:G,...Q?{requestId:Q}:{},ip:T.ip};if($)$(Y);else if(f==="json")console.log(JSON.stringify(Y));else{let E=Q?` [${Q.slice(0,8)}]`:"";console.log(`[${Y.timestamp}] ${Y.method} ${Y.path}${E}`)}return u?.()}};var V=(R)=>{if(!R||!R._def)return{type:"object"};let f=R._def,_=f.typeName;if(_==="ZodObject"){let Z=typeof f.shape==="function"?f.shape():f.shape,$={},T=[];for(let[u,G]of Object.entries(Z||{})){let Q=G;if($[u]=V(Q),Q?._def?.typeName!=="ZodOptional"&&Q?._def?.typeName!=="ZodDefault")T.push(u)}return{type:"object",properties:$,...T.length?{required:T}:{}}}if(_==="ZodString"){let Z={type:"string"};for(let $ of f.checks||[])if($.kind==="min")Z.minLength=$.value;else if($.kind==="max")Z.maxLength=$.value;else if($.kind==="email")Z.format="email";else if($.kind==="uuid")Z.format="uuid";return Z}if(_==="ZodNumber"){let Z={type:"number"};for(let $ of f.checks||[])if($.kind==="int")Z.type="integer";else if($.kind==="min")Z[$.inclusive===!1?"exclusiveMinimum":"minimum"]=$.value;else if($.kind==="max")Z[$.inclusive===!1?"exclusiveMaximum":"maximum"]=$.value;return Z}if(_==="ZodNullable")return{anyOf:[V(f.innerType),{type:"null"}]};if(_==="ZodBoolean")return{type:"boolean"};if(_==="ZodArray")return{type:"array",items:V(f.type)};if(_==="ZodOptional"||_==="ZodDefault")return V(f.innerType);if(_==="ZodEffects")return V(f.schema);if(_==="ZodLiteral")return{const:f.value};if(_==="ZodDate")return{type:"string",format:"date-time"};if(_==="ZodRecord")return{type:"object",additionalProperties:V(f.valueType)};if(_==="ZodUnion"&&Array.isArray(f.options))return{anyOf:f.options.map(V)};if(_==="ZodEnum")return{type:"string",enum:f.values};return{type:"object"}},w=(R)=>{if(!R)return{type:"object"};if("_def"in R)return V(R);return JSON.parse(JSON.stringify(R))},WR=(R,f={})=>{let _={},Z=new Set(["/docs","/docs/json",...f.excludePaths||[]]),$=!1,T=!1;for(let Q of R){if(Z.has(Q.path))continue;let Y=("/"+Q.path).replace(/\/+/g,"/").replace(/:([a-zA-Z0-9_]+)/g,"{$1}").replace(/\/\*$/,"/{wildcard}");if(!_[Y])_[Y]={};let E=Q.method.toLowerCase(),X=[],g=void 0,B=void 0,M=void 0,z=null,I=[];for(let F of Q.handlers){if(!F)continue;if(F.__isBareAuth)$=!0,I.push({bearerAuth:[]});if(F.__isBasicAuth)T=!0,I.push({basicAuth:[]});let L=F.__routeSchemas;if(L){if(L.detail)M=L.detail;if(L.params)z=w(L.params);if(L.query){let C=w(L.query),J=new Set(C.required||[]);for(let[A,j]of Object.entries(C.properties||{}))X.push({name:A,in:"query",required:J.has(A),schema:j})}if(L.headers){let C=w(L.headers),J=new Set(C.required||[]);for(let[A,j]of Object.entries(C.properties||{}))X.push({name:A,in:"header",required:J.has(A),schema:j})}if(L.response)B=L.response}if(F.__schema&&!g)g={required:!0,content:{"application/json":{schema:w(F.__schema)}}}}let H=[],K=Q.path.matchAll(/:([a-zA-Z0-9_]+)/g);for(let F of K){let L=F[1],C=z?.properties?.[L]||{type:"string"};H.push({name:L,in:"path",required:!0,schema:C})}if(/\/\*$/.test(Q.path))H.push({name:"wildcard",in:"path",required:!0,schema:{type:"string"}});let D=[...H,...X],S={"200":"Success","201":"Created","202":"Accepted","204":"No Content","400":"Bad Request","401":"Unauthorized","403":"Forbidden","404":"Not Found","409":"Conflict","413":"Payload Too Large","415":"Unsupported Media Type","422":"Unprocessable Entity","429":"Too Many Requests","500":"Internal Server Error","503":"Service Unavailable"},U={};if(B&&o(B))for(let[F,L]of Object.entries(B))U[F]={description:S[F]||`Response ${F}`,content:{"application/json":{schema:w(L)}}};else U["200"]={description:"Success",...B?{content:{"application/json":{schema:w(B)}}}:{}};_[Y][E]={summary:M?.summary||`${Q.method} ${Y}`,...M?.description?{description:M.description}:{},...M?.tags?{tags:M.tags}:{},...I.length?{security:I}:{},...D.length?{parameters:D}:{},...g?{requestBody:g}:{},responses:U}}let u={};if($)u.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"};if(T)u.basicAuth={type:"http",scheme:"basic"};let G={...u,...f.securitySchemes||{}};return{openapi:"3.1.0",info:{title:f.title||"BareJS API",version:f.version||"1.0.0",...f.description?{description:f.description}:{}},...f.servers?.length?{servers:f.servers}:{},...f.tags?.length?{tags:f.tags}:{},...Object.keys(G).length>0?{components:{securitySchemes:G}}:{},...f.security?.length?{security:f.security}:{},paths:_}},jR=(R)=>R.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"),AR=(R,f="BareJS API Docs")=>{let _=f.replace(/[<>&"]/g,""),Z=jR(R);return`<!doctype html>
|
|
58
|
+
<html>
|
|
59
|
+
<head>
|
|
60
|
+
<title>${_}</title>
|
|
61
|
+
<meta charset="utf-8" />
|
|
62
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
63
|
+
</head>
|
|
64
|
+
<body>
|
|
65
|
+
<script id="api-reference" data-url="${Z}"></script>
|
|
66
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
67
|
+
</body>
|
|
68
|
+
</html>`};var NR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,PR=Array.from({length:256},(R,f)=>f.toString(16).padStart(2,"0")),ZR=(R)=>{let f=new Uint8Array(R);crypto.getRandomValues(f);let _="";for(let Z=0;Z<R;Z++)_+=PR[f[Z]];return _},TR=(R={})=>{let f=R.serverTiming===!1?null:(R.serverTiming||"app").replace(/[^a-zA-Z0-9_.-]/g,""),_=R.exposeTraceparent??!0,Z=R.onSpan;return async($,T)=>{let u=performance.now(),G=$.req.headers.get("traceparent")?.trim().toLowerCase(),Q=G?NR.exec(G):null,Y=Q&&Q[2]!=="00000000000000000000000000000000"?Q[2]:ZR(16),E=Q&&Q[3]!=="0000000000000000"?Q[3]:void 0,X=Q?Q[4]:"01",g=ZR(8),B=`00-${Y}-${g}-${X}`;if($.set("traceId",Y),$.set("spanId",g),E)$.set("parentSpanId",E);if($.set("traceparent",B),_)$.setHeader("traceparent",B);let M=await T(),z=performance.now()-u;if(f){let I=`${f};dur=${z.toFixed(2)}`;if(M instanceof Response)try{M.headers.append("Server-Timing",I)}catch{}else $.setHeader("Server-Timing",I)}if(Z){let I=$.req.url,H=I.indexOf("/",8),K=H===-1?-1:I.indexOf("?",H),D=H===-1?"/":K===-1?I.slice(H):I.slice(H,K),S=M instanceof Response?M.status:$._status||200;Z({traceId:Y,spanId:g,parentSpanId:E,traceparent:B,method:$.req.method,path:D,status:S,durationMs:z})}return M}},VR=(R="app")=>TR({serverTiming:R,exposeTraceparent:!1});var i=new Set(["__proto__","constructor","prototype"]);class uR{req;params;env;executionCtx;store=new Map;body=void 0;user=void 0;_status=200;_headers=void 0;_setCookies=void 0;_query=null;_cookies=null;_jsonCache=void 0;_jsonParsed=!1;_requestId=null;constructor(R,f={},_={},Z){this.req=R,this.params=f,this.env=_,this.executionCtx=Z}get requestId(){if(!this._requestId)this._requestId=this.req.headers.get("x-request-id")||crypto.randomUUID();return this._requestId}get ip(){return this.req.headers.get("cf-connecting-ip")||this.req.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||this.req.headers.get("x-real-ip")||"127.0.0.1"}get query(){if(this._query)return this._query;let R=Object.create(null),f=this.req.url.indexOf("?");if(f!==-1){let _=new URLSearchParams(this.req.url.slice(f+1));for(let[Z,$]of _)if(!i.has(Z))R[Z]=$}return this._query=R,R}get cookies(){if(this._cookies)return this._cookies;let R=Object.create(null),f=this.req.headers.get("cookie");if(f)for(let _ of f.split(";")){let Z=_.indexOf("=");if(Z===-1)continue;let $=_.slice(0,Z).trim();if(!$||i.has($))continue;try{R[$]=decodeURIComponent(_.slice(Z+1).trim())}catch{R[$]=_.slice(Z+1).trim()}}return this._cookies=R,R}get(R){return this.store.get(R)}set(R,f){return this.store.set(R,f),this}status(R){return this._status=R,this}setHeader(R,f){if(!this._headers)this._headers=Object.create(null);else if(Object.getPrototypeOf(this._headers)===Object.prototype)this._headers={...this._headers};let _=R.indexOf("\r")!==-1||R.indexOf(`
|
|
69
|
+
`)!==-1?R.replace(/[\r\n]+/g,""):R,Z=f.indexOf("\r")!==-1||f.indexOf(`
|
|
70
|
+
`)!==-1?f.replace(/[\r\n]+/g,""):f;return this._headers[_.toLowerCase()]=Z,this}appendHeader(R,f){if(R.toLowerCase()==="set-cookie"){if(!this._setCookies)this._setCookies=[];return this._setCookies.push(f),this}return this.setHeader(R,f)}setCookie(R,f,_={}){let $=[`${R.replace(/[\r\n;= ]+/g,"")}=${encodeURIComponent(f)}`];if($.push(`Path=${(_.path??"/").replace(/[\r\n;]+/g,"")}`),_.maxAge!==void 0)$.push(`Max-Age=${Math.floor(_.maxAge)}`);if(_.domain)$.push(`Domain=${_.domain.replace(/[\r\n;]+/g,"")}`);if(_.httpOnly!==!1)$.push("HttpOnly");if(_.secure)$.push("Secure");return $.push(`SameSite=${_.sameSite??"Lax"}`),this.appendHeader("Set-Cookie",$.join("; "))}deleteCookie(R,f="/"){return this.setCookie(R,"",{maxAge:0,path:f})}async jsonBody(R=1048576){if(this._jsonParsed)return this._jsonCache;let f=await this.req.text();if(new TextEncoder().encode(f).byteLength>R){let _=new Error("Payload Too Large");throw _.status=413,_}try{this._jsonCache=f?JSON.parse(f):null}catch{let _=new Error("Malformed JSON payload");throw _.status=400,_}return this._jsonParsed=!0,this._jsonCache}async textBody(){return this.req.text()}buildHeaders(R){let f=new Headers;if(this._headers)for(let _ in this._headers)f.set(_,this._headers[_]);if(this._setCookies)for(let _=0;_<this._setCookies.length;_++)f.append("set-cookie",this._setCookies[_]);if(!f.has("content-type"))f.set("content-type",R);return f}json(R,f){return new Response(JSON.stringify(R),{status:f??this._status,headers:this.buildHeaders("application/json; charset=utf-8")})}text(R,f){return new Response(R,{status:f??this._status,headers:this.buildHeaders("text/plain; charset=utf-8")})}html(R,f){return new Response(R,{status:f??this._status,headers:this.buildHeaders("text/html; charset=utf-8")})}send(R,f){return this.json({status:this._status,msg:R,...f})}redirect(R,f=302){let _=new Headers;if(this._headers)for(let Z in this._headers)_.set(Z,this._headers[Z]);return _.set("location",R.replace(/[\r\n]+/g,"")),new Response(null,{status:f,headers:_})}}class n{children=Object.create(null);paramNode=null;wildcardNode=null;entry=null;paramNames=[];insert(R,f){let _=this,Z=R.split("/").filter(Boolean),$=[];for(let T of Z)if(T==="*"){if(!_.wildcardNode)_.wildcardNode=new n;_=_.wildcardNode;break}else if(T.startsWith(":")){if(!_.paramNode)_.paramNode=new n;$.push(T.slice(1)),_=_.paramNode}else{if(!_.children[T])_.children[T]=new n;_=_.children[T]}_.entry=f,_.paramNames=$}search(R){let f=R.split("/").filter(Boolean),_=(Z,$,T)=>{if($===f.length){if(!Z.entry)return null;let Q=Object.create(null);for(let Y=0;Y<Z.paramNames.length;Y++){let E=Z.paramNames[Y];if(!i.has(E))Q[E]=T[Y]}return{entry:Z.entry,params:Q}}let u=f[$],G=Z.children[u];if(G){let Q=_(G,$+1,T);if(Q)return Q}if(Z.paramNode){T.push(u);let Q=_(Z.paramNode,$+1,T);if(Q)return Q;T.pop()}if(Z.wildcardNode&&Z.wildcardNode.entry){let Q=Object.create(null);for(let Y=0;Y<Z.wildcardNode.paramNames.length;Y++){let E=Z.wildcardNode.paramNames[Y];if(!i.has(E))Q[E]=T[Y]}return Q["*"]=f.slice($).join("/"),{entry:Z.wildcardNode.entry,params:Q}}return null};return _(this,0,[])}}class qR{staticRoutes=new Map;dynamicTrees=new Map;middlewares=[];requestHooks=[];responseHooks=[];errorHandler=null;use(R){return this.middlewares.push(R),this}onRequest(R){return this.requestHooks.push(R),this}onResponse(R){return this.responseHooks.push(R),this}onError(R){return this.errorHandler=R,this}add(R,f,..._){if(_.length===0)return this;let Z=_[_.length-1],$=_.slice(0,-1),T=f.startsWith("/")?f:`/${f}`,u={middlewares:$,handler:Z};if(!T.includes(":")&&!T.includes("*"))this.staticRoutes.set(`${R}:${T}`,u);else{let G=this.dynamicTrees.get(R);if(!G)G=new n,this.dynamicTrees.set(R,G);G.insert(T,u)}return this}get(R,...f){return this.add("GET",R,...f)}post(R,...f){return this.add("POST",R,...f)}put(R,...f){return this.add("PUT",R,...f)}patch(R,...f){return this.add("PATCH",R,...f)}delete(R,...f){return this.add("DELETE",R,...f)}options(R,...f){return this.add("OPTIONS",R,...f)}head(R,...f){return this.add("HEAD",R,...f)}all(R,...f){for(let _ of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.add(_,R,...f);return this}normalizeResponse(R,f){if(f instanceof Response)return f;if(typeof f==="string")return R.text(f);if(f===null||f===void 0)return new Response(null,{status:204});return R.json(f)}fetch=async(R,f,_)=>{let Z=R.url,$=Z.indexOf("/",8),T=$===-1?-1:Z.indexOf("?",$),u=$===-1?"/":T===-1?Z.slice($):Z.slice($,T),G=R.method,Q=this.staticRoutes.get(`${G}:${u}`),Y={};if(!Q){let X=this.dynamicTrees.get(G);if(X){let g=X.search(u);if(g)Q=g.entry,Y=g.params}}let E=new uR(R,Y,f??{},_);try{for(let I=0;I<this.requestHooks.length;I++)await this.requestHooks[I](E);let X=Q?[...this.middlewares,...Q.middlewares,Q.handler]:[...this.middlewares,()=>new Response(JSON.stringify({status:404,message:"Not Found"}),{status:404,headers:{"content-type":"application/json; charset=utf-8"}})],g=-1,B=async(I)=>{if(I<=g)throw new Error("next() called multiple times");g=I;let H=X[I];if(!H)return;return H(E,()=>B(I+1))},M=await B(0),z=this.normalizeResponse(E,M);for(let I=0;I<this.responseHooks.length;I++)await this.responseHooks[I](E,z);return z}catch(X){if(this.errorHandler)return this.errorHandler(X,E);let g=X?.status>=400&&X?.status<600?X.status:500;return new Response(JSON.stringify({status:g,message:g<500?X?.message||"Bad Request":"Internal Server Error"}),{status:g,headers:{"content-type":"application/json; charset=utf-8"}})}};request(R,f,_){let Z=R.startsWith("http://")||R.startsWith("https://")?R:`http://localhost${R.startsWith("/")?R:`/${R}`}`;return this.fetch(new Request(Z,f),_)}}function Gf(){let R=new Map;return{do(f,_){let Z=R.get(f);if(Z)return Z;let $=Promise.resolve().then(_).finally(()=>{R.delete(f)});return R.set(f,$),$},size(){return R.size}}}export{m as z,TR as tracing,FR as timeout,eR as t,XR as standard,VR as serverTiming,HR as securityHeaders,AR as renderDocsHTML,UR as redisStore,LR as rateLimit,gR as native,JR as logger,CR as healthcheck,WR as generateOpenAPISpec,Gf as createSingleflight,zR as cors,SR as circuitBreaker,DR as bareTreaty,$R as bareClient,m as Z,sR as Type,uR as EdgeContext,b as BareRouter,qR as BareJS,qR as BareEdge};
|