barejs 0.2.6 → 0.2.7

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
@@ -127,7 +127,7 @@ Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostnam
127
127
  ```typescript
128
128
  import { BareJS, cors, securityHeaders } from 'barejs/edge';
129
129
 
130
- // Zero node:* imports (~195 KB bundle)
130
+ // Zero node:* imports (~50 KB bundle)
131
131
  const app = new BareJS<{ API_KEY: string }>()
132
132
  .use(securityHeaders())
133
133
  .use(cors({ origin: '*' }))
@@ -171,10 +171,10 @@ Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitat
171
171
 
172
172
  | Scenario | **BareJS** | **ElysiaJS** | **Hono** |
173
173
  | :--- | :---: | :---: | :---: |
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> |
174
+ | **1. 100 Routes + Dynamic Params** | **`1.31 µs`**<br><sub>`p99: 8.02 µs`</sub> | `1.82 µs`<br><sub>`p99: 8.54 µs`</sub> | `4.16 µs`<br><sub>`p99: 15.57 µs`</sub> |
175
+ | **2. 10 Middlewares + Deep Path** | **`1.13 µs`**<br><sub>`p99: 6.53 µs`</sub> | `2.02 µs`<br><sub>`p99: 9.29 µs`</sub> | `4.07 µs`<br><sub>`p99: 15.11 µs`</sub> |
176
+ | **3. POST JSON + Schema Validation** | **`3.54 µs`**<br><sub>`p99: 12.30 µs`</sub> | `4.53 µs`<br><sub>`p99: 14.47 µs`</sub> | `4.89 µs`<br><sub>`p99: 15.93 µs`</sub> |
177
+ | **4. Async Handler + Query Parsing** | **`2.11 µs`**<br><sub>`p99: 9.87 µs`</sub> | `2.44 µs`<br><sub>`p99: 10.52 µs`</sub> | `3.17 µs`<br><sub>`p99: 12.50 µs`</sub> |
178
178
 
179
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`)
180
180
 
@@ -190,21 +190,21 @@ BareJS is a complete, zero-boilerplate backend platform—every module below shi
190
190
 
191
191
  | Category | Built-In Capabilities |
192
192
  | :--- | :--- |
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 |
193
+ | **Core & Routing** | $O(1)$ static `switch` + radix jump-table + $O(1)$ grouped sibling dispatch (`: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 (`50 KB` bundle for Cloudflare Workers, Vercel Edge, Deno Deploy), `app.listenCluster()`, composable `app.use(plugin)` carrying routes + **`app.macro()`**, 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`, **`cookies`**, single or **per-status `response: { 200, 404 }`**, `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()`), strict compile-time **`bareTreaty(app \| url)`** (`api.users({ id: 42 }).get()` & `.subscribe()` WebSocket in-memory or network with typed `data`/`error` unions), automatic **OpenAPI 3.1** spec (`/docs/json`, per-status responses & cookie params) + 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, CRLF header/cookie/redirect guards, `cors()`, `csrf()`, `securityHeaders()`, `rateLimit()` (flood-resistant), `trustProxy(boolean \| string[])` CIDR allowlist |
197
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()` |
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` |
198
+ | **Real-Time, Files & Ops** | Parameterized WebSockets (`app.ws('/ws/:room')` with fail-closed `body`/`query`/`headers` schemas & pub/sub on Bun / `uWebSockets.js`), **Generator Streaming** (`function*` / `async function*`), Server-Sent Events (`ctx.sse()`), **`file()` 1-liner** (root jail + download), `ctx.upload()` & $O(\text{chunk})$ streaming `ctx.uploadStream()`, `staticFile()` (ETag, `304`, Range `206`, SPA fallback, LRU cache), `compress()` (`zstd`/`br`/`gzip`), zero-dep W3C **`tracing()` / `serverTiming()`**, `useLog({ format: 'json' })`, `healthcheck()`, `app.onDrain()` + IPC `DRAIN_REQUEST` |
199
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) |
200
200
 
201
201
  ---
202
202
 
203
203
  ## Documentation
204
204
 
205
- - **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs, code examples, and live CI benchmark dashboard.
205
+ - **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs with `Ctrl+K` instant search, sticky TOC, code examples, and live CI benchmark dashboard.
206
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`.
207
+ - **[Comprehensive Guide](./docs/guide.md)** — Scaffolding, validation & auto-coercion, cookies & uploads, `file()`, generator streaming, security suite, `app.derive()`, `app.macro()`, WebSockets, SSE, JSON-RPC 2.0, OpenAPI 3.1, `tracing()`/`serverTiming()`, `listenCluster()`, `uWebSockets.js`, native `tls`, `barejs/edge`, and `bareClient`/`bareTreaty`.
208
208
  - **[External Integrations](./docs/integrations.md)** — Ready-to-use recipes for Better-Auth, GraphQL Yoga, Auth0, Clerk, Sentry, and OpenTelemetry.
209
209
  - **[API & Configuration Reference](./docs/reference.md)** — Complete `Context` (`ctx`) & `BareJS` API tables, `poolSize`, `bare.config.ts`, and `NODE_ENV` settings.
210
210
  - **[Benchmarks](./BENCHMARKS.md)** — Full 7-scenario results and reproduction instructions.
@@ -216,7 +216,7 @@ BareJS is a complete, zero-boilerplate backend platform—every module below shi
216
216
 
217
217
  ## Status, Contributing & License
218
218
 
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`).
219
+ - **Status:** Active `0.2.x` development (**493 tests across 35 files**). 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`).
220
220
  - **Security:** See [SECURITY.md](./SECURITY.md) for reporting vulnerabilities.
221
221
  - **Contributing:** See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup and release workflows.
222
222
  - **License:** [MIT](./LICENSE) — Maintained by [xarhang](https://github.com/xarhang).
package/dist/edge.js CHANGED
@@ -1,40 +1,40 @@
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})) {
1
+ import*as r from"@sinclair/typebox/compiler";import{z as GR}from"zod";var c=GR,A=(R,f=400)=>Response.json(R,{status:f,headers:{"Content-Type":"application/json"}});var YR=(R)=>{let f=e(R),_=async(Z,$)=>{try{let T=Z instanceof Object&&"req"in Z,u=T?await Z.jsonBody():await Z.json(),Y=f(u);if(!Y.ok)return A({status:"error",code:Y.error?.code||"TYPE_MISMATCH",message:Y.error?.message||"Validation failed",...Y.error?.path?{field:Y.error.path}:{}});if(T)Z.body=Y.data;return $?$():void 0}catch(T){if(T?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Invalid JSON payload"})}};return _.__schema=R,_};var t=(R)=>Boolean(R&&typeof R==="object"&&"~standard"in R&&R["~standard"]&&typeof R["~standard"].validate==="function"),p=(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"}}},ER=(R)=>{let f=async(_,Z)=>{try{let $=_ instanceof Object&&"req"in _,T=$?await _.jsonBody():await _.json(),u=await R["~standard"].validate(T),Y=p(u);if(!Y.ok)return A({status:"error",code:"VALIDATION_FAILED",errors:Y.error});if($)_.body=Y.data;return Z?Z():void 0}catch($){if($?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Invalid JSON payload"})}};return f.__schema=R,f};var s=(R,f)=>{if(f===void 0)return!0;if(Array.isArray(f))return f.some((_)=>s(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},d=(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(!d(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,$)||!d(R[$],f[$]))return!1}return!0},V=(R,f,_,Z)=>{if(!f||typeof f!=="object")return{ok:!0};if(Object.hasOwn(f,"const")&&!d(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(($)=>d($,R)))return{ok:!1,error:{message:`Value at '${_||"root"}' must be one of enum values`,path:_}};if(f.not&&typeof f.not==="object"&&V(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=V(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(V(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(V(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(!s(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(d(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=V(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=V(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 g=Object.keys(R).length;if(typeof f.minProperties==="number"&&g<f.minProperties)return{ok:!1,error:{message:`Object at '${_||"root"}' must have at least ${f.minProperties} properties`,path:_}};if(typeof f.maxProperties==="number"&&g>f.maxProperties)return{ok:!1,error:{message:`Object at '${_||"root"}' must have at most ${f.maxProperties} properties`,path:_}}}if(T)for(let g=0;g<T.length;g++){let G=T[g];if(!Object.hasOwn(R,G)||R[G]===void 0){let E=$?.[G]?.type;return{ok:!1,error:{message:E?`Field '${G}' must be of type ${E}`:`Missing required field '${G}'`,path:_?`${_}.${G}`:G}}}}if($){let g=Object.keys($);for(let G=0;G<g.length;G++){let E=g[G];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 Q=_?`${_}.${E}`:E,B=V(R[E],$[E],Q,!1);if(!B.ok)return B}}let Y=new Set;if(f.patternProperties&&typeof f.patternProperties==="object"){let g=Object.keys(R);for(let[G,E]of Object.entries(f.patternProperties)){let X;try{X=new RegExp(G)}catch{continue}for(let Q=0;Q<g.length;Q++){let B=g[Q];if(!X.test(B))continue;Y.add(B);let M=V(R[B],E,_?`${_}.${B}`:B,!1);if(!M.ok)return M}}}if(f.dependentRequired&&typeof f.dependentRequired==="object")for(let[g,G]of Object.entries(f.dependentRequired)){if(!Object.hasOwn(R,g)||!Array.isArray(G))continue;for(let E of G)if(!Object.hasOwn(R,E))return{ok:!1,error:{message:`Field '${E}' is required when '${g}' is present`,path:_?`${_}.${E}`:E}}}if(f.additionalProperties===!1){let g=Object.keys(R);for(let G=0;G<g.length;G++){let E=g[G];if((!$||!Object.hasOwn($,E))&&!Y.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 g=Object.keys(R);for(let G=0;G<g.length;G++){let E=g[G];if((!$||!Object.hasOwn($,E))&&!Y.has(E)){let X=V(R[E],f.additionalProperties,_?`${_}.${E}`:E,!1);if(!X.ok)return X}}}}return{ok:!0}},e=(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=V($,R,"",_);return T.ok?{ok:!0,data:$}:T}},y=(R)=>{if(R&&"_def"in R)return(f)=>{let _=R.safeParse(f);return _.success?{ok:!0,data:_.data}:{ok:!1,error:_.error.flatten()}};if(t(R)){let f=R["~standard"].validate;return(_)=>{let Z=f(_);if(Z&&typeof Z.then==="function")return Z.then(($)=>p($),()=>({ok:!1,error:{message:"Validation failed"}}));return p(Z)}}try{let f=r.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 e(R)}},a=(R,f,_,Z,$)=>{if(!R)return null;let T=`ar_${Z}_${$}`,u=`j_${Z}_${$}`,Y=`ai_${Z}_${$}`;if(R.type==="array"&&R.items){let E=a(R.items,Y,`${T}[${u}] = `,Z+1,$+1);if(E===null)return null;return`if (Array.isArray(${f})) {
2
2
  const ${T} = new Array(${f}.length);
3
3
  for (let ${u} = 0; ${u} < ${f}.length; ${u}++) {
4
- const ${G} = ${f}[${u}];
4
+ const ${Y} = ${f}[${u}];
5
5
  ${E}
6
6
  }
7
7
  ${_}${T};
8
8
  } else {
9
9
  ${_}${f};
10
- }`}let Q=`ao_${Z}_${$}`,Y=d(R,G,Q,Z+1);if(Y===null)return null;return`if (Array.isArray(${f})) {
10
+ }`}let g=`ao_${Z}_${$}`,G=v(R,Y,g,Z+1);if(G===null)return null;return`if (Array.isArray(${f})) {
11
11
  const ${T} = new Array(${f}.length);
12
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};
13
+ const ${Y} = ${f}[${u}];
14
+ if (${Y} && typeof ${Y} === 'object' && !Array.isArray(${Y})) {
15
+ const ${g} = {};
16
+ ${G} ${T}[${u}] = ${g};
17
17
  } else {
18
- ${T}[${u}] = ${G};
18
+ ${T}[${u}] = ${Y};
19
19
  }
20
20
  }
21
21
  ${_}${T};
22
22
  } else {
23
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) {
24
+ }`},v=(R,f,_,Z=0)=>{let $=R?.properties;if(!$||typeof $!=="object")return null;let T="",u=0;for(let[Y,g]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let G=JSON.stringify(Y),E=`v_${Z}_${u++}`,X=`d_${Z}_${u}`;if(T+=`const ${E} = Object.hasOwn(${f}, ${G}) ? ${f}[${G}] : undefined;
25
+ `,g?.type==="array"&&g?.items){let B=a(g.items,E,`${_}[${G}] = `,Z,u);if(B!==null){T+=`if (${E} !== undefined) {
26
26
  ${B}
27
27
  }
28
- `;continue}}let g=d(Q,E,X,Z+1);if(g!==null)T+=`if (${E} !== undefined) {
28
+ `;continue}}let Q=v(g,E,X,Z+1);if(Q!==null)T+=`if (${E} !== undefined) {
29
29
  `,T+=` if (${E} && typeof ${E} === 'object' && !Array.isArray(${E})) {
30
30
  `,T+=` const ${X} = {};
31
- ${g} ${_}[${Y}] = ${X};
31
+ ${Q} ${_}[${G}] = ${X};
32
32
  `,T+=` } else {
33
- ${_}[${Y}] = ${E};
33
+ ${_}[${G}] = ${E};
34
34
  }
35
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) {
36
+ `;else T+=`if (${E} !== undefined) ${_}[${G}] = ${E};
37
+ `}return T},m=(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 m(R.items);if(R.properties&&typeof R.properties==="object"){for(let f of Object.values(R.properties))if(m(f))return!0}return!1},RR=(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(RR(Z,f))_=!0}return _},P=(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,Y)=>f.items[Y]?P(u,f.items[Y]):u);if(f.items&&typeof f.items==="object")return R.map((u)=>P(u,f.items));return R}let _=f.anyOf||f.oneOf;if(Array.isArray(_)&&_.length>0){let u=null;for(let Y of _)if(Y&&typeof Y==="object"&&y(Y)(R).ok){u=Y;break}if(u){if(f.properties&&typeof f.properties==="object"){let Y={...f.properties,...u.properties||{}},g={};for(let[G,E]of Object.entries(Y)){if(G==="__proto__"||G==="constructor"||G==="prototype")continue;if(Object.hasOwn(R,G)&&R[G]!==void 0)g[G]=P(R[G],E)}return g}return P(R,u)}if(!f.properties)return R}if(Array.isArray(f.allOf)){let u={};if(RR(f,u)){let Y={};for(let[g,G]of Object.entries(u)){if(g==="__proto__"||g==="constructor"||g==="prototype")continue;if(Object.hasOwn(R,g)&&R[g]!==void 0)Y[g]=P(R[g],G)}return Y}}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={},Y=Z?f.properties:null;if(Y)for(let[g,G]of Object.entries(Y)){if(g==="__proto__"||g==="constructor"||g==="prototype")continue;if(Object.hasOwn(R,g)&&R[g]!==void 0)u[g]=P(R[g],G)}if($||T){let g=$?Object.entries(f.patternProperties).map(([G,E])=>({re:new RegExp(G),sub:E})):[];for(let G of Object.keys(R)){if(G==="__proto__"||G==="constructor"||G==="prototype")continue;if(R[G]===void 0||Y&&Object.hasOwn(Y,G))continue;let E=!1;for(let X=0;X<g.length;X++)if(g[X].re.test(G)){u[G]=P(R[G],g[X].sub),E=!0;break}if(!E&&T)u[G]=P(R[G],f.additionalProperties)}}return u}return R},k=(R)=>{if(!R||"_def"in R||t(R))return null;if(m(R))return(_)=>P(_,R);if(R.type==="array"&&R.items){if(R.items.type==="array")return(Z)=>P(Z,R);let _=v(R.items,"item","outItem");if(_===null)return(Z)=>P(Z,R);return new Function(`return function(arr) {
38
38
  if (!Array.isArray(arr)) return arr;
39
39
  const len = arr.length;
40
40
  const out = new Array(len);
@@ -49,12 +49,12 @@ ${g} ${_}[${Y}] = ${X};
49
49
  }
50
50
  }
51
51
  return out;
52
- }`)()}let f=d(R,"o","out");if(f===null)return(_)=>N(_,R);return new Function(`return function(o) {
52
+ }`)()}let f=v(R,"o","out");if(f===null)return(_)=>P(_,R);return new Function(`return function(o) {
53
53
  if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
54
54
  const out = {};
55
55
  ${f}
56
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,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),AR=(R,f="BareJS API Docs")=>{let _=f.replace(/[<>&"]/g,""),Z=jR(R);return`<!doctype html>
57
+ }`)()},MR=/^[1-5]\d\d$/,h=(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(!MR.test(f[_]))return!1;return!0},fR=(R)=>{if(h(R)){let $=new Map;for(let[T,u]of Object.entries(R)){let Y=Number(T);if(Number.isInteger(Y)&&Y>=100&&Y<=599)$.set(Y,fR(u))}return(T,u)=>{let Y=u??(T instanceof Response?T.status:200),g=$.get(Y);return g?g(T,Y):T}}let f=y(R),_=k(R),Z=($)=>{if(!$.ok)return A({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)}},BR=(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},IR=/^\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 Y=$[T];if(typeof Y!=="string")continue;let g=BR(u);if(g==="number"||g==="integer"||g==="ZodNumber"){if(/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(Y)){let G=Number(Y);if(Number.isFinite(G))$[T]=G}}else if(g==="boolean"||g==="ZodBoolean"){if(Y==="true")$[T]=!0;else if(Y==="false")$[T]=!1}}return $},_R=(R)=>{let f=R.body?y(R.body):null,_=R.query?y(R.query):null,Z=R.params?y(R.params):null,$=R.headers?y(R.headers):null,T=R.cookies?y(R.cookies):null,u=R.stripUnknown&&R.body?k(R.body):null,Y=R.stripUnknown&&R.query?k(R.query):null,g=R.stripUnknown&&R.params?k(R.params):null,G=R.stripUnknown&&R.cookies?k(R.cookies):null,E=R.response?fR(R.response):null,X=R.maxBodySize??1048576,Q=[],B=new Set;{let F=R.query;while(F?._def?.schema)F=F._def.schema;let K=F?.properties||(F?._def?.shape?typeof F._def.shape==="function"?F._def.shape():F._def.shape:null),H=(S)=>{let C=S;while(C?._def){let U=C._def.typeName;if(U==="ZodOptional"||U==="ZodDefault"||U==="ZodNullable")C=C._def.innerType;else if(U==="ZodEffects")C=C._def.schema;else break}return C};if(K)for(let[S,C]of Object.entries(K)){let U=H(C);if(!(U?.type==="array"||U?._def?.typeName==="ZodArray"))continue;Q.push(S);let W=H(U.items??U._def?.type),q=W?.type??W?._def?.typeName;if(q==="number"||q==="integer"||q==="ZodNumber")B.add(S)}}let M=Boolean(Z||_||$||T),D=(F)=>{let K=()=>{if(!T)return;let C=l(F.cookies,R.cookies),U=T(C);if(U&&typeof U.then==="function")return U.then((W)=>{if(!W.ok)return A({status:"error",code:"COOKIES_INVALID",error:W.error});F._cookies=G?G(W.data):W.data;return});let j=U;if(!j.ok)return A({status:"error",code:"COOKIES_INVALID",error:j.error});F._cookies=G?G(j.data):j.data;return},H=()=>{if(!$)return K();let C={};F.req.headers.forEach((W,q)=>{let O=q.toLowerCase();if(O!=="__proto__"&&O!=="constructor"&&O!=="prototype")C[O]=W});let U=$(C);if(U&&typeof U.then==="function")return U.then((W)=>W.ok?K():A({status:"error",code:"HEADERS_INVALID",error:W.error}));let j=U;if(!j.ok)return A({status:"error",code:"HEADERS_INVALID",error:j.error});return K()},S=()=>{if(!_)return H();let C=l(F.query,R.query);for(let W of Q){let q=F.queryAll(W);if(q.length>0)C[W]=q.map((O)=>B.has(W)&&IR.test(O)?Number(O):O)}let U=_(C);if(U&&typeof U.then==="function")return U.then((W)=>{if(!W.ok)return A({status:"error",code:"QUERY_INVALID",error:W.error});return F._query=Y?Y(W.data):W.data,H()});let j=U;if(!j.ok)return A({status:"error",code:"QUERY_INVALID",error:j.error});return F._query=Y?Y(j.data):j.data,H()};if(Z){let C=l(F.params,R.params),U=Z(C);if(U&&typeof U.then==="function")return U.then((W)=>{if(!W.ok)return A({status:"error",code:"PARAMS_INVALID",error:W.error});return F.params=g?g(W.data):W.data,S()});let j=U;if(!j.ok)return A({status:"error",code:"PARAMS_INVALID",error:j.error});F.params=g?g(j.data):j.data}return S()};if(!f){let F=(K,H)=>{if(M){let S=D(K);if(S&&typeof S.then==="function")return S.then((C)=>C?C:H?H():void 0);if(S)return S}return H?H():void 0};if(F.__routeSchemas=R,E)F.__responseFilter=E;return F}let I=Boolean(R.body&&"_def"in R.body),z=(F,K,H)=>{if(!K.ok)return A({status:"error",code:"VALIDATION_FAILED",error:K.error});return F.body=u?u(K.data):K.data,H?H():void 0},J=(F,K,H)=>{let S;try{S=f(K)}catch{if(I)return R.body.safeParseAsync(K).then((C)=>{if(!C.success)return A({status:"error",code:"VALIDATION_FAILED",error:C.error.flatten()});return F.body=u?u(C.data):C.data,H?H():void 0});S={ok:!1,error:{message:"Validation failed"}}}if(S&&typeof S.then==="function")return S.then((C)=>z(F,C,H));return z(F,S,H)},L=(F,K)=>{let H;try{H=F.jsonBodySyncOrAsync(X)}catch(S){if(S?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Malformed JSON payload"})}if(H&&typeof H.then==="function")return H.then((S)=>J(F,S,K),(S)=>{if(S?.status===413)return A({status:"error",code:"PAYLOAD_TOO_LARGE",message:"Payload Too Large"},413);return A({status:"error",message:"Malformed JSON payload"})});return J(F,H,K)},N=(F,K)=>{if(M){let H=D(F);if(H&&typeof H.then==="function")return H.then((S)=>S?S:L(F,K));if(H)return H}return L(F,K)};if(N.__schema=R.body,N.__routeSchemas=R,E)N.__responseFilter=E;return N};class i{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(_R(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 i($,[...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 i||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 Y=u;Y<this.routes.length;Y++)this.routes[Y].handlers=[...this.groupMiddleware,...Z,...this.routes[Y].handlers.slice(this.groupMiddleware.length)]}return this._onRouteMutate?.(),this}let _=[R,...f];for(let Z=0;Z<_.length;Z++){let $=_[Z];if($ instanceof i||$&&$.routes)this._mountRouter("",$);else if($&&typeof $.install==="function")$.install(this);else if(typeof $==="function")this.groupMiddleware.push($)}return this._onRouteMutate?.(),this}}import{Type as Rf,Type as ff}from"@sinclair/typebox";var $R=(R,f,_)=>{let Z=f;if(_?.params){let Y=_.params;Z=Z.replace(/:([a-zA-Z0-9_]+)(?=\/|\?|$)/g,(g,G)=>Object.hasOwn(Y,G)&&Y[G]!==void 0?encodeURIComponent(String(Y[G])):g)}let $=R.endsWith("/")?R.slice(0,-1):R,T=Z.startsWith("/")?Z:`/${Z}`,u=`${$}${T}`;if(_?.query){let Y=new URLSearchParams;for(let[G,E]of Object.entries(_.query))if(E!==void 0)Y.set(G,String(E));let g=Y.toString();if(g)u+=(u.includes("?")?"&":"?")+g}return u},ZR=(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},TR=(R)=>{if(typeof R==="string"||R instanceof ArrayBuffer||ArrayBuffer.isView(R))return R;return JSON.stringify(R)},DR=(R,f,_)=>{let Z=new Set,$=new Set,T=new Set,u=1,Y=new URL(f),g=R?.wsRoutes,G=null,E={};if(g&&g.size>0){let Q=g.get(Y.pathname);if(Q)G=Q;else{let B=Y.pathname.split("/").filter(Boolean);for(let[M,D]of g.entries()){let I=M.split("/").filter(Boolean);if(I.length!==B.length)continue;let z={},J=!0;for(let L=0;L<I.length;L++)if(I[L].startsWith(":"))z[I[L].slice(1)]=decodeURIComponent(B[L]);else if(I[L]!==B[L]){J=!1;break}if(J){G=D,E=z;break}}}}let X={data:G?{...G,params:E}:{params:E},send(Q){if(u!==1)return;let B=ZR(Q);for(let M of Z)M(B)},close(Q=1000,B=""){if(u===3)return;u=3;for(let M of T)M(Q,B)}};return queueMicrotask(async()=>{if(u!==1)return;if(G?.__validateUpgrade)try{let Q=await G.__validateUpgrade(f,_);if(!Q?.ok){X.close(1008,Q?.code||"WS_UPGRADE_INVALID");return}if(Q.query!==void 0)X.data.query=Q.query;if(Q.headers!==void 0)X.data.headers=Q.headers}catch{X.close(1008,"WS_UPGRADE_INVALID");return}if(u!==1)return;G?.open?.(X);for(let Q of $)Q()}),{get readyState(){return u},send(Q){if(u!==1)throw new Error("WebSocket is closed");G?.message?.(X,TR(Q))},onMessage(Q){return Z.add(Q),()=>Z.delete(Q)},onOpen(Q){return $.add(Q),()=>$.delete(Q)},onClose(Q){return T.add(Q),()=>T.delete(Q)},close(Q=1000,B=""){if(u===3)return;u=3,G?.close?.(X,Q,B);for(let M of T)M(Q,B)}}},zR=(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 Y=ZR(u.data);for(let g of Z)g(Y)},_.onopen=()=>{for(let u of $)u()},_.onclose=(u)=>{for(let Y of T)Y(u.code,u.reason)},{get readyState(){return _.readyState},send(u){_.send(TR(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,Y){_.close(u,Y)}}},HR=new Set(["get","post","put","patch","delete"]),uR=(R,f={})=>{let _=typeof R==="object"&&R!==null&&typeof R.fetch==="function",Z=_?"http://localhost":R,$=f.fetch??(_?(X,Q)=>R.fetch(new Request(String(X),Q)):fetch),T=f.headers??{},u=async(X,Q,B)=>{let M=$R(Z,Q,B),D=new Headers;for(let[L,N]of Object.entries(T))D.set(L,N);if(B?.headers)for(let[L,N]of Object.entries(B.headers))D.set(L,N);let I={method:X,headers:D};if(B?.body!==void 0&&X!=="GET"&&X!=="HEAD"){let L=B.body;if(typeof L==="string"||L instanceof FormData||L instanceof URLSearchParams||L instanceof Blob||L instanceof ArrayBuffer||ArrayBuffer.isView(L)||typeof ReadableStream!=="undefined"&&L instanceof ReadableStream){if(L instanceof FormData)D.delete("content-type");I.body=L}else{if(!D.has("content-type"))D.set("Content-Type","application/json");I.body=JSON.stringify(L)}}let z=await $(M,I),J=null;if(z.status!==204&&z.status!==205&&z.status!==304){let L=(z.headers.get("content-type")||"").toLowerCase();if(L.includes("application/json")||L.includes("+json")){let N=await z.text();if(N)try{J=JSON.parse(N)}catch{J=N}else J=null}else J=await z.text()}if(!z.ok)return{ok:!1,data:null,error:J,status:z.status,headers:z.headers};return{ok:!0,data:J,error:null,status:z.status,headers:z.headers}},Y=async(X,Q,B)=>{let M=await u(X,Q,B);if(!M.ok){let D=new Error(`HTTP ${M.status}`);throw D.status=M.status,D.data=M.error,D}return M.data},g=(X,Q)=>{let B=$R(Z,X,Q),M={...T,...Q?.headers||{}};return _?DR(R,B,M):zR(B)},G=(X)=>{return new Proxy((B)=>{if(typeof B==="string"||typeof B==="number")return G([...X,encodeURIComponent(String(B))]);let M=[...X];for(let D of Object.values(B))M.push(encodeURIComponent(String(D)));return G(M)},{get(B,M){if(typeof M==="symbol")return;if(M==="then"||M==="catch"||M==="finally")return;if(HR.has(M)){let D=M.toUpperCase(),I="/"+X.join("/");return(z)=>u(D,I,z)}if(M==="subscribe"){let D="/"+X.join("/");return(I)=>g(D,I)}return G([...X,M])}})};return{get:(X,Q)=>Y("GET",X,Q),post:(X,Q)=>Y("POST",X,Q),put:(X,Q)=>Y("PUT",X,Q),patch:(X,Q)=>Y("PATCH",X,Q),delete:(X,Q)=>Y("DELETE",X,Q),safe:{get:(X,Q)=>u("GET",X,Q),post:(X,Q)=>u("POST",X,Q),put:(X,Q)=>u("PUT",X,Q),patch:(X,Q)=>u("PATCH",X,Q),delete:(X,Q)=>u("DELETE",X,Q)},treaty:G([]),ws:g}},LR=(R,f={})=>uR(R,f).treaty;var n=(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`)},FR=(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((Q)=>Q.trim()).includes("origin"))E.setHeader("Vary",`${X}, Origin`)};if(typeof f==="string"){if(f===""){let M=(D,I)=>{if(D.req.method==="OPTIONS")return new Response(null,{status:204,headers:{Vary:"Origin"}});D.setHeader("Vary","Origin");let z=I?.();if(z&&typeof z.then==="function")return z.then((J)=>{if(J instanceof Response)n(J.headers);else u(D);return J});if(z instanceof Response)n(z.headers);else u(D);return z};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 Q={status:204,headers:X},B=(M,D)=>{if(M.req.method==="OPTIONS")return new Response(null,Q);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=D?.();if(I&&typeof I.then==="function")return I.then((z)=>{if(z instanceof Response){if(z.headers.set("Access-Control-Allow-Origin",f),z.headers.set("Access-Control-Allow-Methods",_),f!=="*")n(z.headers);if(E)z.headers.set("Access-Control-Allow-Credentials","true");if($)z.headers.set("Access-Control-Expose-Headers",$)}else if(f!=="*")u(M);return z});if(I instanceof Response){if(I.headers.set("Access-Control-Allow-Origin",f),I.headers.set("Access-Control-Allow-Methods",_),f!=="*")n(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 Y=Array.isArray(f)?new Set(f):null,g=(E)=>{if(!E)return null;if(Y)return Y.has(E)?E:null;return f(E)?E:null},G=(E,X)=>{let Q=g(E.req.headers.get("origin"));if(E.req.method==="OPTIONS"){let M={"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":Z,Vary:"Origin"};if(Q)M["Access-Control-Allow-Origin"]=Q;if(T&&Q)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",_),Q){if(E.setHeader("Access-Control-Allow-Origin",Q),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(n(M.headers),M.headers.set("Access-Control-Allow-Methods",_),Q){if(M.headers.set("Access-Control-Allow-Origin",Q),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(n(B.headers),B.headers.set("Access-Control-Allow-Methods",_),Q){if(B.headers.set("Access-Control-Allow-Origin",Q),T)B.headers.set("Access-Control-Allow-Credentials","true")}if($)B.headers.set("Access-Control-Expose-Headers",$)}else u(E);return B};return G.__isCors=!0,G};var SR=(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((Y)=>{if(Y instanceof Response)for(let g=0;g<_;g++){let G=f[g];if(!Y.headers.has(G[0]))Y.headers.set(G[0],G[1])}return Y});if(u instanceof Response)for(let Y=0;Y<_;Y++){let g=f[Y];if(!u.headers.has(g[0]))u.headers.set(g[0],g[1])}return u}};var UR=(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??((G)=>G.ip),u=R.store,Y=(G,E,X,Q,B)=>{let M=Math.max(0,_-E),D=String(Math.ceil(X/1000));if(G.setHeader("X-RateLimit-Limit",String(_)),G.setHeader("X-RateLimit-Remaining",String(M)),G.setHeader("X-RateLimit-Reset",D),E>_){let I=Math.max(1,Math.ceil((X-Q)/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":D}})}return B?.()};if(u)return async(G,E)=>{let X=Date.now(),Q=T(G),{count:B,resetAt:M}=await u.increment(Q,f);return Y(G,B,M,X,E)};let g=new Map;return(G,E)=>{let X=Date.now(),Q=T(G),B=g.get(Q);if(!B||X>=B.resetAt){if(g.size>=$)for(let[D,I]of g){if(X>=I.resetAt)g.delete(D);if(g.size<$)break}let M=Q;if(g.size>=$&&!g.has(Q)){M="\x00__overflow__";let D=g.get(M);if(D&&X<D.resetAt)return D.count++,Y(G,D.count,D.resetAt,X,E)}B={count:1,resetAt:X+f},g.delete(M),g.set(M,B)}else B.count++,g.delete(Q),g.set(Q,B);return Y(G,B.count,B.resetAt,X,E)}};var KR=(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,Y)=>{let g;try{let G=Promise.resolve(Y()),E=new Promise((X)=>{g=setTimeout(()=>{u._detached=!0,G.catch(()=>{}),X(Response.json({status:"error",code:"REQUEST_TIMEOUT",message:Z},{status:_}))},$)});return await Promise.race([G,E])}finally{if(g!==void 0)clearTimeout(g)}};return T.__timeout={ms:$,status:_,message:Z},T};var CR=(R={})=>{let f=R.failureThreshold??5,_=R.resetTimeoutMs??30000,Z=R.isFailure??((M,D)=>Boolean(D)||M instanceof Response&&(M.status>=500||M.status===408)),$="CLOSED",T=0,u=0,Y=!1,g=0,G=0,E=0,X=(M)=>{if($!==M){let D=$;$=M,g++;try{R.onStateChange?.(D,M)}catch{}}},Q=async(M)=>{if($==="OPEN"){let L=Date.now()-u;if(L<_){let N=Math.max(1,Math.ceil((_-L)/1000));return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":String(N)}})}X("HALF_OPEN")}let D=!1;if($==="HALF_OPEN"){if(Y)return Response.json({status:"error",code:"CIRCUIT_OPEN",message:"Service temporarily unavailable"},{status:503,headers:{"Retry-After":"1"}});Y=!0,D=!0}let I=g,z,J=D?++G:0;if(D)E=J,z=setTimeout(()=>{if(E===J&&I===g)Y=!1,E=0,u=Date.now(),X("OPEN")},Math.min(Math.max(_,1),2147483647));try{let L=await M();if(I!==g)return L;if(Z(L)){if(T++,D||T>=f)u=Date.now(),X("OPEN")}else if(T=0,D)X("CLOSED");return L}catch(L){if(I===g&&Z(void 0,L)){if(T++,D||T>=f)u=Date.now(),X("OPEN")}throw L}finally{if(z!==void 0)clearTimeout(z);if(D&&E===J)Y=!1,E=0}},B=(M,D)=>Q(()=>D?D():void 0);return B.__circuitBreaker=Q,B};var WR=(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),Y=async(X,Q,B)=>{if(Z){await R.send("SET",[X,Q,"PX",String(B)]);return}try{await R.set(X,Q,"PX",B)}catch{if(await R.set(X,Q),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)))}},g=async(X,Q)=>{if(Z)await R.send("PEXPIRE",[X,String(Q)]);else if(typeof R.pexpire==="function")await R.pexpire(X,Q);else if(typeof R.expire==="function")await R.expire(X,Math.max(1,Math.ceil(Q/1000)))},G=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,Q){let B=`${_}rl:${X}`,M=Number(await u(B));if(M===1)await g(B,Q);let D=Q,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 z=Number(await R.ttl(B));I=z<0?z:z*1000}if(I===-1)await g(B,Q);else if(I!==null&&Number.isFinite(I)&&I>0)D=I;return{count:M,resetAt:Date.now()+D}},async get(X){let Q=await $(`${_}idem:${X}`);if(!Q)return;try{let B=JSON.parse(typeof Q==="string"?Q:String(Q));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,Q,B){let M={status:Q.status,expiresAt:Q.expiresAt};if(Q.rawBody!==void 0){if(M.rawBodyBase64=Buffer.from(Q.rawBody).toString("base64"),M.contentType=Q.contentType,Q.headers)M.headers=Q.headers}else M.body=Q.body;await Y(`${_}idem:${X}`,JSON.stringify(M),B)},async acquireToken(X,Q=30000){let B=`${_}idem:lock:${X}`,M=crypto.randomUUID();if(Z){let I=await R.send("SET",[B,M,"PX",String(Q),"NX"]);return I==="OK"||I===!0?M:null}let D=await R.set(B,M,"PX",Q,"NX");return D==="OK"||D===!0||D===1?M:null},async acquire(X,Q=30000){let B=await this.acquireToken(X,Q);if(!B)return!1;let M=G.get(X);if(!M)M=[],G.set(X,M);return M.push(B),!0},async release(X,Q){let B=`${_}idem:lock:${X}`,M=Q;if(M===void 0){let I=G.get(X);if(M=I?.pop(),I&&I.length===0)G.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,Q){await Y(`${_}rev:${X}`,"1",Q)},async isRevoked(X){let Q=await $(`${_}rev:${X}`);return Q!==null&&Q!==void 0}}};var JR=(R={})=>{let f=R.path??"/health",_=R.readyPath,Z=R.checks,$=Date.now(),T=async()=>{let u={},Y=!0;if(Z){let G=Object.entries(Z);await Promise.all(G.map(async([E,X])=>{try{let Q=await X();if(u[E]=Q?"ok":"fail",!Q)Y=!1}catch{u[E]="fail",Y=!1}}))}let g={status:Y?"ok":"degraded",uptimeMs:Date.now()-$,timestamp:new Date().toISOString()};if(R.version)g.version=R.version;if(Z)g.checks=u;return Response.json(g,{status:Y?200:503})};return{install(u){if(u.get(f,T),_&&_!==f)u.get(_,T)}}};var jR=(R)=>{let f=R.indexOf("/",8);if(f===-1)return"/";let _=R.indexOf("?",f);return _===-1?R.slice(f):R.slice(f,_)},AR=(R={})=>{let f=R.format??"pretty",_=R.requestId??!0,Z=R.skip,$=R.onLog;return(T,u)=>{let Y=jR(T.req.url);if(Z?.(T,Y))return u?.();let g=_?T.requestId:void 0;if(g)T.setHeader("x-request-id",g);let G={timestamp:new Date().toISOString(),method:T.req.method,path:Y,...g?{requestId:g}:{},ip:T.ip};if($)$(G);else if(f==="json")console.log(JSON.stringify(G));else{let E=g?` [${g.slice(0,8)}]`:"";console.log(`[${G.timestamp}] ${G.method} ${G.path}${E}`)}return u?.()}};var w=(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,Y]of Object.entries(Z||{})){let g=Y;if($[u]=w(g),g?._def?.typeName!=="ZodOptional"&&g?._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:[w(f.innerType),{type:"null"}]};if(_==="ZodBoolean")return{type:"boolean"};if(_==="ZodArray")return{type:"array",items:w(f.type)};if(_==="ZodOptional"||_==="ZodDefault")return w(f.innerType);if(_==="ZodEffects")return w(f.schema);if(_==="ZodLiteral")return{const:f.value};if(_==="ZodDate")return{type:"string",format:"date-time"};if(_==="ZodRecord")return{type:"object",additionalProperties:w(f.valueType)};if(_==="ZodUnion"&&Array.isArray(f.options))return{anyOf:f.options.map(w)};if(_==="ZodEnum")return{type:"string",enum:f.values};return{type:"object"}},b=(R)=>{if(!R)return{type:"object"};if("_def"in R)return w(R);return JSON.parse(JSON.stringify(R))},NR=(R,f={})=>{let _={},Z=new Set(["/docs","/docs/json",...f.excludePaths||[]]),$=!1,T=!1;for(let g of R){if(Z.has(g.path))continue;let G=("/"+g.path).replace(/\/+/g,"/").replace(/:([a-zA-Z0-9_]+)/g,"{$1}").replace(/\/\*$/,"/{wildcard}");if(!_[G])_[G]={};let E=g.method.toLowerCase(),X=[],Q=void 0,B=void 0,M=void 0,D=null,I=[];for(let K of g.handlers){if(!K)continue;if(K.__isBareAuth)$=!0,I.push({bearerAuth:[]});if(K.__isBasicAuth)T=!0,I.push({basicAuth:[]});let H=K.__routeSchemas;if(H){if(H.detail)M=H.detail;if(H.params)D=b(H.params);if(H.query){let S=b(H.query),C=new Set(S.required||[]);for(let[U,j]of Object.entries(S.properties||{}))X.push({name:U,in:"query",required:C.has(U),schema:j})}if(H.headers){let S=b(H.headers),C=new Set(S.required||[]);for(let[U,j]of Object.entries(S.properties||{}))X.push({name:U,in:"header",required:C.has(U),schema:j})}if(H.cookies){let S=b(H.cookies),C=new Set(S.required||[]);for(let[U,j]of Object.entries(S.properties||{}))X.push({name:U,in:"cookie",required:C.has(U),schema:j})}if(H.response)B=H.response}if(K.__schema&&!Q)Q={required:!0,content:{"application/json":{schema:b(K.__schema)}}}}let z=[],J=g.path.matchAll(/:([a-zA-Z0-9_]+)/g);for(let K of J){let H=K[1],S=D?.properties?.[H]||{type:"string"};z.push({name:H,in:"path",required:!0,schema:S})}if(/\/\*$/.test(g.path))z.push({name:"wildcard",in:"path",required:!0,schema:{type:"string"}});let L=[...z,...X],N={"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"},F={};if(B&&h(B))for(let[K,H]of Object.entries(B))F[K]={description:N[K]||`Response ${K}`,content:{"application/json":{schema:b(H)}}};else F["200"]={description:"Success",...B?{content:{"application/json":{schema:b(B)}}}:{}};_[G][E]={summary:M?.summary||`${g.method} ${G}`,...M?.description?{description:M.description}:{},...M?.tags?{tags:M.tags}:{},...I.length?{security:I}:{},...L.length?{parameters:L}:{},...Q?{requestBody:Q}:{},responses:F}}let u={};if($)u.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"};if(T)u.basicAuth={type:"http",scheme:"basic"};let Y={...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(Y).length>0?{components:{securitySchemes:Y}}:{},...f.security?.length?{security:f.security}:{},paths:_}},PR=(R)=>R.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),VR=(R,f="BareJS API Docs")=>{let _=f.replace(/[<>&"]/g,""),Z=PR(R);return`<!doctype html>
58
58
  <html>
59
59
  <head>
60
60
  <title>${_}</title>
@@ -65,6 +65,6 @@ ${g} ${_}[${Y}] = ${X};
65
65
  <script id="api-reference" data-url="${Z}"></script>
66
66
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
67
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(`
68
+ </html>`};var qR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,OR=Array.from({length:256},(R,f)=>f.toString(16).padStart(2,"0")),gR=(R)=>{let f=new Uint8Array(R);crypto.getRandomValues(f);let _="";for(let Z=0;Z<R;Z++)_+=OR[f[Z]];return _},QR=(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(),Y=$.req.headers.get("traceparent")?.trim().toLowerCase(),g=Y?qR.exec(Y):null,G=g&&g[2]!=="00000000000000000000000000000000"?g[2]:gR(16),E=g&&g[3]!=="0000000000000000"?g[3]:void 0,X=g?g[4]:"01",Q=gR(8),B=`00-${G}-${Q}-${X}`;if($.set("traceId",G),$.set("spanId",Q),E)$.set("parentSpanId",E);if($.set("traceparent",B),_)$.setHeader("traceparent",B);let M=await T(),D=performance.now()-u;if(f){let I=`${f};dur=${D.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,z=I.indexOf("/",8),J=z===-1?-1:I.indexOf("?",z),L=z===-1?"/":J===-1?I.slice(z):I.slice(z,J),N=M instanceof Response?M.status:$._status||200;Z({traceId:G,spanId:Q,parentSpanId:E,traceparent:B,method:$.req.method,path:L,status:N,durationMs:D})}return M}},wR=(R="app")=>QR({serverTiming:R,exposeTraceparent:!1});var o=new Set(["__proto__","constructor","prototype"]);class XR{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(!o.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(!$||o.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
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};
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 x{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 x;_=_.wildcardNode;break}else if(T.startsWith(":")){if(!_.paramNode)_.paramNode=new x;$.push(T.slice(1)),_=_.paramNode}else{if(!_.children[T])_.children[T]=new x;_=_.children[T]}_.entry=f,_.paramNames=$}search(R){let f=R.split("/").filter(Boolean),_=(Z,$,T)=>{if($===f.length){if(!Z.entry)return null;let g=Object.create(null);for(let G=0;G<Z.paramNames.length;G++){let E=Z.paramNames[G];if(!o.has(E))g[E]=T[G]}return{entry:Z.entry,params:g}}let u=f[$],Y=Z.children[u];if(Y){let g=_(Y,$+1,T);if(g)return g}if(Z.paramNode){T.push(u);let g=_(Z.paramNode,$+1,T);if(g)return g;T.pop()}if(Z.wildcardNode&&Z.wildcardNode.entry){let g=Object.create(null);for(let G=0;G<Z.wildcardNode.paramNames.length;G++){let E=Z.wildcardNode.paramNames[G];if(!o.has(E))g[E]=T[G]}return g["*"]=f.slice($).join("/"),{entry:Z.wildcardNode.entry,params:g}}return null};return _(this,0,[])}}class yR{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 Y=this.dynamicTrees.get(R);if(!Y)Y=new x,this.dynamicTrees.set(R,Y);Y.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),Y=R.method,g=this.staticRoutes.get(`${Y}:${u}`),G={};if(!g){let X=this.dynamicTrees.get(Y);if(X){let Q=X.search(u);if(Q)g=Q.entry,G=Q.params}}let E=new XR(R,G,f??{},_);try{for(let I=0;I<this.requestHooks.length;I++)await this.requestHooks[I](E);let X=g?[...this.middlewares,...g.middlewares,g.handler]:[...this.middlewares,()=>new Response(JSON.stringify({status:404,message:"Not Found"}),{status:404,headers:{"content-type":"application/json; charset=utf-8"}})],Q=-1,B=async(I)=>{if(I<=Q)throw new Error("next() called multiple times");Q=I;let z=X[I];if(!z)return;return z(E,()=>B(I+1))},M=await B(0),D=this.normalizeResponse(E,M);for(let I=0;I<this.responseHooks.length;I++)await this.responseHooks[I](E,D);return D}catch(X){if(this.errorHandler)return this.errorHandler(X,E);let Q=X?.status>=400&&X?.status<600?X.status:500;return new Response(JSON.stringify({status:Q,message:Q<500?X?.message||"Bad Request":"Internal Server Error"}),{status:Q,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 Mf(){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{c as z,QR as tracing,KR as timeout,ff as t,ER as standard,wR as serverTiming,SR as securityHeaders,VR as renderDocsHTML,WR as redisStore,UR as rateLimit,YR as native,AR as logger,JR as healthcheck,NR as generateOpenAPISpec,Mf as createSingleflight,FR as cors,CR as circuitBreaker,LR as bareTreaty,uR as bareClient,c as Z,Rf as Type,XR as EdgeContext,i as BareRouter,yR as BareJS,yR as BareEdge};