barejs 0.2.3 → 0.2.4
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 +4 -4
- package/dist/index.js +1 -1
- package/dist/node.js +1 -1
- package/package.json +1 -1
- package/src/runtime/uws.ts +4 -2
package/README.md
CHANGED
|
@@ -126,10 +126,10 @@ Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitat
|
|
|
126
126
|
|
|
127
127
|
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
128
128
|
| :--- | :---: | :---: | :---: |
|
|
129
|
-
| **1. 100 Routes + Dynamic Params** | **`1.
|
|
130
|
-
| **2. 10 Middlewares + Deep Path** | **`1.
|
|
131
|
-
| **3. POST JSON + Schema Validation** | **`4.
|
|
132
|
-
| **4. Async Handler + Query Parsing** | `2.
|
|
129
|
+
| **1. 100 Routes + Dynamic Params** | **`1.46 µs`**<br><sub>`p99: 8.20 µs`</sub> | `1.87 µs`<br><sub>`p99: 8.44 µs`</sub> | `4.45 µs`<br><sub>`p99: 18.55 µs`</sub> |
|
|
130
|
+
| **2. 10 Middlewares + Deep Path** | **`1.48 µs`**<br><sub>`p99: 8.21 µs`</sub> | `1.89 µs`<br><sub>`p99: 8.90 µs`</sub> | `4.13 µs`<br><sub>`p99: 14.78 µs`</sub> |
|
|
131
|
+
| **3. POST JSON + Schema Validation** | **`4.08 µs`**<br><sub>`p99: 14.60 µs`</sub> | `4.65 µs`<br><sub>`p99: 15.04 µs`</sub> | `5.28 µs`<br><sub>`p99: 18.34 µs`</sub> |
|
|
132
|
+
| **4. Async Handler + Query Parsing** | `2.34 µs`<br><sub>`p99: 10.40 µs`</sub> | `2.30 µs`<br><sub>`p99: 9.53 µs`</sub> | `3.17 µs`<br><sub>`p99: 13.02 µs`</sub> |
|
|
133
133
|
|
|
134
134
|
> Last Updated: 2026-11-26 (github action — `linux`, AMD EPYC 7763 64-Core Processor, Bun `1.4.5`, Elysia `1.4.21`, Hono `4.11.4`)
|
|
135
135
|
|
package/dist/index.js
CHANGED
|
@@ -127,7 +127,7 @@ ${U} ${X}[${q}] = ${_};
|
|
|
127
127
|
<script id="api-reference" data-url="${Y}"></script>
|
|
128
128
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
129
129
|
</body>
|
|
130
|
-
</html>`};function u2($,Q){let X=Q;if(Q.startsWith("http://")||Q.startsWith("https://")||Q.startsWith("ws://")||Q.startsWith("wss://")){let z=Q.indexOf("/",8),M=z===-1?-1:Q.indexOf("?",z);X=z===-1?"/":M===-1?Q.slice(z):Q.slice(z,M)}else{let z=Q.indexOf("?");if(z!==-1)X=Q.slice(0,z)}let Y=X.replace(/\/+/g,"/"),W=Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y,H=$.get(W);if(H)return{handler:H};let J=W.split("/").filter(Boolean);for(let[z,M]of $){if(!z.includes(":")&&!z.includes("*"))continue;let q=z.split("/").filter(Boolean),B={},_=!0;for(let U=0;U<q.length;U++){let A=q[U];if(A==="*"){B["*"]=J.slice(U).join("/");break}if(U>=J.length){_=!1;break}if(A.startsWith(":"))B[A.slice(1)]=J[U];else if(A!==J[U]){_=!1;break}}if(_&&(q.includes("*")||q.length===J.length))return{handler:M,params:B}}return}var dM=typeof globalThis.Bun?.zstdCompressSync==="function"?($)=>globalThis.Bun.zstdCompressSync($):void 0,d9={name:"bun",serve($){let{ws:Q,routes:X}=$,Y;try{Y=Q?Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){if(W.headers.get("upgrade")?.toLowerCase()==="websocket"){let J=u2(Q.routes,W.url);if(J&&H.upgrade(W,{data:J.params?{...J.handler,params:J.params}:J.handler}))return}return $.fetch(W,H?.requestIP?.(W)?.address)},websocket:Q.adapter}):Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){return $.fetch(W,H?.requestIP?.(W)?.address)}})}catch(W){if(W?.code==="EADDRINUSE"||/in use/i.test(W?.message||""))throw new Error(`[BareJS] Port ${$.port} is already in use on ${$.hostname}. Choose a different port or stop the existing process.`);throw W}return{stop(W=!1){Y.stop(W)},port:Y.port??$.port,raw:Y}},gzip($,Q){return Bun.gzipSync($,{level:Q})},zstd:dM,openFile($){let Q=Bun.file($);return{get type(){return Q.type},full(){return Q},slice(X,Y){return Q.slice(X,Y)}}},password:{hash($,Q){if(Q.algorithm==="bcrypt"){let X=Math.max(4,Math.min(31,Q.timeCost));return Bun.password.hash($,{algorithm:"bcrypt",cost:X})}return Bun.password.hash($,Q)},verify($,Q){return Bun.password.verify($,Q)}}};import{createHash as iM,randomBytes as pM,scrypt as cM,timingSafeEqual as lM}from"crypto";import{createServer as oM}from"http";import{createReadStream as l9}from"fs";import{extname as sM}from"path";import{Readable as o9}from"stream";import*as T1 from"zlib";import{createRequire as m9}from"module";import{join as mM}from"path";var nM={200:"200 OK",201:"201 Created",202:"202 Accepted",204:"204 No Content",206:"206 Partial Content",301:"301 Moved Permanently",302:"302 Found",304:"304 Not Modified",400:"400 Bad Request",401:"401 Unauthorized",403:"403 Forbidden",404:"404 Not Found",405:"405 Method Not Allowed",409:"409 Conflict",413:"413 Payload Too Large",415:"415 Unsupported Media Type",422:"422 Unprocessable Entity",429:"429 Too Many Requests",500:"500 Internal Server Error",502:"502 Bad Gateway",503:"503 Service Unavailable"};function KQ($){return nM[$]||`${$}`}function u9(){if(typeof globalThis.Bun!=="undefined"||typeof globalThis.Deno!=="undefined")return null;try{return m9(mM(process.cwd(),"package.json"))("uWebSockets.js")}catch{try{return m9(import.meta.url)("uWebSockets.js")}catch{return null}}}class i9{res=null;params={};store=new Map;_status=200;_headers=void 0;_setCookies=void 0;_queryStr="";_query=void 0;_url="/";_method="GET";_reqHeaders=void 0;_req=void 0;_peerIp=void 0;_responded=!1;_inSync=!1;_aborted=!1;reset(){if(this.res=null,this.params={},this.store.size>0)this.store.clear();this._status=200,this._headers=void 0,this._setCookies=void 0,this._queryStr="",this._query=void 0,this._url="/",this._method="GET",this._reqHeaders=void 0,this._req=void 0,this._peerIp=void 0,this._responded=!1,this._inSync=!1,this._aborted=!1}get req(){if(!this._req){let $=this._queryStr?`?${this._queryStr}`:"",Q=this._reqHeaders?.host||"localhost";this._req=new Request(`http://${Q}${this._url}${$}`,{method:this._method,headers:this._reqHeaders})}return this._req}get query(){if(!this._query){let $={};if(this._queryStr){let Q=new URLSearchParams(this._queryStr);for(let[X,Y]of Q)if(X in $)if(Array.isArray($[X]))$[X].push(Y);else $[X]=[$[X],Y];else $[X]=Y}this._query=$}return this._query}get ip(){let $=this._reqHeaders?.["x-forwarded-for"];if($){let Q=$.indexOf(",");return(Q===-1?$:$.slice(0,Q)).trim()}return this._reqHeaders?.["x-real-ip"]||this._reqHeaders?.["cf-connecting-ip"]||this._peerIp||"127.0.0.1"}status($){return this._status=$,this}setHeader($,Q){if(!this._headers)this._headers={};return this._headers[$.toLowerCase()]=Q,this}getHeader($){return this._reqHeaders?.[$.toLowerCase()]}header($){return this.getHeader($)}set($,Q){return this.store.set($,Q),this}get($){return this.store.get($)}_flushJson($,Q){if(this._status!==200)$.writeStatus(KQ(this._status));if($.writeHeader("content-type","application/json"),this._headers){for(let X in this._headers)if(X!=="content-type")$.writeHeader(X,this._headers[X])}if(this._setCookies)for(let X=0;X<this._setCookies.length;X++)$.writeHeader("set-cookie",this._setCookies[X]);$.end(Q)}json($){let Q=this.res;if(!Q||this._responded||this._aborted)return;this._responded=!0;let X=JSON.stringify($);if(this._inSync)this._flushJson(Q,X);else Q.cork(()=>this._flushJson(Q,X));return}_flushText($,Q,X){if(X!==200)$.writeStatus(KQ(X));if(this._headers)for(let Y in this._headers)$.writeHeader(Y,this._headers[Y]);if(this._setCookies)for(let Y=0;Y<this._setCookies.length;Y++)$.writeHeader("set-cookie",this._setCookies[Y]);$.end(Q)}text($,Q){let X=this.res;if(!X||this._responded||this._aborted)return;this._responded=!0;let Y=Q??this._status;if(this._inSync)this._flushText(X,$,Y);else X.cork(()=>this._flushText(X,$,Y));return}html($,Q){return this.setHeader("content-type","text/html; charset=utf-8"),this.text($,Q)}redirect($,Q=302){return this.setHeader("location",$),this.text("",Q)}}function jX($,Q){let X=Q.status;if(X!==200)$.writeStatus(KQ(X));Q.headers.forEach((W,H)=>{$.writeHeader(H,W)});let Y=Q.headers;if(typeof Y.getSetCookie==="function"){let W=Y.getSetCookie();for(let H=0;H<W.length;H++)$.writeHeader("set-cookie",W[H])}}function p9($,Q,X){if(!Q.body){if(X?.())return;$.cork(()=>{jX($,Q),$.end()});return}let Y=Q.body.getReader(),W=!1,H=()=>{Y.read().then(({value:J,done:z})=>{if(X?.()){try{Y.cancel()}catch{}return}if(z){$.cork(()=>{if(!W)jX($,Q),W=!0;$.end()});return}if(J&&J.byteLength>0){let M=Buffer.from(J.buffer,J.byteOffset,J.byteLength),q=!0;if($.cork(()=>{if(!W)jX($,Q),W=!0;q=$.write(M)}),!q&&typeof $.onWritable==="function"){$.onWritable(()=>{return H(),!0});return}}H()},()=>{if(!X?.())try{$.close()}catch{}})};H()}function n9($,Q,X){if(Q?._responded)return;if(X instanceof Response){p9($,X);return}if(typeof X==="string"){if(Q)Q.text(X);else $.end(X);return}if(Q)Q.json(X??null);else $.writeHeader("content-type","application/json"),$.end(JSON.stringify(X??null))}function KX($,Q){let X=Q?.status>=400&&Q?.status<500?Q.status:500;$.writeStatus(KQ(X)),$.writeHeader("content-type","application/json");let Y=X===500?Q?.message||"Internal Server Error":Q?.message||"Bad Request";$.end(JSON.stringify({status:X,message:Y}))}var uM={GET:"get",HEAD:"head",DELETE:"del",OPTIONS:"options"};function c9($,Q){let X=Q.App(),Y=!1,W=[],H=4096,J=0;if($.uwsRoutes)for(let U of $.uwsRoutes){let A=uM[U.method];if(!A)continue;let{rawHandler:G,paramNames:D}=U,R=D.length,O=G.toString(),b=/\b(?:getHeader|header|ip|req)\b/.test(O),I=/\b(?:query|req)\b/.test(O);X[A](U.path,(j,g)=>{let V=W.length>0?W.pop():new i9;if(V.res=j,R>0){let o={};for(let T=0;T<R;T++)o[D[T]]=g.getParameter(T);V.params=o}if(I)V._queryStr=g.getQuery(),V._url=g.getUrl(),V._method=U.method;if(b){let o={};g.forEach((T,P)=>{o[T]=P}),V._reqHeaders=o,V._url=g.getUrl(),V._method=U.method}V._inSync=!0;try{let o=G(V);if(V._inSync=!1,o&&typeof o.then==="function"){j.onAborted(()=>{V._aborted=!0}),o.then((T)=>{if(!V._aborted&&!V._responded)j.cork(()=>n9(j,V,T));if(V.reset(),W.length<4096)W.push(V)},(T)=>{if(!V._aborted&&!V._responded)j.cork(()=>KX(j,T));if(V.reset(),W.length<4096)W.push(V)});return}if(!V._responded)n9(j,V,o);if(V.reset(),W.length<4096)W.push(V)}catch(o){if(V._inSync=!1,!V._responded)KX(j,o);if(V.reset(),W.length<4096)W.push(V)}})}if(X.any("/*",(U,A)=>{let G=!1;U.onAborted(()=>{G=!0});let D=A.getMethod().toUpperCase(),R=A.getUrl(),O=A.getQuery(),b=new Headers,I="localhost";A.forEach((i,p)=>{if(i==="host")I=p;b.append(i,p)});let j=`http://${I}${R}${O?`?${O}`:""}`,g="127.0.0.1";try{g=Buffer.from(U.getRemoteAddressAsText()).toString()||"127.0.0.1"}catch{}let V=(i)=>{if(G)return;J++;let p=new Request(j,{method:D,headers:b,body:i&&i.length>0?i:void 0});Promise.resolve($.fetch(p,g)).then((C)=>{if(J=Math.max(0,J-1),G)return;p9(U,C,()=>G)},(C)=>{if(J=Math.max(0,J-1),!G)U.cork(()=>KX(U,C))})};if(D==="GET"||D==="HEAD"){V();return}let o=[],T=0,P=$.maxRequestBodySize||10485760,u=!1;U.onData((i,p)=>{if(G||u)return;let C=Buffer.from(i);if(T+=C.length,T>P){u=!0,U.cork(()=>{U.writeStatus("413 Payload Too Large"),U.writeHeader("content-type","application/json"),U.end(JSON.stringify({status:413,message:"Payload Too Large"}))});return}if(C.length>0)o.push(C);if(p)V(o.length===0?void 0:o.length===1?o[0]:Buffer.concat(o))})}),$.ws){let U=$.ws,A=(G)=>{let D=G.getUserData();if(!D.wrapped)D.wrapped={data:D.handler,send(R,O){return G.send(R,O??typeof R!=="string")},subscribe(R){return typeof G.subscribe==="function"?G.subscribe(R):!1},unsubscribe(R){return typeof G.unsubscribe==="function"?G.unsubscribe(R):!1},publish(R,O,b){return typeof G.publish==="function"?G.publish(R,O,b??typeof O!=="string"):!1},close(R,O){if(typeof G.end==="function")G.end(R,O);else if(typeof G.close==="function")G.close()},raw:G};return D.wrapped};X.ws("/*",{upgrade(G,D,R){let O=D.getUrl(),b=D.getQuery(),I=`http://localhost${O}${b?`?${b}`:""}`,j=u2(U.routes,I);if(!j){G.writeStatus("404 Not Found").end();return}let g=j.params?{...j.handler,params:j.params}:j.handler;G.upgrade({handler:g,wrapped:null},D.getHeader("sec-websocket-key"),D.getHeader("sec-websocket-protocol"),D.getHeader("sec-websocket-extensions"),R)},open(G){U.adapter.open(A(G))},message(G,D,R){let O=R?new Uint8Array(D):Buffer.from(D).toString("utf8");U.adapter.message(A(G),O)},drain(G){U.adapter.drain(A(G))},close(G,D,R){let O=R&&R.byteLength>0?Buffer.from(R).toString("utf8"):"";U.adapter.close(A(G),D,O)}})}let z=null,M=$.port,q=new Promise((U,A)=>{X.listen($.hostname,$.port,(G)=>{if(!G){A(new Error(`[BareJS] uWebSockets.js failed to listen on ${$.hostname}:${$.port}`));return}z=G;try{M=Q.us_socket_local_port(G)||$.port}catch{M=$.port}U()})}),B=()=>{if(z){try{Q.us_listen_socket_close(z)}catch{}z=null}},_=async(U=5000)=>{B();let A=Date.now()+U;while(J>0&&Date.now()<A)await new Promise((G)=>setTimeout(G,10))};return Object.defineProperty(X,"port",{get:()=>M,configurable:!0}),X.stop=B,X.drain=_,X.ready=q,{get port(){return M},stop:B,drain:_,raw:X,ready:q}}var FX=16384,ZX=8,bX=1,tM=64;function s9($,Q,X,Y){return new Promise((W,H)=>{cM($,Q,X,Y,(J,z)=>{if(J)H(J);else W(z)})})}async function rM($){let Q=pM(16),X=await s9($,Q,tM,{N:FX,r:ZX,p:bX});return`$scrypt$N=${FX},r=${ZX},p=${bX}$${Q.toString("base64url")}$${X.toString("base64url")}`}async function aM($,Q){let X=Q.split("$");if(X.length!==5||X[1]!=="scrypt")return!1;let Y={};for(let B of X[2].split(",")){let[_,U]=B.split("=");if(_&&U)Y[_]=Number(U)}let W=Y.N||FX,H=Y.r||ZX,J=Y.p||bX;if(!Number.isFinite(W)||!Number.isFinite(H)||!Number.isFinite(J))return!1;let z=Buffer.from(X[3],"base64url"),M=Buffer.from(X[4],"base64url");if(z.length===0||M.length===0)return!1;let q=await s9($,z,M.length,{N:W,r:H,p:J});return q.length===M.length&&lM(q,M)}var eM={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".wasm":"application/wasm",".pdf":"application/pdf",".mp4":"video/mp4",".mp3":"audio/mpeg",".csv":"text/csv; charset=utf-8"};function $q($,Q){let Y=`http://${$.headers.host||"localhost"}${$.url||"/"}`,W=$.method||"GET",H=$.headers["content-length"];if(H!==void 0){let _=Number(Array.isArray(H)?H[0]:H);if(Number.isFinite(_)&&_>Q)return{errorStatus:413}}let J=new Headers,z=$.rawHeaders;if(z&&z.length>0)for(let _=0;_<z.length;_+=2)J.append(z[_],z[_+1]);else for(let[_,U]of Object.entries($.headers)){if(U===void 0)continue;if(Array.isArray(U))for(let A of U)J.append(_,A);else J.set(_,U)}let M=W!=="GET"&&W!=="HEAD",q;if(M){let _=0,U=$;q=new ReadableStream({start(A){U.on("data",(G)=>{if(_+=G.byteLength,_>Q){let D=new Error("Payload Too Large");D.status=413,A.error(D),U.destroy();return}A.enqueue(new Uint8Array(G.buffer,G.byteOffset,G.byteLength))}),U.on("end",()=>{try{A.close()}catch{}}),U.on("error",(G)=>{try{A.error(G)}catch{}})},cancel(){U.destroy()}})}let B={method:W,headers:J};if(q)B.body=q,B.duplex="half";return{request:new Request(Y,B)}}async function Qq($,Q){if(Q.writableEnded||Q.destroyed)return;let X={};$.headers.forEach((H,J)=>{if(J.toLowerCase()==="set-cookie")return;X[J]=H});let Y=typeof $.headers.getSetCookie==="function"?$.headers.getSetCookie():[];if(Y.length>0)X["set-cookie"]=Y;if(Q.writeHead($.status,X),typeof Q.flushHeaders==="function")Q.flushHeaders();if(!$.body){Q.end();return}let W=$.body.getReader();try{while(!0){let{done:H,value:J}=await W.read();if(H)break;if(Q.destroyed||Q.writableEnded){await W.cancel().catch(()=>{});break}if(J&&J.byteLength>0){if(!Q.write(J))await new Promise((M)=>{let q=()=>{Q.off("close",B),M()},B=()=>{Q.off("drain",q),M()};Q.once("drain",q),Q.once("close",B)})}}}finally{try{W.releaseLock()}catch{}if(!Q.writableEnded&&!Q.destroyed)Q.end()}}var t9={name:"node",serve($){if($.engine!=="http"){let H=u9();if(H)return c9($,H);if($.engine==="uws")throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.")}let Q=oM(async(H,J)=>{let z=$q(H,$.maxRequestBodySize);if(z.errorStatus===413||!z.request){J.writeHead(413,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:"Payload Too Large"})),H.resume();return}let M=H.socket?.remoteAddress;try{let q=await $.fetch(z.request,M);await Qq(q,J)}catch(q){if(!J.headersSent){let B=q?.status===413?413:500;J.writeHead(B,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:q?.message||"Internal Server Error"}))}else if(!J.writableEnded)J.end()}});if($.ws){let H=$.ws,J=null,z=()=>{if(!J)J=import("ws").then((A)=>new A.WebSocketServer({noServer:!0}),()=>null);return J},M="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",q=16777216,B=(U,A)=>{let G=A.length,D;if(G<126)D=Buffer.allocUnsafe(2),D[0]=128|U,D[1]=G;else if(G<65536)D=Buffer.allocUnsafe(4),D[0]=128|U,D[1]=126,D.writeUInt16BE(G,2);else D=Buffer.allocUnsafe(10),D[0]=128|U,D[1]=127,D.writeBigUInt64BE(BigInt(G),2);return Buffer.concat([D,A])},_=(U,A,G,D)=>{let R=U.headers["sec-websocket-key"];if(!R||Array.isArray(R)){A.write(`HTTP/1.1 400 Bad Request\r
|
|
130
|
+
</html>`};function u2($,Q){let X=Q;if(Q.startsWith("http://")||Q.startsWith("https://")||Q.startsWith("ws://")||Q.startsWith("wss://")){let z=Q.indexOf("/",8),M=z===-1?-1:Q.indexOf("?",z);X=z===-1?"/":M===-1?Q.slice(z):Q.slice(z,M)}else{let z=Q.indexOf("?");if(z!==-1)X=Q.slice(0,z)}let Y=X.replace(/\/+/g,"/"),W=Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y,H=$.get(W);if(H)return{handler:H};let J=W.split("/").filter(Boolean);for(let[z,M]of $){if(!z.includes(":")&&!z.includes("*"))continue;let q=z.split("/").filter(Boolean),B={},_=!0;for(let U=0;U<q.length;U++){let A=q[U];if(A==="*"){B["*"]=J.slice(U).join("/");break}if(U>=J.length){_=!1;break}if(A.startsWith(":"))B[A.slice(1)]=J[U];else if(A!==J[U]){_=!1;break}}if(_&&(q.includes("*")||q.length===J.length))return{handler:M,params:B}}return}var dM=typeof globalThis.Bun?.zstdCompressSync==="function"?($)=>globalThis.Bun.zstdCompressSync($):void 0,d9={name:"bun",serve($){let{ws:Q,routes:X}=$,Y;try{Y=Q?Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){if(W.headers.get("upgrade")?.toLowerCase()==="websocket"){let J=u2(Q.routes,W.url);if(J&&H.upgrade(W,{data:J.params?{...J.handler,params:J.params}:J.handler}))return}return $.fetch(W,H?.requestIP?.(W)?.address)},websocket:Q.adapter}):Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){return $.fetch(W,H?.requestIP?.(W)?.address)}})}catch(W){if(W?.code==="EADDRINUSE"||/in use/i.test(W?.message||""))throw new Error(`[BareJS] Port ${$.port} is already in use on ${$.hostname}. Choose a different port or stop the existing process.`);throw W}return{stop(W=!1){Y.stop(W)},port:Y.port??$.port,raw:Y}},gzip($,Q){return Bun.gzipSync($,{level:Q})},zstd:dM,openFile($){let Q=Bun.file($);return{get type(){return Q.type},full(){return Q},slice(X,Y){return Q.slice(X,Y)}}},password:{hash($,Q){if(Q.algorithm==="bcrypt"){let X=Math.max(4,Math.min(31,Q.timeCost));return Bun.password.hash($,{algorithm:"bcrypt",cost:X})}return Bun.password.hash($,Q)},verify($,Q){return Bun.password.verify($,Q)}}};import{createHash as iM,randomBytes as pM,scrypt as cM,timingSafeEqual as lM}from"crypto";import{createServer as oM}from"http";import{createReadStream as l9}from"fs";import{extname as sM}from"path";import{Readable as o9}from"stream";import*as T1 from"zlib";import{createRequire as m9}from"module";import{join as mM}from"path";var nM={200:"200 OK",201:"201 Created",202:"202 Accepted",204:"204 No Content",206:"206 Partial Content",301:"301 Moved Permanently",302:"302 Found",304:"304 Not Modified",400:"400 Bad Request",401:"401 Unauthorized",403:"403 Forbidden",404:"404 Not Found",405:"405 Method Not Allowed",409:"409 Conflict",413:"413 Payload Too Large",415:"415 Unsupported Media Type",422:"422 Unprocessable Entity",429:"429 Too Many Requests",500:"500 Internal Server Error",502:"502 Bad Gateway",503:"503 Service Unavailable"};function KQ($){return nM[$]||`${$}`}function u9(){if(typeof globalThis.Bun!=="undefined"||typeof globalThis.Deno!=="undefined")return null;try{return m9(mM(process.cwd(),"package.json"))("uWebSockets.js")}catch{try{return m9(import.meta.url)("uWebSockets.js")}catch{return null}}}class i9{res=null;params={};store=new Map;_status=200;_headers=void 0;_setCookies=void 0;_queryStr="";_query=void 0;_url="/";_method="GET";_reqHeaders=void 0;_req=void 0;_peerIp=void 0;_responded=!1;_inSync=!1;_aborted=!1;reset(){if(this.res=null,this.params={},this.store.size>0)this.store.clear();this._status=200,this._headers=void 0,this._setCookies=void 0,this._queryStr="",this._query=void 0,this._url="/",this._method="GET",this._reqHeaders=void 0,this._req=void 0,this._peerIp=void 0,this._responded=!1,this._inSync=!1,this._aborted=!1}get req(){if(!this._req){let $=this._queryStr?`?${this._queryStr}`:"",Q=this._reqHeaders?.host||"localhost";this._req=new Request(`http://${Q}${this._url}${$}`,{method:this._method,headers:this._reqHeaders})}return this._req}get query(){if(!this._query){let $={};if(this._queryStr){let Q=new URLSearchParams(this._queryStr);for(let[X,Y]of Q)if(X in $)if(Array.isArray($[X]))$[X].push(Y);else $[X]=[$[X],Y];else $[X]=Y}this._query=$}return this._query}get ip(){let $=this._reqHeaders?.["x-forwarded-for"];if($){let Q=$.indexOf(",");return(Q===-1?$:$.slice(0,Q)).trim()}return this._reqHeaders?.["x-real-ip"]||this._reqHeaders?.["cf-connecting-ip"]||this._peerIp||"127.0.0.1"}status($){return this._status=$,this}setHeader($,Q){if(!this._headers)this._headers={};return this._headers[$.toLowerCase()]=Q,this}getHeader($){return this._reqHeaders?.[$.toLowerCase()]}header($){return this.getHeader($)}set($,Q){return this.store.set($,Q),this}get($){return this.store.get($)}_flushJson($,Q){if(this._status!==200)$.writeStatus(KQ(this._status));if($.writeHeader("content-type","application/json"),this._headers){for(let X in this._headers)if(X!=="content-type")$.writeHeader(X,this._headers[X])}if(this._setCookies)for(let X=0;X<this._setCookies.length;X++)$.writeHeader("set-cookie",this._setCookies[X]);$.end(Q)}json($){let Q=this.res;if(!Q||this._responded||this._aborted)return;this._responded=!0;let X=JSON.stringify($);if(this._inSync)this._flushJson(Q,X);else Q.cork(()=>this._flushJson(Q,X));return}_flushText($,Q,X){if(X!==200)$.writeStatus(KQ(X));if(this._headers)for(let Y in this._headers)$.writeHeader(Y,this._headers[Y]);if(this._setCookies)for(let Y=0;Y<this._setCookies.length;Y++)$.writeHeader("set-cookie",this._setCookies[Y]);$.end(Q)}text($,Q){let X=this.res;if(!X||this._responded||this._aborted)return;this._responded=!0;let Y=Q??this._status;if(this._inSync)this._flushText(X,$,Y);else X.cork(()=>this._flushText(X,$,Y));return}html($,Q){return this.setHeader("content-type","text/html; charset=utf-8"),this.text($,Q)}redirect($,Q=302){return this.setHeader("location",$),this.text("",Q)}}function jX($,Q){let X=Q.status;if(X!==200)$.writeStatus(KQ(X));Q.headers.forEach((W,H)=>{if(H!=="content-length"&&H!=="transfer-encoding")$.writeHeader(H,W)});let Y=Q.headers;if(typeof Y.getSetCookie==="function"){let W=Y.getSetCookie();for(let H=0;H<W.length;H++)$.writeHeader("set-cookie",W[H])}}function p9($,Q,X){if(!Q.body){if(X?.())return;$.cork(()=>{jX($,Q),$.end()});return}let Y=Q.body.getReader(),W=!1,H=()=>{Y.read().then(({value:J,done:z})=>{if(X?.()){try{Y.cancel()}catch{}return}if(z){$.cork(()=>{if(!W)jX($,Q),W=!0;$.end()});return}if(J&&J.byteLength>0){let M=Buffer.from(J.buffer,J.byteOffset,J.byteLength),q=!0;if($.cork(()=>{if(!W)jX($,Q),W=!0;q=$.write(M)}),!q&&typeof $.onWritable==="function"){$.onWritable(()=>{return H(),!0});return}}H()},()=>{if(!X?.())try{$.close()}catch{}})};H()}function n9($,Q,X){if(Q?._responded)return;if(X instanceof Response){p9($,X);return}if(typeof X==="string"){if(Q)Q.text(X);else $.end(X);return}if(Q)Q.json(X??null);else $.writeHeader("content-type","application/json"),$.end(JSON.stringify(X??null))}function KX($,Q){let X=Q?.status>=400&&Q?.status<500?Q.status:500;$.writeStatus(KQ(X)),$.writeHeader("content-type","application/json");let Y=X===500?Q?.message||"Internal Server Error":Q?.message||"Bad Request";$.end(JSON.stringify({status:X,message:Y}))}var uM={GET:"get",HEAD:"head",DELETE:"del",OPTIONS:"options"};function c9($,Q){let X=Q.App(),Y=!1,W=[],H=4096,J=0;if($.uwsRoutes)for(let U of $.uwsRoutes){let A=uM[U.method];if(!A)continue;let{rawHandler:G,paramNames:D}=U,R=D.length,O=G.toString(),b=/\b(?:getHeader|header|ip|req)\b/.test(O),I=/\b(?:query|req)\b/.test(O);X[A](U.path,(j,g)=>{let V=W.length>0?W.pop():new i9;if(V.res=j,R>0){let o={};for(let T=0;T<R;T++)o[D[T]]=g.getParameter(T);V.params=o}if(I)V._queryStr=g.getQuery(),V._url=g.getUrl(),V._method=U.method;if(b){let o={};g.forEach((T,P)=>{o[T]=P}),V._reqHeaders=o,V._url=g.getUrl(),V._method=U.method}V._inSync=!0;try{let o=G(V);if(V._inSync=!1,o&&typeof o.then==="function"){j.onAborted(()=>{V._aborted=!0}),o.then((T)=>{if(!V._aborted&&!V._responded)j.cork(()=>n9(j,V,T));if(V.reset(),W.length<4096)W.push(V)},(T)=>{if(!V._aborted&&!V._responded)j.cork(()=>KX(j,T));if(V.reset(),W.length<4096)W.push(V)});return}if(!V._responded)n9(j,V,o);if(V.reset(),W.length<4096)W.push(V)}catch(o){if(V._inSync=!1,!V._responded)KX(j,o);if(V.reset(),W.length<4096)W.push(V)}})}if(X.any("/*",(U,A)=>{let G=!1;U.onAborted(()=>{G=!0});let D=A.getMethod().toUpperCase(),R=A.getUrl(),O=A.getQuery(),b=new Headers,I="localhost";A.forEach((i,p)=>{if(i==="host")I=p;b.append(i,p)});let j=`http://${I}${R}${O?`?${O}`:""}`,g="127.0.0.1";try{g=Buffer.from(U.getRemoteAddressAsText()).toString()||"127.0.0.1"}catch{}let V=(i)=>{if(G)return;J++;let p=new Request(j,{method:D,headers:b,body:i&&i.length>0?i:void 0});Promise.resolve($.fetch(p,g)).then((C)=>{if(J=Math.max(0,J-1),G)return;p9(U,C,()=>G)},(C)=>{if(J=Math.max(0,J-1),!G)U.cork(()=>KX(U,C))})};if(D==="GET"||D==="HEAD"){V();return}let o=[],T=0,P=$.maxRequestBodySize||10485760,u=!1;U.onData((i,p)=>{if(G||u)return;let C=Buffer.from(new Uint8Array(i));if(T+=C.length,T>P){u=!0,U.cork(()=>{U.writeStatus("413 Payload Too Large"),U.writeHeader("content-type","application/json"),U.end(JSON.stringify({status:413,message:"Payload Too Large"}))});return}if(C.length>0)o.push(C);if(p)V(o.length===0?void 0:o.length===1?o[0]:Buffer.concat(o))})}),$.ws){let U=$.ws,A=(G)=>{let D=G.getUserData();if(!D.wrapped)D.wrapped={data:D.handler,send(R,O){return G.send(R,O??typeof R!=="string")},subscribe(R){return typeof G.subscribe==="function"?G.subscribe(R):!1},unsubscribe(R){return typeof G.unsubscribe==="function"?G.unsubscribe(R):!1},publish(R,O,b){return typeof G.publish==="function"?G.publish(R,O,b??typeof O!=="string"):!1},close(R,O){if(typeof G.end==="function")G.end(R,O);else if(typeof G.close==="function")G.close()},raw:G};return D.wrapped};X.ws("/*",{upgrade(G,D,R){let O=D.getUrl(),b=D.getQuery(),I=`http://localhost${O}${b?`?${b}`:""}`,j=u2(U.routes,I);if(!j){G.writeStatus("404 Not Found").end();return}let g=j.params?{...j.handler,params:j.params}:j.handler;G.upgrade({handler:g,wrapped:null},D.getHeader("sec-websocket-key"),D.getHeader("sec-websocket-protocol"),D.getHeader("sec-websocket-extensions"),R)},open(G){U.adapter.open(A(G))},message(G,D,R){let O=R?new Uint8Array(D):Buffer.from(D).toString("utf8");U.adapter.message(A(G),O)},drain(G){U.adapter.drain(A(G))},close(G,D,R){let O=R&&R.byteLength>0?Buffer.from(R).toString("utf8"):"";U.adapter.close(A(G),D,O)}})}let z=null,M=$.port,q=new Promise((U,A)=>{X.listen($.hostname,$.port,(G)=>{if(!G){A(new Error(`[BareJS] uWebSockets.js failed to listen on ${$.hostname}:${$.port}`));return}z=G;try{M=Q.us_socket_local_port(G)||$.port}catch{M=$.port}U()})}),B=()=>{if(z){try{Q.us_listen_socket_close(z)}catch{}z=null}},_=async(U=5000)=>{B();let A=Date.now()+U;while(J>0&&Date.now()<A)await new Promise((G)=>setTimeout(G,10))};return Object.defineProperty(X,"port",{get:()=>M,configurable:!0}),X.stop=B,X.drain=_,X.ready=q,{get port(){return M},stop:B,drain:_,raw:X,ready:q}}var FX=16384,ZX=8,bX=1,tM=64;function s9($,Q,X,Y){return new Promise((W,H)=>{cM($,Q,X,Y,(J,z)=>{if(J)H(J);else W(z)})})}async function rM($){let Q=pM(16),X=await s9($,Q,tM,{N:FX,r:ZX,p:bX});return`$scrypt$N=${FX},r=${ZX},p=${bX}$${Q.toString("base64url")}$${X.toString("base64url")}`}async function aM($,Q){let X=Q.split("$");if(X.length!==5||X[1]!=="scrypt")return!1;let Y={};for(let B of X[2].split(",")){let[_,U]=B.split("=");if(_&&U)Y[_]=Number(U)}let W=Y.N||FX,H=Y.r||ZX,J=Y.p||bX;if(!Number.isFinite(W)||!Number.isFinite(H)||!Number.isFinite(J))return!1;let z=Buffer.from(X[3],"base64url"),M=Buffer.from(X[4],"base64url");if(z.length===0||M.length===0)return!1;let q=await s9($,z,M.length,{N:W,r:H,p:J});return q.length===M.length&&lM(q,M)}var eM={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".wasm":"application/wasm",".pdf":"application/pdf",".mp4":"video/mp4",".mp3":"audio/mpeg",".csv":"text/csv; charset=utf-8"};function $q($,Q){let Y=`http://${$.headers.host||"localhost"}${$.url||"/"}`,W=$.method||"GET",H=$.headers["content-length"];if(H!==void 0){let _=Number(Array.isArray(H)?H[0]:H);if(Number.isFinite(_)&&_>Q)return{errorStatus:413}}let J=new Headers,z=$.rawHeaders;if(z&&z.length>0)for(let _=0;_<z.length;_+=2)J.append(z[_],z[_+1]);else for(let[_,U]of Object.entries($.headers)){if(U===void 0)continue;if(Array.isArray(U))for(let A of U)J.append(_,A);else J.set(_,U)}let M=W!=="GET"&&W!=="HEAD",q;if(M){let _=0,U=$;q=new ReadableStream({start(A){U.on("data",(G)=>{if(_+=G.byteLength,_>Q){let D=new Error("Payload Too Large");D.status=413,A.error(D),U.destroy();return}A.enqueue(new Uint8Array(G.buffer,G.byteOffset,G.byteLength))}),U.on("end",()=>{try{A.close()}catch{}}),U.on("error",(G)=>{try{A.error(G)}catch{}})},cancel(){U.destroy()}})}let B={method:W,headers:J};if(q)B.body=q,B.duplex="half";return{request:new Request(Y,B)}}async function Qq($,Q){if(Q.writableEnded||Q.destroyed)return;let X={};$.headers.forEach((H,J)=>{if(J.toLowerCase()==="set-cookie")return;X[J]=H});let Y=typeof $.headers.getSetCookie==="function"?$.headers.getSetCookie():[];if(Y.length>0)X["set-cookie"]=Y;if(Q.writeHead($.status,X),typeof Q.flushHeaders==="function")Q.flushHeaders();if(!$.body){Q.end();return}let W=$.body.getReader();try{while(!0){let{done:H,value:J}=await W.read();if(H)break;if(Q.destroyed||Q.writableEnded){await W.cancel().catch(()=>{});break}if(J&&J.byteLength>0){if(!Q.write(J))await new Promise((M)=>{let q=()=>{Q.off("close",B),M()},B=()=>{Q.off("drain",q),M()};Q.once("drain",q),Q.once("close",B)})}}}finally{try{W.releaseLock()}catch{}if(!Q.writableEnded&&!Q.destroyed)Q.end()}}var t9={name:"node",serve($){if($.engine!=="http"){let H=u9();if(H)return c9($,H);if($.engine==="uws")throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.")}let Q=oM(async(H,J)=>{let z=$q(H,$.maxRequestBodySize);if(z.errorStatus===413||!z.request){J.writeHead(413,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:"Payload Too Large"})),H.resume();return}let M=H.socket?.remoteAddress;try{let q=await $.fetch(z.request,M);await Qq(q,J)}catch(q){if(!J.headersSent){let B=q?.status===413?413:500;J.writeHead(B,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:q?.message||"Internal Server Error"}))}else if(!J.writableEnded)J.end()}});if($.ws){let H=$.ws,J=null,z=()=>{if(!J)J=import("ws").then((A)=>new A.WebSocketServer({noServer:!0}),()=>null);return J},M="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",q=16777216,B=(U,A)=>{let G=A.length,D;if(G<126)D=Buffer.allocUnsafe(2),D[0]=128|U,D[1]=G;else if(G<65536)D=Buffer.allocUnsafe(4),D[0]=128|U,D[1]=126,D.writeUInt16BE(G,2);else D=Buffer.allocUnsafe(10),D[0]=128|U,D[1]=127,D.writeBigUInt64BE(BigInt(G),2);return Buffer.concat([D,A])},_=(U,A,G,D)=>{let R=U.headers["sec-websocket-key"];if(!R||Array.isArray(R)){A.write(`HTTP/1.1 400 Bad Request\r
|
|
131
131
|
\r
|
|
132
132
|
`),A.destroy();return}let O=iM("sha1").update(R.trim()+M).digest("base64");A.write(`HTTP/1.1 101 Switching Protocols\r
|
|
133
133
|
Upgrade: websocket\r
|
package/dist/node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as DY}from"node:module";var GY=Object.create;var{getPrototypeOf:BY,defineProperty:PQ,getOwnPropertyNames:_Y}=Object;var UY=Object.prototype.hasOwnProperty;var i2=($,Q,X)=>{X=$!=null?GY(BY($)):{};let Y=Q||!$||!$.__esModule?PQ(X,"default",{value:$,enumerable:!0}):X;for(let W of _Y($))if(!UY.call(Y,W))PQ(Y,W,{get:()=>$[W],enumerable:!0});return Y};var D8=($,Q)=>{for(var X in Q)PQ($,X,{get:Q[X],enumerable:!0,configurable:!0,set:(Y)=>Q[X]=()=>Y})};var p2=DY(import.meta.url);function C2($,Q){let X=Q;if(Q.startsWith("http://")||Q.startsWith("https://")||Q.startsWith("ws://")||Q.startsWith("wss://")){let z=Q.indexOf("/",8),M=z===-1?-1:Q.indexOf("?",z);X=z===-1?"/":M===-1?Q.slice(z):Q.slice(z,M)}else{let z=Q.indexOf("?");if(z!==-1)X=Q.slice(0,z)}let Y=X.replace(/\/+/g,"/"),W=Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y,H=$.get(W);if(H)return{handler:H};let J=W.split("/").filter(Boolean);for(let[z,M]of $){if(!z.includes(":")&&!z.includes("*"))continue;let q=z.split("/").filter(Boolean),B={},_=!0;for(let U=0;U<q.length;U++){let A=q[U];if(A==="*"){B["*"]=J.slice(U).join("/");break}if(U>=J.length){_=!1;break}if(A.startsWith(":"))B[A.slice(1)]=J[U];else if(A!==J[U]){_=!1;break}}if(_&&(q.includes("*")||q.length===J.length))return{handler:M,params:B}}return}var AY=typeof globalThis.Bun?.zstdCompressSync==="function"?($)=>globalThis.Bun.zstdCompressSync($):void 0,TX={name:"bun",serve($){let{ws:Q,routes:X}=$,Y;try{Y=Q?Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){if(W.headers.get("upgrade")?.toLowerCase()==="websocket"){let J=C2(Q.routes,W.url);if(J&&H.upgrade(W,{data:J.params?{...J.handler,params:J.params}:J.handler}))return}return $.fetch(W,H?.requestIP?.(W)?.address)},websocket:Q.adapter}):Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){return $.fetch(W,H?.requestIP?.(W)?.address)}})}catch(W){if(W?.code==="EADDRINUSE"||/in use/i.test(W?.message||""))throw new Error(`[BareJS] Port ${$.port} is already in use on ${$.hostname}. Choose a different port or stop the existing process.`);throw W}return{stop(W=!1){Y.stop(W)},port:Y.port??$.port,raw:Y}},gzip($,Q){return Bun.gzipSync($,{level:Q})},zstd:AY,openFile($){let Q=Bun.file($);return{get type(){return Q.type},full(){return Q},slice(X,Y){return Q.slice(X,Y)}}},password:{hash($,Q){if(Q.algorithm==="bcrypt"){let X=Math.max(4,Math.min(31,Q.timeCost));return Bun.password.hash($,{algorithm:"bcrypt",cost:X})}return Bun.password.hash($,Q)},verify($,Q){return Bun.password.verify($,Q)}}};import{createHash as SY,randomBytes as OY,scrypt as wY,timingSafeEqual as jY}from"node:crypto";import{createServer as KY}from"node:http";import{createReadStream as dX}from"node:fs";import{extname as FY}from"node:path";import{Readable as mX}from"node:stream";import*as z1 from"node:zlib";import{createRequire as gX}from"node:module";import{join as NY}from"node:path";var LY={200:"200 OK",201:"201 Created",202:"202 Accepted",204:"204 No Content",206:"206 Partial Content",301:"301 Moved Permanently",302:"302 Found",304:"304 Not Modified",400:"400 Bad Request",401:"401 Unauthorized",403:"403 Forbidden",404:"404 Not Found",405:"405 Method Not Allowed",409:"409 Conflict",413:"413 Payload Too Large",415:"415 Unsupported Media Type",422:"422 Unprocessable Entity",429:"429 Too Many Requests",500:"500 Internal Server Error",502:"502 Bad Gateway",503:"503 Service Unavailable"};function y1($){return LY[$]||`${$}`}function xX(){if(typeof globalThis.Bun!=="undefined"||typeof globalThis.Deno!=="undefined")return null;try{return gX(NY(process.cwd(),"package.json"))("uWebSockets.js")}catch{try{return gX(import.meta.url)("uWebSockets.js")}catch{return null}}}class vX{res=null;params={};store=new Map;_status=200;_headers=void 0;_setCookies=void 0;_queryStr="";_query=void 0;_url="/";_method="GET";_reqHeaders=void 0;_req=void 0;_peerIp=void 0;_responded=!1;_inSync=!1;_aborted=!1;reset(){if(this.res=null,this.params={},this.store.size>0)this.store.clear();this._status=200,this._headers=void 0,this._setCookies=void 0,this._queryStr="",this._query=void 0,this._url="/",this._method="GET",this._reqHeaders=void 0,this._req=void 0,this._peerIp=void 0,this._responded=!1,this._inSync=!1,this._aborted=!1}get req(){if(!this._req){let $=this._queryStr?`?${this._queryStr}`:"",Q=this._reqHeaders?.host||"localhost";this._req=new Request(`http://${Q}${this._url}${$}`,{method:this._method,headers:this._reqHeaders})}return this._req}get query(){if(!this._query){let $={};if(this._queryStr){let Q=new URLSearchParams(this._queryStr);for(let[X,Y]of Q)if(X in $)if(Array.isArray($[X]))$[X].push(Y);else $[X]=[$[X],Y];else $[X]=Y}this._query=$}return this._query}get ip(){let $=this._reqHeaders?.["x-forwarded-for"];if($){let Q=$.indexOf(",");return(Q===-1?$:$.slice(0,Q)).trim()}return this._reqHeaders?.["x-real-ip"]||this._reqHeaders?.["cf-connecting-ip"]||this._peerIp||"127.0.0.1"}status($){return this._status=$,this}setHeader($,Q){if(!this._headers)this._headers={};return this._headers[$.toLowerCase()]=Q,this}getHeader($){return this._reqHeaders?.[$.toLowerCase()]}header($){return this.getHeader($)}set($,Q){return this.store.set($,Q),this}get($){return this.store.get($)}_flushJson($,Q){if(this._status!==200)$.writeStatus(y1(this._status));if($.writeHeader("content-type","application/json"),this._headers){for(let X in this._headers)if(X!=="content-type")$.writeHeader(X,this._headers[X])}if(this._setCookies)for(let X=0;X<this._setCookies.length;X++)$.writeHeader("set-cookie",this._setCookies[X]);$.end(Q)}json($){let Q=this.res;if(!Q||this._responded||this._aborted)return;this._responded=!0;let X=JSON.stringify($);if(this._inSync)this._flushJson(Q,X);else Q.cork(()=>this._flushJson(Q,X));return}_flushText($,Q,X){if(X!==200)$.writeStatus(y1(X));if(this._headers)for(let Y in this._headers)$.writeHeader(Y,this._headers[Y]);if(this._setCookies)for(let Y=0;Y<this._setCookies.length;Y++)$.writeHeader("set-cookie",this._setCookies[Y]);$.end(Q)}text($,Q){let X=this.res;if(!X||this._responded||this._aborted)return;this._responded=!0;let Y=Q??this._status;if(this._inSync)this._flushText(X,$,Y);else X.cork(()=>this._flushText(X,$,Y));return}html($,Q){return this.setHeader("content-type","text/html; charset=utf-8"),this.text($,Q)}redirect($,Q=302){return this.setHeader("location",$),this.text("",Q)}}function IQ($,Q){let X=Q.status;if(X!==200)$.writeStatus(y1(X));Q.headers.forEach((W,H)=>{$.writeHeader(H,W)});let Y=Q.headers;if(typeof Y.getSetCookie==="function"){let W=Y.getSetCookie();for(let H=0;H<W.length;H++)$.writeHeader("set-cookie",W[H])}}function yX($,Q,X){if(!Q.body){if(X?.())return;$.cork(()=>{IQ($,Q),$.end()});return}let Y=Q.body.getReader(),W=!1,H=()=>{Y.read().then(({value:J,done:z})=>{if(X?.()){try{Y.cancel()}catch{}return}if(z){$.cork(()=>{if(!W)IQ($,Q),W=!0;$.end()});return}if(J&&J.byteLength>0){let M=Buffer.from(J.buffer,J.byteOffset,J.byteLength),q=!0;if($.cork(()=>{if(!W)IQ($,Q),W=!0;q=$.write(M)}),!q&&typeof $.onWritable==="function"){$.onWritable(()=>{return H(),!0});return}}H()},()=>{if(!X?.())try{$.close()}catch{}})};H()}function kX($,Q,X){if(Q?._responded)return;if(X instanceof Response){yX($,X);return}if(typeof X==="string"){if(Q)Q.text(X);else $.end(X);return}if(Q)Q.json(X??null);else $.writeHeader("content-type","application/json"),$.end(JSON.stringify(X??null))}function fQ($,Q){let X=Q?.status>=400&&Q?.status<500?Q.status:500;$.writeStatus(y1(X)),$.writeHeader("content-type","application/json");let Y=X===500?Q?.message||"Internal Server Error":Q?.message||"Bad Request";$.end(JSON.stringify({status:X,message:Y}))}var RY={GET:"get",HEAD:"head",DELETE:"del",OPTIONS:"options"};function hX($,Q){let X=Q.App(),Y=!1,W=[],H=4096,J=0;if($.uwsRoutes)for(let U of $.uwsRoutes){let A=RY[U.method];if(!A)continue;let{rawHandler:G,paramNames:D}=U,R=D.length,O=G.toString(),b=/\b(?:getHeader|header|ip|req)\b/.test(O),I=/\b(?:query|req)\b/.test(O);X[A](U.path,(j,g)=>{let V=W.length>0?W.pop():new vX;if(V.res=j,R>0){let o={};for(let T=0;T<R;T++)o[D[T]]=g.getParameter(T);V.params=o}if(I)V._queryStr=g.getQuery(),V._url=g.getUrl(),V._method=U.method;if(b){let o={};g.forEach((T,P)=>{o[T]=P}),V._reqHeaders=o,V._url=g.getUrl(),V._method=U.method}V._inSync=!0;try{let o=G(V);if(V._inSync=!1,o&&typeof o.then==="function"){j.onAborted(()=>{V._aborted=!0}),o.then((T)=>{if(!V._aborted&&!V._responded)j.cork(()=>kX(j,V,T));if(V.reset(),W.length<4096)W.push(V)},(T)=>{if(!V._aborted&&!V._responded)j.cork(()=>fQ(j,T));if(V.reset(),W.length<4096)W.push(V)});return}if(!V._responded)kX(j,V,o);if(V.reset(),W.length<4096)W.push(V)}catch(o){if(V._inSync=!1,!V._responded)fQ(j,o);if(V.reset(),W.length<4096)W.push(V)}})}if(X.any("/*",(U,A)=>{let G=!1;U.onAborted(()=>{G=!0});let D=A.getMethod().toUpperCase(),R=A.getUrl(),O=A.getQuery(),b=new Headers,I="localhost";A.forEach((i,p)=>{if(i==="host")I=p;b.append(i,p)});let j=`http://${I}${R}${O?`?${O}`:""}`,g="127.0.0.1";try{g=Buffer.from(U.getRemoteAddressAsText()).toString()||"127.0.0.1"}catch{}let V=(i)=>{if(G)return;J++;let p=new Request(j,{method:D,headers:b,body:i&&i.length>0?i:void 0});Promise.resolve($.fetch(p,g)).then((C)=>{if(J=Math.max(0,J-1),G)return;yX(U,C,()=>G)},(C)=>{if(J=Math.max(0,J-1),!G)U.cork(()=>fQ(U,C))})};if(D==="GET"||D==="HEAD"){V();return}let o=[],T=0,P=$.maxRequestBodySize||10485760,u=!1;U.onData((i,p)=>{if(G||u)return;let C=Buffer.from(i);if(T+=C.length,T>P){u=!0,U.cork(()=>{U.writeStatus("413 Payload Too Large"),U.writeHeader("content-type","application/json"),U.end(JSON.stringify({status:413,message:"Payload Too Large"}))});return}if(C.length>0)o.push(C);if(p)V(o.length===0?void 0:o.length===1?o[0]:Buffer.concat(o))})}),$.ws){let U=$.ws,A=(G)=>{let D=G.getUserData();if(!D.wrapped)D.wrapped={data:D.handler,send(R,O){return G.send(R,O??typeof R!=="string")},subscribe(R){return typeof G.subscribe==="function"?G.subscribe(R):!1},unsubscribe(R){return typeof G.unsubscribe==="function"?G.unsubscribe(R):!1},publish(R,O,b){return typeof G.publish==="function"?G.publish(R,O,b??typeof O!=="string"):!1},close(R,O){if(typeof G.end==="function")G.end(R,O);else if(typeof G.close==="function")G.close()},raw:G};return D.wrapped};X.ws("/*",{upgrade(G,D,R){let O=D.getUrl(),b=D.getQuery(),I=`http://localhost${O}${b?`?${b}`:""}`,j=C2(U.routes,I);if(!j){G.writeStatus("404 Not Found").end();return}let g=j.params?{...j.handler,params:j.params}:j.handler;G.upgrade({handler:g,wrapped:null},D.getHeader("sec-websocket-key"),D.getHeader("sec-websocket-protocol"),D.getHeader("sec-websocket-extensions"),R)},open(G){U.adapter.open(A(G))},message(G,D,R){let O=R?new Uint8Array(D):Buffer.from(D).toString("utf8");U.adapter.message(A(G),O)},drain(G){U.adapter.drain(A(G))},close(G,D,R){let O=R&&R.byteLength>0?Buffer.from(R).toString("utf8"):"";U.adapter.close(A(G),D,O)}})}let z=null,M=$.port,q=new Promise((U,A)=>{X.listen($.hostname,$.port,(G)=>{if(!G){A(new Error(`[BareJS] uWebSockets.js failed to listen on ${$.hostname}:${$.port}`));return}z=G;try{M=Q.us_socket_local_port(G)||$.port}catch{M=$.port}U()})}),B=()=>{if(z){try{Q.us_listen_socket_close(z)}catch{}z=null}},_=async(U=5000)=>{B();let A=Date.now()+U;while(J>0&&Date.now()<A)await new Promise((G)=>setTimeout(G,10))};return Object.defineProperty(X,"port",{get:()=>M,configurable:!0}),X.stop=B,X.drain=_,X.ready=q,{get port(){return M},stop:B,drain:_,raw:X,ready:q}}var TQ=16384,gQ=8,kQ=1,ZY=64;function nX($,Q,X,Y){return new Promise((W,H)=>{wY($,Q,X,Y,(J,z)=>{if(J)H(J);else W(z)})})}async function bY($){let Q=OY(16),X=await nX($,Q,ZY,{N:TQ,r:gQ,p:kQ});return`$scrypt$N=${TQ},r=${gQ},p=${kQ}$${Q.toString("base64url")}$${X.toString("base64url")}`}async function CY($,Q){let X=Q.split("$");if(X.length!==5||X[1]!=="scrypt")return!1;let Y={};for(let B of X[2].split(",")){let[_,U]=B.split("=");if(_&&U)Y[_]=Number(U)}let W=Y.N||TQ,H=Y.r||gQ,J=Y.p||kQ;if(!Number.isFinite(W)||!Number.isFinite(H)||!Number.isFinite(J))return!1;let z=Buffer.from(X[3],"base64url"),M=Buffer.from(X[4],"base64url");if(z.length===0||M.length===0)return!1;let q=await nX($,z,M.length,{N:W,r:H,p:J});return q.length===M.length&&jY(q,M)}var EY={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".wasm":"application/wasm",".pdf":"application/pdf",".mp4":"video/mp4",".mp3":"audio/mpeg",".csv":"text/csv; charset=utf-8"};function VY($,Q){let Y=`http://${$.headers.host||"localhost"}${$.url||"/"}`,W=$.method||"GET",H=$.headers["content-length"];if(H!==void 0){let _=Number(Array.isArray(H)?H[0]:H);if(Number.isFinite(_)&&_>Q)return{errorStatus:413}}let J=new Headers,z=$.rawHeaders;if(z&&z.length>0)for(let _=0;_<z.length;_+=2)J.append(z[_],z[_+1]);else for(let[_,U]of Object.entries($.headers)){if(U===void 0)continue;if(Array.isArray(U))for(let A of U)J.append(_,A);else J.set(_,U)}let M=W!=="GET"&&W!=="HEAD",q;if(M){let _=0,U=$;q=new ReadableStream({start(A){U.on("data",(G)=>{if(_+=G.byteLength,_>Q){let D=new Error("Payload Too Large");D.status=413,A.error(D),U.destroy();return}A.enqueue(new Uint8Array(G.buffer,G.byteOffset,G.byteLength))}),U.on("end",()=>{try{A.close()}catch{}}),U.on("error",(G)=>{try{A.error(G)}catch{}})},cancel(){U.destroy()}})}let B={method:W,headers:J};if(q)B.body=q,B.duplex="half";return{request:new Request(Y,B)}}async function PY($,Q){if(Q.writableEnded||Q.destroyed)return;let X={};$.headers.forEach((H,J)=>{if(J.toLowerCase()==="set-cookie")return;X[J]=H});let Y=typeof $.headers.getSetCookie==="function"?$.headers.getSetCookie():[];if(Y.length>0)X["set-cookie"]=Y;if(Q.writeHead($.status,X),typeof Q.flushHeaders==="function")Q.flushHeaders();if(!$.body){Q.end();return}let W=$.body.getReader();try{while(!0){let{done:H,value:J}=await W.read();if(H)break;if(Q.destroyed||Q.writableEnded){await W.cancel().catch(()=>{});break}if(J&&J.byteLength>0){if(!Q.write(J))await new Promise((M)=>{let q=()=>{Q.off("close",B),M()},B=()=>{Q.off("drain",q),M()};Q.once("drain",q),Q.once("close",B)})}}}finally{try{W.releaseLock()}catch{}if(!Q.writableEnded&&!Q.destroyed)Q.end()}}var h1={name:"node",serve($){if($.engine!=="http"){let H=xX();if(H)return hX($,H);if($.engine==="uws")throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.")}let Q=KY(async(H,J)=>{let z=VY(H,$.maxRequestBodySize);if(z.errorStatus===413||!z.request){J.writeHead(413,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:"Payload Too Large"})),H.resume();return}let M=H.socket?.remoteAddress;try{let q=await $.fetch(z.request,M);await PY(q,J)}catch(q){if(!J.headersSent){let B=q?.status===413?413:500;J.writeHead(B,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:q?.message||"Internal Server Error"}))}else if(!J.writableEnded)J.end()}});if($.ws){let H=$.ws,J=null,z=()=>{if(!J)J=import("ws").then((A)=>new A.WebSocketServer({noServer:!0}),()=>null);return J},M="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",q=16777216,B=(U,A)=>{let G=A.length,D;if(G<126)D=Buffer.allocUnsafe(2),D[0]=128|U,D[1]=G;else if(G<65536)D=Buffer.allocUnsafe(4),D[0]=128|U,D[1]=126,D.writeUInt16BE(G,2);else D=Buffer.allocUnsafe(10),D[0]=128|U,D[1]=127,D.writeBigUInt64BE(BigInt(G),2);return Buffer.concat([D,A])},_=(U,A,G,D)=>{let R=U.headers["sec-websocket-key"];if(!R||Array.isArray(R)){A.write(`HTTP/1.1 400 Bad Request\r
|
|
1
|
+
import{createRequire as DY}from"node:module";var GY=Object.create;var{getPrototypeOf:BY,defineProperty:PQ,getOwnPropertyNames:_Y}=Object;var UY=Object.prototype.hasOwnProperty;var i2=($,Q,X)=>{X=$!=null?GY(BY($)):{};let Y=Q||!$||!$.__esModule?PQ(X,"default",{value:$,enumerable:!0}):X;for(let W of _Y($))if(!UY.call(Y,W))PQ(Y,W,{get:()=>$[W],enumerable:!0});return Y};var D8=($,Q)=>{for(var X in Q)PQ($,X,{get:Q[X],enumerable:!0,configurable:!0,set:(Y)=>Q[X]=()=>Y})};var p2=DY(import.meta.url);function C2($,Q){let X=Q;if(Q.startsWith("http://")||Q.startsWith("https://")||Q.startsWith("ws://")||Q.startsWith("wss://")){let z=Q.indexOf("/",8),M=z===-1?-1:Q.indexOf("?",z);X=z===-1?"/":M===-1?Q.slice(z):Q.slice(z,M)}else{let z=Q.indexOf("?");if(z!==-1)X=Q.slice(0,z)}let Y=X.replace(/\/+/g,"/"),W=Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y,H=$.get(W);if(H)return{handler:H};let J=W.split("/").filter(Boolean);for(let[z,M]of $){if(!z.includes(":")&&!z.includes("*"))continue;let q=z.split("/").filter(Boolean),B={},_=!0;for(let U=0;U<q.length;U++){let A=q[U];if(A==="*"){B["*"]=J.slice(U).join("/");break}if(U>=J.length){_=!1;break}if(A.startsWith(":"))B[A.slice(1)]=J[U];else if(A!==J[U]){_=!1;break}}if(_&&(q.includes("*")||q.length===J.length))return{handler:M,params:B}}return}var AY=typeof globalThis.Bun?.zstdCompressSync==="function"?($)=>globalThis.Bun.zstdCompressSync($):void 0,TX={name:"bun",serve($){let{ws:Q,routes:X}=$,Y;try{Y=Q?Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){if(W.headers.get("upgrade")?.toLowerCase()==="websocket"){let J=C2(Q.routes,W.url);if(J&&H.upgrade(W,{data:J.params?{...J.handler,params:J.params}:J.handler}))return}return $.fetch(W,H?.requestIP?.(W)?.address)},websocket:Q.adapter}):Bun.serve({port:$.port,hostname:$.hostname,reusePort:$.reusePort,maxRequestBodySize:$.maxRequestBodySize,...X?{routes:X}:{},fetch(W,H){return $.fetch(W,H?.requestIP?.(W)?.address)}})}catch(W){if(W?.code==="EADDRINUSE"||/in use/i.test(W?.message||""))throw new Error(`[BareJS] Port ${$.port} is already in use on ${$.hostname}. Choose a different port or stop the existing process.`);throw W}return{stop(W=!1){Y.stop(W)},port:Y.port??$.port,raw:Y}},gzip($,Q){return Bun.gzipSync($,{level:Q})},zstd:AY,openFile($){let Q=Bun.file($);return{get type(){return Q.type},full(){return Q},slice(X,Y){return Q.slice(X,Y)}}},password:{hash($,Q){if(Q.algorithm==="bcrypt"){let X=Math.max(4,Math.min(31,Q.timeCost));return Bun.password.hash($,{algorithm:"bcrypt",cost:X})}return Bun.password.hash($,Q)},verify($,Q){return Bun.password.verify($,Q)}}};import{createHash as SY,randomBytes as OY,scrypt as wY,timingSafeEqual as jY}from"node:crypto";import{createServer as KY}from"node:http";import{createReadStream as dX}from"node:fs";import{extname as FY}from"node:path";import{Readable as mX}from"node:stream";import*as z1 from"node:zlib";import{createRequire as gX}from"node:module";import{join as NY}from"node:path";var LY={200:"200 OK",201:"201 Created",202:"202 Accepted",204:"204 No Content",206:"206 Partial Content",301:"301 Moved Permanently",302:"302 Found",304:"304 Not Modified",400:"400 Bad Request",401:"401 Unauthorized",403:"403 Forbidden",404:"404 Not Found",405:"405 Method Not Allowed",409:"409 Conflict",413:"413 Payload Too Large",415:"415 Unsupported Media Type",422:"422 Unprocessable Entity",429:"429 Too Many Requests",500:"500 Internal Server Error",502:"502 Bad Gateway",503:"503 Service Unavailable"};function y1($){return LY[$]||`${$}`}function xX(){if(typeof globalThis.Bun!=="undefined"||typeof globalThis.Deno!=="undefined")return null;try{return gX(NY(process.cwd(),"package.json"))("uWebSockets.js")}catch{try{return gX(import.meta.url)("uWebSockets.js")}catch{return null}}}class vX{res=null;params={};store=new Map;_status=200;_headers=void 0;_setCookies=void 0;_queryStr="";_query=void 0;_url="/";_method="GET";_reqHeaders=void 0;_req=void 0;_peerIp=void 0;_responded=!1;_inSync=!1;_aborted=!1;reset(){if(this.res=null,this.params={},this.store.size>0)this.store.clear();this._status=200,this._headers=void 0,this._setCookies=void 0,this._queryStr="",this._query=void 0,this._url="/",this._method="GET",this._reqHeaders=void 0,this._req=void 0,this._peerIp=void 0,this._responded=!1,this._inSync=!1,this._aborted=!1}get req(){if(!this._req){let $=this._queryStr?`?${this._queryStr}`:"",Q=this._reqHeaders?.host||"localhost";this._req=new Request(`http://${Q}${this._url}${$}`,{method:this._method,headers:this._reqHeaders})}return this._req}get query(){if(!this._query){let $={};if(this._queryStr){let Q=new URLSearchParams(this._queryStr);for(let[X,Y]of Q)if(X in $)if(Array.isArray($[X]))$[X].push(Y);else $[X]=[$[X],Y];else $[X]=Y}this._query=$}return this._query}get ip(){let $=this._reqHeaders?.["x-forwarded-for"];if($){let Q=$.indexOf(",");return(Q===-1?$:$.slice(0,Q)).trim()}return this._reqHeaders?.["x-real-ip"]||this._reqHeaders?.["cf-connecting-ip"]||this._peerIp||"127.0.0.1"}status($){return this._status=$,this}setHeader($,Q){if(!this._headers)this._headers={};return this._headers[$.toLowerCase()]=Q,this}getHeader($){return this._reqHeaders?.[$.toLowerCase()]}header($){return this.getHeader($)}set($,Q){return this.store.set($,Q),this}get($){return this.store.get($)}_flushJson($,Q){if(this._status!==200)$.writeStatus(y1(this._status));if($.writeHeader("content-type","application/json"),this._headers){for(let X in this._headers)if(X!=="content-type")$.writeHeader(X,this._headers[X])}if(this._setCookies)for(let X=0;X<this._setCookies.length;X++)$.writeHeader("set-cookie",this._setCookies[X]);$.end(Q)}json($){let Q=this.res;if(!Q||this._responded||this._aborted)return;this._responded=!0;let X=JSON.stringify($);if(this._inSync)this._flushJson(Q,X);else Q.cork(()=>this._flushJson(Q,X));return}_flushText($,Q,X){if(X!==200)$.writeStatus(y1(X));if(this._headers)for(let Y in this._headers)$.writeHeader(Y,this._headers[Y]);if(this._setCookies)for(let Y=0;Y<this._setCookies.length;Y++)$.writeHeader("set-cookie",this._setCookies[Y]);$.end(Q)}text($,Q){let X=this.res;if(!X||this._responded||this._aborted)return;this._responded=!0;let Y=Q??this._status;if(this._inSync)this._flushText(X,$,Y);else X.cork(()=>this._flushText(X,$,Y));return}html($,Q){return this.setHeader("content-type","text/html; charset=utf-8"),this.text($,Q)}redirect($,Q=302){return this.setHeader("location",$),this.text("",Q)}}function IQ($,Q){let X=Q.status;if(X!==200)$.writeStatus(y1(X));Q.headers.forEach((W,H)=>{if(H!=="content-length"&&H!=="transfer-encoding")$.writeHeader(H,W)});let Y=Q.headers;if(typeof Y.getSetCookie==="function"){let W=Y.getSetCookie();for(let H=0;H<W.length;H++)$.writeHeader("set-cookie",W[H])}}function yX($,Q,X){if(!Q.body){if(X?.())return;$.cork(()=>{IQ($,Q),$.end()});return}let Y=Q.body.getReader(),W=!1,H=()=>{Y.read().then(({value:J,done:z})=>{if(X?.()){try{Y.cancel()}catch{}return}if(z){$.cork(()=>{if(!W)IQ($,Q),W=!0;$.end()});return}if(J&&J.byteLength>0){let M=Buffer.from(J.buffer,J.byteOffset,J.byteLength),q=!0;if($.cork(()=>{if(!W)IQ($,Q),W=!0;q=$.write(M)}),!q&&typeof $.onWritable==="function"){$.onWritable(()=>{return H(),!0});return}}H()},()=>{if(!X?.())try{$.close()}catch{}})};H()}function kX($,Q,X){if(Q?._responded)return;if(X instanceof Response){yX($,X);return}if(typeof X==="string"){if(Q)Q.text(X);else $.end(X);return}if(Q)Q.json(X??null);else $.writeHeader("content-type","application/json"),$.end(JSON.stringify(X??null))}function fQ($,Q){let X=Q?.status>=400&&Q?.status<500?Q.status:500;$.writeStatus(y1(X)),$.writeHeader("content-type","application/json");let Y=X===500?Q?.message||"Internal Server Error":Q?.message||"Bad Request";$.end(JSON.stringify({status:X,message:Y}))}var RY={GET:"get",HEAD:"head",DELETE:"del",OPTIONS:"options"};function hX($,Q){let X=Q.App(),Y=!1,W=[],H=4096,J=0;if($.uwsRoutes)for(let U of $.uwsRoutes){let A=RY[U.method];if(!A)continue;let{rawHandler:G,paramNames:D}=U,R=D.length,O=G.toString(),b=/\b(?:getHeader|header|ip|req)\b/.test(O),I=/\b(?:query|req)\b/.test(O);X[A](U.path,(j,g)=>{let V=W.length>0?W.pop():new vX;if(V.res=j,R>0){let o={};for(let T=0;T<R;T++)o[D[T]]=g.getParameter(T);V.params=o}if(I)V._queryStr=g.getQuery(),V._url=g.getUrl(),V._method=U.method;if(b){let o={};g.forEach((T,P)=>{o[T]=P}),V._reqHeaders=o,V._url=g.getUrl(),V._method=U.method}V._inSync=!0;try{let o=G(V);if(V._inSync=!1,o&&typeof o.then==="function"){j.onAborted(()=>{V._aborted=!0}),o.then((T)=>{if(!V._aborted&&!V._responded)j.cork(()=>kX(j,V,T));if(V.reset(),W.length<4096)W.push(V)},(T)=>{if(!V._aborted&&!V._responded)j.cork(()=>fQ(j,T));if(V.reset(),W.length<4096)W.push(V)});return}if(!V._responded)kX(j,V,o);if(V.reset(),W.length<4096)W.push(V)}catch(o){if(V._inSync=!1,!V._responded)fQ(j,o);if(V.reset(),W.length<4096)W.push(V)}})}if(X.any("/*",(U,A)=>{let G=!1;U.onAborted(()=>{G=!0});let D=A.getMethod().toUpperCase(),R=A.getUrl(),O=A.getQuery(),b=new Headers,I="localhost";A.forEach((i,p)=>{if(i==="host")I=p;b.append(i,p)});let j=`http://${I}${R}${O?`?${O}`:""}`,g="127.0.0.1";try{g=Buffer.from(U.getRemoteAddressAsText()).toString()||"127.0.0.1"}catch{}let V=(i)=>{if(G)return;J++;let p=new Request(j,{method:D,headers:b,body:i&&i.length>0?i:void 0});Promise.resolve($.fetch(p,g)).then((C)=>{if(J=Math.max(0,J-1),G)return;yX(U,C,()=>G)},(C)=>{if(J=Math.max(0,J-1),!G)U.cork(()=>fQ(U,C))})};if(D==="GET"||D==="HEAD"){V();return}let o=[],T=0,P=$.maxRequestBodySize||10485760,u=!1;U.onData((i,p)=>{if(G||u)return;let C=Buffer.from(new Uint8Array(i));if(T+=C.length,T>P){u=!0,U.cork(()=>{U.writeStatus("413 Payload Too Large"),U.writeHeader("content-type","application/json"),U.end(JSON.stringify({status:413,message:"Payload Too Large"}))});return}if(C.length>0)o.push(C);if(p)V(o.length===0?void 0:o.length===1?o[0]:Buffer.concat(o))})}),$.ws){let U=$.ws,A=(G)=>{let D=G.getUserData();if(!D.wrapped)D.wrapped={data:D.handler,send(R,O){return G.send(R,O??typeof R!=="string")},subscribe(R){return typeof G.subscribe==="function"?G.subscribe(R):!1},unsubscribe(R){return typeof G.unsubscribe==="function"?G.unsubscribe(R):!1},publish(R,O,b){return typeof G.publish==="function"?G.publish(R,O,b??typeof O!=="string"):!1},close(R,O){if(typeof G.end==="function")G.end(R,O);else if(typeof G.close==="function")G.close()},raw:G};return D.wrapped};X.ws("/*",{upgrade(G,D,R){let O=D.getUrl(),b=D.getQuery(),I=`http://localhost${O}${b?`?${b}`:""}`,j=C2(U.routes,I);if(!j){G.writeStatus("404 Not Found").end();return}let g=j.params?{...j.handler,params:j.params}:j.handler;G.upgrade({handler:g,wrapped:null},D.getHeader("sec-websocket-key"),D.getHeader("sec-websocket-protocol"),D.getHeader("sec-websocket-extensions"),R)},open(G){U.adapter.open(A(G))},message(G,D,R){let O=R?new Uint8Array(D):Buffer.from(D).toString("utf8");U.adapter.message(A(G),O)},drain(G){U.adapter.drain(A(G))},close(G,D,R){let O=R&&R.byteLength>0?Buffer.from(R).toString("utf8"):"";U.adapter.close(A(G),D,O)}})}let z=null,M=$.port,q=new Promise((U,A)=>{X.listen($.hostname,$.port,(G)=>{if(!G){A(new Error(`[BareJS] uWebSockets.js failed to listen on ${$.hostname}:${$.port}`));return}z=G;try{M=Q.us_socket_local_port(G)||$.port}catch{M=$.port}U()})}),B=()=>{if(z){try{Q.us_listen_socket_close(z)}catch{}z=null}},_=async(U=5000)=>{B();let A=Date.now()+U;while(J>0&&Date.now()<A)await new Promise((G)=>setTimeout(G,10))};return Object.defineProperty(X,"port",{get:()=>M,configurable:!0}),X.stop=B,X.drain=_,X.ready=q,{get port(){return M},stop:B,drain:_,raw:X,ready:q}}var TQ=16384,gQ=8,kQ=1,ZY=64;function nX($,Q,X,Y){return new Promise((W,H)=>{wY($,Q,X,Y,(J,z)=>{if(J)H(J);else W(z)})})}async function bY($){let Q=OY(16),X=await nX($,Q,ZY,{N:TQ,r:gQ,p:kQ});return`$scrypt$N=${TQ},r=${gQ},p=${kQ}$${Q.toString("base64url")}$${X.toString("base64url")}`}async function CY($,Q){let X=Q.split("$");if(X.length!==5||X[1]!=="scrypt")return!1;let Y={};for(let B of X[2].split(",")){let[_,U]=B.split("=");if(_&&U)Y[_]=Number(U)}let W=Y.N||TQ,H=Y.r||gQ,J=Y.p||kQ;if(!Number.isFinite(W)||!Number.isFinite(H)||!Number.isFinite(J))return!1;let z=Buffer.from(X[3],"base64url"),M=Buffer.from(X[4],"base64url");if(z.length===0||M.length===0)return!1;let q=await nX($,z,M.length,{N:W,r:H,p:J});return q.length===M.length&&jY(q,M)}var EY={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".wasm":"application/wasm",".pdf":"application/pdf",".mp4":"video/mp4",".mp3":"audio/mpeg",".csv":"text/csv; charset=utf-8"};function VY($,Q){let Y=`http://${$.headers.host||"localhost"}${$.url||"/"}`,W=$.method||"GET",H=$.headers["content-length"];if(H!==void 0){let _=Number(Array.isArray(H)?H[0]:H);if(Number.isFinite(_)&&_>Q)return{errorStatus:413}}let J=new Headers,z=$.rawHeaders;if(z&&z.length>0)for(let _=0;_<z.length;_+=2)J.append(z[_],z[_+1]);else for(let[_,U]of Object.entries($.headers)){if(U===void 0)continue;if(Array.isArray(U))for(let A of U)J.append(_,A);else J.set(_,U)}let M=W!=="GET"&&W!=="HEAD",q;if(M){let _=0,U=$;q=new ReadableStream({start(A){U.on("data",(G)=>{if(_+=G.byteLength,_>Q){let D=new Error("Payload Too Large");D.status=413,A.error(D),U.destroy();return}A.enqueue(new Uint8Array(G.buffer,G.byteOffset,G.byteLength))}),U.on("end",()=>{try{A.close()}catch{}}),U.on("error",(G)=>{try{A.error(G)}catch{}})},cancel(){U.destroy()}})}let B={method:W,headers:J};if(q)B.body=q,B.duplex="half";return{request:new Request(Y,B)}}async function PY($,Q){if(Q.writableEnded||Q.destroyed)return;let X={};$.headers.forEach((H,J)=>{if(J.toLowerCase()==="set-cookie")return;X[J]=H});let Y=typeof $.headers.getSetCookie==="function"?$.headers.getSetCookie():[];if(Y.length>0)X["set-cookie"]=Y;if(Q.writeHead($.status,X),typeof Q.flushHeaders==="function")Q.flushHeaders();if(!$.body){Q.end();return}let W=$.body.getReader();try{while(!0){let{done:H,value:J}=await W.read();if(H)break;if(Q.destroyed||Q.writableEnded){await W.cancel().catch(()=>{});break}if(J&&J.byteLength>0){if(!Q.write(J))await new Promise((M)=>{let q=()=>{Q.off("close",B),M()},B=()=>{Q.off("drain",q),M()};Q.once("drain",q),Q.once("close",B)})}}}finally{try{W.releaseLock()}catch{}if(!Q.writableEnded&&!Q.destroyed)Q.end()}}var h1={name:"node",serve($){if($.engine!=="http"){let H=xX();if(H)return hX($,H);if($.engine==="uws")throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.")}let Q=KY(async(H,J)=>{let z=VY(H,$.maxRequestBodySize);if(z.errorStatus===413||!z.request){J.writeHead(413,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:"Payload Too Large"})),H.resume();return}let M=H.socket?.remoteAddress;try{let q=await $.fetch(z.request,M);await PY(q,J)}catch(q){if(!J.headersSent){let B=q?.status===413?413:500;J.writeHead(B,{"content-type":"application/json"}),J.end(JSON.stringify({status:"error",message:q?.message||"Internal Server Error"}))}else if(!J.writableEnded)J.end()}});if($.ws){let H=$.ws,J=null,z=()=>{if(!J)J=import("ws").then((A)=>new A.WebSocketServer({noServer:!0}),()=>null);return J},M="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",q=16777216,B=(U,A)=>{let G=A.length,D;if(G<126)D=Buffer.allocUnsafe(2),D[0]=128|U,D[1]=G;else if(G<65536)D=Buffer.allocUnsafe(4),D[0]=128|U,D[1]=126,D.writeUInt16BE(G,2);else D=Buffer.allocUnsafe(10),D[0]=128|U,D[1]=127,D.writeBigUInt64BE(BigInt(G),2);return Buffer.concat([D,A])},_=(U,A,G,D)=>{let R=U.headers["sec-websocket-key"];if(!R||Array.isArray(R)){A.write(`HTTP/1.1 400 Bad Request\r
|
|
2
2
|
\r
|
|
3
3
|
`),A.destroy();return}let O=SY("sha1").update(R.trim()+M).digest("base64");A.write(`HTTP/1.1 101 Switching Protocols\r
|
|
4
4
|
Upgrade: websocket\r
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"author": "xarhang",
|
|
5
5
|
"description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
|
|
6
6
|
"main": "./dist/index.js",
|
package/src/runtime/uws.ts
CHANGED
|
@@ -230,7 +230,9 @@ function writeUwsHeaders(res: any, webRes: Response): void {
|
|
|
230
230
|
const status = webRes.status;
|
|
231
231
|
if (status !== 200) res.writeStatus(statusLine(status));
|
|
232
232
|
webRes.headers.forEach((value, key) => {
|
|
233
|
-
|
|
233
|
+
if (key !== 'content-length' && key !== 'transfer-encoding') {
|
|
234
|
+
res.writeHeader(key, value);
|
|
235
|
+
}
|
|
234
236
|
});
|
|
235
237
|
const anyHeaders = webRes.headers as any;
|
|
236
238
|
if (typeof anyHeaders.getSetCookie === 'function') {
|
|
@@ -514,7 +516,7 @@ export function serveUws(
|
|
|
514
516
|
|
|
515
517
|
res.onData((ab: ArrayBuffer, isLast: boolean) => {
|
|
516
518
|
if (aborted || rejected) return;
|
|
517
|
-
const chunk = Buffer.from(ab);
|
|
519
|
+
const chunk = Buffer.from(new Uint8Array(ab));
|
|
518
520
|
totalLen += chunk.length;
|
|
519
521
|
if (totalLen > maxBody) {
|
|
520
522
|
rejected = true;
|