diesel-core 1.6.7 → 1.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adaptor/node/main.d.ts +2 -1
- package/dist/adaptor/node/main.js +3 -1
- package/dist/src/constant.js +1 -0
- package/dist/{main.js → src/main.js} +2 -2
- package/package.json +1 -1
- /package/dist/{ctx.js → src/ctx.js} +0 -0
- /package/dist/{handleRequest.js → src/handleRequest.js} +0 -0
- /package/dist/{http-exception.js → src/http-exception.js} +0 -0
- /package/dist/{request_pipeline.js → src/request_pipeline.js} +0 -0
- /package/dist/{router → src/router}/find-my-way.js +0 -0
- /package/dist/{router → src/router}/interface.js +0 -0
- /package/dist/{router → src/router}/trie.js +0 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import * as http from 'node:http';
|
|
1
2
|
export interface options {
|
|
2
3
|
fetch: (req: Request, ...args: any) => Response | Promise<Response>;
|
|
3
4
|
port: number;
|
|
4
5
|
}
|
|
5
|
-
export declare function serve(options: options):
|
|
6
|
+
export declare function serve(options: options): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
@@ -89,6 +89,7 @@ function sendWebResToNodeRes(webRes, nodeRes) {
|
|
|
89
89
|
}
|
|
90
90
|
function serve(options) {
|
|
91
91
|
var _this = this;
|
|
92
|
+
var _a;
|
|
92
93
|
var server = http.createServer(function (request, response) { return __awaiter(_this, void 0, void 0, function () {
|
|
93
94
|
var webRequest, webRes;
|
|
94
95
|
return __generator(this, function (_a) {
|
|
@@ -106,5 +107,6 @@ function serve(options) {
|
|
|
106
107
|
}
|
|
107
108
|
});
|
|
108
109
|
}); });
|
|
109
|
-
server.listen(options.port, function () { return console.log(
|
|
110
|
+
server.listen((_a = options.port) !== null && _a !== void 0 ? _a : 3000, function () { var _a; return console.log("node server running on port ".concat((_a = options.port) !== null && _a !== void 0 ? _a : 3000)); });
|
|
111
|
+
return server;
|
|
110
112
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var A=Object.create;var{getPrototypeOf:D,defineProperty:t,getOwnPropertyNames:p,getOwnPropertyDescriptor:N}=Object,s=Object.prototype.hasOwnProperty;var d=(P,T,E)=>{E=P!=null?A(D(P)):{};let o=T||!P||!P.__esModule?t(E,"default",{value:P,enumerable:!0}):E;for(let O of p(P))if(!s.call(o,O))t(o,O,{get:()=>P[O],enumerable:!0});return o},e=new WeakMap,r=(P)=>{var T=e.get(P),E;if(T)return T;if(T=t({},"__esModule",{value:!0}),P&&typeof P==="object"||typeof P==="function")p(P).map((o)=>!s.call(T,o)&&t(T,o,{get:()=>P[o],enumerable:!(E=N(P,o))||E.enumerable}));return e.set(P,T),T},H=(P,T)=>()=>(T||P((T={exports:{}}).exports,T),T.exports);var I=(P,T)=>{for(var E in T)t(P,E,{get:T[E],enumerable:!0,configurable:!0,set:(o)=>T[E]=()=>o})};var S=(P,T)=>()=>(P&&(T=P(P=0)),T);var c=((P)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(P,{get:(T,E)=>(typeof require!=="undefined"?require:T)[E]}):P)(function(P){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+P+'" is not supported')});var n=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];export{n as supportedMethods};
|
|
@@ -261,6 +261,6 @@ ${$}`)}function a1(f,$,Z,J){if(f.isLeafNode||J.commonPrefix!==!1){if(Z=Z||"(empt
|
|
|
261
261
|
${z.join(`
|
|
262
262
|
`)}
|
|
263
263
|
}
|
|
264
|
-
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",j)(m4,Y,r0,O,w,H)};class I1{children;isEndOfWord;handler;isDynamic;pattern;path;methodMap;segmentCount;params;middlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=null,this.isDynamic=!1,this.pattern="",this.path="",this.methodMap=new Map,this.segmentCount=0,this.params=[],this.middlewares=[]}}class Gf{root;cachedSegments;globalMiddlewares;constructor(){this.root=new I1,this.cachedSegments=new Map,this.globalMiddlewares=[]}pushMidl(f,...$){let Z=this.root,J=f.split("/").filter(Boolean);if(f==="/"){Z.handler=$[0],this.globalMiddlewares.push(...$);return}for(let z of J){let Q=z;if(z.startsWith(":"))Q=":";else if(z.startsWith("*"))Z.middlewares.push(...$);if(!Z.children[Q])Z.children[Q]=new I1;Z=Z.children[Q]}Z.middlewares.push(...$),Z.handler=$[0]}insert(f,$){let Z=this.root,J=f.split("/").filter(Boolean);if(this.cachedSegments.set(f,J),f==="/"){Z.isEndOfWord=!0,Z.handler=$.handler,Z.path=f,Z.methodMap.set($.method,$.handler),Z.segmentCount=0,Z.params=[];return}for(let z of J){let Q=z,Y=!1;if(z.startsWith(":"))Y=!0,Q=":";if(z==="*")Q="*";if(!Z.children[Q])Z.children[Q]=new I1;Z=Z.children[Q],Z.isDynamic=Y,Z.pattern=z}Z.params=J.filter((z)=>z.startsWith(":")).map((z)=>z.slice(1)),Z.isEndOfWord=!0,Z.path=f,Z.segmentCount=J.length,Z.methodMap.set($.method,$.handler),Z.handler=$.handler}search(f,$){let Z=this.root,J=this.cachedSegments.get(f)||f.split("/").filter(Boolean),z=[...this.globalMiddlewares];for(let Y of J){let X=Y;if(Z.children[X])Z=Z.children[X];else if(Z.children[":"])Z=Z.children[":"];else if(Z.children["*"]){Z=Z.children["*"];break}else return{handler:z};if(Z.middlewares.length>0)z.push(...Z.middlewares)}if(!Z.isEndOfWord||Z.segmentCount!==J.length)return{handler:z};let Q=Z.methodMap.get($);if(Q)z.push(Q);return{params:Z.params,handler:z}}}class S1{trie=new Gf;cache=new Map;add(f,$,Z){this.trie.insert($,{method:f,handler:Z})}addMiddleware(f,...$){this.trie.pushMidl(f,...$)}find(f,$){return this.trie.search($,f)}}var l7=W4(n7(),1);class J1{router=l7.default({});add(f,$,Z){this.router.on(f,$,Z)}addMiddleware(f,...$){}find(f,$){let Z=this.router.find(f,$);if(Z)return{handler:[Z.handler],params:Z.params};return null}}class ff{children;isEndOfWord;handlers;paramName;middlewares;constructor(){this.children={},this.handlers=new Map,this.isEndOfWord=!1,this.paramName=[],this.middlewares=[]}}class p7{root;globalMiddlewares;constructor(){this.root=new ff,this.globalMiddlewares=[]}pushMiddleware(f,...$){if(f==="/"){this.globalMiddlewares.push(...$);return}let Z=this.root,J=f.split("/").filter(Boolean);for(let z of J){let Q=z;if(z.startsWith(":"))Q=":";else if(z.startsWith("*"))Z.middlewares.push(...$);if(!Z.children[Q])Z.children[Q]=new ff;Z=Z.children[Q]}Z.middlewares.push(...$)}insert(f,$,Z){let J=this.root,z=$.split("/").filter(Boolean);if($==="/"){J.isEndOfWord=!0,J.handlers.set(f,Z),J.paramName=[];return}for(let Q of z){let Y=Q;if(Q.startsWith(":"))Y=":";if(!J.children[Y])J.children[Y]=new ff;J=J.children[Y]}J.paramName=z.filter((Q)=>Q.startsWith(":")).map((Q)=>Q.slice(1)),J.handlers.set(f,Z),J.isEndOfWord=!0}search(f,$){let Z=this.root,J=$.split("/").filter(Boolean),z=[...this.globalMiddlewares];for(let Y of J){if(Z.children[Y])Z=Z.children[Y];else if(Z.children[":"])Z=Z.children[":"];else if(Z.children["*"]){Z=Z.children["*"];break}else return{handler:z};if(Z.middlewares.length>0)z.push(...Z.middlewares)}let Q=Z.handlers.get(f);if(Q)z.push(Q);return{params:Z.paramName,handler:z}}}class tf{trie;cache=new Map;constructor(){this.trie=new p7}add(f,$,Z){this.trie.insert(f,$,Z)}addMiddleware(f,...$){this.trie.pushMiddleware(f,...$)}find(f,$){return this.trie.search(f,$)}}class ef{static create(f){switch(f){case"t2":return new tf;case"trie":return new S1;case"fastify":return new J1;case"fs":return new J1;case"find-my-way":return new J1;case"findmyway":return new J1;default:return new S1}}}var D0={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},f4=(f,$,Z)=>{let J=D0[f]||D0.reset,z=Z?.method?D0.method[Z.method]||D0.reset:D0.reset,Q=Z?.status?Z.status>=500?D0.error:Z.status>=400?D0.warn:D0.info:D0.reset;console.log(`
|
|
264
|
+
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",j)(m4,Y,r0,O,w,H)};class I1{children;isEndOfWord;handler;isDynamic;pattern;path;methodMap;segmentCount;params;middlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=null,this.isDynamic=!1,this.pattern="",this.path="",this.methodMap=new Map,this.segmentCount=0,this.params=[],this.middlewares=[]}}class Gf{root;cachedSegments;globalMiddlewares;constructor(){this.root=new I1,this.cachedSegments=new Map,this.globalMiddlewares=[]}pushMidl(f,...$){let Z=this.root,J=f.split("/").filter(Boolean);if(f==="/"){Z.handler=$[0],this.globalMiddlewares.push(...$);return}for(let z of J){let Q=z;if(z.startsWith(":"))Q=":";else if(z.startsWith("*"))Z.middlewares.push(...$);if(!Z.children[Q])Z.children[Q]=new I1;Z=Z.children[Q]}Z.middlewares.push(...$),Z.handler=$[0]}insert(f,$){let Z=this.root,J=f.split("/").filter(Boolean);if(this.cachedSegments.set(f,J),f==="/"){Z.isEndOfWord=!0,Z.handler=$.handler,Z.path=f,Z.methodMap.set($.method,$.handler),Z.segmentCount=0,Z.params=[];return}for(let z of J){let Q=z,Y=!1;if(z.startsWith(":"))Y=!0,Q=":";if(z==="*")Q="*";if(!Z.children[Q])Z.children[Q]=new I1;Z=Z.children[Q],Z.isDynamic=Y,Z.pattern=z}Z.params=J.filter((z)=>z.startsWith(":")).map((z)=>z.slice(1)),Z.isEndOfWord=!0,Z.path=f,Z.segmentCount=J.length,Z.methodMap.set($.method,$.handler),Z.handler=$.handler}search(f,$){let Z=this.root,J=this.cachedSegments.get(f)||f.split("/").filter(Boolean),z=[...this.globalMiddlewares];for(let Y of J){let X=Y;if(Z.children[X])Z=Z.children[X];else if(Z.children[":"])Z=Z.children[":"];else if(Z.children["*"]){Z=Z.children["*"];break}else return{handler:z};if(Z.middlewares.length>0)z.push(...Z.middlewares)}if(!Z.isEndOfWord||Z.segmentCount!==J.length)return{handler:z};let Q=Z.methodMap.get($);if(Q)z.push(Q);return{params:Z.params,handler:z}}}class S1{trie=new Gf;cache=new Map;add(f,$,Z){this.trie.insert($,{method:f,handler:Z})}addMiddleware(f,...$){this.trie.pushMidl(f,...$)}find(f,$){return this.trie.search($,f)}}var l7=W4(n7(),1);class J1{router=l7.default({});add(f,$,Z){this.router.on(f,$,Z)}addMiddleware(f,...$){}find(f,$){let Z=this.router.find(f,$);if(Z)return{handler:[Z.handler],params:Z.params};return null}}class ff{children;isEndOfWord;handlers;paramName;middlewares;constructor(){this.children={},this.handlers=new Map,this.isEndOfWord=!1,this.paramName=[],this.middlewares=[]}}class p7{root;globalMiddlewares;constructor(){this.root=new ff,this.globalMiddlewares=[]}pushMiddleware(f,...$){if(f==="/"){this.globalMiddlewares.push(...$);return}let Z=this.root,J=f.split("/").filter(Boolean);for(let z of J){let Q=z;if(z.startsWith(":"))Q=":";else if(z.startsWith("*"))Z.middlewares.push(...$);if(!Z.children[Q])Z.children[Q]=new ff;Z=Z.children[Q]}Z.middlewares.push(...$)}insert(f,$,Z){let J=this.root,z=$.split("/").filter(Boolean);if($==="/"){J.isEndOfWord=!0,J.handlers.set(f,Z),J.paramName=[];return}for(let Q of z){let Y=Q;if(Q.startsWith(":"))Y=":";if(!J.children[Y])J.children[Y]=new ff;J=J.children[Y]}J.paramName=z.filter((Q)=>Q.startsWith(":")).map((Q)=>Q.slice(1)),J.handlers.set(f,Z),J.isEndOfWord=!0}search(f,$){let Z=this.root,J=$.split("/").filter(Boolean),z=[...this.globalMiddlewares];for(let Y of J){if(Z.children[Y])Z=Z.children[Y];else if(Z.children[":"])Z=Z.children[":"];else if(Z.children["*"]){Z=Z.children["*"];break}else return{handler:z};if(Z.middlewares.length>0)z.push(...Z.middlewares)}let Q=Z.handlers.get(f);if(Q)z.push(Q);return{params:Z.paramName,handler:z}}}class tf{trie;cache=new Map;constructor(){this.trie=new p7}add(f,$,Z){this.trie.insert(f,$,Z)}addMiddleware(f,...$){this.trie.pushMiddleware(f,...$)}find(f,$){return this.trie.search(f,$)}}class ef{static create(f){switch(f){case"t2":return new tf;case"trie":return new S1;case"fastify":return new J1;case"fs":return new J1;case"find-my-way":return new J1;case"findmyway":return new J1;default:return new S1}}}var o7=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];var D0={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},f4=(f,$,Z)=>{let J=D0[f]||D0.reset,z=Z?.method?D0.method[Z.method]||D0.reset:D0.reset,Q=Z?.status?Z.status>=500?D0.error:Z.status>=400?D0.warn:D0.info:D0.reset;console.log(`
|
|
265
265
|
${J}[${f.toUpperCase()}]${D0.reset} ${$} - ${z}${Z?.method||""}${D0.reset}`);let Y={timestamp:new Date().toISOString(),...Z,status:Z?.status?`${Q}${Z.status}${D0.reset}`:void 0,method:Z?.method?`${z>J}${Z.method}${D0.reset}`:void 0};console.log(JSON.stringify(Y,null,2)+`
|
|
266
|
-
`)},o7=(f)=>{let{app:$,logger:Z,logLevel:J="info",onRequest:z,onSend:Q,onError:Y}=f||{};$?.addHooks("onRequest",(X)=>{X.req.startTime=Date.now(),Z?.()??f4(J,"Incoming Request",{method:X.req.method,url:X.path,headers:{"user-agent":X.req.headers.get("user-agent"),"content-type":X.req.headers.get("content-type")}}),z?.(X)}),$?.addHooks("onSend",async(X,W)=>{let H=`${Date.now()-X.req.startTime}ms`;Z?.()??f4(J,"Response Sent",{method:X.req.method,url:X.url.toString(),status:W.status,duration:H,reqId:X.get?.("requestId"),headers:{"content-type":W.headers.get("content-type")}});let w=await Q?.(X);if(w instanceof Response)return w}),$?.addHooks("onError",async(X,W,H)=>{Z?.()??f4("error","Unhandled Error",{method:H.method,url:W,status:500,error:X.message});let w=await Y?.(X,W,H);if(w instanceof Response)return w})},$4=(f,$,Z,J=0,z,Q)=>{let Y=D0.method[$]||D0.reset,X=J>=500?D0.error:J>=400?D0.warn:D0.info,W=Q?`[${Q}] `:"",H=f==="<--"?`${f} ${Y}${$}${D0.reset} ${Z} ${W}`:`${f} ${Y}${$}${D0.reset} ${Z} ${X}${J}${D0.reset} ${z??""} ${W}`;console.log(H)},m9=(f)=>{let $=Date.now()-f;return $<1000?`${$}ms`:`${Math.round($/1000)}s`},r7=(f)=>{let{app:$,log:Z,onRequest:J,onSend:z,onError:Q}=f;$.addHooks("onRequest",(Y)=>{let{req:X,path:W}=Y;X.startTime=Date.now(),Z?.()??$4("<--",X.method,W),J?.(X,W)}),$.addHooks("onSend",async(Y,X)=>{let{method:W,url:H}=Y.req,w=new URL(H).pathname,K=Y.get?.("requestId");Z?.()??$4("-->",W,w,X?.status,m9(Y.req.startTime),K);let O=await z?.(Y);return O instanceof Response?O:X}),$.addHooks("onError",async(Y,X,W)=>{let H=W.path;Z?.()??$4(Y.message,W.method,H,500);let w=await Q?.(Y,H,W);if(w instanceof Response)return w})};function s7(f,$){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(Z)=>{try{let J=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!J)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(J.startsWith("Bearer "))J=J.slice(7);let z=f?.verify(J,$);if(!z)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);Z.set("user",z)}catch(J){let z="Invalid token";if(J.name==="TokenExpiredError")z="Token expired";else if(J.name==="JsonWebTokenError")z="Malformed or tampered token";return Z.json({message:"Unauthorized",error:z},401)}}}function a7(f,$,Z){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!$)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(J)=>{try{let z=J.cookies?.accessToken??J.req?.headers?.get("Authorization");if(!z)return J.json({message:"Unauthorized",error:"No token provided"},401);if(z.startsWith("Bearer "))z=z.slice(7);let Q=f?.verify(z,Z);if(!Q)return J.json({message:"Unauthorized",error:"Token could not be decoded"},401);let Y=await $.findById(Q._id).select("-password -refreshToken");if(!Y)return J.json({message:"Unauthorized: User not found"},404);J.set("user",Y);return}catch(z){let Q="Invalid token";if(z.name==="TokenExpiredError")Q="Token expired";else if(z.name==="JsonWebTokenError")Q="Malformed or tampered token";return J.json({message:"Unauthorized",error:Q},401)}}}var d9=(f,$)=>{try{return $(f)}catch{return f.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return $(Z)}catch{return Z}})}},i9=(f)=>d9(f,decodeURI),$f=(f)=>{let $=f.indexOf("/",f.indexOf(":")+4),Z=$;for(;Z<f.length;Z++){let J=f.charCodeAt(Z);if(J===37){let z=f.indexOf("?",Z),Q=f.slice($,z===-1?void 0:z);return i9(Q.includes("%25")?Q.replace(/%25/g,"%2525"):Q)}else if(J===63)break}return f.slice($,Z)};var J4=Symbol.for,n0=Symbol("kCapture"),$Z=J4("events.errorMonitor"),n9=Symbol("events.maxEventTargetListeners"),l9=Symbol("events.maxEventTargetListenersWarned"),t7=J4("nodejs.rejection"),p9=J4("nodejs.rejection"),e7=Array.prototype.slice,l0=10,h0=function f($){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[n0]=$?.captureRejections?Boolean($?.captureRejections):W0[n0])this.emit=a9},W0=h0.prototype={};W0._events=void 0;W0._eventsCount=0;W0._maxListeners=void 0;W0.setMaxListeners=function f($){return z4($,"setMaxListeners",0),this._maxListeners=$,this};W0.constructor=h0;W0.getMaxListeners=function f(){return this?._maxListeners??l0};function ZZ(f,$){var{_events:Z}=f;if($[0]??=new Error("Unhandled error."),!Z)throw $[0];var J=Z[$Z];if(J)for(var z of e7.call(J))z.apply(f,$);var Q=Z.error;if(!Q)throw $[0];for(var z of e7.call(Q))z.apply(f,$);return!0}function o9(f,$,Z,J){$.then(void 0,function(z){queueMicrotask(()=>r9(f,z,Z,J))})}function r9(f,$,Z,J){if(typeof f[t7]==="function")f[t7]($,Z,...J);else try{f[n0]=!1,f.emit("error",$)}finally{f[n0]=!0}}var s9=function f($,...Z){if($==="error")return ZZ(this,Z);var{_events:J}=this;if(J===void 0)return!1;var z=J[$];if(z===void 0)return!1;let Q=z.length>1?z.slice():z;for(let Y=0,{length:X}=Q;Y<X;Y++){let W=Q[Y];switch(Z.length){case 0:W.call(this);break;case 1:W.call(this,Z[0]);break;case 2:W.call(this,Z[0],Z[1]);break;case 3:W.call(this,Z[0],Z[1],Z[2]);break;default:W.apply(this,Z);break}}return!0},a9=function f($,...Z){if($==="error")return ZZ(this,Z);var{_events:J}=this;if(J===void 0)return!1;var z=J[$];if(z===void 0)return!1;let Q=z.length>1?z.slice():z;for(let Y=0,{length:X}=Q;Y<X;Y++){let W=Q[Y],H;switch(Z.length){case 0:H=W.call(this);break;case 1:H=W.call(this,Z[0]);break;case 2:H=W.call(this,Z[0],Z[1]);break;case 3:H=W.call(this,Z[0],Z[1],Z[2]);break;default:H=W.apply(this,Z);break}if(H!==void 0&&typeof H?.then==="function"&&H.then===Promise.prototype.then)o9(this,H,$,Z)}return!0};W0.emit=s9;W0.addListener=function f($,Z){M1(Z);var J=this._events;if(!J)J=this._events={__proto__:null},this._eventsCount=0;else if(J.newListener)this.emit("newListener",$,Z.listener??Z);var z=J[$];if(!z)J[$]=[Z],this._eventsCount++;else{z.push(Z);var Q=this._maxListeners??l0;if(Q>0&&z.length>Q&&!z.warned)JZ(this,$,z)}return this};W0.on=W0.addListener;W0.prependListener=function f($,Z){M1(Z);var J=this._events;if(!J)J=this._events={__proto__:null},this._eventsCount=0;else if(J.newListener)this.emit("newListener",$,Z.listener??Z);var z=J[$];if(!z)J[$]=[Z],this._eventsCount++;else{z.unshift(Z);var Q=this._maxListeners??l0;if(Q>0&&z.length>Q&&!z.warned)JZ(this,$,z)}return this};function JZ(f,$,Z){Z.warned=!0;let J=new Error(`Possible EventEmitter memory leak detected. ${Z.length} ${String($)} listeners added to [${f.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);J.name="MaxListenersExceededWarning",J.emitter=f,J.type=$,J.count=Z.length,console.warn(J)}function zZ(f,$,...Z){this.removeListener(f,$),$.apply(this,Z)}W0.once=function f($,Z){M1(Z);let J=zZ.bind(this,$,Z);return J.listener=Z,this.addListener($,J),this};W0.prependOnceListener=function f($,Z){M1(Z);let J=zZ.bind(this,$,Z);return J.listener=Z,this.prependListener($,J),this};W0.removeListener=function f($,Z){M1(Z);var{_events:J}=this;if(!J)return this;var z=J[$];if(!z)return this;var Q=z.length;let Y=-1;for(let X=Q-1;X>=0;X--)if(z[X]===Z||z[X].listener===Z){Y=X;break}if(Y<0)return this;if(Y===0)z.shift();else z.splice(Y,1);if(z.length===0)delete J[$],this._eventsCount--;return this};W0.off=W0.removeListener;W0.removeAllListeners=function f($){var{_events:Z}=this;if($&&Z){if(Z[$])delete Z[$],this._eventsCount--}else this._events={__proto__:null};return this};W0.listeners=function f($){var{_events:Z}=this;if(!Z)return[];var J=Z[$];if(!J)return[];return J.map((z)=>z.listener??z)};W0.rawListeners=function f($){var{_events:Z}=this;if(!Z)return[];var J=Z[$];if(!J)return[];return J.slice()};W0.listenerCount=function f($){var{_events:Z}=this;if(!Z)return 0;return Z[$]?.length??0};W0.eventNames=function f(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};W0[n0]=!1;function t9(f,$,Z){var J=Z?.signal;if(QZ(J,"options.signal"),J?.aborted)throw new Z4(void 0,{cause:J?.reason});let{resolve:z,reject:Q,promise:Y}=$newPromiseCapability(Promise),X=(w)=>{if(f.removeListener($,W),J!=null)Zf(J,"abort",H);Q(w)},W=(...w)=>{if(typeof f.removeListener==="function")f.removeListener("error",X);if(J!=null)Zf(J,"abort",H);z(w)};if(fZ(f,$,W,{once:!0}),$!=="error"&&typeof f.once==="function")f.once("error",X);function H(){Zf(f,$,W),Zf(f,"error",X),Q(new Z4(void 0,{cause:J?.reason}))}if(J!=null)fZ(J,"abort",H,{once:!0});return Y}function e9(f,$){return f.listeners($)}function f6(f,...$){z4(f,"setMaxListeners",0);var Z;if($&&(Z=$.length))for(let J=0;J<Z;J++)$[J].setMaxListeners(f);else l0=f}function $6(f,$){return f.listenerCount($)}function Zf(f,$,Z,J){if(typeof f.removeListener==="function")f.removeListener($,Z);else f.removeEventListener($,Z,J)}function fZ(f,$,Z,J){if(typeof f.on==="function")if(J.once)f.once($,Z);else f.on($,Z);else f.addEventListener($,Z,J)}class Z4 extends Error{constructor(f="The operation was aborted",$=void 0){if($!==void 0&&typeof $!=="object")throw z1("options","Object",$);super(f,$);this.code="ABORT_ERR",this.name="AbortError"}}function z1(f,$,Z){let J=new TypeError(`The "${f}" argument must be of type ${$}. Received ${Z}`);return J.code="ERR_INVALID_ARG_TYPE",J}function Z6(f,$,Z){let J=new RangeError(`The "${f}" argument is out of range. It must be ${$}. Received ${Z}`);return J.code="ERR_OUT_OF_RANGE",J}function QZ(f,$){if(f!==void 0&&(f===null||typeof f!=="object"||!("aborted"in f)))throw z1($,"AbortSignal",f)}function z4(f,$,Z,J){if(typeof f!=="number")throw z1($,"number",f);if(Z!=null&&f<Z||J!=null&&f>J||(Z!=null||J!=null)&&Number.isNaN(f))throw Z6($,`${Z!=null?`>= ${Z}`:""}${Z!=null&&J!=null?" && ":""}${J!=null?`<= ${J}`:""}`,f)}function M1(f){if(typeof f!=="function")throw new TypeError("The listener must be a function")}function J6(f,$){if(typeof f!=="boolean")throw z1($,"boolean",f)}function z6(f){return f?._maxListeners??l0}function Q6(f,$){if(f===void 0)throw z1("signal","AbortSignal",f);if(QZ(f,"signal"),typeof $!=="function")throw z1("listener","function",$);let Z;if(f.aborted)queueMicrotask(()=>$());else f.addEventListener("abort",$,{__proto__:null,once:!0}),Z=()=>{f.removeEventListener("abort",$)};return{__proto__:null,[Symbol.dispose](){Z?.()}}}Object.defineProperties(h0,{captureRejections:{get(){return W0[n0]},set(f){J6(f,"EventEmitter.captureRejections"),W0[n0]=f},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return l0},set:(f)=>{z4(f,"defaultMaxListeners",0),l0=f}},kMaxEventTargetListeners:{value:n9,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:l9,enumerable:!1,configurable:!1,writable:!1}});Object.assign(h0,{once:t9,getEventListeners:e9,getMaxListeners:z6,setMaxListeners:f6,EventEmitter:h0,usingDomains:!1,captureRejectionSymbol:p9,errorMonitor:$Z,addAbortListener:Q6,init:h0,listenerCount:$6});var YZ=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];class A1{static instance;routes;tempRoutes;tempMiddlewares=new Map;router;hasOnReqHook;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#f=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;get;post;put;patch;delete;any;head;options;propfind;constructor(f={}){YZ.forEach((j)=>{this[j.toLocaleLowerCase()]=(M,...S)=>{return this.addRoute(j,M,S),this}});let{router:$="t2",routerInstance:Z,errorFormat:J="json",platform:z="bun",enableFileRouting:Q=!1,prefixApiUrl:Y="",baseApiUrl:X="",jwtSecret:W,idleTimeOut:H=10,pipelineArchitecture:w=!1,logger:K,onError:O}=f;if(Z)this.router=Z;else this.router=ef.create($);if(this.errorFormat=J,this.platform=z,!A1.instance)A1.instance=this;if(w)this.#f=!0;if(this.errorFormat=J,this.emitter=new h0,this.prefixApiUrl=Y??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=H??10,this.enableFileRouter=Q??!1,this.baseApiUrl=X||"",this.user_jwt_secret=W||process.env.DIESEL_JWT_SECRET||"default_diesel_secret_for_jwt",this.tempRoutes=new Map,this.corsConfig=null,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},O)this.addHooks("onError",(j,M)=>{console.log("Got an exception:",j),console.log("Request Path:",M)});if(K)this.useLogger({app:this,onError(j){console.error("Got an exception:",j)}});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router(f){if(!this.instance)this.instance=new A1;return new Proxy(this.instance,{get($,Z,J){return(z,Q)=>{let Y=f+z;return $[Z](Y,Q)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...f)=>{return this.FilterRoutes=f,this.setupFilter()},permitAll:()=>{for(let f of this?.FilterRoutes){if(f.endsWith("/"))f=f.slice(0,-1);this.filters.add(f)}return this.FilterRoutes=null,this.setupFilter()},authenticate:(f)=>{if(f?.length)for(let $ of f)this.filterFunction.push($)},authenticateJwt:(f)=>{this.filterFunction.push(s7(f,this.user_jwt_secret))},authenticateJwtDB:(f,$)=>{this.filterFunction.push(a7(f,$,this.user_jwt_secret))}}}redirect(f,$,Z){return this.any(f,(J)=>{let z=J.params,Q=$;if(z)for(let X in z)Q=Q.replace(`:${X}`,z[X]);let Y=J.url.search;if(Y)Q+=Y;return J.redirect(Q,Z)}),this}static(f,$){return this.staticPath=f,this.staticRequestPath=$,this}staticHtml(f){return this.staticFiles={...this.staticFiles,...f},this}addHooks(f,$){if(typeof f!=="string")throw new Error("hookName must be a string");if(typeof $!=="function")throw new Error("callback must be a instance of function");switch(f){case"onRequest":this.router.addMiddleware("/",$),this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler?.push($),this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler?.push($),this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend?.push($),this.hasOnSendHook=!0;break;case"onError":this.hooks.onError?.push($),this.hasOnError=!0;break;case"onClose":this.hooks.onClose?.push($);break;default:throw new Error(`Unknown hook type: ${f}`)}return this}useLogger(f){return r7(f),this}useAdvancedLogger(f){return o7(f),this}BunRoute(f,$,...Z){if(!$||typeof $!=="string")throw new Error("give a path in string format");let J;if(typeof Z[0]==="string"||typeof Z[0]==="object")J=Z[0];if(typeof J!=="undefined"){let Q=typeof J==="string"?J:JSON.stringify(J)}let z=i4(this,f.toUpperCase(),$,...Z);return this.routes[$]=z,this}listen(f,...$){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let Z="0.0.0.0",J=void 0,z={};for(let Y of $)if(typeof Y==="string")Z=Y;else if(typeof Y==="function")J=Y;else if(typeof Y==="object"&&Y!==null)z=Y;let Q={port:f,hostname:Z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)Q.routes=this.routes;if(z.cert&&z.key)Q.certFile=z.cert,Q.keyFile=z.key;if(this.serverInstance=Bun?.serve(Q),J)J();return this.serverInstance}close(f){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,f?f():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch(){return this.tempRoutes=null,this.tempMiddlewares=null,(f,$,Z)=>{return this.#$(f,void 0,$,Z)}}fetch(){if(this.tempRoutes=null,this.tempMiddlewares=null,this.platform==="cf"||this.platform==="cloudflare"){if(this.#f){let f=Ff(this);return($,Z,J)=>{return f($,this,void 0,Z,J).catch(async(z)=>{return this.handleError(z,$f($.url),$)})}}return(f,$,Z)=>{return this.#$(f,void 0,$,Z)}}if(this.#f){let f=Ff(this);return($,Z)=>{return f($,this,Z,void 0,void 0).catch(async(J)=>{return this.handleError(J,$f($.url),$)})}}return this.#$.bind(this)}async#$(f,$,Z,J){let z=$f(f.url),Q=this.router.find(f.method,z),Y=new V1(f,$,z,Q?.path,Q?.params,Z,J);try{if(this.hasFilterEnabled){let H=await N1(this,z,Y);if(H)return H}if(this.hasPreHandlerHook){let H=await r0("preHandler",this.hooks.preHandler,[Y]);if(H)return H}let X,W=Q?.handler;if(W.length===1){let H=W[0](Y);X=U1(H)?await H:H}else for(let H=0;H<W.length;H++){let w=W[H](Y);if(X=U1(w)?await w:w,X)break}if(this.hasOnSendHook){let H=await r0("onSend",this.hooks.onSend,[Y,X]);if(H)return H}if(X)return X;return await R1(this,Y,z)}catch(X){return this.handleError(X,z,f)}}async handleError(f,$,Z){let z=this.errorFormat,Q=await r0("onError",this.hooks.onError,[f,$,Z]);if(Q)return Q;if(f&&typeof f==="object"&&f.name==="HTTPException"){let W=f;if(W.res)return W.res;return z==="json"?Response.json({error:W.message},{status:W.status}):new Response(W.message,{status:W.status})}let Y=f instanceof Error?f.message:"Internal Server Error",X=f instanceof Error?f.stack:void 0;if(z==="json"){let W={error:Y,...!1,path:$};return Response.json(W,{status:500,headers:{"Content-Type":"application/json"}})}else{let W=`Error: ${Y}`;return new Response(W,{headers:{"Content-Type":"text/plain"},status:500})}}mount(f,$){let Z=f.endsWith("/*")?f.slice(0,-1):f,J=Z==="/"?0:Z.length;this.any(f,(z)=>{let Q=new URL(z.req.url);Q.pathname=Q.pathname.slice(J)||"/";let Y=new Request(Q.toString(),z.req);return $(Y,z.env,z.executionContext)})}route(f,$){f=f&&f.length>0?f:$?.prefixApiUrl;let Z=$?.tempRoutes??new Map;for(let[J,z]of Z.entries()){let Q=J.replace(/::\w+$/,""),Y=`${f}${Q}`,X=z.handlers.slice(0,-1);this.router.addMiddleware(Y,...X);let W=z.handlers[z.handlers.length-1],H=z.method;try{this.router.add(H,Y,W)}catch(w){console.error(`Error inserting ${Y}:`,w)}}for(let[J,z]of $?.tempMiddlewares?.entries()){let Q=J==="/"?f||"/":`${f}${J}`;this.router.addMiddleware(Q,...z)}return $=null,this}register(f,$){return this.route(f,$)}addRoute(f,$,Z){if(typeof $!=="string")throw new Error(`Error in ${Z[Z.length-1]}: Path must be a string. Received: ${typeof $}`);if(typeof f!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof f}`);this.tempRoutes?.set($+"::"+f,{method:f,handlers:Z});let J=Z.slice(0,-1),z=Z[Z.length-1];if(J.length>0)J.forEach((Q)=>{this.router.addMiddleware($,Q);return});try{if(f==="ANY"){let Q=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let Y of Q)try{this.router.add(Y,$,z)}catch(X){}}else this.router.add(f,$,z)}catch(Q){console.error(`Error inserting ${$}:`,Q)}}use(f,...$){if(typeof f==="string"){let Z=f==="/"?"/":f;if(!this.tempMiddlewares?.has(Z))this.tempMiddlewares?.set(Z,[]);this.tempMiddlewares?.get(Z).push(...$),this.router.addMiddleware(Z,...$)}else if(typeof f==="function"){let Z=[f,...$];if(!this.tempMiddlewares?.has("/"))this.tempMiddlewares?.set("/",[]);this.tempMiddlewares?.get("/").push(...$);for(let J of Z)this.router.addMiddleware("/",J)}return this}routeNotFound(f){return this.routeNotFoundFunc=f,this}onMethod(f,$,...Z){let J=Array.isArray(f)?f:[f];for(let z of J){let Q=z.toLowerCase();if(Q in this)this[Q]($,...Z);else this.addRoute(z.toUpperCase(),$,Z)}return this}on(f,$){return this.emitter.on(f,$),this}emit(f,...$){return this.emitter.emit(f,...$),this}}export{A1 as default};
|
|
266
|
+
`)},r7=(f)=>{let{app:$,logger:Z,logLevel:J="info",onRequest:z,onSend:Q,onError:Y}=f||{};$?.addHooks("onRequest",(X)=>{X.req.startTime=Date.now(),Z?.()??f4(J,"Incoming Request",{method:X.req.method,url:X.path,headers:{"user-agent":X.req.headers.get("user-agent"),"content-type":X.req.headers.get("content-type")}}),z?.(X)}),$?.addHooks("onSend",async(X,W)=>{let H=`${Date.now()-X.req.startTime}ms`;Z?.()??f4(J,"Response Sent",{method:X.req.method,url:X.url.toString(),status:W.status,duration:H,reqId:X.get?.("requestId"),headers:{"content-type":W.headers.get("content-type")}});let w=await Q?.(X);if(w instanceof Response)return w}),$?.addHooks("onError",async(X,W,H)=>{Z?.()??f4("error","Unhandled Error",{method:H.method,url:W,status:500,error:X.message});let w=await Y?.(X,W,H);if(w instanceof Response)return w})},$4=(f,$,Z,J=0,z,Q)=>{let Y=D0.method[$]||D0.reset,X=J>=500?D0.error:J>=400?D0.warn:D0.info,W=Q?`[${Q}] `:"",H=f==="<--"?`${f} ${Y}${$}${D0.reset} ${Z} ${W}`:`${f} ${Y}${$}${D0.reset} ${Z} ${X}${J}${D0.reset} ${z??""} ${W}`;console.log(H)},m9=(f)=>{let $=Date.now()-f;return $<1000?`${$}ms`:`${Math.round($/1000)}s`},s7=(f)=>{let{app:$,log:Z,onRequest:J,onSend:z,onError:Q}=f;$.addHooks("onRequest",(Y)=>{let{req:X,path:W}=Y;X.startTime=Date.now(),Z?.()??$4("<--",X.method,W),J?.(X,W)}),$.addHooks("onSend",async(Y,X)=>{let{method:W,url:H}=Y.req,w=new URL(H).pathname,K=Y.get?.("requestId");Z?.()??$4("-->",W,w,X?.status,m9(Y.req.startTime),K);let O=await z?.(Y);return O instanceof Response?O:X}),$.addHooks("onError",async(Y,X,W)=>{let H=W.path;Z?.()??$4(Y.message,W.method,H,500);let w=await Q?.(Y,H,W);if(w instanceof Response)return w})};function a7(f,$){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(Z)=>{try{let J=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!J)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(J.startsWith("Bearer "))J=J.slice(7);let z=f?.verify(J,$);if(!z)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);Z.set("user",z)}catch(J){let z="Invalid token";if(J.name==="TokenExpiredError")z="Token expired";else if(J.name==="JsonWebTokenError")z="Malformed or tampered token";return Z.json({message:"Unauthorized",error:z},401)}}}function t7(f,$,Z){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!$)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(J)=>{try{let z=J.cookies?.accessToken??J.req?.headers?.get("Authorization");if(!z)return J.json({message:"Unauthorized",error:"No token provided"},401);if(z.startsWith("Bearer "))z=z.slice(7);let Q=f?.verify(z,Z);if(!Q)return J.json({message:"Unauthorized",error:"Token could not be decoded"},401);let Y=await $.findById(Q._id).select("-password -refreshToken");if(!Y)return J.json({message:"Unauthorized: User not found"},404);J.set("user",Y);return}catch(z){let Q="Invalid token";if(z.name==="TokenExpiredError")Q="Token expired";else if(z.name==="JsonWebTokenError")Q="Malformed or tampered token";return J.json({message:"Unauthorized",error:Q},401)}}}var d9=(f,$)=>{try{return $(f)}catch{return f.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return $(Z)}catch{return Z}})}},i9=(f)=>d9(f,decodeURI),$f=(f)=>{let $=f.indexOf("/",f.indexOf(":")+4),Z=$;for(;Z<f.length;Z++){let J=f.charCodeAt(Z);if(J===37){let z=f.indexOf("?",Z),Q=f.slice($,z===-1?void 0:z);return i9(Q.includes("%25")?Q.replace(/%25/g,"%2525"):Q)}else if(J===63)break}return f.slice($,Z)};var J4=Symbol.for,n0=Symbol("kCapture"),ZZ=J4("events.errorMonitor"),n9=Symbol("events.maxEventTargetListeners"),l9=Symbol("events.maxEventTargetListenersWarned"),e7=J4("nodejs.rejection"),p9=J4("nodejs.rejection"),fZ=Array.prototype.slice,l0=10,h0=function f($){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[n0]=$?.captureRejections?Boolean($?.captureRejections):W0[n0])this.emit=a9},W0=h0.prototype={};W0._events=void 0;W0._eventsCount=0;W0._maxListeners=void 0;W0.setMaxListeners=function f($){return z4($,"setMaxListeners",0),this._maxListeners=$,this};W0.constructor=h0;W0.getMaxListeners=function f(){return this?._maxListeners??l0};function JZ(f,$){var{_events:Z}=f;if($[0]??=new Error("Unhandled error."),!Z)throw $[0];var J=Z[ZZ];if(J)for(var z of fZ.call(J))z.apply(f,$);var Q=Z.error;if(!Q)throw $[0];for(var z of fZ.call(Q))z.apply(f,$);return!0}function o9(f,$,Z,J){$.then(void 0,function(z){queueMicrotask(()=>r9(f,z,Z,J))})}function r9(f,$,Z,J){if(typeof f[e7]==="function")f[e7]($,Z,...J);else try{f[n0]=!1,f.emit("error",$)}finally{f[n0]=!0}}var s9=function f($,...Z){if($==="error")return JZ(this,Z);var{_events:J}=this;if(J===void 0)return!1;var z=J[$];if(z===void 0)return!1;let Q=z.length>1?z.slice():z;for(let Y=0,{length:X}=Q;Y<X;Y++){let W=Q[Y];switch(Z.length){case 0:W.call(this);break;case 1:W.call(this,Z[0]);break;case 2:W.call(this,Z[0],Z[1]);break;case 3:W.call(this,Z[0],Z[1],Z[2]);break;default:W.apply(this,Z);break}}return!0},a9=function f($,...Z){if($==="error")return JZ(this,Z);var{_events:J}=this;if(J===void 0)return!1;var z=J[$];if(z===void 0)return!1;let Q=z.length>1?z.slice():z;for(let Y=0,{length:X}=Q;Y<X;Y++){let W=Q[Y],H;switch(Z.length){case 0:H=W.call(this);break;case 1:H=W.call(this,Z[0]);break;case 2:H=W.call(this,Z[0],Z[1]);break;case 3:H=W.call(this,Z[0],Z[1],Z[2]);break;default:H=W.apply(this,Z);break}if(H!==void 0&&typeof H?.then==="function"&&H.then===Promise.prototype.then)o9(this,H,$,Z)}return!0};W0.emit=s9;W0.addListener=function f($,Z){M1(Z);var J=this._events;if(!J)J=this._events={__proto__:null},this._eventsCount=0;else if(J.newListener)this.emit("newListener",$,Z.listener??Z);var z=J[$];if(!z)J[$]=[Z],this._eventsCount++;else{z.push(Z);var Q=this._maxListeners??l0;if(Q>0&&z.length>Q&&!z.warned)zZ(this,$,z)}return this};W0.on=W0.addListener;W0.prependListener=function f($,Z){M1(Z);var J=this._events;if(!J)J=this._events={__proto__:null},this._eventsCount=0;else if(J.newListener)this.emit("newListener",$,Z.listener??Z);var z=J[$];if(!z)J[$]=[Z],this._eventsCount++;else{z.unshift(Z);var Q=this._maxListeners??l0;if(Q>0&&z.length>Q&&!z.warned)zZ(this,$,z)}return this};function zZ(f,$,Z){Z.warned=!0;let J=new Error(`Possible EventEmitter memory leak detected. ${Z.length} ${String($)} listeners added to [${f.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);J.name="MaxListenersExceededWarning",J.emitter=f,J.type=$,J.count=Z.length,console.warn(J)}function QZ(f,$,...Z){this.removeListener(f,$),$.apply(this,Z)}W0.once=function f($,Z){M1(Z);let J=QZ.bind(this,$,Z);return J.listener=Z,this.addListener($,J),this};W0.prependOnceListener=function f($,Z){M1(Z);let J=QZ.bind(this,$,Z);return J.listener=Z,this.prependListener($,J),this};W0.removeListener=function f($,Z){M1(Z);var{_events:J}=this;if(!J)return this;var z=J[$];if(!z)return this;var Q=z.length;let Y=-1;for(let X=Q-1;X>=0;X--)if(z[X]===Z||z[X].listener===Z){Y=X;break}if(Y<0)return this;if(Y===0)z.shift();else z.splice(Y,1);if(z.length===0)delete J[$],this._eventsCount--;return this};W0.off=W0.removeListener;W0.removeAllListeners=function f($){var{_events:Z}=this;if($&&Z){if(Z[$])delete Z[$],this._eventsCount--}else this._events={__proto__:null};return this};W0.listeners=function f($){var{_events:Z}=this;if(!Z)return[];var J=Z[$];if(!J)return[];return J.map((z)=>z.listener??z)};W0.rawListeners=function f($){var{_events:Z}=this;if(!Z)return[];var J=Z[$];if(!J)return[];return J.slice()};W0.listenerCount=function f($){var{_events:Z}=this;if(!Z)return 0;return Z[$]?.length??0};W0.eventNames=function f(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};W0[n0]=!1;function t9(f,$,Z){var J=Z?.signal;if(YZ(J,"options.signal"),J?.aborted)throw new Z4(void 0,{cause:J?.reason});let{resolve:z,reject:Q,promise:Y}=$newPromiseCapability(Promise),X=(w)=>{if(f.removeListener($,W),J!=null)Zf(J,"abort",H);Q(w)},W=(...w)=>{if(typeof f.removeListener==="function")f.removeListener("error",X);if(J!=null)Zf(J,"abort",H);z(w)};if($Z(f,$,W,{once:!0}),$!=="error"&&typeof f.once==="function")f.once("error",X);function H(){Zf(f,$,W),Zf(f,"error",X),Q(new Z4(void 0,{cause:J?.reason}))}if(J!=null)$Z(J,"abort",H,{once:!0});return Y}function e9(f,$){return f.listeners($)}function f6(f,...$){z4(f,"setMaxListeners",0);var Z;if($&&(Z=$.length))for(let J=0;J<Z;J++)$[J].setMaxListeners(f);else l0=f}function $6(f,$){return f.listenerCount($)}function Zf(f,$,Z,J){if(typeof f.removeListener==="function")f.removeListener($,Z);else f.removeEventListener($,Z,J)}function $Z(f,$,Z,J){if(typeof f.on==="function")if(J.once)f.once($,Z);else f.on($,Z);else f.addEventListener($,Z,J)}class Z4 extends Error{constructor(f="The operation was aborted",$=void 0){if($!==void 0&&typeof $!=="object")throw z1("options","Object",$);super(f,$);this.code="ABORT_ERR",this.name="AbortError"}}function z1(f,$,Z){let J=new TypeError(`The "${f}" argument must be of type ${$}. Received ${Z}`);return J.code="ERR_INVALID_ARG_TYPE",J}function Z6(f,$,Z){let J=new RangeError(`The "${f}" argument is out of range. It must be ${$}. Received ${Z}`);return J.code="ERR_OUT_OF_RANGE",J}function YZ(f,$){if(f!==void 0&&(f===null||typeof f!=="object"||!("aborted"in f)))throw z1($,"AbortSignal",f)}function z4(f,$,Z,J){if(typeof f!=="number")throw z1($,"number",f);if(Z!=null&&f<Z||J!=null&&f>J||(Z!=null||J!=null)&&Number.isNaN(f))throw Z6($,`${Z!=null?`>= ${Z}`:""}${Z!=null&&J!=null?" && ":""}${J!=null?`<= ${J}`:""}`,f)}function M1(f){if(typeof f!=="function")throw new TypeError("The listener must be a function")}function J6(f,$){if(typeof f!=="boolean")throw z1($,"boolean",f)}function z6(f){return f?._maxListeners??l0}function Q6(f,$){if(f===void 0)throw z1("signal","AbortSignal",f);if(YZ(f,"signal"),typeof $!=="function")throw z1("listener","function",$);let Z;if(f.aborted)queueMicrotask(()=>$());else f.addEventListener("abort",$,{__proto__:null,once:!0}),Z=()=>{f.removeEventListener("abort",$)};return{__proto__:null,[Symbol.dispose](){Z?.()}}}Object.defineProperties(h0,{captureRejections:{get(){return W0[n0]},set(f){J6(f,"EventEmitter.captureRejections"),W0[n0]=f},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return l0},set:(f)=>{z4(f,"defaultMaxListeners",0),l0=f}},kMaxEventTargetListeners:{value:n9,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:l9,enumerable:!1,configurable:!1,writable:!1}});Object.assign(h0,{once:t9,getEventListeners:e9,getMaxListeners:z6,setMaxListeners:f6,EventEmitter:h0,usingDomains:!1,captureRejectionSymbol:p9,errorMonitor:ZZ,addAbortListener:Q6,init:h0,listenerCount:$6});class A1{static instance;routes;tempRoutes;tempMiddlewares=new Map;router;hasOnReqHook;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#f=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;get;post;put;patch;delete;any;head;options;propfind;constructor(f={}){o7.forEach((j)=>{this[j.toLocaleLowerCase()]=(M,...S)=>{return this.addRoute(j,M,S),this}});let{router:$="t2",routerInstance:Z,errorFormat:J="json",platform:z="bun",enableFileRouting:Q=!1,prefixApiUrl:Y="",baseApiUrl:X="",jwtSecret:W,idleTimeOut:H=10,pipelineArchitecture:w=!1,logger:K,onError:O}=f;if(Z)this.router=Z;else this.router=ef.create($);if(this.errorFormat=J,this.platform=z,!A1.instance)A1.instance=this;if(w)this.#f=!0;if(this.errorFormat=J,this.emitter=new h0,this.prefixApiUrl=Y??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=H??10,this.enableFileRouter=Q??!1,this.baseApiUrl=X||"",this.user_jwt_secret=W||process.env.DIESEL_JWT_SECRET||"default_diesel_secret_for_jwt",this.tempRoutes=new Map,this.corsConfig=null,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},O)this.addHooks("onError",(j,M)=>{console.log("Got an exception:",j),console.log("Request Path:",M)});if(K)this.useLogger({app:this});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router(f){if(!this.instance)this.instance=new A1;return new Proxy(this.instance,{get($,Z,J){return(z,Q)=>{let Y=f+z;return $[Z](Y,Q)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...f)=>{return this.FilterRoutes=f,this.setupFilter()},permitAll:()=>{for(let f of this?.FilterRoutes){if(f.endsWith("/"))f=f.slice(0,-1);this.filters.add(f)}return this.FilterRoutes=null,this.setupFilter()},authenticate:(f)=>{if(f?.length)for(let $ of f)this.filterFunction.push($)},authenticateJwt:(f)=>{this.filterFunction.push(a7(f,this.user_jwt_secret))},authenticateJwtDB:(f,$)=>{this.filterFunction.push(t7(f,$,this.user_jwt_secret))}}}redirect(f,$,Z){return this.any(f,(J)=>{let z=J.params,Q=$;if(z)for(let X in z)Q=Q.replace(`:${X}`,z[X]);let Y=J.url.search;if(Y)Q+=Y;return J.redirect(Q,Z)}),this}static(f,$){return this.staticPath=f,this.staticRequestPath=$,this}staticHtml(f){return this.staticFiles={...this.staticFiles,...f},this}addHooks(f,$){if(typeof f!=="string")throw new Error("hookName must be a string");if(typeof $!=="function")throw new Error("callback must be a instance of function");switch(f){case"onRequest":this.router.addMiddleware("/",$),this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler?.push($),this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler?.push($),this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend?.push($),this.hasOnSendHook=!0;break;case"onError":this.hooks.onError?.push($),this.hasOnError=!0;break;case"onClose":this.hooks.onClose?.push($);break;default:throw new Error(`Unknown hook type: ${f}`)}return this}useLogger(f){return s7(f),this}useAdvancedLogger(f){return r7(f),this}BunRoute(f,$,...Z){if(!$||typeof $!=="string")throw new Error("give a path in string format");let J;if(typeof Z[0]==="string"||typeof Z[0]==="object")J=Z[0];if(typeof J!=="undefined"){let Q=typeof J==="string"?J:JSON.stringify(J)}let z=i4(this,f.toUpperCase(),$,...Z);return this.routes[$]=z,this}listen(f,...$){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let Z="0.0.0.0",J=void 0,z={};for(let Y of $)if(typeof Y==="string")Z=Y;else if(typeof Y==="function")J=Y;else if(typeof Y==="object"&&Y!==null)z=Y;let Q={port:f,hostname:Z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)Q.routes=this.routes;if(z.cert&&z.key)Q.certFile=z.cert,Q.keyFile=z.key;return this.serverInstance=Bun?.serve(Q),J&&J(),this.serverInstance}close(f){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,f?f():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch(){return this.tempRoutes=null,this.tempMiddlewares=null,(f,$,Z)=>{return this.#$(f,void 0,$,Z)}}fetch(){if(this.tempRoutes=null,this.tempMiddlewares=null,this.platform==="cf"||this.platform==="cloudflare"){if(this.#f){let f=Ff(this);return($,Z,J)=>{return f($,this,void 0,Z,J).catch(async(z)=>{return this.handleError(z,$f($.url),$)})}}return(f,$,Z)=>{return this.#$(f,void 0,$,Z)}}if(this.#f){let f=Ff(this);return($,Z)=>{return f($,this,Z,void 0,void 0).catch(async(J)=>{return this.handleError(J,$f($.url),$)})}}return this.#$.bind(this)}async#$(f,$,Z,J){let z=$f(f.url),Q=this.router.find(f.method,z),Y=new V1(f,$,z,Q?.path,Q?.params,Z,J);try{if(this.hasFilterEnabled){let H=await N1(this,z,Y);if(H)return H}if(this.hasPreHandlerHook){let H=await r0("preHandler",this.hooks.preHandler,[Y]);if(H)return H}let X,W=Q?.handler;if(W.length===1){let H=W[0](Y);X=U1(H)?await H:H}else for(let H=0;H<W.length;H++){let w=W[H](Y);if(X=U1(w)?await w:w,X)break}if(this.hasOnSendHook){let H=await r0("onSend",this.hooks.onSend,[Y,X]);if(H)return H}if(X)return X;return await R1(this,Y,z)}catch(X){return this.handleError(X,z,f)}}async handleError(f,$,Z){let z=this.errorFormat,Q=await r0("onError",this.hooks.onError,[f,$,Z]);if(Q)return Q;if(f&&typeof f==="object"&&f.name==="HTTPException"){let W=f;if(console.error(`HTTPException on path: ${$}`,{status:W.status,message:W.message,cause:W.cause,res:W.res,stack:W.stack}),W.res)return W.res;return z==="json"?Response.json({error:W.message},{status:W.status}):new Response(W.message,{status:W.status})}let Y=f instanceof Error?f.message:"Internal Server Error",X=f instanceof Error?f.stack:void 0;if(console.error(`Error on path: ${$}`,{message:Y,stack:X}),z==="json"){let W={error:Y,...!1,path:$};return Response.json(W,{status:500,headers:{"Content-Type":"application/json"}})}else{let W=`Error: ${Y}`;return new Response(W,{headers:{"Content-Type":"text/plain"},status:500})}}mount(f,$){let Z=f.endsWith("/*")?f.slice(0,-1):f,J=Z==="/"?0:Z.length;this.any(f,(z)=>{let Q=new URL(z.req.url);Q.pathname=Q.pathname.slice(J)||"/";let Y=new Request(Q.toString(),z.req);return $(Y,z.env,z.executionContext)})}route(f,$){f=f&&f.length>0?f:$?.prefixApiUrl;let Z=$?.tempRoutes??new Map;for(let[J,z]of Z.entries()){let Q=J.replace(/::\w+$/,""),Y=`${f}${Q}`,X=z.handlers.slice(0,-1);this.router.addMiddleware(Y,...X);let W=z.handlers[z.handlers.length-1],H=z.method;try{this.router.add(H,Y,W)}catch(w){console.error(`Error inserting ${Y}:`,w)}}for(let[J,z]of $?.tempMiddlewares?.entries()){let Q=J==="/"?f||"/":`${f}${J}`;this.router.addMiddleware(Q,...z)}return $=null,this}register(f,$){return this.route(f,$)}addRoute(f,$,Z){if(typeof $!=="string")throw new Error(`Error in ${Z[Z.length-1]}: Path must be a string. Received: ${typeof $}`);if(typeof f!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof f}`);this.tempRoutes?.set($+"::"+f,{method:f,handlers:Z});let J=Z.slice(0,-1),z=Z[Z.length-1];if(J.length>0)J.forEach((Q)=>{this.router.addMiddleware($,Q);return});try{if(f==="ANY"){let Q=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let Y of Q)try{this.router.add(Y,$,z)}catch(X){}}else this.router.add(f,$,z)}catch(Q){console.error(`Error inserting ${$}:`,Q)}}use(f,...$){if(typeof f==="string"){let Z=f==="/"?"/":f;if(!this.tempMiddlewares?.has(Z))this.tempMiddlewares?.set(Z,[]);this.tempMiddlewares?.get(Z).push(...$),this.router.addMiddleware(Z,...$)}else if(typeof f==="function"){let Z=[f,...$];if(!this.tempMiddlewares?.has("/"))this.tempMiddlewares?.set("/",[]);this.tempMiddlewares?.get("/").push(...$);for(let J of Z)this.router.addMiddleware("/",J)}return this}routeNotFound(f){return this.routeNotFoundFunc=f,this}onMethod(f,$,...Z){let J=Array.isArray(f)?f:[f];for(let z of J){let Q=z.toLowerCase();if(Q in this)this[Q]($,...Z);else this.addRoute(z.toUpperCase(),$,Z)}return this}on(f,$){return this.emitter.on(f,$),this}emit(f,...$){return this.emitter.emit(f,...$),this}}export{A1 as default};
|
package/package.json
CHANGED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|