diesel-core 1.5.4 → 1.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/handleRequest.js +11 -11
- package/dist/main.d.ts +11 -7
- package/dist/main.js +35 -35
- package/dist/request_pipeline.js +37 -37
- package/dist/router/regex.d.ts +2 -0
- package/dist/types.d.ts +8 -7
- package/dist/utils/request.util.js +1 -1
- package/package.json +1 -1
package/dist/handleRequest.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var bf=Object.create;var{getPrototypeOf:
|
|
1
|
+
var bf=Object.create;var{getPrototypeOf:qf,defineProperty:M,getOwnPropertyNames:m,getOwnPropertyDescriptor:Tf}=Object,i=Object.prototype.hasOwnProperty;var _f=(f,w,g)=>{g=f!=null?bf(qf(f)):{};let A=w||!f||!f.__esModule?M(g,"default",{value:f,enumerable:!0}):g;for(let $ of m(f))if(!i.call(A,$))M(A,$,{get:()=>f[$],enumerable:!0});return A},u=new WeakMap,Pf=(f)=>{var w=u.get(f),g;if(w)return w;if(w=M({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")m(f).map((A)=>!i.call(w,A)&&M(w,A,{get:()=>f[A],enumerable:!(g=Tf(f,A))||g.enumerable}));return u.set(f,w),w},S=(f,w)=>()=>(w||f((w={exports:{}}).exports,w),w.exports);var If=(f,w)=>{for(var g in w)M(f,g,{get:w[g],enumerable:!0,configurable:!0,set:(A)=>w[g]=()=>A})};var cf=(f,w)=>()=>(f&&(w=f(f=0)),w);var xf=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(w,g)=>(typeof require!=="undefined"?require:w)[g]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var Af={};If(Af,{sep:()=>ff,resolve:()=>H,relative:()=>l,posix:()=>wf,parse:()=>e,normalize:()=>b,join:()=>d,isAbsolute:()=>r,format:()=>t,extname:()=>a,dirname:()=>s,delimiter:()=>gf,default:()=>kf,basename:()=>p,_makeLong:()=>o});function j(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function n(f,w){var g="",A=0,$=-1,z=0,Y;for(var Z=0;Z<=f.length;++Z){if(Z<f.length)Y=f.charCodeAt(Z);else if(Y===47)break;else Y=47;if(Y===47){if($===Z-1||z===1);else if($!==Z-1&&z===2){if(g.length<2||A!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var C=g.lastIndexOf("/");if(C!==g.length-1){if(C===-1)g="",A=0;else g=g.slice(0,C),A=g.length-1-g.lastIndexOf("/");$=Z,z=0;continue}}else if(g.length===2||g.length===1){g="",A=0,$=Z,z=0;continue}}if(w){if(g.length>0)g+="/..";else g="..";A=2}}else{if(g.length>0)g+="/"+f.slice($+1,Z);else g=f.slice($+1,Z);A=Z-$-1}$=Z,z=0}else if(Y===46&&z!==-1)++z;else z=-1}return g}function yf(f,w){var g=w.dir||w.root,A=w.base||(w.name||"")+(w.ext||"");if(!g)return A;if(g===w.root)return g+A;return g+f+A}function H(){var f="",w=!1,g;for(var A=arguments.length-1;A>=-1&&!w;A--){var $;if(A>=0)$=arguments[A];else{if(g===void 0)g=process.cwd();$=g}if(j($),$.length===0)continue;f=$+"/"+f,w=$.charCodeAt(0)===47}if(f=n(f,!w),w)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function b(f){if(j(f),f.length===0)return".";var w=f.charCodeAt(0)===47,g=f.charCodeAt(f.length-1)===47;if(f=n(f,!w),f.length===0&&!w)f=".";if(f.length>0&&g)f+="/";if(w)return"/"+f;return f}function r(f){return j(f),f.length>0&&f.charCodeAt(0)===47}function d(){if(arguments.length===0)return".";var f;for(var w=0;w<arguments.length;++w){var g=arguments[w];if(j(g),g.length>0)if(f===void 0)f=g;else f+="/"+g}if(f===void 0)return".";return b(f)}function l(f,w){if(j(f),j(w),f===w)return"";if(f=H(f),w=H(w),f===w)return"";var g=1;for(;g<f.length;++g)if(f.charCodeAt(g)!==47)break;var A=f.length,$=A-g,z=1;for(;z<w.length;++z)if(w.charCodeAt(z)!==47)break;var Y=w.length,Z=Y-z,C=$<Z?$:Z,X=-1,J=0;for(;J<=C;++J){if(J===C){if(Z>C){if(w.charCodeAt(z+J)===47)return w.slice(z+J+1);else if(J===0)return w.slice(z+J)}else if($>C){if(f.charCodeAt(g+J)===47)X=J;else if(J===0)X=0}break}var W=f.charCodeAt(g+J),V=w.charCodeAt(z+J);if(W!==V)break;else if(W===47)X=J}var F="";for(J=g+X+1;J<=A;++J)if(J===A||f.charCodeAt(J)===47)if(F.length===0)F+="..";else F+="/..";if(F.length>0)return F+w.slice(z+X);else{if(z+=X,w.charCodeAt(z)===47)++z;return w.slice(z)}}function o(f){return f}function s(f){if(j(f),f.length===0)return".";var w=f.charCodeAt(0),g=w===47,A=-1,$=!0;for(var z=f.length-1;z>=1;--z)if(w=f.charCodeAt(z),w===47){if(!$){A=z;break}}else $=!1;if(A===-1)return g?"/":".";if(g&&A===1)return"//";return f.slice(0,A)}function p(f,w){if(w!==void 0&&typeof w!=="string")throw new TypeError('"ext" argument must be a string');j(f);var g=0,A=-1,$=!0,z;if(w!==void 0&&w.length>0&&w.length<=f.length){if(w.length===f.length&&w===f)return"";var Y=w.length-1,Z=-1;for(z=f.length-1;z>=0;--z){var C=f.charCodeAt(z);if(C===47){if(!$){g=z+1;break}}else{if(Z===-1)$=!1,Z=z+1;if(Y>=0)if(C===w.charCodeAt(Y)){if(--Y===-1)A=z}else Y=-1,A=Z}}if(g===A)A=Z;else if(A===-1)A=f.length;return f.slice(g,A)}else{for(z=f.length-1;z>=0;--z)if(f.charCodeAt(z)===47){if(!$){g=z+1;break}}else if(A===-1)$=!1,A=z+1;if(A===-1)return"";return f.slice(g,A)}}function a(f){j(f);var w=-1,g=0,A=-1,$=!0,z=0;for(var Y=f.length-1;Y>=0;--Y){var Z=f.charCodeAt(Y);if(Z===47){if(!$){g=Y+1;break}continue}if(A===-1)$=!1,A=Y+1;if(Z===46){if(w===-1)w=Y;else if(z!==1)z=1}else if(w!==-1)z=-1}if(w===-1||A===-1||z===0||z===1&&w===A-1&&w===g+1)return"";return f.slice(w,A)}function t(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return yf("/",f)}function e(f){j(f);var w={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return w;var g=f.charCodeAt(0),A=g===47,$;if(A)w.root="/",$=1;else $=0;var z=-1,Y=0,Z=-1,C=!0,X=f.length-1,J=0;for(;X>=$;--X){if(g=f.charCodeAt(X),g===47){if(!C){Y=X+1;break}continue}if(Z===-1)C=!1,Z=X+1;if(g===46){if(z===-1)z=X;else if(J!==1)J=1}else if(z!==-1)J=-1}if(z===-1||Z===-1||J===0||J===1&&z===Z-1&&z===Y+1){if(Z!==-1)if(Y===0&&A)w.base=w.name=f.slice(1,Z);else w.base=w.name=f.slice(Y,Z)}else{if(Y===0&&A)w.name=f.slice(1,z),w.base=f.slice(1,Z);else w.name=f.slice(Y,z),w.base=f.slice(Y,Z);w.ext=f.slice(z,Z)}if(Y>0)w.dir=f.slice(0,Y-1);else if(A)w.dir="/";return w}var ff="/",gf=":",wf,kf;var $f=cf(()=>{wf=((f)=>(f.posix=f,f))({resolve:H,normalize:b,isAbsolute:r,join:d,relative:l,_makeLong:o,dirname:s,basename:p,extname:a,format:t,parse:e,sep:ff,delimiter:gf,win32:null,posix:null}),kf=wf});var Yf=S((lf)=>{var hf=/[|\\{}()[\]^$+*?.]/g,uf=Object.prototype.hasOwnProperty,T=function(f,w){return uf.apply(f,[w])};lf.escapeRegExpChars=function(f){if(!f)return"";return String(f).replace(hf,"\\$&")};var mf={"&":"&","<":"<",">":">",'"':""","'":"'"},nf=/[&<>'"]/g;function rf(f){return mf[f]||f}var df=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -10,16 +10,16 @@ function encode_char(c) {
|
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
12
|
`;lf.escapeXML=function(f){return f==null?"":String(f).replace(nf,rf)};function zf(){return Function.prototype.toString.call(this)+`;
|
|
13
|
-
`+df}try{if(typeof Object.defineProperty==="function")Object.defineProperty(lf.escapeXML,"toString",{value:zf});else lf.escapeXML.toString=zf}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}lf.shallowCopy=function(f,w){if(w=w||{},f!==null&&f!==void 0)for(var g in w){if(!
|
|
14
|
-
`),Y=Math.max(A-3,0),Z=Math.min(z.length,A+3),C=$(g),
|
|
13
|
+
`+df}try{if(typeof Object.defineProperty==="function")Object.defineProperty(lf.escapeXML,"toString",{value:zf});else lf.escapeXML.toString=zf}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}lf.shallowCopy=function(f,w){if(w=w||{},f!==null&&f!==void 0)for(var g in w){if(!T(w,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=w[g]}return f};lf.shallowCopyFromList=function(f,w,g){if(g=g||[],w=w||{},f!==null&&f!==void 0)for(var A=0;A<g.length;A++){var $=g[A];if(typeof w[$]!="undefined"){if(!T(w,$))continue;if($==="__proto__"||$==="constructor")continue;f[$]=w[$]}}return f};lf.cache={_data:{},set:function(f,w){this._data[f]=w},get:function(f){return this._data[f]},remove:function(f){delete this._data[f]},reset:function(){this._data={}}};lf.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(w){return w[1].toUpperCase()})};lf.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();lf.hasOwnOnlyObject=function(f){var w=lf.createNullProtoObjWherePossible();for(var g in f)if(T(f,g))w[g]=f[g];return w}});var Zf=S((O1,f1)=>{f1.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var Uf=S((jf)=>{var I=(()=>({})),N=($f(),Pf(Af)),G=Yf(),Vf=!1,g1=Zf().version,w1="<",A1=">",$1="%",Qf="locals",z1="ejs",J1="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",Bf=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],Y1=Bf.concat("cache"),Cf=/^\uFEFF/,_=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;jf.cache=G.cache;jf.fileLoader=I.readFileSync;jf.localsName=Qf;jf.promiseImpl=new Function("return this;")().Promise;jf.resolveInclude=function(f,w,g){var{dirname:A,extname:$,resolve:z}=N,Y=z(g?w:A(w),f),Z=$(f);if(!Z)Y+=".ejs";return Y};function Wf(f,w){var g;if(w.some(function(A){return g=jf.resolveInclude(f,A,!0),I.existsSync(g)}))return g}function Z1(f,w){var g,A,$=w.views,z=/^[A-Za-z]+:\\|^\//.exec(f);if(z&&z.length)if(f=f.replace(/^\/*/,""),Array.isArray(w.root))g=Wf(f,w.root);else g=jf.resolveInclude(f,w.root||"/",!0);else{if(w.filename){if(A=jf.resolveInclude(f,w.filename),I.existsSync(A))g=A}if(!g&&Array.isArray($))g=Wf(f,$);if(!g&&typeof w.includer!=="function")throw new Error('Could not find the include file "'+w.escapeFunction(f)+'"')}return g}function U(f,w){var g,A=f.filename,$=arguments.length>1;if(f.cache){if(!A)throw new Error("cache option requires a filename");if(g=jf.cache.get(A),g)return g;if(!$)w=Xf(A).toString().replace(Cf,"")}else if(!$){if(!A)throw new Error("Internal EJS error: no file name or template provided");w=Xf(A).toString().replace(Cf,"")}if(g=jf.compile(w,f),f.cache)jf.cache.set(A,g);return g}function V1(f,w,g){var A;if(!g)if(typeof jf.promiseImpl=="function")return new jf.promiseImpl(function($,z){try{A=U(f)(w),$(A)}catch(Y){z(Y)}});else throw new Error("Please provide a callback function");else{try{A=U(f)(w)}catch($){return g($)}g(null,A)}}function Xf(f){return jf.fileLoader(f)}function C1(f,w){var g=G.shallowCopy(G.createNullProtoObjWherePossible(),w);if(g.filename=Z1(f,g),typeof w.includer==="function"){var A=w.includer(f,g.filename);if(A){if(A.filename)g.filename=A.filename;if(A.template)return U(g,A.template)}}return U(g)}function Ff(f,w,g,A,$){var z=w.split(`
|
|
14
|
+
`),Y=Math.max(A-3,0),Z=Math.min(z.length,A+3),C=$(g),X=z.slice(Y,Z).map(function(J,W){var V=W+Y+1;return(V==A?" >> ":" ")+V+"| "+J}).join(`
|
|
15
15
|
`);throw f.path=C,f.message=(C||"ejs")+":"+A+`
|
|
16
|
-
`+
|
|
16
|
+
`+X+`
|
|
17
17
|
|
|
18
|
-
`+f.message,f}function
|
|
18
|
+
`+f.message,f}function Gf(f){return f.replace(/;(\s*$)/,"$1")}jf.compile=function f(w,g){var A;if(g&&g.scope){if(!Vf)console.warn("`scope` option is deprecated and will be removed in EJS 3"),Vf=!0;if(!g.context)g.context=g.scope;delete g.scope}return A=new Q(w,g),A.compile()};jf.render=function(f,w,g){var A=w||G.createNullProtoObjWherePossible(),$=g||G.createNullProtoObjWherePossible();if(arguments.length==2)G.shallowCopyFromList($,A,Bf);return U($,f)(A)};jf.renderFile=function(){var f=Array.prototype.slice.call(arguments),w=f.shift(),g,A={filename:w},$,z;if(typeof arguments[arguments.length-1]=="function")g=f.pop();if(f.length){if($=f.shift(),f.length)G.shallowCopy(A,f.pop());else{if($.settings){if($.settings.views)A.views=$.settings.views;if($.settings["view cache"])A.cache=!0;if(z=$.settings["view options"],z)G.shallowCopy(A,z)}G.shallowCopyFromList(A,$,Y1)}A.filename=w}else $=G.createNullProtoObjWherePossible();return V1(A,$,g)};jf.Template=Q;jf.clearCache=function(){jf.cache.reset()};function Q(f,w){var g=G.hasOwnOnlyObject(w),A=G.createNullProtoObjWherePossible();if(this.templateText=f,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",A.client=g.client||!1,A.escapeFunction=g.escape||g.escapeFunction||G.escapeXML,A.compileDebug=g.compileDebug!==!1,A.debug=!!g.debug,A.filename=g.filename,A.openDelimiter=g.openDelimiter||jf.openDelimiter||w1,A.closeDelimiter=g.closeDelimiter||jf.closeDelimiter||A1,A.delimiter=g.delimiter||jf.delimiter||$1,A.strict=g.strict||!1,A.context=g.context,A.cache=g.cache||!1,A.rmWhitespace=g.rmWhitespace,A.root=g.root,A.includer=g.includer,A.outputFunctionName=g.outputFunctionName,A.localsName=g.localsName||jf.localsName||Qf,A.views=g.views,A.async=g.async,A.destructuredLocals=g.destructuredLocals,A.legacyInclude=typeof g.legacyInclude!="undefined"?!!g.legacyInclude:!0,A.strict)A._with=!1;else A._with=typeof g._with!="undefined"?g._with:!0;this.opts=A,this.regex=this.createRegex()}Q.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Q.prototype={createRegex:function(){var f=J1,w=G.escapeRegExpChars(this.opts.delimiter),g=G.escapeRegExpChars(this.opts.openDelimiter),A=G.escapeRegExpChars(this.opts.closeDelimiter);return f=f.replace(/%/g,w).replace(/</g,g).replace(/>/g,A),new RegExp(f)},compile:function(){var f,w,g=this.opts,A="",$="",z=g.escapeFunction,Y,Z=g.filename?JSON.stringify(g.filename):"undefined";if(!this.source){if(this.generateSource(),A+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
20
|
`,g.outputFunctionName){if(!_.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");A+=" var "+g.outputFunctionName+` = __append;
|
|
21
21
|
`}if(g.localsName&&!_.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var C=" var __locals = ("+g.localsName+` || {}),
|
|
22
|
-
`;for(var
|
|
22
|
+
`;for(var X=0;X<g.destructuredLocals.length;X++){var J=g.destructuredLocals[X];if(!_.test(J))throw new Error("destructuredLocals["+X+"] is not a valid JS identifier.");if(X>0)C+=`,
|
|
23
23
|
`;C+=J+" = __locals."+J}A+=C+`;
|
|
24
24
|
`}if(g._with!==!1)A+=" with ("+g.localsName+` || {}) {
|
|
25
25
|
`,$+=` }
|
|
@@ -32,7 +32,7 @@ try {
|
|
|
32
32
|
rethrow(e, __lines, __filename, __line, escapeFn);
|
|
33
33
|
}
|
|
34
34
|
`;else f=this.source;if(g.client){if(f="escapeFn = escapeFn || "+z.toString()+`;
|
|
35
|
-
`+f,g.compileDebug)f="rethrow = rethrow || "+
|
|
35
|
+
`+f,g.compileDebug)f="rethrow = rethrow || "+Ff.toString()+`;
|
|
36
36
|
`+f}if(g.strict)f=`"use strict";
|
|
37
37
|
`+f;if(g.debug)console.log(f);if(g.compileDebug&&g.filename)f=f+`
|
|
38
38
|
//# sourceURL=`+Z+`
|
|
@@ -40,7 +40,7 @@ try {
|
|
|
40
40
|
|
|
41
41
|
`,B.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
42
|
`,B.message+="https://github.com/RyanZim/EJS-Lint",!g.async)B.message+=`
|
|
43
|
-
`,B.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw B}var
|
|
43
|
+
`,B.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw B}var W=g.client?w:function B(K){var O=function(Sf,h){var E=G.shallowCopy(G.createNullProtoObjWherePossible(),K);if(h)E=G.shallowCopy(E,h);return C1(Sf,g)(E)};return w.apply(g.context,[K||G.createNullProtoObjWherePossible(),z,O,Ff])};if(g.filename&&typeof Object.defineProperty==="function"){var V=g.filename,F=N.basename(V,N.extname(V));try{Object.defineProperty(W,"name",{value:F,writable:!1,enumerable:!1,configurable:!0})}catch(B){}}return W},generateSource:function(){var f=this.opts;if(f.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
44
|
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var w=this,g=this.parseTemplateText(),A=this.opts.delimiter,$=this.opts.openDelimiter,z=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(Y,Z){var C;if(Y.indexOf($+A)===0&&Y.indexOf($+A+A)!==0){if(C=g[Z+2],!(C==A+z||C=="-"+A+z||C=="_"+A+z))throw new Error('Could not find matching close tag for "'+Y+'".')}w.scanLine(Y)})},parseTemplateText:function(){var f=this.templateText,w=this.regex,g=w.exec(f),A=[],$;while(g){if($=g.index,$!==0)A.push(f.substring(0,$)),f=f.slice($);A.push(g[0]),f=f.slice(g[0].length),g=w.exec(f)}if(f)A.push(f);return A},_addOutput:function(f){if(this.truncate)f=f.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!f)return f;f=f.replace(/\\/g,"\\\\"),f=f.replace(/\n/g,"\\n"),f=f.replace(/\r/g,"\\r"),f=f.replace(/"/g,"\\\""),this.source+=' ; __append("'+f+`")
|
|
45
45
|
`},scanLine:function(f){var w=this,g=this.opts.delimiter,A=this.opts.openDelimiter,$=this.opts.closeDelimiter,z=0;switch(z=f.split(`
|
|
46
46
|
`).length-1,f){case A+g:case A+g+"_":this.mode=Q.modes.EVAL;break;case A+g+"=":this.mode=Q.modes.ESCAPED;break;case A+g+"-":this.mode=Q.modes.RAW;break;case A+g+"#":this.mode=Q.modes.COMMENT;break;case A+g+g:this.mode=Q.modes.LITERAL,this.source+=' ; __append("'+f.replace(A+g+g,A+g)+`")
|
|
@@ -48,7 +48,7 @@ try {
|
|
|
48
48
|
`;break;case g+$:case"-"+g+$:case"_"+g+$:if(this.mode==Q.modes.LITERAL)this._addOutput(f);this.mode=null,this.truncate=f.indexOf("-")===0||f.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Q.modes.EVAL:case Q.modes.ESCAPED:case Q.modes.RAW:if(f.lastIndexOf("//")>f.lastIndexOf(`
|
|
49
49
|
`))f+=`
|
|
50
50
|
`}switch(this.mode){case Q.modes.EVAL:this.source+=" ; "+f+`
|
|
51
|
-
`;break;case Q.modes.ESCAPED:this.source+=" ; __append(escapeFn("+
|
|
52
|
-
`;break;case Q.modes.RAW:this.source+=" ; __append("+
|
|
51
|
+
`;break;case Q.modes.ESCAPED:this.source+=" ; __append(escapeFn("+Gf(f)+`))
|
|
52
|
+
`;break;case Q.modes.RAW:this.source+=" ; __append("+Gf(f)+`)
|
|
53
53
|
`;break;case Q.modes.COMMENT:break;case Q.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(w.opts.compileDebug&&z)this.currentLine+=z,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
-
`}};jf.escapeXML=
|
|
54
|
+
`}};jf.escapeXML=G.escapeXML;jf.__express=jf.renderFile;jf.VERSION=g1;jf.name=z1;if(typeof window!="undefined")window.ejs=jf});function R(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var c=null;async function Kf(){if(!c){let f=await Promise.resolve().then(() => _f(Uf(),1));c=f.default||f}return c}class x{req;server;pathname;routePattern;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,w,g,A=""){this.req=f,this.server=w,this.pathname=g,this.routePattern=A}setHeader(f,w){return this.headers.set(f,w),this}removeHeader(f){return this.headers.delete(f),this}set(f,w){return this.contextData[f]=w,this}get(f){return this.contextData[f]}get ip(){return this.server.requestIP(this.req)?.address??null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=Df(this.routePattern,this.pathname)}catch(f){let w=f instanceof Error?f.message:String(f);throw new Error(`Failed to extract route parameters: ${w}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let f=await Lf(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f}catch(f){throw new Error("Invalid request body format")}})();return this.parsedBody}text(f,w=200){return new Response(f,{status:w,headers:this.headers})}send(f,w=200){let g;if(f instanceof Uint8Array)g="Uint8Array";else if(f instanceof ArrayBuffer)g="ArrayBuffer";else g=typeof f;let A=g==="object"&&f!==null?JSON.stringify(f):f;return new Response(A,{status:w,headers:this.headers})}json(f,w=200){return Response.json(f,{status:w,headers:this.headers})}file(f,w,g=200){let A=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",w??R(f));return new Response(A,{status:g,headers:this.headers})}async ejs(f,w={},g=200){let A=await Kf();try{let $=await Bun.file(f).text(),z=A.render($,w),Y=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(z,{status:g,headers:Y})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}}redirect(f,w=302){return this.headers.set("Location",f),new Response(null,{status:w,headers:this.headers})}setCookie(f,w,g={}){let A=`${encodeURIComponent(f)}=${encodeURIComponent(w)}`;if(g.maxAge)A+=`; Max-Age=${g.maxAge}`;if(g.expires)A+=`; Expires=${g.expires.toUTCString()}`;if(g.path)A+=`; Path=${g.path}`;if(g.domain)A+=`; Domain=${g.domain}`;if(g.secure)A+="; Secure";if(g.httpOnly)A+="; HttpOnly";if(g.sameSite)A+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",A),this}get cookies(){if(!this.parsedCookies){let f=this.req.headers.get("cookie");this.parsedCookies=f?Hf(f):{}}return this.parsedCookies}stream(f){let w=new Headers(this.headers),g=new ReadableStream({async start(A){await f(A),A.close()}});return new Response(g,{headers:w})}yieldStream(f){return new Response}}function R1(f,w,g,A){let $=null,z=null,Y=null,Z=null,C={},X=null;return{req:f,server:w,pathname:g,headers:new Headers,setHeader(J,W){return this.headers.set(J,W),this},removeHeader(J){return this.headers.delete(J),this},set(J,W){return C[J]=W,this},get(J){return C[J]},get ip(){return this.server.requestIP(f)?.address??null},get url(){if(!X)X=new URL(f.url);return X},get query(){if(!$){if(!this.url.search)return{};$=Object.fromEntries(this.url.searchParams)}return $},get params(){if(!z&&A)try{z=Df(A,g)}catch(J){let W=J instanceof Error?J.message:String(J);throw new Error(`Failed to extract route parameters: ${W}`)}return z??{}},get body(){if(f.method==="GET")return Promise.resolve({});if(!Z)Z=(async()=>{try{let J=await Lf(f);if(J.error)throw new Error(J.error);return Object.keys(J).length===0?null:J}catch(J){throw new Error("Invalid request body format")}})();return Z},text(J,W=200){return new Response(J,{status:W,headers:this.headers})},send(J,W=200){let V;if(J instanceof Uint8Array)V="Uint8Array";else if(J instanceof ArrayBuffer)V="ArrayBuffer";else V=typeof J;let F=V==="object"&&J!==null?JSON.stringify(J):J;return new Response(F,{status:W,headers:this.headers})},json(J,W=200){return Response.json(J,{status:W,headers:this.headers})},file(J,W,V=200){let F=Bun.file(J);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",W??R(J));return new Response(F,{status:V,headers:this.headers})},async ejs(J,W={},V=200){let F=await Kf();try{let B=await Bun.file(J).text(),K=F.render(B,W),O=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(K,{status:V,headers:O})}catch(B){return console.error("EJS Rendering Error:",B),new Response("Error rendering template",{status:500})}},redirect(J,W=302){return this.headers.set("Location",J),new Response(null,{status:W,headers:this.headers})},stream(J){let W=new Headers(this.headers),V=new ReadableStream({async start(F){await J(F),F.close()}});return new Response(V,{headers:W})},yieldStream(J){return new Response("not working stream yet.")},setCookie(J,W,V={}){let F=`${encodeURIComponent(J)}=${encodeURIComponent(W)}`;if(V.maxAge)F+=`; Max-Age=${V.maxAge}`;if(V.expires)F+=`; Expires=${V.expires.toUTCString()}`;if(V.path)F+=`; Path=${V.path}`;if(V.domain)F+=`; Domain=${V.domain}`;if(V.secure)F+="; Secure";if(V.httpOnly)F+="; HttpOnly";if(V.sameSite)F+=`; SameSite=${V.sameSite}`;return this.headers.append("Set-Cookie",F),this},get cookies(){if(!Y){let J=this.req.headers.get("cookie");Y=J?Hf(J):{}}return Y}}}function Hf(f){return Object.fromEntries(f.split(";").map((w)=>{let[g,...A]=w.trim().split("=");return[g,decodeURIComponent(A.join("="))]}))}function Df(f,w){let g={},A=f.split("/"),[$]=w.split("?"),z=$.split("/");if(A.length!==z.length)return null;for(let Y=0;Y<A.length;Y++){let Z=A[Y];if(Z.charCodeAt(0)===58)g[Z.slice(1)]=z[Y]}return g}async function Lf(f){let w=f.headers.get("Content-Type")||"";if(!w)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};if(w.startsWith("application/json"))return await f.json();if(w.startsWith("application/x-www-form-urlencoded")){let A=await f.text();return Object.fromEntries(new URLSearchParams(A))}if(w.startsWith("multipart/form-data")){let A=await f.formData(),$={};for(let[z,Y]of A.entries())$[z]=Y;return $}return{error:"Unknown request body type"}}var N1=(f,w)=>{try{return w(f)}catch{return f.replace(/(?:%[0-9A-Fa-f]{2})+/g,(g)=>{try{return w(g)}catch{return g}})}},y=(f)=>N1(f,decodeURI),P1=(f)=>{let w=f.indexOf("/",f.indexOf(":")+4),g=w;for(;g<f.length;g++){let A=f.charCodeAt(g);if(A===37){let $=f.indexOf("?",g),z=f.slice(w,$===-1?void 0:$);return y(z.includes("%25")?z.replace(/%25/g,"%2525"):z)}else if(A===63)break}return f.slice(w,g)};async function v(f,w,g){if(!w?.length)return;for(let A=0;A<w.length;A++){let $=w[A](...g),z=$ instanceof Promise?await $:$;if(z&&f!=="onRequest")return z}}async function vf(f,w,g){let A=f.globalMiddlewares;if(A.length)for(let z of A){let Y=await z(g);if(Y)return Y}let $=f.middlewares.get(w);if($&&$.length)for(let z of $){let Y=await z(g);if(Y)return Y}return null}async function x1(f,w,g){for(let A of f){let $=await A(w,g);if($)return $}}async function Of(f,w,g){let A=await U1(f,w,g),$=A instanceof Promise?await A:A;if($)return $}async function U1(f,w,g){if(w.endsWith("/"))w=w.slice(0,-1);if(!f.filters.has(w))if(f.filterFunction.length)for(let A of f.filterFunction){let $=await A(g);if($)return $}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function Ef(f,w,g){if(f.staticPath){let $=!0;if(f.staticRequestPath)$=g.startsWith(f.staticRequestPath);if($){let z=await K1(f,g,w);if(z)return z;let Y=f.trie.search("*",w.req.method);if(Y?.handler)return await Y.handler(w)}}let A=f.routeNotFoundFunc(w);return A instanceof Promise?await A:A||k(404,`404 Route not found for ${g}`)}function k(f,w){return new Response(JSON.stringify({error:w}),{status:f,headers:{"Content-Type":"application/json"}})}async function K1(f,w,g){if(!f.staticPath)return null;let A=`${f.staticPath}${w}`;if(await Bun.file(A).exists()){let z=R(A);return g.file(A,z,200)}return null}async function H1(f,w,g){let A,$=f.url.indexOf("/",f.url.indexOf(":")+4),z=$;for(;z<f.url.length;z++){let J=f.url.charCodeAt(z);if(J===37){let W=f.url.indexOf("?",z),V=f.url.slice($,W===-1?void 0:W);A=y(V.includes("%25")?V.replace(/%25/g,"%2525"):V);break}else if(J===63)break}if(!A)A=f.url.slice($,z);let Y=g.trie.search(A,f.method),Z=new x(f,w,A,Y?.path);if(g.hasOnReqHook)await v("onRequest",g.hooks.onRequest,[f,A,w]);if(g.hasMiddleware){let J=await vf(g,A,Z);if(J)return J}if(g.hasFilterEnabled){let J=await Of(g,A,Z);if(J)return J}if(!Y)return await Ef(g,Z,A);if(g.hasPreHandlerHook){let J=await v("preHandler",g.hooks.preHandler,[Z]);if(J)return J}let C=Y.handler(Z),X=C instanceof Promise?await C:C;if(g.hasOnSendHook){let J=await v("onSend",g.hooks.onSend,[Z,X]);if(J)return J}if(X instanceof Response)return X;return k(500,"No response returned from handler.")}export{H1 as default};
|
package/dist/main.d.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { CompileConfig, ContextType, corsT, FilterMethods, HookType, listenArgsT
|
|
|
3
3
|
import { Server } from "bun";
|
|
4
4
|
import { AdvancedLoggerOptions, LoggerOptions } from "./middlewares/logger/logger.js";
|
|
5
5
|
import { EventEmitter } from 'events';
|
|
6
|
+
type errorFormat = 'json' | 'text' | 'html' | string;
|
|
6
7
|
export default class Diesel {
|
|
8
|
+
#private;
|
|
7
9
|
private static instance;
|
|
8
10
|
fecth: any;
|
|
9
11
|
routes: Record<string, Function>;
|
|
@@ -24,7 +26,6 @@ export default class Diesel {
|
|
|
24
26
|
filterFunction: Function[];
|
|
25
27
|
private hasFilterEnabled;
|
|
26
28
|
private serverInstance;
|
|
27
|
-
staticPath: any;
|
|
28
29
|
staticFiles: any;
|
|
29
30
|
user_jwt_secret: string;
|
|
30
31
|
private baseApiUrl;
|
|
@@ -33,10 +34,11 @@ export default class Diesel {
|
|
|
33
34
|
routeNotFoundFunc: (c: ContextType) => void | Promise<void> | Promise<Response> | Response;
|
|
34
35
|
private prefixApiUrl;
|
|
35
36
|
compileConfig: CompileConfig | null;
|
|
36
|
-
private newPipelineArchitecture;
|
|
37
37
|
emitter: EventEmitter;
|
|
38
|
-
errorFormat:
|
|
39
|
-
|
|
38
|
+
errorFormat: errorFormat;
|
|
39
|
+
staticPath: any;
|
|
40
|
+
staticRequestPath: string | undefined;
|
|
41
|
+
constructor({ jwtSecret, baseApiUrl, enableFileRouting, idleTimeOut, prefixApiUrl, onError, logger, pipelineArchitecture, errorFormat }?: {
|
|
40
42
|
jwtSecret?: string;
|
|
41
43
|
baseApiUrl?: string;
|
|
42
44
|
enableFileRouting?: boolean;
|
|
@@ -45,6 +47,7 @@ export default class Diesel {
|
|
|
45
47
|
onError?: boolean;
|
|
46
48
|
logger?: boolean;
|
|
47
49
|
pipelineArchitecture?: boolean;
|
|
50
|
+
errorFormat?: errorFormat;
|
|
48
51
|
});
|
|
49
52
|
static router(prefix: string): Diesel;
|
|
50
53
|
/**
|
|
@@ -55,10 +58,10 @@ export default class Diesel {
|
|
|
55
58
|
*/
|
|
56
59
|
setupFilter(): FilterMethods;
|
|
57
60
|
redirect(incomingPath: string, redirectPath: string, statusCode?: 302): this;
|
|
58
|
-
serveStatic(filePath: string): this;
|
|
59
|
-
static(path: string): this;
|
|
61
|
+
serveStatic(filePath: string, requestPath?: string): this;
|
|
62
|
+
static(path: string, requestPath?: string): this;
|
|
60
63
|
staticHtml(args: Record<string, string>): this;
|
|
61
|
-
addHooks<T extends HookType>(typeOfHook: T, fnc:
|
|
64
|
+
addHooks<T extends HookType>(typeOfHook: T, fnc: Hooks[T][number]): this;
|
|
62
65
|
private compile;
|
|
63
66
|
private registerFileRoutes;
|
|
64
67
|
private loadRoutes;
|
|
@@ -113,3 +116,4 @@ export default class Diesel {
|
|
|
113
116
|
on(event: string | symbol, listener: EventListener): void;
|
|
114
117
|
emit(event: string | symbol, ...args: any): void;
|
|
115
118
|
}
|
|
119
|
+
export {};
|
package/dist/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f0=Object.create;var{getPrototypeOf:K0,defineProperty:_,getOwnPropertyNames:K1,getOwnPropertyDescriptor:F0}=Object,F1=Object.prototype.hasOwnProperty;var U0=($,z,Z)=>{Z=$!=null?f0(K0($)):{};let C=z||!$||!$.__esModule?_(Z,"default",{value:$,enumerable:!0}):Z;for(let J of K1($))if(!F1.call(C,J))_(C,J,{get:()=>$[J],enumerable:!0});return C},f1=new WeakMap,D0=($)=>{var z=f1.get($),Z;if(z)return z;if(z=_({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function")K1($).map((C)=>!F1.call(z,C)&&_(z,C,{get:()=>$[C],enumerable:!(Z=F0($,C))||Z.enumerable}));return f1.set($,z),z},p=($,z)=>()=>(z||$((z={exports:{}}).exports,z),z.exports);var N0=($,z)=>{for(var Z in z)_($,Z,{get:z[Z],enumerable:!0,configurable:!0,set:(C)=>z[Z]=()=>C})};var q0=($,z)=>()=>($&&(z=$($=0)),z);var A0=(($)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy($,{get:(z,Z)=>(typeof require!=="undefined"?require:z)[Z]}):$)(function($){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});var R1={};N0(R1,{sep:()=>M1,resolve:()=>c,relative:()=>q1,posix:()=>I1,parse:()=>H1,normalize:()=>s,join:()=>N1,isAbsolute:()=>D1,format:()=>j1,extname:()=>L1,dirname:()=>S1,delimiter:()=>O1,default:()=>O,basename:()=>w1,_makeLong:()=>A1});function S($){if(typeof $!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify($))}function U1($,z){var Z="",C=0,J=-1,X=0,Q;for(var Y=0;Y<=$.length;++Y){if(Y<$.length)Q=$.charCodeAt(Y);else if(Q===47)break;else Q=47;if(Q===47){if(J===Y-1||X===1);else if(J!==Y-1&&X===2){if(Z.length<2||C!==2||Z.charCodeAt(Z.length-1)!==46||Z.charCodeAt(Z.length-2)!==46){if(Z.length>2){var B=Z.lastIndexOf("/");if(B!==Z.length-1){if(B===-1)Z="",C=0;else Z=Z.slice(0,B),C=Z.length-1-Z.lastIndexOf("/");J=Y,X=0;continue}}else if(Z.length===2||Z.length===1){Z="",C=0,J=Y,X=0;continue}}if(z){if(Z.length>0)Z+="/..";else Z="..";C=2}}else{if(Z.length>0)Z+="/"+$.slice(J+1,Y);else Z=$.slice(J+1,Y);C=Y-J-1}J=Y,X=0}else if(Q===46&&X!==-1)++X;else X=-1}return Z}function S0($,z){var Z=z.dir||z.root,C=z.base||(z.name||"")+(z.ext||"");if(!Z)return C;if(Z===z.root)return Z+C;return Z+$+C}function c(){var $="",z=!1,Z;for(var C=arguments.length-1;C>=-1&&!z;C--){var J;if(C>=0)J=arguments[C];else{if(Z===void 0)Z=process.cwd();J=Z}if(S(J),J.length===0)continue;$=J+"/"+$,z=J.charCodeAt(0)===47}if($=U1($,!z),z)if($.length>0)return"/"+$;else return"/";else if($.length>0)return $;else return"."}function s($){if(S($),$.length===0)return".";var z=$.charCodeAt(0)===47,Z=$.charCodeAt($.length-1)===47;if($=U1($,!z),$.length===0&&!z)$=".";if($.length>0&&Z)$+="/";if(z)return"/"+$;return $}function D1($){return S($),$.length>0&&$.charCodeAt(0)===47}function N1(){if(arguments.length===0)return".";var $;for(var z=0;z<arguments.length;++z){var Z=arguments[z];if(S(Z),Z.length>0)if($===void 0)$=Z;else $+="/"+Z}if($===void 0)return".";return s($)}function q1($,z){if(S($),S(z),$===z)return"";if($=c($),z=c(z),$===z)return"";var Z=1;for(;Z<$.length;++Z)if($.charCodeAt(Z)!==47)break;var C=$.length,J=C-Z,X=1;for(;X<z.length;++X)if(z.charCodeAt(X)!==47)break;var Q=z.length,Y=Q-X,B=J<Y?J:Y,G=-1,V=0;for(;V<=B;++V){if(V===B){if(Y>B){if(z.charCodeAt(X+V)===47)return z.slice(X+V+1);else if(V===0)return z.slice(X+V)}else if(J>B){if($.charCodeAt(Z+V)===47)G=V;else if(V===0)G=0}break}var W=$.charCodeAt(Z+V),f=z.charCodeAt(X+V);if(W!==f)break;else if(W===47)G=V}var K="";for(V=Z+G+1;V<=C;++V)if(V===C||$.charCodeAt(V)===47)if(K.length===0)K+="..";else K+="/..";if(K.length>0)return K+z.slice(X+G);else{if(X+=G,z.charCodeAt(X)===47)++X;return z.slice(X)}}function A1($){return $}function S1($){if(S($),$.length===0)return".";var z=$.charCodeAt(0),Z=z===47,C=-1,J=!0;for(var X=$.length-1;X>=1;--X)if(z=$.charCodeAt(X),z===47){if(!J){C=X;break}}else J=!1;if(C===-1)return Z?"/":".";if(Z&&C===1)return"//";return $.slice(0,C)}function w1($,z){if(z!==void 0&&typeof z!=="string")throw new TypeError('"ext" argument must be a string');S($);var Z=0,C=-1,J=!0,X;if(z!==void 0&&z.length>0&&z.length<=$.length){if(z.length===$.length&&z===$)return"";var Q=z.length-1,Y=-1;for(X=$.length-1;X>=0;--X){var B=$.charCodeAt(X);if(B===47){if(!J){Z=X+1;break}}else{if(Y===-1)J=!1,Y=X+1;if(Q>=0)if(B===z.charCodeAt(Q)){if(--Q===-1)C=X}else Q=-1,C=Y}}if(Z===C)C=Y;else if(C===-1)C=$.length;return $.slice(Z,C)}else{for(X=$.length-1;X>=0;--X)if($.charCodeAt(X)===47){if(!J){Z=X+1;break}}else if(C===-1)J=!1,C=X+1;if(C===-1)return"";return $.slice(Z,C)}}function L1($){S($);var z=-1,Z=0,C=-1,J=!0,X=0;for(var Q=$.length-1;Q>=0;--Q){var Y=$.charCodeAt(Q);if(Y===47){if(!J){Z=Q+1;break}continue}if(C===-1)J=!1,C=Q+1;if(Y===46){if(z===-1)z=Q;else if(X!==1)X=1}else if(z!==-1)X=-1}if(z===-1||C===-1||X===0||X===1&&z===C-1&&z===Z+1)return"";return $.slice(z,C)}function j1($){if($===null||typeof $!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof $);return S0("/",$)}function H1($){S($);var z={root:"",dir:"",base:"",ext:"",name:""};if($.length===0)return z;var Z=$.charCodeAt(0),C=Z===47,J;if(C)z.root="/",J=1;else J=0;var X=-1,Q=0,Y=-1,B=!0,G=$.length-1,V=0;for(;G>=J;--G){if(Z=$.charCodeAt(G),Z===47){if(!B){Q=G+1;break}continue}if(Y===-1)B=!1,Y=G+1;if(Z===46){if(X===-1)X=G;else if(V!==1)V=1}else if(X!==-1)V=-1}if(X===-1||Y===-1||V===0||V===1&&X===Y-1&&X===Q+1){if(Y!==-1)if(Q===0&&C)z.base=z.name=$.slice(1,Y);else z.base=z.name=$.slice(Q,Y)}else{if(Q===0&&C)z.name=$.slice(1,X),z.base=$.slice(1,Y);else z.name=$.slice(Q,X),z.base=$.slice(Q,Y);z.ext=$.slice(X,Y)}if(Q>0)z.dir=$.slice(0,Q-1);else if(C)z.dir="/";return z}var M1="/",O1=":",I1,O;var r=q0(()=>{I1=(($)=>($.posix=$,$))({resolve:c,normalize:s,isAbsolute:D1,join:N1,relative:q1,_makeLong:A1,dirname:S1,basename:w1,extname:L1,format:j1,parse:H1,sep:M1,delimiter:O1,win32:null,posix:null}),O=I1});var b1=p((I0)=>{var w0=/[|\\{}()[\]^$+*?.]/g,L0=Object.prototype.hasOwnProperty,t=function($,z){return L0.apply($,[z])};I0.escapeRegExpChars=function($){if(!$)return"";return String($).replace(w0,"\\$&")};var j0={"&":"&","<":"<",">":">",'"':""","'":"'"},H0=/[&<>'"]/g;function M0($){return j0[$]||$}var O0=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -9,17 +9,17 @@ var K0=Object.create;var{getPrototypeOf:F0,defineProperty:b,getOwnPropertyNames:
|
|
|
9
9
|
function encode_char(c) {
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
|
-
`;I0.escapeXML=function($){return $==null?"":String($).replace(M0
|
|
13
|
-
`+
|
|
12
|
+
`;I0.escapeXML=function($){return $==null?"":String($).replace(H0,M0)};function T1(){return Function.prototype.toString.call(this)+`;
|
|
13
|
+
`+O0}try{if(typeof Object.defineProperty==="function")Object.defineProperty(I0.escapeXML,"toString",{value:T1});else I0.escapeXML.toString=T1}catch($){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}I0.shallowCopy=function($,z){if(z=z||{},$!==null&&$!==void 0)for(var Z in z){if(!t(z,Z))continue;if(Z==="__proto__"||Z==="constructor")continue;$[Z]=z[Z]}return $};I0.shallowCopyFromList=function($,z,Z){if(Z=Z||[],z=z||{},$!==null&&$!==void 0)for(var C=0;C<Z.length;C++){var J=Z[C];if(typeof z[J]!="undefined"){if(!t(z,J))continue;if(J==="__proto__"||J==="constructor")continue;$[J]=z[J]}}return $};I0.cache={_data:{},set:function($,z){this._data[$]=z},get:function($){return this._data[$]},remove:function($){delete this._data[$]},reset:function(){this._data={}}};I0.hyphenToCamel=function($){return $.replace(/-[a-z]/g,function(z){return z[1].toUpperCase()})};I0.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();I0.hasOwnOnlyObject=function($){var z=I0.createNullProtoObjWherePossible();for(var Z in $)if(t($,Z))z[Z]=$[Z];return z}});var E1=p((M4,v0)=>{v0.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var l1=p((m1)=>{var Z1=(()=>({})),E=(r(),D0(R1)),U=b1(),P1=!1,g0=E1().version,x0="<",k0=">",y0="%",c1="locals",c0="ejs",u0="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",u1=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],m0=u1.concat("cache"),v1=/^\uFEFF/,e=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;m1.cache=U.cache;m1.fileLoader=Z1.readFileSync;m1.localsName=c1;m1.promiseImpl=new Function("return this;")().Promise;m1.resolveInclude=function($,z,Z){var{dirname:C,extname:J,resolve:X}=E,Q=X(Z?z:C(z),$),Y=J($);if(!Y)Q+=".ejs";return Q};function g1($,z){var Z;if(z.some(function(C){return Z=m1.resolveInclude($,C,!0),Z1.existsSync(Z)}))return Z}function h0($,z){var Z,C,J=z.views,X=/^[A-Za-z]+:\\|^\//.exec($);if(X&&X.length)if($=$.replace(/^\/*/,""),Array.isArray(z.root))Z=g1($,z.root);else Z=m1.resolveInclude($,z.root||"/",!0);else{if(z.filename){if(C=m1.resolveInclude($,z.filename),Z1.existsSync(C))Z=C}if(!Z&&Array.isArray(J))Z=g1($,J);if(!Z&&typeof z.includer!=="function")throw new Error('Could not find the include file "'+z.escapeFunction($)+'"')}return Z}function P($,z){var Z,C=$.filename,J=arguments.length>1;if($.cache){if(!C)throw new Error("cache option requires a filename");if(Z=m1.cache.get(C),Z)return Z;if(!J)z=x1(C).toString().replace(v1,"")}else if(!J){if(!C)throw new Error("Internal EJS error: no file name or template provided");z=x1(C).toString().replace(v1,"")}if(Z=m1.compile(z,$),$.cache)m1.cache.set(C,Z);return Z}function d0($,z,Z){var C;if(!Z)if(typeof m1.promiseImpl=="function")return new m1.promiseImpl(function(J,X){try{C=P($)(z),J(C)}catch(Q){X(Q)}});else throw new Error("Please provide a callback function");else{try{C=P($)(z)}catch(J){return Z(J)}Z(null,C)}}function x1($){return m1.fileLoader($)}function i0($,z){var Z=U.shallowCopy(U.createNullProtoObjWherePossible(),z);if(Z.filename=h0($,Z),typeof z.includer==="function"){var C=z.includer($,Z.filename);if(C){if(C.filename)Z.filename=C.filename;if(C.template)return P(Z,C.template)}}return P(Z)}function k1($,z,Z,C,J){var X=z.split(`
|
|
14
14
|
`),Q=Math.max(C-3,0),Y=Math.min(X.length,C+3),B=J(Z),G=X.slice(Q,Y).map(function(V,W){var f=W+Q+1;return(f==C?" >> ":" ")+f+"| "+V}).join(`
|
|
15
15
|
`);throw $.path=B,$.message=(B||"ejs")+":"+C+`
|
|
16
16
|
`+G+`
|
|
17
17
|
|
|
18
|
-
`+$.message,$}function
|
|
18
|
+
`+$.message,$}function y1($){return $.replace(/;(\s*$)/,"$1")}m1.compile=function $(z,Z){var C;if(Z&&Z.scope){if(!P1)console.warn("`scope` option is deprecated and will be removed in EJS 3"),P1=!0;if(!Z.context)Z.context=Z.scope;delete Z.scope}return C=new q(z,Z),C.compile()};m1.render=function($,z,Z){var C=z||U.createNullProtoObjWherePossible(),J=Z||U.createNullProtoObjWherePossible();if(arguments.length==2)U.shallowCopyFromList(J,C,u1);return P(J,$)(C)};m1.renderFile=function(){var $=Array.prototype.slice.call(arguments),z=$.shift(),Z,C={filename:z},J,X;if(typeof arguments[arguments.length-1]=="function")Z=$.pop();if($.length){if(J=$.shift(),$.length)U.shallowCopy(C,$.pop());else{if(J.settings){if(J.settings.views)C.views=J.settings.views;if(J.settings["view cache"])C.cache=!0;if(X=J.settings["view options"],X)U.shallowCopy(C,X)}U.shallowCopyFromList(C,J,m0)}C.filename=z}else J=U.createNullProtoObjWherePossible();return d0(C,J,Z)};m1.Template=q;m1.clearCache=function(){m1.cache.reset()};function q($,z){var Z=U.hasOwnOnlyObject(z),C=U.createNullProtoObjWherePossible();if(this.templateText=$,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",C.client=Z.client||!1,C.escapeFunction=Z.escape||Z.escapeFunction||U.escapeXML,C.compileDebug=Z.compileDebug!==!1,C.debug=!!Z.debug,C.filename=Z.filename,C.openDelimiter=Z.openDelimiter||m1.openDelimiter||x0,C.closeDelimiter=Z.closeDelimiter||m1.closeDelimiter||k0,C.delimiter=Z.delimiter||m1.delimiter||y0,C.strict=Z.strict||!1,C.context=Z.context,C.cache=Z.cache||!1,C.rmWhitespace=Z.rmWhitespace,C.root=Z.root,C.includer=Z.includer,C.outputFunctionName=Z.outputFunctionName,C.localsName=Z.localsName||m1.localsName||c1,C.views=Z.views,C.async=Z.async,C.destructuredLocals=Z.destructuredLocals,C.legacyInclude=typeof Z.legacyInclude!="undefined"?!!Z.legacyInclude:!0,C.strict)C._with=!1;else C._with=typeof Z._with!="undefined"?Z._with:!0;this.opts=C,this.regex=this.createRegex()}q.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};q.prototype={createRegex:function(){var $=u0,z=U.escapeRegExpChars(this.opts.delimiter),Z=U.escapeRegExpChars(this.opts.openDelimiter),C=U.escapeRegExpChars(this.opts.closeDelimiter);return $=$.replace(/%/g,z).replace(/</g,Z).replace(/>/g,C),new RegExp($)},compile:function(){var $,z,Z=this.opts,C="",J="",X=Z.escapeFunction,Q,Y=Z.filename?JSON.stringify(Z.filename):"undefined";if(!this.source){if(this.generateSource(),C+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
|
-
`,Z.outputFunctionName){if(
|
|
21
|
-
`}if(Z.localsName
|
|
22
|
-
`;for(var G=0;G<Z.destructuredLocals.length;G++){var V=Z.destructuredLocals[G];if(
|
|
20
|
+
`,Z.outputFunctionName){if(!e.test(Z.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");C+=" var "+Z.outputFunctionName+` = __append;
|
|
21
|
+
`}if(Z.localsName&&!e.test(Z.localsName))throw new Error("localsName is not a valid JS identifier.");if(Z.destructuredLocals&&Z.destructuredLocals.length){var B=" var __locals = ("+Z.localsName+` || {}),
|
|
22
|
+
`;for(var G=0;G<Z.destructuredLocals.length;G++){var V=Z.destructuredLocals[G];if(!e.test(V))throw new Error("destructuredLocals["+G+"] is not a valid JS identifier.");if(G>0)B+=`,
|
|
23
23
|
`;B+=V+" = __locals."+V}C+=B+`;
|
|
24
24
|
`}if(Z._with!==!1)C+=" with ("+Z.localsName+` || {}) {
|
|
25
25
|
`,J+=` }
|
|
@@ -32,7 +32,7 @@ try {
|
|
|
32
32
|
rethrow(e, __lines, __filename, __line, escapeFn);
|
|
33
33
|
}
|
|
34
34
|
`;else $=this.source;if(Z.client){if($="escapeFn = escapeFn || "+X.toString()+`;
|
|
35
|
-
`+$,Z.compileDebug)$="rethrow = rethrow || "+
|
|
35
|
+
`+$,Z.compileDebug)$="rethrow = rethrow || "+k1.toString()+`;
|
|
36
36
|
`+$}if(Z.strict)$=`"use strict";
|
|
37
37
|
`+$;if(Z.debug)console.log($);if(Z.compileDebug&&Z.filename)$=$+`
|
|
38
38
|
//# sourceURL=`+Y+`
|
|
@@ -40,18 +40,18 @@ try {
|
|
|
40
40
|
|
|
41
41
|
`,N.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
42
|
`,N.message+="https://github.com/RyanZim/EJS-Lint",!Z.async)N.message+=`
|
|
43
|
-
`,N.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw N}var W=Z.client?z:function N(T){var
|
|
43
|
+
`,N.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw N}var W=Z.client?z:function N(T){var w=function(A,o){var n=U.shallowCopy(U.createNullProtoObjWherePossible(),T);if(o)n=U.shallowCopy(n,o);return i0(A,Z)(n)};return z.apply(Z.context,[T||U.createNullProtoObjWherePossible(),X,w,k1])};if(Z.filename&&typeof Object.defineProperty==="function"){var f=Z.filename,K=E.basename(f,E.extname(f));try{Object.defineProperty(W,"name",{value:K,writable:!1,enumerable:!1,configurable:!0})}catch(N){}}return W},generateSource:function(){var $=this.opts;if($.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
44
|
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var z=this,Z=this.parseTemplateText(),C=this.opts.delimiter,J=this.opts.openDelimiter,X=this.opts.closeDelimiter;if(Z&&Z.length)Z.forEach(function(Q,Y){var B;if(Q.indexOf(J+C)===0&&Q.indexOf(J+C+C)!==0){if(B=Z[Y+2],!(B==C+X||B=="-"+C+X||B=="_"+C+X))throw new Error('Could not find matching close tag for "'+Q+'".')}z.scanLine(Q)})},parseTemplateText:function(){var $=this.templateText,z=this.regex,Z=z.exec($),C=[],J;while(Z){if(J=Z.index,J!==0)C.push($.substring(0,J)),$=$.slice(J);C.push(Z[0]),$=$.slice(Z[0].length),Z=z.exec($)}if($)C.push($);return C},_addOutput:function($){if(this.truncate)$=$.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!$)return $;$=$.replace(/\\/g,"\\\\"),$=$.replace(/\n/g,"\\n"),$=$.replace(/\r/g,"\\r"),$=$.replace(/"/g,"\\\""),this.source+=' ; __append("'+$+`")
|
|
45
45
|
`},scanLine:function($){var z=this,Z=this.opts.delimiter,C=this.opts.openDelimiter,J=this.opts.closeDelimiter,X=0;switch(X=$.split(`
|
|
46
|
-
`).length-1,$){case C+Z:case C+Z+"_":this.mode=
|
|
47
|
-
`;break;case Z+Z+J:this.mode=
|
|
48
|
-
`;break;case Z+J:case"-"+Z+J:case"_"+Z+J:if(this.mode==
|
|
46
|
+
`).length-1,$){case C+Z:case C+Z+"_":this.mode=q.modes.EVAL;break;case C+Z+"=":this.mode=q.modes.ESCAPED;break;case C+Z+"-":this.mode=q.modes.RAW;break;case C+Z+"#":this.mode=q.modes.COMMENT;break;case C+Z+Z:this.mode=q.modes.LITERAL,this.source+=' ; __append("'+$.replace(C+Z+Z,C+Z)+`")
|
|
47
|
+
`;break;case Z+Z+J:this.mode=q.modes.LITERAL,this.source+=' ; __append("'+$.replace(Z+Z+J,Z+J)+`")
|
|
48
|
+
`;break;case Z+J:case"-"+Z+J:case"_"+Z+J:if(this.mode==q.modes.LITERAL)this._addOutput($);this.mode=null,this.truncate=$.indexOf("-")===0||$.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case q.modes.EVAL:case q.modes.ESCAPED:case q.modes.RAW:if($.lastIndexOf("//")>$.lastIndexOf(`
|
|
49
49
|
`))$+=`
|
|
50
|
-
`}switch(this.mode){case
|
|
51
|
-
`;break;case
|
|
52
|
-
`;break;case
|
|
53
|
-
`;break;case
|
|
54
|
-
`}};
|
|
50
|
+
`}switch(this.mode){case q.modes.EVAL:this.source+=" ; "+$+`
|
|
51
|
+
`;break;case q.modes.ESCAPED:this.source+=" ; __append(escapeFn("+y1($)+`))
|
|
52
|
+
`;break;case q.modes.RAW:this.source+=" ; __append("+y1($)+`)
|
|
53
|
+
`;break;case q.modes.COMMENT:break;case q.modes.LITERAL:this._addOutput($);break}}else this._addOutput($)}if(z.opts.compileDebug&&X)this.currentLine+=X,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
+
`}};m1.escapeXML=U.escapeXML;m1.__express=m1.renderFile;m1.VERSION=g0;m1.name=c0;if(typeof window!="undefined")window.ejs=m1});class k{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class y{root;constructor(){this.root=new k}pushMidl($,...z){let Z=this.root,C=$.split("/").filter(Boolean);if($==="/"){Z.handler.push(...z);return}for(let J of C){let X=J;if(J.startsWith(":"))X=":";if(!Z.children[X])Z.children[X]=new k;Z=Z.children[X]}Z.handler.push(...z)}insert($,z){let Z=this.root,C=$.split("/").filter(Boolean);if($==="/"){Z.isEndOfWord=!0,Z.handler.push(z.handler),Z.path=$,Z.method.push(z.method);return}for(let J of C){let X=!1,Q=J;if(J.startsWith(":"))X=!0,Q=":";if(!Z.children[Q])Z.children[Q]=new k;Z=Z.children[Q],Z.isDynamic=X,Z.pattern=J}Z.isEndOfWord=!0,Z.path=$,Z.method.push(z.method),Z.handler.push(z.handler)}search($,z){let Z=this.root,C=$.split("/").filter(Boolean),J=C.length;for(let Y of C){let B=Y;if(!Z.children[B])if(Z.children[":"])Z=Z.children[":"];else return null;else Z=Z.children[B]}let X=Z.path.split("/").filter(Boolean);if(J!==X.length)return null;if(Z.method.indexOf(z)!==-1)return{path:Z.path,handler:Z.handler[0],pattern:Z.pattern};return null}}function b($){switch($.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var z1=null;async function o1(){if(!z1){let $=await Promise.resolve().then(() => U0(l1(),1));z1=$.default||$}return z1}class v{req;server;pathname;routePattern;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor($,z,Z,C=""){this.req=$,this.server=z,this.pathname=Z,this.routePattern=C}setHeader($,z){return this.headers.set($,z),this}removeHeader($){return this.headers.delete($),this}set($,z){return this.contextData[$]=z,this}get($){return this.contextData[$]}get ip(){return this.server.requestIP(this.req)?.address??null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=p1(this.routePattern,this.pathname)}catch($){let z=$ instanceof Error?$.message:String($);throw new Error(`Failed to extract route parameters: ${z}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let $=await s1(this.req);if($.error)throw new Error($.error);return Object.keys($).length===0?null:$}catch($){throw new Error("Invalid request body format")}})();return this.parsedBody}text($,z=200){return new Response($,{status:z,headers:this.headers})}send($,z=200){let Z;if($ instanceof Uint8Array)Z="Uint8Array";else if($ instanceof ArrayBuffer)Z="ArrayBuffer";else Z=typeof $;let C=Z==="object"&&$!==null?JSON.stringify($):$;return new Response(C,{status:z,headers:this.headers})}json($,z=200){return Response.json($,{status:z,headers:this.headers})}file($,z,Z=200){let C=Bun.file($);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",z??b($));return new Response(C,{status:Z,headers:this.headers})}async ejs($,z={},Z=200){let C=await o1();try{let J=await Bun.file($).text(),X=C.render(J,z),Q=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(X,{status:Z,headers:Q})}catch(J){return console.error("EJS Rendering Error:",J),new Response("Error rendering template",{status:500})}}redirect($,z=302){return this.headers.set("Location",$),new Response(null,{status:z,headers:this.headers})}setCookie($,z,Z={}){let C=`${encodeURIComponent($)}=${encodeURIComponent(z)}`;if(Z.maxAge)C+=`; Max-Age=${Z.maxAge}`;if(Z.expires)C+=`; Expires=${Z.expires.toUTCString()}`;if(Z.path)C+=`; Path=${Z.path}`;if(Z.domain)C+=`; Domain=${Z.domain}`;if(Z.secure)C+="; Secure";if(Z.httpOnly)C+="; HttpOnly";if(Z.sameSite)C+=`; SameSite=${Z.sameSite}`;return this.headers.append("Set-Cookie",C),this}get cookies(){if(!this.parsedCookies){let $=this.req.headers.get("cookie");this.parsedCookies=$?n1($):{}}return this.parsedCookies}stream($){let z=new Headers(this.headers),Z=new ReadableStream({async start(C){await $(C),C.close()}});return new Response(Z,{headers:z})}yieldStream($){return new Response}}function e0($,z,Z,C){let J=null,X=null,Q=null,Y=null,B={},G=null;return{req:$,server:z,pathname:Z,headers:new Headers,setHeader(V,W){return this.headers.set(V,W),this},removeHeader(V){return this.headers.delete(V),this},set(V,W){return B[V]=W,this},get(V){return B[V]},get ip(){return this.server.requestIP($)?.address??null},get url(){if(!G)G=new URL($.url);return G},get query(){if(!J){if(!this.url.search)return{};J=Object.fromEntries(this.url.searchParams)}return J},get params(){if(!X&&C)try{X=p1(C,Z)}catch(V){let W=V instanceof Error?V.message:String(V);throw new Error(`Failed to extract route parameters: ${W}`)}return X??{}},get body(){if($.method==="GET")return Promise.resolve({});if(!Y)Y=(async()=>{try{let V=await s1($);if(V.error)throw new Error(V.error);return Object.keys(V).length===0?null:V}catch(V){throw new Error("Invalid request body format")}})();return Y},text(V,W=200){return new Response(V,{status:W,headers:this.headers})},send(V,W=200){let f;if(V instanceof Uint8Array)f="Uint8Array";else if(V instanceof ArrayBuffer)f="ArrayBuffer";else f=typeof V;let K=f==="object"&&V!==null?JSON.stringify(V):V;return new Response(K,{status:W,headers:this.headers})},json(V,W=200){return Response.json(V,{status:W,headers:this.headers})},file(V,W,f=200){let K=Bun.file(V);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",W??b(V));return new Response(K,{status:f,headers:this.headers})},async ejs(V,W={},f=200){let K=await o1();try{let N=await Bun.file(V).text(),T=K.render(N,W),w=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(T,{status:f,headers:w})}catch(N){return console.error("EJS Rendering Error:",N),new Response("Error rendering template",{status:500})}},redirect(V,W=302){return this.headers.set("Location",V),new Response(null,{status:W,headers:this.headers})},stream(V){let W=new Headers(this.headers),f=new ReadableStream({async start(K){await V(K),K.close()}});return new Response(f,{headers:W})},yieldStream(V){return new Response("not working stream yet.")},setCookie(V,W,f={}){let K=`${encodeURIComponent(V)}=${encodeURIComponent(W)}`;if(f.maxAge)K+=`; Max-Age=${f.maxAge}`;if(f.expires)K+=`; Expires=${f.expires.toUTCString()}`;if(f.path)K+=`; Path=${f.path}`;if(f.domain)K+=`; Domain=${f.domain}`;if(f.secure)K+="; Secure";if(f.httpOnly)K+="; HttpOnly";if(f.sameSite)K+=`; SameSite=${f.sameSite}`;return this.headers.append("Set-Cookie",K),this},get cookies(){if(!Q){let V=this.req.headers.get("cookie");Q=V?n1(V):{}}return Q}}}function n1($){return Object.fromEntries($.split(";").map((z)=>{let[Z,...C]=z.trim().split("=");return[Z,decodeURIComponent(C.join("="))]}))}function p1($,z){let Z={},C=$.split("/"),[J]=z.split("?"),X=J.split("/");if(C.length!==X.length)return null;for(let Q=0;Q<C.length;Q++){let Y=C[Q];if(Y.charCodeAt(0)===58)Z[Y.slice(1)]=X[Q]}return Z}async function s1($){let z=$.headers.get("Content-Type")||"";if(!z)return{};if($.headers.get("Content-Length")==="0"||!$.body)return{};if(z.startsWith("application/json"))return await $.json();if(z.startsWith("application/x-www-form-urlencoded")){let C=await $.text();return Object.fromEntries(new URLSearchParams(C))}if(z.startsWith("multipart/form-data")){let C=await $.formData(),J={};for(let[X,Q]of C.entries())J[X]=Q;return J}return{error:"Unknown request body type"}}async function L($,z,Z){if(!z?.length)return;for(let C=0;C<z.length;C++){let J=z[C](...Z),X=J instanceof Promise?await J:J;if(X&&$!=="onRequest")return X}}async function r1($,z,Z){let C=$.globalMiddlewares;if(C.length)for(let X of C){let Q=await X(Z);if(Q)return Q}let J=$.middlewares.get(z);if(J&&J.length)for(let X of J){let Q=await X(Z);if(Q)return Q}return null}async function a1($,z,Z){for(let C of $){let J=await C(z,Z);if(J)return J}}async function h($,z,Z){let C=await $4($,z,Z),J=C instanceof Promise?await C:C;if(J)return J}async function $4($,z,Z){if(z.endsWith("/"))z=z.slice(0,-1);if(!$.filters.has(z))if($.filterFunction.length)for(let C of $.filterFunction){let J=await C(Z);if(J)return J}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function d($,z,Z){if($.staticPath){let J=!0;if($.staticRequestPath)J=Z.startsWith($.staticRequestPath);if(J){let X=await Z4($,Z,z);if(X)return X;let Q=$.trie.search("*",z.req.method);if(Q?.handler)return await Q.handler(z)}}let C=$.routeNotFoundFunc(z);return C instanceof Promise?await C:C||I(404,`404 Route not found for ${Z}`)}function I($,z){return new Response(JSON.stringify({error:z}),{status:$,headers:{"Content-Type":"application/json"}})}async function Z4($,z,Z){if(!$.staticPath)return null;let C=`${$.staticPath}${z}`;if(await Bun.file(C).exists()){let X=b(C);return Z.file(C,X,200)}return null}var i=($)=>$.constructor.name==="AsyncFunction",C1=($,z,Z,...C)=>{if(z.length>5)$.push(`
|
|
55
55
|
for (let i = 0; i < diesel.hooks.${Z}.length; i++) {
|
|
56
56
|
const result = diesel.hooks.${Z}[i](${C});
|
|
57
57
|
const finalResult = result instanceof Promise ? await result : result;
|
|
@@ -63,7 +63,7 @@ try {
|
|
|
63
63
|
`);else $.push(`
|
|
64
64
|
const ${Z}${X}Result = diesel.hooks.${Z}[${X}](${C})
|
|
65
65
|
if (${Z}${X}Result && '${Z}' !== 'onRequest') return ${Z}${X}Result
|
|
66
|
-
`)})},
|
|
66
|
+
`)})},z4=($)=>{$.push(`
|
|
67
67
|
let pathname;
|
|
68
68
|
const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
|
|
69
69
|
let i = start;
|
|
@@ -81,7 +81,7 @@ try {
|
|
|
81
81
|
if (!pathname) {
|
|
82
82
|
pathname = req.url.slice(start, i);
|
|
83
83
|
}
|
|
84
|
-
`)},
|
|
84
|
+
`)},C4=($,z)=>{if(z.length<=5)for(let Z=0;Z<z.length;Z++)if(i(z[Z]))$.push(`
|
|
85
85
|
const resultMiddleware${Z} = await globalMiddlewares[${Z}](ctx);
|
|
86
86
|
if (resultMiddleware${Z}) return resultMiddleware${Z};
|
|
87
87
|
`);else $.push(`
|
|
@@ -92,11 +92,11 @@ try {
|
|
|
92
92
|
const result = await globalMiddlewares[i](ctx);
|
|
93
93
|
if (result) return result;
|
|
94
94
|
}
|
|
95
|
-
`)},
|
|
95
|
+
`)},t1=($,z)=>{let Z=[],C=z.globalMiddlewares||[],J=$?.hasOnReqHook?z.hooks.onRequest:[],X=$?.hasPreHandlerHook?z.hooks.preHandler:[],Q=$?.hasOnSendHook?z.hooks.onSend:[];if(z4(Z),Z.push(`
|
|
96
96
|
const routeHandler = diesel.trie.search(pathname, req.method);
|
|
97
|
-
`),J&&J.length>0)
|
|
97
|
+
`),J&&J.length>0)C1(Z,J,"onRequest","req","pathname","server");if(Z.push(`
|
|
98
98
|
const ctx = new Context(req, server, pathname, routeHandler?.path)
|
|
99
|
-
`),$?.hasMiddleware){if(C.length>0)
|
|
99
|
+
`),$?.hasMiddleware){if(C.length>0)C4(Z,C);if(z.middlewares.size>0)Z.push(`
|
|
100
100
|
const local = diesel.middlewares.get(pathname)
|
|
101
101
|
if (local && local.length) {
|
|
102
102
|
for (const middleware of local) {
|
|
@@ -109,10 +109,10 @@ try {
|
|
|
109
109
|
if (filterResponse) return filterResponse;
|
|
110
110
|
`);if(Z.push(`
|
|
111
111
|
if (!routeHandler) return await handleRouteNotFound(diesel, ctx, pathname);
|
|
112
|
-
`),$.hasPreHandlerHook)
|
|
112
|
+
`),$.hasPreHandlerHook)C1(Z,X,"preHandler","ctx");if(Z.push(`
|
|
113
113
|
const result = routeHandler.handler(ctx);
|
|
114
114
|
const finalResult = result instanceof Promise ? await result : result;
|
|
115
|
-
`),$.hasOnSendHook)
|
|
115
|
+
`),$.hasOnSendHook)C1(Z,Q,"onSend","ctx","finalResult");Z.push(`
|
|
116
116
|
if (finalResult instanceof Response) return finalResult;
|
|
117
117
|
return generateErrorResponse(500, "No response returned from handler.");
|
|
118
118
|
`);let Y=`
|
|
@@ -120,7 +120,7 @@ try {
|
|
|
120
120
|
${Z.join(`
|
|
121
121
|
`)}
|
|
122
122
|
}
|
|
123
|
-
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",Y)(h,d,
|
|
123
|
+
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",Y)(h,d,I,C,v)},e1=($,z,Z,C,...J)=>{let X=[],Q;if(typeof J[0]==="string"||typeof J[0]==="object")Q=J[0];let Y=J,B=$?.hasMiddleware?z.globalMiddlewares:[],G=$?.hasMiddleware?z.middlewares.get(C)||[]:[],V=[...B,...G],W=$?.hasOnReqHook?z.hooks.onRequest:[],f=z.filters.has(C),K=z.filterFunction;if(W&&W?.length>0)X.push(`
|
|
124
124
|
const onRequestResult = await runHooks(
|
|
125
125
|
"onRequest",
|
|
126
126
|
onRequestHooks,
|
|
@@ -146,27 +146,27 @@ try {
|
|
|
146
146
|
return new Response("Method Not Allowed", { status: 405 });
|
|
147
147
|
`),typeof Q!=="undefined")if(typeof Q==="string")X.push(`
|
|
148
148
|
return new Response(${JSON.stringify(Q)});
|
|
149
|
-
`);else{let
|
|
150
|
-
return new Response(${JSON.stringify(
|
|
149
|
+
`);else{let w=JSON.stringify(Q);X.push(`
|
|
150
|
+
return new Response(${JSON.stringify(w)}, {
|
|
151
151
|
headers: { "content-type": "application/json; charset=utf-8" }
|
|
152
152
|
});
|
|
153
|
-
`)}else if(Y.length===1){let
|
|
153
|
+
`)}else if(Y.length===1){let w=Y[0];if(i(w))X.push(`
|
|
154
154
|
const response = await handlers[0](req, server);
|
|
155
155
|
if (response instanceof Response) return response;
|
|
156
156
|
`);else X.push(`
|
|
157
157
|
const response = handlers[0](req, server);
|
|
158
158
|
if (response instanceof Response) return response;
|
|
159
|
-
`)}else Y.forEach((
|
|
160
|
-
const response${
|
|
161
|
-
if (response${
|
|
159
|
+
`)}else Y.forEach((w,A)=>{if(i(w))X.push(`
|
|
160
|
+
const response${A} = await handlers[${A}](req, server);
|
|
161
|
+
if (response${A} instanceof Response) return response${A};
|
|
162
162
|
`);else X.push(`
|
|
163
|
-
const response${
|
|
164
|
-
if (response${
|
|
163
|
+
const response${A} = handlers[${A}](req, server);
|
|
164
|
+
if (response${A} instanceof Response) return response${A};
|
|
165
165
|
`)});let N=`
|
|
166
166
|
return async function(req, server) {
|
|
167
167
|
${X.join(`
|
|
168
168
|
`)}
|
|
169
169
|
}
|
|
170
|
-
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",N)(
|
|
170
|
+
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",N)(a1,Y,L,K,W,V)};r();var{default:W1}=(()=>({}));var D={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"}},J1=($,z,Z)=>{let C=D[$]||D.reset,J=Z?.method?D.method[Z.method]||D.reset:D.reset,X=Z?.status?Z.status>=500?D.error:Z.status>=400?D.warn:D.info:D.reset;console.log(`
|
|
171
171
|
${C}[${$.toUpperCase()}]${D.reset} ${z} - ${J}${Z?.method||""}${D.reset}`);let Q={timestamp:new Date().toISOString(),...Z,status:Z?.status?`${X}${Z.status}${D.reset}`:void 0,method:Z?.method?`${J>C}${Z.method}${D.reset}`:void 0};console.log(JSON.stringify(Q,null,2)+`
|
|
172
|
-
`)},Z0=($)=>{let{app:z,logger:Z,logLevel:C="info",onRequest:J,onSend:X,onError:Q}=$||{};z?.addHooks("onRequest",(Y)=>{Y.req.startTime=Date.now(),Z?.()??Q1(C,"Incoming Request",{method:Y.req.method,url:Y.pathname,headers:{"user-agent":Y.req.headers.get("user-agent"),"content-type":Y.req.headers.get("content-type")}}),J?.(Y)}),z?.addHooks("onSend",async(Y,B)=>{let G=`${Date.now()-Y.req.startTime}ms`;Z?.()??Q1(C,"Response Sent",{method:Y.req.method,url:Y.url.toString(),status:B.status,duration:G,reqId:Y.get?.("requestId"),headers:{"content-type":B.headers.get("content-type")}});let V=await X?.(Y);if(V instanceof Response)return V}),z?.addHooks("onError",async(Y,B)=>{Z?.()??Q1("error","Unhandled Error",{method:B.req.method,url:B.pathname,status:500,error:Y.message});let G=await Q?.(Y,B);if(G instanceof Response)return G})},Y1=($,z,Z,C=0,J,X)=>{let Q=D.method[z]||D.reset,Y=C>=500?D.error:C>=400?D.warn:D.info,B=X?`[${X}] `:"",G=$==="<--"?`${$} ${Q}${z}${D.reset} ${Z} ${B}`:`${$} ${Q}${z}${D.reset} ${Z} ${Y}${C}${D.reset} ${J??""} ${B}`;console.log(G)},X4=($)=>{let z=Date.now()-$;return z<1000?`${z}ms`:`${Math.round(z/1000)}s`},z0=($)=>{let{app:z,log:Z,onRequest:C,onSend:J,onError:X}=$;z.addHooks("onRequest",(Q)=>{let{req:Y,pathname:B}=Q;Y.startTime=Date.now(),Z?.()??Y1("<--",Y.method,B),C?.(Y,B)}),z.addHooks("onSend",async(Q,Y)=>{let{method:B,url:G}=Q.req,V=new URL(G).pathname,W=Q.get?.("requestId");Z?.()??Y1("-->",B,V,Y.status,X4(Q.req.startTime),W);let f=await J?.(Q);if(f instanceof Response)return f}),z.addHooks("onError",async(Q,Y)=>{let{req:B,pathname:G}=Y;Z?.()??Y1(Q.message,B.method,G,500);let V=await X?.(Q,B,G);if(V instanceof Response)return V})};function C0($,z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(Z)=>{try{let C=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!C)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(C.startsWith("Bearer "))C=C.slice(7);let J=$?.verify(C,z);if(!J)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);Z.set("user",J)}catch(C){let J="Invalid token";if(C.name==="TokenExpiredError")J="Token expired";else if(C.name==="JsonWebTokenError")J="Malformed or tampered token";return Z.json({message:"Unauthorized",error:J},401)}}}function J0($,z,Z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!z)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(C)=>{try{let J=C.cookies?.accessToken??C.req?.headers?.get("Authorization");if(!J)return C.json({message:"Unauthorized",error:"No token provided"},401);if(J.startsWith("Bearer "))J=J.slice(7);let X=$?.verify(J,Z);if(!X)return C.json({message:"Unauthorized",error:"Token could not be decoded"},401);let Q=await z.findById(X._id).select("-password -refreshToken");if(!Q)return C.json({message:"Unauthorized: User not found"},404);C.set("user",Q);return}catch(J){let X="Invalid token";if(J.name==="TokenExpiredError")X="Token expired";else if(J.name==="JsonWebTokenError")X="Malformed or tampered token";return C.json({message:"Unauthorized",error:X},401)}}}var Q4=($,z)=>{try{return z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return z(Z)}catch{return Z}})}},V1=($)=>Q4($,decodeURI),o=($)=>{let z=$.indexOf("/",$.indexOf(":")+4),Z=z;for(;Z<$.length;Z++){let C=$.charCodeAt(Z);if(C===37){let J=$.indexOf("?",Z),X=$.slice(z,J===-1?void 0:J);return V1(X.includes("%25")?X.replace(/%25/g,"%2525"):X)}else if(C===63)break}return $.slice(z,Z)};var G1=Symbol.for,M=Symbol("kCapture"),V0=G1("events.errorMonitor"),Y4=Symbol("events.maxEventTargetListeners"),V4=Symbol("events.maxEventTargetListenersWarned"),X0=G1("nodejs.rejection"),B4=G1("nodejs.rejection"),Q0=Array.prototype.slice,O=10,j=function $(z){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[M]=z?.captureRejections?Boolean(z?.captureRejections):F[M])this.emit=K4},F=j.prototype={};F._events=void 0;F._eventsCount=0;F._maxListeners=void 0;F.setMaxListeners=function $(z){return W1(z,"setMaxListeners",0),this._maxListeners=z,this};F.constructor=j;F.getMaxListeners=function $(){return this?._maxListeners??O};function B0($,z){var{_events:Z}=$;if(z[0]??=new Error("Unhandled error."),!Z)throw z[0];var C=Z[V0];if(C)for(var J of Q0.call(C))J.apply($,z);var X=Z.error;if(!X)throw z[0];for(var J of Q0.call(X))J.apply($,z);return!0}function G4($,z,Z,C){z.then(void 0,function(J){queueMicrotask(()=>W4($,J,Z,C))})}function W4($,z,Z,C){if(typeof $[X0]==="function")$[X0](z,Z,...C);else try{$[M]=!1,$.emit("error",z)}finally{$[M]=!0}}var f4=function $(z,...Z){if(z==="error")return B0(this,Z);var{_events:C}=this;if(C===void 0)return!1;var J=C[z];if(J===void 0)return!1;let X=J.length>1?J.slice():J;for(let Q=0,{length:Y}=X;Q<Y;Q++){let B=X[Q];switch(Z.length){case 0:B.call(this);break;case 1:B.call(this,Z[0]);break;case 2:B.call(this,Z[0],Z[1]);break;case 3:B.call(this,Z[0],Z[1],Z[2]);break;default:B.apply(this,Z);break}}return!0},K4=function $(z,...Z){if(z==="error")return B0(this,Z);var{_events:C}=this;if(C===void 0)return!1;var J=C[z];if(J===void 0)return!1;let X=J.length>1?J.slice():J;for(let Q=0,{length:Y}=X;Q<Y;Q++){let B=X[Q],G;switch(Z.length){case 0:G=B.call(this);break;case 1:G=B.call(this,Z[0]);break;case 2:G=B.call(this,Z[0],Z[1]);break;case 3:G=B.call(this,Z[0],Z[1],Z[2]);break;default:G=B.apply(this,Z);break}if(G!==void 0&&typeof G?.then==="function"&&G.then===Promise.prototype.then)G4(this,G,z,Z)}return!0};F.emit=f4;F.addListener=function $(z,Z){g(Z);var C=this._events;if(!C)C=this._events={__proto__:null},this._eventsCount=0;else if(C.newListener)this.emit("newListener",z,Z.listener??Z);var J=C[z];if(!J)C[z]=[Z],this._eventsCount++;else{J.push(Z);var X=this._maxListeners??O;if(X>0&&J.length>X&&!J.warned)G0(this,z,J)}return this};F.on=F.addListener;F.prependListener=function $(z,Z){g(Z);var C=this._events;if(!C)C=this._events={__proto__:null},this._eventsCount=0;else if(C.newListener)this.emit("newListener",z,Z.listener??Z);var J=C[z];if(!J)C[z]=[Z],this._eventsCount++;else{J.unshift(Z);var X=this._maxListeners??O;if(X>0&&J.length>X&&!J.warned)G0(this,z,J)}return this};function G0($,z,Z){Z.warned=!0;let C=new Error(`Possible EventEmitter memory leak detected. ${Z.length} ${String(z)} listeners added to [${$.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);C.name="MaxListenersExceededWarning",C.emitter=$,C.type=z,C.count=Z.length,console.warn(C)}function W0($,z,...Z){this.removeListener($,z),z.apply(this,Z)}F.once=function $(z,Z){g(Z);let C=W0.bind(this,z,Z);return C.listener=Z,this.addListener(z,C),this};F.prependOnceListener=function $(z,Z){g(Z);let C=W0.bind(this,z,Z);return C.listener=Z,this.prependListener(z,C),this};F.removeListener=function $(z,Z){g(Z);var{_events:C}=this;if(!C)return this;var J=C[z];if(!J)return this;var X=J.length;let Q=-1;for(let Y=X-1;Y>=0;Y--)if(J[Y]===Z||J[Y].listener===Z){Q=Y;break}if(Q<0)return this;if(Q===0)J.shift();else J.splice(Q,1);if(J.length===0)delete C[z],this._eventsCount--;return this};F.off=F.removeListener;F.removeAllListeners=function $(z){var{_events:Z}=this;if(z&&Z){if(Z[z])delete Z[z],this._eventsCount--}else this._events={__proto__:null};return this};F.listeners=function $(z){var{_events:Z}=this;if(!Z)return[];var C=Z[z];if(!C)return[];return C.map((J)=>J.listener??J)};F.rawListeners=function $(z){var{_events:Z}=this;if(!Z)return[];var C=Z[z];if(!C)return[];return C.slice()};F.listenerCount=function $(z){var{_events:Z}=this;if(!Z)return 0;return Z[z]?.length??0};F.eventNames=function $(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};F[M]=!1;function F4($,z,Z){var C=Z?.signal;if(f0(C,"options.signal"),C?.aborted)throw new B1(void 0,{cause:C?.reason});let{resolve:J,reject:X,promise:Q}=$newPromiseCapability(Promise),Y=(V)=>{if($.removeListener(z,B),C!=null)l(C,"abort",G);X(V)},B=(...V)=>{if(typeof $.removeListener==="function")$.removeListener("error",Y);if(C!=null)l(C,"abort",G);J(V)};if(Y0($,z,B,{once:!0}),z!=="error"&&typeof $.once==="function")$.once("error",Y);function G(){l($,z,B),l($,"error",Y),X(new B1(void 0,{cause:C?.reason}))}if(C!=null)Y0(C,"abort",G,{once:!0});return Q}function U4($,z){return $.listeners(z)}function D4($,...z){W1($,"setMaxListeners",0);var Z;if(z&&(Z=z.length))for(let C=0;C<Z;C++)z[C].setMaxListeners($);else O=$}function N4($,z){return $.listenerCount(z)}function l($,z,Z,C){if(typeof $.removeListener==="function")$.removeListener(z,Z);else $.removeEventListener(z,Z,C)}function Y0($,z,Z,C){if(typeof $.on==="function")if(C.once)$.once(z,Z);else $.on(z,Z);else $.addEventListener(z,Z,C)}class B1 extends Error{constructor($="The operation was aborted",z=void 0){if(z!==void 0&&typeof z!=="object")throw I("options","Object",z);super($,z);this.code="ABORT_ERR",this.name="AbortError"}}function I($,z,Z){let C=new TypeError(`The "${$}" argument must be of type ${z}. Received ${Z}`);return C.code="ERR_INVALID_ARG_TYPE",C}function A4($,z,Z){let C=new RangeError(`The "${$}" argument is out of range. It must be ${z}. Received ${Z}`);return C.code="ERR_OUT_OF_RANGE",C}function f0($,z){if($!==void 0&&($===null||typeof $!=="object"||!("aborted"in $)))throw I(z,"AbortSignal",$)}function W1($,z,Z,C){if(typeof $!=="number")throw I(z,"number",$);if(Z!=null&&$<Z||C!=null&&$>C||(Z!=null||C!=null)&&Number.isNaN($))throw A4(z,`${Z!=null?`>= ${Z}`:""}${Z!=null&&C!=null?" && ":""}${C!=null?`<= ${C}`:""}`,$)}function g($){if(typeof $!=="function")throw new TypeError("The listener must be a function")}function w4($,z){if(typeof $!=="boolean")throw I(z,"boolean",$)}function q4($){return $?._maxListeners??O}function S4($,z){if($===void 0)throw I("signal","AbortSignal",$);if(f0($,"signal"),typeof z!=="function")throw I("listener","function",z);let Z;if($.aborted)queueMicrotask(()=>z());else $.addEventListener("abort",z,{__proto__:null,once:!0}),Z=()=>{$.removeEventListener("abort",z)};return{__proto__:null,[Symbol.dispose](){Z?.()}}}Object.defineProperties(j,{captureRejections:{get(){return F[M]},set($){w4($,"EventEmitter.captureRejections"),F[M]=$},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return O},set:($)=>{W1($,"defaultMaxListeners",0),O=$}},kMaxEventTargetListeners:{value:Y4,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:V4,enumerable:!1,configurable:!1,writable:!1}});Object.assign(j,{once:F4,getEventListeners:U4,getMaxListeners:q4,setMaxListeners:D4,EventEmitter:j,usingDomains:!1,captureRejectionSymbol:B4,errorMonitor:V0,addAbortListener:S4,init:j,listenerCount:N4});class x{static instance;fecth;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;newPipelineArchitecture=!1;emitter;errorFormat;constructor({jwtSecret:$,baseApiUrl:z,enableFileRouting:Z,idleTimeOut:C,prefixApiUrl:J,onError:X,logger:Q,pipelineArchitecture:Y}={}){if(!x.instance)x.instance=this;if(Y)this.newPipelineArchitecture=!0;if(this.errorFormat="json",this.emitter=new j,this.prefixApiUrl=J??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=C??10,this.enableFileRouter=Z??!1,this.baseApiUrl=z||"",this.user_jwt_secret=$||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new y,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},X)this.addHooks("onError",(B,G)=>{console.log("Got an exception:",B),console.log("Request Path:",G.pathname)});if(Q)this.useLogger({app:this,onError(B){console.error("Got an exception:",B)}});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($){if(!this.instance)this.instance=new x;return new Proxy(this.instance,{get(z,Z,C){return(J,X)=>{let Q=$+J;return z[Z](Q,X)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.FilterRoutes=null,this.setupFilter()},authenticate:($)=>{if($?.length)for(let z of $)this.filterFunction.push(z)},authenticateJwt:($)=>{this.filterFunction.push(C0($,this.user_jwt_secret))},authenticateJwtDB:($,z)=>{this.filterFunction.push(J0($,z,this.user_jwt_secret))}}}redirect($,z,Z){return this.any($,(C)=>{let J=C.params,X=z;if(J)for(let Y in J)X=X.replace(`:${Y}`,J[Y]);let Q=C.url.search;if(Q)X+=Q;return C.redirect(X,Z)}),this}serveStatic($){return this.staticPath=$,this}static($){return this.staticPath=$,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,z){if(typeof $!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(z);break;case"preHandler":this.hooks.preHandler?.push(z);break;case"postHandler":this.hooks.postHandler?.push(z);break;case"onSend":this.hooks.onSend?.push(z);break;case"onError":this.hooks.onError?.push(z);break;case"onClose":this.hooks.onClose?.push(z);break;default:throw new Error(`Unknown hook type: ${$}`)}return this}compile(){let $={hasMiddleware:!1,hasOnReqHook:!1,hasPreHandlerHook:!1,hasOnError:!1,hasPostHandlerHook:!1,hasOnSendHook:!1,hasFilterEnabled:!1};if(this.hasFilterEnabled)$.hasFilterEnabled=!0,this.hasFilterEnabled=!0;if(this?.globalMiddlewares?.length>0)$.hasMiddleware=!0,this.hasMiddleware=!0;for(let[z,Z]of this?.middlewares?.entries())if(Z.length>0){$.hasMiddleware=!0,this.hasMiddleware=!0;break}if(this?.enableFileRouter){let z=process.cwd(),Z=R.join(z,"src","routes");if(f1?.existsSync(Z))this.loadRoutes(Z,"")}if(this?.hooks?.onRequest&&this.hooks.onRequest.length>0)$.hasOnReqHook=!0,this.hasOnReqHook=!0;if(this?.hooks?.preHandler&&this.hooks.preHandler.length>0)$.hasPreHandlerHook=!0,this.hasPreHandlerHook=!0;if(this?.hooks?.postHandler&&this.hooks.postHandler?.length>0)$.hasPostHandlerHook=!0,this.hasPostHandlerHook=!0;if(this?.hooks?.onSend&&this.hooks.onSend?.length>0)$.hasOnSendHook=!0,this.hasOnSendHook=!0;if(this?.hooks?.onError&&this.hooks.onError?.length>0)$.hasOnError=!0,this.hasOnError=!0;return setTimeout(()=>{this.tempRoutes=null},2000),this.compileConfig=$,$}async registerFileRoutes($,z,Z){let C=await import($),J;if(Z===".ts")J=R.basename($,".ts");else if(Z===".js")J=R.basename($,".js");let X=z+"/"+J;if(X.endsWith("/index"))X=z;else if(X.endsWith("/api"))X=z;X=X.replace(/\[(.*?)\]/g,":$1");let Q=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let Y of Q)if(C[Y]){let B=Y.toLowerCase(),G=C[Y];this[B](`${this.baseApiUrl}${X}`,G)}}async loadRoutes($,z){let Z=await f1.promises.readdir($);for(let C of Z){let J=R.join($,C);if((await f1.promises.stat(J)).isDirectory())await this.loadRoutes(J,z+"/"+C);else if(C.endsWith(".ts"))await this.registerFileRoutes(J,z,".ts");else if(C.endsWith(".js"))await this.registerFileRoutes(J,z,".js")}}useLogger($){return z0($),this}useAdvancedLogger($){return Z0($),this}BunRoute($,z,...Z){if(!z||typeof z!=="string")throw new Error("give a path in string format");if(!this.compileConfig)this.compile();let C;if(typeof Z[0]==="string"||typeof Z[0]==="object")C=Z[0];if(typeof C!=="undefined"){let X=typeof C==="string"?C:JSON.stringify(C)}let J=$0(this.compileConfig,this,$.toUpperCase(),z,...Z);return this.routes[z]=J,this}listen($,...z){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let Z="0.0.0.0",C=void 0,J={};for(let Q of z)if(typeof Q==="string")Z=Q;else if(typeof Q==="function")C=Q;else if(typeof Q==="object"&&Q!==null)J=Q;let X={port:$,hostname:Z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)X.routes=this.routes;if(J.cert&&J.key)X.certFile=J.cert,X.keyFile=J.key;if(this.serverInstance=Bun?.serve(X),C)C();return this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}fetch(){let $=this.compile();if(this.newPipelineArchitecture){let z=e1($,this);return(Z,C)=>{return z(Z,C,this).catch(async(J)=>{return console.error("Unhandled handler error:",J),await L("onError",this.hooks.onError,[J,Z,o(Z.url),C])||H(500,"Internal Server Error")})}}return this.handleRequests.bind(this)}async handleRequests($,z){let Z,C=$.url.indexOf("/",$.url.indexOf(":")+4),J=C;for(;J<$.url.length;J++){let Y=$.url.charCodeAt(J);if(Y===37){let B=$.url.indexOf("?",J),G=$.url.slice(C,B===-1?void 0:B);Z=V1(G.includes("%25")?G.replace(/%25/g,"%2525"):G);break}else if(Y===63)break}if(!Z)Z=$.url.slice(C,J);let X=this.trie.search(Z,$.method),Q=new v($,z,Z,X?.path);try{if(this.hasOnReqHook)await L("onRequest",this.hooks.onRequest,[Q]);if(this.hasMiddleware){let G=await a1(this,Z,Q);if(G)return G}if(this.hasFilterEnabled){let G=await h(this,Z,Q);if(G)return G}if(!X)return await d(this,Q,Z);if(this.hasPreHandlerHook){let G=await L("preHandler",this.hooks.preHandler,[Q]);if(G)return G}let Y=X.handler(Q),B=Y instanceof Promise?await Y:Y;if(this.hasOnSendHook){let G=await L("onSend",this.hooks.onSend,[Q,B]);if(G)return G}if(B instanceof Response)return B}catch(Y){return this.handleError(Y,Q)}return H(500,"No response returned from handler.")}async handleError($,z){let C=this.errorFormat||"json",J=o(z.req.url),X=await L("onError",this.hooks.onError,[$,z]);if(X)return X;if($ instanceof X1){if($.res)return $.res;return C==="json"?Response.json({error:$.message},{status:$.status}):new Response($.message,{status:$.status})}if(C==="json"){let Q={error:$?.message??"Internal Server Error",...!1,path:J};return Response.json(Q,{status:500,headers:{"Content-Type":"application/json"}})}else{let Q=`Error: ${$?.message??"Internal Server Error"}`;return new Response(Q,{headers:{"Content-Type":"text/plain"},status:500})}}route($,z){$=$&&$.length>0?$:z?.prefixApiUrl;let Z=z?.tempRoutes??new Map;for(let[C,J]of Z.entries()){let X=C.replace(/::\w+$/,""),Q=`${$}${X}`;if(!this.middlewares.has(Q))this.middlewares.set(Q,[]);J.handlers.slice(0,-1).forEach((V)=>{let W=this.middlewares.get(Q);if(!W.includes(V))W.push(V)});let B=J.handlers[J.handlers.length-1],G=J.method;try{this.trie.insert(Q,{handler:B,method:G})}catch(V){console.error(`Error inserting ${Q}:`,V)}}return z=null,this}register($,z){return this.route($,z)}addRoute($,z,Z){if(typeof z!=="string")throw new Error(`Error in ${Z[Z.length-1]}: Path must be a string. Received: ${typeof z}`);if(typeof $!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(z+"::"+$,{method:$,handlers:Z});let C=Z.slice(0,-1),J=Z[Z.length-1];if(C.length>0){if(!this.middlewares.has(z))this.middlewares.set(z,[]);C.forEach((X)=>{if(z==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...C])];else if(!this.middlewares.get(z)?.includes(X))this.middlewares.get(z)?.push(X)})}try{if($==="ANY"){let X=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let Q of X)this.trie.insert(z,{handler:J,method:Q})}this.trie.insert(z,{handler:J,method:$})}catch(X){console.error(`Error inserting ${z}:`,X)}}use($,z){if(Array.isArray($))$.forEach((C)=>{if(typeof C==="function")this.globalMiddlewares.push(C)});if(typeof $==="function"){if(this.globalMiddlewares.push($),Array.isArray(z))z.forEach((C)=>{this.globalMiddlewares.push(C)});return this}return(Array.isArray($)?$.filter((C)=>typeof C==="string"):[$].filter((C)=>typeof C==="string")).forEach((C)=>{if(!this.middlewares.has(C))this.middlewares.set(C,[]);if(z)(Array.isArray(z)?z:[z]).forEach((X)=>{this.middlewares.get(C)?.push(X)})}),this}get($,...z){return this.addRoute("GET",$,z),this}post($,...z){return this.addRoute("POST",$,z),this}put($,...z){return this.addRoute("PUT",$,z),this}patch($,...z){return this.addRoute("PATCH",$,z),this}delete($,...z){return this.addRoute("DELETE",$,z),this}any($,...z){return this.addRoute("ANY",$,z),this}head($,...z){return this.addRoute("HEAD",$,z),this}options($,...z){return this.addRoute("OPTIONS",$,z),this}propfind($,...z){return this.addRoute("PROPFIND",$,z),this}routeNotFound($){return this.routeNotFoundFunc=$,this}on($,z){this.emitter.on($,z)}emit($,...z){this.emitter.emit($,...z)}}export{x as default};
|
|
172
|
+
`)},$0=($)=>{let{app:z,logger:Z,logLevel:C="info",onRequest:J,onSend:X,onError:Q}=$||{};z?.addHooks("onRequest",(Y)=>{Y.req.startTime=Date.now(),Z?.()??J1(C,"Incoming Request",{method:Y.req.method,url:Y.pathname,headers:{"user-agent":Y.req.headers.get("user-agent"),"content-type":Y.req.headers.get("content-type")}}),J?.(Y)}),z?.addHooks("onSend",async(Y,B)=>{let G=`${Date.now()-Y.req.startTime}ms`;Z?.()??J1(C,"Response Sent",{method:Y.req.method,url:Y.url.toString(),status:B.status,duration:G,reqId:Y.get?.("requestId"),headers:{"content-type":B.headers.get("content-type")}});let V=await X?.(Y);if(V instanceof Response)return V}),z?.addHooks("onError",async(Y,B)=>{Z?.()??J1("error","Unhandled Error",{method:B.req.method,url:B.pathname,status:500,error:Y.message});let G=await Q?.(Y,B);if(G instanceof Response)return G})},X1=($,z,Z,C=0,J,X)=>{let Q=D.method[z]||D.reset,Y=C>=500?D.error:C>=400?D.warn:D.info,B=X?`[${X}] `:"",G=$==="<--"?`${$} ${Q}${z}${D.reset} ${Z} ${B}`:`${$} ${Q}${z}${D.reset} ${Z} ${Y}${C}${D.reset} ${J??""} ${B}`;console.log(G)},J4=($)=>{let z=Date.now()-$;return z<1000?`${z}ms`:`${Math.round(z/1000)}s`},Z0=($)=>{let{app:z,log:Z,onRequest:C,onSend:J,onError:X}=$;z.addHooks("onRequest",(Q)=>{let{req:Y,pathname:B}=Q;Y.startTime=Date.now(),Z?.()??X1("<--",Y.method,B),C?.(Y,B)}),z.addHooks("onSend",async(Q,Y)=>{let{method:B,url:G}=Q.req,V=new URL(G).pathname,W=Q.get?.("requestId");Z?.()??X1("-->",B,V,Y.status,J4(Q.req.startTime),W);let f=await J?.(Q);if(f instanceof Response)return f}),z.addHooks("onError",async(Q,Y)=>{let{req:B,pathname:G}=Y;Z?.()??X1(Q.message,B.method,G,500);let V=await X?.(Q,B,G);if(V instanceof Response)return V})};function z0($,z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(Z)=>{try{let C=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!C)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(C.startsWith("Bearer "))C=C.slice(7);let J=$?.verify(C,z);if(!J)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);Z.set("user",J)}catch(C){let J="Invalid token";if(C.name==="TokenExpiredError")J="Token expired";else if(C.name==="JsonWebTokenError")J="Malformed or tampered token";return Z.json({message:"Unauthorized",error:J},401)}}}function C0($,z,Z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!z)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(C)=>{try{let J=C.cookies?.accessToken??C.req?.headers?.get("Authorization");if(!J)return C.json({message:"Unauthorized",error:"No token provided"},401);if(J.startsWith("Bearer "))J=J.slice(7);let X=$?.verify(J,Z);if(!X)return C.json({message:"Unauthorized",error:"Token could not be decoded"},401);let Q=await z.findById(X._id).select("-password -refreshToken");if(!Q)return C.json({message:"Unauthorized: User not found"},404);C.set("user",Q);return}catch(J){let X="Invalid token";if(J.name==="TokenExpiredError")X="Token expired";else if(J.name==="JsonWebTokenError")X="Malformed or tampered token";return C.json({message:"Unauthorized",error:X},401)}}}var X4=($,z)=>{try{return z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return z(Z)}catch{return Z}})}},Q1=($)=>X4($,decodeURI),Y1=($)=>{let z=$.indexOf("/",$.indexOf(":")+4),Z=z;for(;Z<$.length;Z++){let C=$.charCodeAt(Z);if(C===37){let J=$.indexOf("?",Z),X=$.slice(z,J===-1?void 0:J);return Q1(X.includes("%25")?X.replace(/%25/g,"%2525"):X)}else if(C===63)break}return $.slice(z,Z)};var B1=Symbol.for,H=Symbol("kCapture"),Y0=B1("events.errorMonitor"),Q4=Symbol("events.maxEventTargetListeners"),Y4=Symbol("events.maxEventTargetListenersWarned"),J0=B1("nodejs.rejection"),V4=B1("nodejs.rejection"),X0=Array.prototype.slice,M=10,j=function $(z){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[H]=z?.captureRejections?Boolean(z?.captureRejections):F[H])this.emit=f4},F=j.prototype={};F._events=void 0;F._eventsCount=0;F._maxListeners=void 0;F.setMaxListeners=function $(z){return G1(z,"setMaxListeners",0),this._maxListeners=z,this};F.constructor=j;F.getMaxListeners=function $(){return this?._maxListeners??M};function V0($,z){var{_events:Z}=$;if(z[0]??=new Error("Unhandled error."),!Z)throw z[0];var C=Z[Y0];if(C)for(var J of X0.call(C))J.apply($,z);var X=Z.error;if(!X)throw z[0];for(var J of X0.call(X))J.apply($,z);return!0}function B4($,z,Z,C){z.then(void 0,function(J){queueMicrotask(()=>G4($,J,Z,C))})}function G4($,z,Z,C){if(typeof $[J0]==="function")$[J0](z,Z,...C);else try{$[H]=!1,$.emit("error",z)}finally{$[H]=!0}}var W4=function $(z,...Z){if(z==="error")return V0(this,Z);var{_events:C}=this;if(C===void 0)return!1;var J=C[z];if(J===void 0)return!1;let X=J.length>1?J.slice():J;for(let Q=0,{length:Y}=X;Q<Y;Q++){let B=X[Q];switch(Z.length){case 0:B.call(this);break;case 1:B.call(this,Z[0]);break;case 2:B.call(this,Z[0],Z[1]);break;case 3:B.call(this,Z[0],Z[1],Z[2]);break;default:B.apply(this,Z);break}}return!0},f4=function $(z,...Z){if(z==="error")return V0(this,Z);var{_events:C}=this;if(C===void 0)return!1;var J=C[z];if(J===void 0)return!1;let X=J.length>1?J.slice():J;for(let Q=0,{length:Y}=X;Q<Y;Q++){let B=X[Q],G;switch(Z.length){case 0:G=B.call(this);break;case 1:G=B.call(this,Z[0]);break;case 2:G=B.call(this,Z[0],Z[1]);break;case 3:G=B.call(this,Z[0],Z[1],Z[2]);break;default:G=B.apply(this,Z);break}if(G!==void 0&&typeof G?.then==="function"&&G.then===Promise.prototype.then)B4(this,G,z,Z)}return!0};F.emit=W4;F.addListener=function $(z,Z){g(Z);var C=this._events;if(!C)C=this._events={__proto__:null},this._eventsCount=0;else if(C.newListener)this.emit("newListener",z,Z.listener??Z);var J=C[z];if(!J)C[z]=[Z],this._eventsCount++;else{J.push(Z);var X=this._maxListeners??M;if(X>0&&J.length>X&&!J.warned)B0(this,z,J)}return this};F.on=F.addListener;F.prependListener=function $(z,Z){g(Z);var C=this._events;if(!C)C=this._events={__proto__:null},this._eventsCount=0;else if(C.newListener)this.emit("newListener",z,Z.listener??Z);var J=C[z];if(!J)C[z]=[Z],this._eventsCount++;else{J.unshift(Z);var X=this._maxListeners??M;if(X>0&&J.length>X&&!J.warned)B0(this,z,J)}return this};function B0($,z,Z){Z.warned=!0;let C=new Error(`Possible EventEmitter memory leak detected. ${Z.length} ${String(z)} listeners added to [${$.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);C.name="MaxListenersExceededWarning",C.emitter=$,C.type=z,C.count=Z.length,console.warn(C)}function G0($,z,...Z){this.removeListener($,z),z.apply(this,Z)}F.once=function $(z,Z){g(Z);let C=G0.bind(this,z,Z);return C.listener=Z,this.addListener(z,C),this};F.prependOnceListener=function $(z,Z){g(Z);let C=G0.bind(this,z,Z);return C.listener=Z,this.prependListener(z,C),this};F.removeListener=function $(z,Z){g(Z);var{_events:C}=this;if(!C)return this;var J=C[z];if(!J)return this;var X=J.length;let Q=-1;for(let Y=X-1;Y>=0;Y--)if(J[Y]===Z||J[Y].listener===Z){Q=Y;break}if(Q<0)return this;if(Q===0)J.shift();else J.splice(Q,1);if(J.length===0)delete C[z],this._eventsCount--;return this};F.off=F.removeListener;F.removeAllListeners=function $(z){var{_events:Z}=this;if(z&&Z){if(Z[z])delete Z[z],this._eventsCount--}else this._events={__proto__:null};return this};F.listeners=function $(z){var{_events:Z}=this;if(!Z)return[];var C=Z[z];if(!C)return[];return C.map((J)=>J.listener??J)};F.rawListeners=function $(z){var{_events:Z}=this;if(!Z)return[];var C=Z[z];if(!C)return[];return C.slice()};F.listenerCount=function $(z){var{_events:Z}=this;if(!Z)return 0;return Z[z]?.length??0};F.eventNames=function $(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};F[H]=!1;function K4($,z,Z){var C=Z?.signal;if(W0(C,"options.signal"),C?.aborted)throw new V1(void 0,{cause:C?.reason});let{resolve:J,reject:X,promise:Q}=$newPromiseCapability(Promise),Y=(V)=>{if($.removeListener(z,B),C!=null)l(C,"abort",G);X(V)},B=(...V)=>{if(typeof $.removeListener==="function")$.removeListener("error",Y);if(C!=null)l(C,"abort",G);J(V)};if(Q0($,z,B,{once:!0}),z!=="error"&&typeof $.once==="function")$.once("error",Y);function G(){l($,z,B),l($,"error",Y),X(new V1(void 0,{cause:C?.reason}))}if(C!=null)Q0(C,"abort",G,{once:!0});return Q}function F4($,z){return $.listeners(z)}function U4($,...z){G1($,"setMaxListeners",0);var Z;if(z&&(Z=z.length))for(let C=0;C<Z;C++)z[C].setMaxListeners($);else M=$}function D4($,z){return $.listenerCount(z)}function l($,z,Z,C){if(typeof $.removeListener==="function")$.removeListener(z,Z);else $.removeEventListener(z,Z,C)}function Q0($,z,Z,C){if(typeof $.on==="function")if(C.once)$.once(z,Z);else $.on(z,Z);else $.addEventListener(z,Z,C)}class V1 extends Error{constructor($="The operation was aborted",z=void 0){if(z!==void 0&&typeof z!=="object")throw R("options","Object",z);super($,z);this.code="ABORT_ERR",this.name="AbortError"}}function R($,z,Z){let C=new TypeError(`The "${$}" argument must be of type ${z}. Received ${Z}`);return C.code="ERR_INVALID_ARG_TYPE",C}function N4($,z,Z){let C=new RangeError(`The "${$}" argument is out of range. It must be ${z}. Received ${Z}`);return C.code="ERR_OUT_OF_RANGE",C}function W0($,z){if($!==void 0&&($===null||typeof $!=="object"||!("aborted"in $)))throw R(z,"AbortSignal",$)}function G1($,z,Z,C){if(typeof $!=="number")throw R(z,"number",$);if(Z!=null&&$<Z||C!=null&&$>C||(Z!=null||C!=null)&&Number.isNaN($))throw N4(z,`${Z!=null?`>= ${Z}`:""}${Z!=null&&C!=null?" && ":""}${C!=null?`<= ${C}`:""}`,$)}function g($){if(typeof $!=="function")throw new TypeError("The listener must be a function")}function q4($,z){if(typeof $!=="boolean")throw R(z,"boolean",$)}function A4($){return $?._maxListeners??M}function S4($,z){if($===void 0)throw R("signal","AbortSignal",$);if(W0($,"signal"),typeof z!=="function")throw R("listener","function",z);let Z;if($.aborted)queueMicrotask(()=>z());else $.addEventListener("abort",z,{__proto__:null,once:!0}),Z=()=>{$.removeEventListener("abort",z)};return{__proto__:null,[Symbol.dispose](){Z?.()}}}Object.defineProperties(j,{captureRejections:{get(){return F[H]},set($){q4($,"EventEmitter.captureRejections"),F[H]=$},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return M},set:($)=>{G1($,"defaultMaxListeners",0),M=$}},kMaxEventTargetListeners:{value:Q4,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:Y4,enumerable:!1,configurable:!1,writable:!1}});Object.assign(j,{once:K4,getEventListeners:F4,getMaxListeners:A4,setMaxListeners:U4,EventEmitter:j,usingDomains:!1,captureRejectionSymbol:V4,errorMonitor:Y0,addAbortListener:S4,init:j,listenerCount:D4});class x{static instance;fecth;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#$=!1;emitter;errorFormat;staticPath;staticRequestPath=void 0;constructor({jwtSecret:$,baseApiUrl:z,enableFileRouting:Z,idleTimeOut:C,prefixApiUrl:J,onError:X,logger:Q,pipelineArchitecture:Y,errorFormat:B="json"}={}){if(this.errorFormat=B,!x.instance)x.instance=this;if(Y)this.#$=!0;if(this.errorFormat=B,this.emitter=new j,this.prefixApiUrl=J??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=C??10,this.enableFileRouter=Z??!1,this.baseApiUrl=z||"",this.user_jwt_secret=$||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new y,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},X)this.addHooks("onError",(G,V)=>{console.log("Got an exception:",G),console.log("Request Path:",V.pathname)});if(Q)this.useLogger({app:this,onError(G){console.error("Got an exception:",G)}});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($){if(!this.instance)this.instance=new x;return new Proxy(this.instance,{get(z,Z,C){return(J,X)=>{let Q=$+J;return z[Z](Q,X)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.FilterRoutes=null,this.setupFilter()},authenticate:($)=>{if($?.length)for(let z of $)this.filterFunction.push(z)},authenticateJwt:($)=>{this.filterFunction.push(z0($,this.user_jwt_secret))},authenticateJwtDB:($,z)=>{this.filterFunction.push(C0($,z,this.user_jwt_secret))}}}redirect($,z,Z){return this.any($,(C)=>{let J=C.params,X=z;if(J)for(let Y in J)X=X.replace(`:${Y}`,J[Y]);let Q=C.url.search;if(Q)X+=Q;return C.redirect(X,Z)}),this}serveStatic($,z){return this.staticPath=$,this.staticRequestPath=z,this}static($,z){return this.staticPath=$,this.staticRequestPath=z,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,z){if(typeof $!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(z);break;case"preHandler":this.hooks.preHandler?.push(z);break;case"postHandler":this.hooks.postHandler?.push(z);break;case"onSend":this.hooks.onSend?.push(z);break;case"onError":this.hooks.onError?.push(z);break;case"onClose":this.hooks.onClose?.push(z);break;default:throw new Error(`Unknown hook type: ${$}`)}return this}compile(){let $={hasMiddleware:!1,hasOnReqHook:!1,hasPreHandlerHook:!1,hasOnError:!1,hasPostHandlerHook:!1,hasOnSendHook:!1,hasFilterEnabled:!1};if(this.hasFilterEnabled)$.hasFilterEnabled=!0,this.hasFilterEnabled=!0;if(this?.globalMiddlewares?.length>0)$.hasMiddleware=!0,this.hasMiddleware=!0;for(let[z,Z]of this?.middlewares?.entries())if(Z.length>0){$.hasMiddleware=!0,this.hasMiddleware=!0;break}if(this?.enableFileRouter){let z=process.cwd(),Z=O.join(z,"src","routes");if(W1?.existsSync(Z))this.loadRoutes(Z,"")}if(this?.hooks?.onRequest&&this.hooks.onRequest.length>0)$.hasOnReqHook=!0,this.hasOnReqHook=!0;if(this?.hooks?.preHandler&&this.hooks.preHandler.length>0)$.hasPreHandlerHook=!0,this.hasPreHandlerHook=!0;if(this?.hooks?.postHandler&&this.hooks.postHandler?.length>0)$.hasPostHandlerHook=!0,this.hasPostHandlerHook=!0;if(this?.hooks?.onSend&&this.hooks.onSend?.length>0)$.hasOnSendHook=!0,this.hasOnSendHook=!0;if(this?.hooks?.onError&&this.hooks.onError?.length>0)$.hasOnError=!0,this.hasOnError=!0;return this.tempRoutes=null,this.compileConfig=$,$}async registerFileRoutes($,z,Z){let C=await import($),J;if(Z===".ts")J=O.basename($,".ts");else if(Z===".js")J=O.basename($,".js");let X=z+"/"+J;if(X.endsWith("/index"))X=z;else if(X.endsWith("/api"))X=z;X=X.replace(/\[(.*?)\]/g,":$1");let Q=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let Y of Q)if(C[Y]){let B=Y.toLowerCase(),G=C[Y];this[B](`${this.baseApiUrl}${X}`,G)}}async loadRoutes($,z){let Z=await W1.promises.readdir($);for(let C of Z){let J=O.join($,C);if((await W1.promises.stat(J)).isDirectory())await this.loadRoutes(J,z+"/"+C);else if(C.endsWith(".ts"))await this.registerFileRoutes(J,z,".ts");else if(C.endsWith(".js"))await this.registerFileRoutes(J,z,".js")}}useLogger($){return Z0($),this}useAdvancedLogger($){return $0($),this}BunRoute($,z,...Z){if(!z||typeof z!=="string")throw new Error("give a path in string format");if(!this.compileConfig)this.compile();let C;if(typeof Z[0]==="string"||typeof Z[0]==="object")C=Z[0];if(typeof C!=="undefined"){let X=typeof C==="string"?C:JSON.stringify(C)}let J=e1(this.compileConfig,this,$.toUpperCase(),z,...Z);return this.routes[z]=J,this}listen($,...z){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let Z="0.0.0.0",C=void 0,J={};for(let Q of z)if(typeof Q==="string")Z=Q;else if(typeof Q==="function")C=Q;else if(typeof Q==="object"&&Q!==null)J=Q;let X={port:$,hostname:Z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)X.routes=this.routes;if(J.cert&&J.key)X.certFile=J.cert,X.keyFile=J.key;if(this.serverInstance=Bun?.serve(X),C)C();return this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}fetch(){let $=this.compile();if(this.#$){let z=t1($,this);return(Z,C)=>{return z(Z,C,this).catch(async(J)=>{return console.error("Unhandled handler error:",J),await L("onError",this.hooks.onError,[J,Z,Y1(Z.url),C])||I(500,"Internal Server Error")})}}return this.handleRequests.bind(this)}async handleRequests($,z){let Z,C=$.url.indexOf("/",$.url.indexOf(":")+4),J=C;for(;J<$.url.length;J++){let Y=$.url.charCodeAt(J);if(Y===37){let B=$.url.indexOf("?",J),G=$.url.slice(C,B===-1?void 0:B);Z=Q1(G.includes("%25")?G.replace(/%25/g,"%2525"):G);break}else if(Y===63)break}if(!Z)Z=$.url.slice(C,J);let X=this.trie.search(Z,$.method),Q=new v($,z,Z,X?.path);try{if(this.hasOnReqHook)await L("onRequest",this.hooks.onRequest,[Q]);if(this.hasMiddleware){let G=await r1(this,Z,Q);if(G)return G}if(this.hasFilterEnabled){let G=await h(this,Z,Q);if(G)return G}if(!X)return await d(this,Q,Z);if(this.hasPreHandlerHook){let G=await L("preHandler",this.hooks.preHandler,[Q]);if(G)return G}let Y=X.handler(Q),B=Y instanceof Promise?await Y:Y;if(this.hasOnSendHook){let G=await L("onSend",this.hooks.onSend,[Q,B]);if(G)return G}if(B instanceof Response)return B}catch(Y){return this.handleError(Y,Q)}return I(500,"No response returned from handler.")}async handleError($,z){let C=this.errorFormat,J=Y1(z.req.url),X=await L("onError",this.hooks.onError,[$,z]);if(X)return X;if($&&typeof $==="object"&&$.name==="HTTPException"){let B=$;if(B.res)return B.res;return C==="json"?Response.json({error:B.message},{status:B.status}):new Response(B.message,{status:B.status})}let Q=$ instanceof Error?$.message:"Internal Server Error",Y=$ instanceof Error?$.stack:void 0;if(C==="json"){let B={error:Q,...!1,path:J};return Response.json(B,{status:500,headers:{"Content-Type":"application/json"}})}else{let B=`Error: ${Q}`;return new Response(B,{headers:{"Content-Type":"text/plain"},status:500})}}route($,z){$=$&&$.length>0?$:z?.prefixApiUrl;let Z=z?.tempRoutes??new Map;for(let[C,J]of Z.entries()){let X=C.replace(/::\w+$/,""),Q=`${$}${X}`;if(!this.middlewares.has(Q))this.middlewares.set(Q,[]);J.handlers.slice(0,-1).forEach((V)=>{let W=this.middlewares.get(Q);if(!W.includes(V))W.push(V)});let B=J.handlers[J.handlers.length-1],G=J.method;try{this.trie.insert(Q,{handler:B,method:G})}catch(V){console.error(`Error inserting ${Q}:`,V)}}return z=null,this}register($,z){return this.route($,z)}addRoute($,z,Z){if(typeof z!=="string")throw new Error(`Error in ${Z[Z.length-1]}: Path must be a string. Received: ${typeof z}`);if(typeof $!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(z+"::"+$,{method:$,handlers:Z});let C=Z.slice(0,-1),J=Z[Z.length-1];if(C.length>0){if(!this.middlewares.has(z))this.middlewares.set(z,[]);C.forEach((X)=>{if(z==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...C])];else if(!this.middlewares.get(z)?.includes(X))this.middlewares.get(z)?.push(X)})}try{if($==="ANY"){let X=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let Q of X)this.trie.insert(z,{handler:J,method:Q})}this.trie.insert(z,{handler:J,method:$})}catch(X){console.error(`Error inserting ${z}:`,X)}}use($,z){if(Array.isArray($))$.forEach((C)=>{if(typeof C==="function")this.globalMiddlewares.push(C)});if(typeof $==="function"){if(this.globalMiddlewares.push($),Array.isArray(z))z.forEach((C)=>{this.globalMiddlewares.push(C)});return this}return(Array.isArray($)?$.filter((C)=>typeof C==="string"):[$].filter((C)=>typeof C==="string")).forEach((C)=>{if(!this.middlewares.has(C))this.middlewares.set(C,[]);if(z)(Array.isArray(z)?z:[z]).forEach((X)=>{this.middlewares.get(C)?.push(X)})}),this}get($,...z){return this.addRoute("GET",$,z),this}post($,...z){return this.addRoute("POST",$,z),this}put($,...z){return this.addRoute("PUT",$,z),this}patch($,...z){return this.addRoute("PATCH",$,z),this}delete($,...z){return this.addRoute("DELETE",$,z),this}any($,...z){return this.addRoute("ANY",$,z),this}head($,...z){return this.addRoute("HEAD",$,z),this}options($,...z){return this.addRoute("OPTIONS",$,z),this}propfind($,...z){return this.addRoute("PROPFIND",$,z),this}routeNotFound($){return this.routeNotFoundFunc=$,this}on($,z){this.emitter.on($,z)}emit($,...z){this.emitter.emit($,...z)}}export{x as default};
|
package/dist/request_pipeline.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var E1=Object.create;var{getPrototypeOf:O1,defineProperty:b,getOwnPropertyNames:h,getOwnPropertyDescriptor:S1}=Object,n=Object.prototype.hasOwnProperty;var
|
|
1
|
+
var E1=Object.create;var{getPrototypeOf:O1,defineProperty:b,getOwnPropertyNames:h,getOwnPropertyDescriptor:S1}=Object,n=Object.prototype.hasOwnProperty;var P1=(f,v,g)=>{g=f!=null?E1(O1(f)):{};let C=v||!f||!f.__esModule?b(g,"default",{value:f,enumerable:!0}):g;for(let w of h(f))if(!n.call(C,w))b(C,w,{get:()=>f[w],enumerable:!0});return C},m=new WeakMap,x1=(f)=>{var v=m.get(f),g;if(v)return v;if(v=b({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")h(f).map((C)=>!n.call(v,C)&&b(v,C,{get:()=>f[C],enumerable:!(g=S1(f,C))||g.enumerable}));return m.set(f,v),v},E=(f,v)=>()=>(v||f((v={exports:{}}).exports,v),v.exports);var c1=(f,v)=>{for(var g in v)b(f,g,{get:v[g],enumerable:!0,configurable:!0,set:(C)=>v[g]=()=>C})};var _1=(f,v)=>()=>(f&&(v=f(f=0)),v);var y1=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(v,g)=>(typeof require!=="undefined"?require:v)[g]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var w1={};c1(w1,{sep:()=>g1,resolve:()=>D,relative:()=>a,posix:()=>C1,parse:()=>f1,normalize:()=>O,join:()=>i,isAbsolute:()=>l,format:()=>p,extname:()=>o,dirname:()=>s,delimiter:()=>v1,default:()=>T1,basename:()=>e,_makeLong:()=>t});function U(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function d(f,v){var g="",C=0,w=-1,$=0,z;for(var K=0;K<=f.length;++K){if(K<f.length)z=f.charCodeAt(K);else if(z===47)break;else z=47;if(z===47){if(w===K-1||$===1);else if(w!==K-1&&$===2){if(g.length<2||C!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var A=g.lastIndexOf("/");if(A!==g.length-1){if(A===-1)g="",C=0;else g=g.slice(0,A),C=g.length-1-g.lastIndexOf("/");w=K,$=0;continue}}else if(g.length===2||g.length===1){g="",C=0,w=K,$=0;continue}}if(v){if(g.length>0)g+="/..";else g="..";C=2}}else{if(g.length>0)g+="/"+f.slice(w+1,K);else g=f.slice(w+1,K);C=K-w-1}w=K,$=0}else if(z===46&&$!==-1)++$;else $=-1}return g}function r1(f,v){var g=v.dir||v.root,C=v.base||(v.name||"")+(v.ext||"");if(!g)return C;if(g===v.root)return g+C;return g+f+C}function D(){var f="",v=!1,g;for(var C=arguments.length-1;C>=-1&&!v;C--){var w;if(C>=0)w=arguments[C];else{if(g===void 0)g=process.cwd();w=g}if(U(w),w.length===0)continue;f=w+"/"+f,v=w.charCodeAt(0)===47}if(f=d(f,!v),v)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function O(f){if(U(f),f.length===0)return".";var v=f.charCodeAt(0)===47,g=f.charCodeAt(f.length-1)===47;if(f=d(f,!v),f.length===0&&!v)f=".";if(f.length>0&&g)f+="/";if(v)return"/"+f;return f}function l(f){return U(f),f.length>0&&f.charCodeAt(0)===47}function i(){if(arguments.length===0)return".";var f;for(var v=0;v<arguments.length;++v){var g=arguments[v];if(U(g),g.length>0)if(f===void 0)f=g;else f+="/"+g}if(f===void 0)return".";return O(f)}function a(f,v){if(U(f),U(v),f===v)return"";if(f=D(f),v=D(v),f===v)return"";var g=1;for(;g<f.length;++g)if(f.charCodeAt(g)!==47)break;var C=f.length,w=C-g,$=1;for(;$<v.length;++$)if(v.charCodeAt($)!==47)break;var z=v.length,K=z-$,A=w<K?w:K,G=-1,J=0;for(;J<=A;++J){if(J===A){if(K>A){if(v.charCodeAt($+J)===47)return v.slice($+J+1);else if(J===0)return v.slice($+J)}else if(w>A){if(f.charCodeAt(g+J)===47)G=J;else if(J===0)G=0}break}var Y=f.charCodeAt(g+J),Z=v.charCodeAt($+J);if(Y!==Z)break;else if(Y===47)G=J}var V="";for(J=g+G+1;J<=C;++J)if(J===C||f.charCodeAt(J)===47)if(V.length===0)V+="..";else V+="/..";if(V.length>0)return V+v.slice($+G);else{if($+=G,v.charCodeAt($)===47)++$;return v.slice($)}}function t(f){return f}function s(f){if(U(f),f.length===0)return".";var v=f.charCodeAt(0),g=v===47,C=-1,w=!0;for(var $=f.length-1;$>=1;--$)if(v=f.charCodeAt($),v===47){if(!w){C=$;break}}else w=!1;if(C===-1)return g?"/":".";if(g&&C===1)return"//";return f.slice(0,C)}function e(f,v){if(v!==void 0&&typeof v!=="string")throw new TypeError('"ext" argument must be a string');U(f);var g=0,C=-1,w=!0,$;if(v!==void 0&&v.length>0&&v.length<=f.length){if(v.length===f.length&&v===f)return"";var z=v.length-1,K=-1;for($=f.length-1;$>=0;--$){var A=f.charCodeAt($);if(A===47){if(!w){g=$+1;break}}else{if(K===-1)w=!1,K=$+1;if(z>=0)if(A===v.charCodeAt(z)){if(--z===-1)C=$}else z=-1,C=K}}if(g===C)C=K;else if(C===-1)C=f.length;return f.slice(g,C)}else{for($=f.length-1;$>=0;--$)if(f.charCodeAt($)===47){if(!w){g=$+1;break}}else if(C===-1)w=!1,C=$+1;if(C===-1)return"";return f.slice(g,C)}}function o(f){U(f);var v=-1,g=0,C=-1,w=!0,$=0;for(var z=f.length-1;z>=0;--z){var K=f.charCodeAt(z);if(K===47){if(!w){g=z+1;break}continue}if(C===-1)w=!1,C=z+1;if(K===46){if(v===-1)v=z;else if($!==1)$=1}else if(v!==-1)$=-1}if(v===-1||C===-1||$===0||$===1&&v===C-1&&v===g+1)return"";return f.slice(v,C)}function p(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return r1("/",f)}function f1(f){U(f);var v={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return v;var g=f.charCodeAt(0),C=g===47,w;if(C)v.root="/",w=1;else w=0;var $=-1,z=0,K=-1,A=!0,G=f.length-1,J=0;for(;G>=w;--G){if(g=f.charCodeAt(G),g===47){if(!A){z=G+1;break}continue}if(K===-1)A=!1,K=G+1;if(g===46){if($===-1)$=G;else if(J!==1)J=1}else if($!==-1)J=-1}if($===-1||K===-1||J===0||J===1&&$===K-1&&$===z+1){if(K!==-1)if(z===0&&C)v.base=v.name=f.slice(1,K);else v.base=v.name=f.slice(z,K)}else{if(z===0&&C)v.name=f.slice(1,$),v.base=f.slice(1,K);else v.name=f.slice(z,$),v.base=f.slice(z,K);v.ext=f.slice($,K)}if(z>0)v.dir=f.slice(0,z-1);else if(C)v.dir="/";return v}var g1="/",v1=":",C1,T1;var $1=_1(()=>{C1=((f)=>(f.posix=f,f))({resolve:D,normalize:O,isAbsolute:l,join:i,relative:a,_makeLong:t,dirname:s,basename:e,extname:o,format:p,parse:f1,sep:g1,delimiter:v1,win32:null,posix:null}),T1=C1});var K1=E((i1)=>{var k1=/[|\\{}()[\]^$+*?.]/g,m1=Object.prototype.hasOwnProperty,P=function(f,v){return m1.apply(f,[v])};i1.escapeRegExpChars=function(f){if(!f)return"";return String(f).replace(k1,"\\$&")};var h1={"&":"&","<":"<",">":">",'"':""","'":"'"},n1=/[&<>'"]/g;function d1(f){return h1[f]||f}var l1=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -10,17 +10,17 @@ function encode_char(c) {
|
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
12
|
`;i1.escapeXML=function(f){return f==null?"":String(f).replace(n1,d1)};function z1(){return Function.prototype.toString.call(this)+`;
|
|
13
|
-
`+l1}try{if(typeof Object.defineProperty==="function")Object.defineProperty(i1.escapeXML,"toString",{value:z1});else i1.escapeXML.toString=z1}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}i1.shallowCopy=function(f,v){if(v=v||{},f!==null&&f!==void 0)for(var g in v){if(!
|
|
14
|
-
`),
|
|
13
|
+
`+l1}try{if(typeof Object.defineProperty==="function")Object.defineProperty(i1.escapeXML,"toString",{value:z1});else i1.escapeXML.toString=z1}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}i1.shallowCopy=function(f,v){if(v=v||{},f!==null&&f!==void 0)for(var g in v){if(!P(v,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=v[g]}return f};i1.shallowCopyFromList=function(f,v,g){if(g=g||[],v=v||{},f!==null&&f!==void 0)for(var C=0;C<g.length;C++){var w=g[C];if(typeof v[w]!="undefined"){if(!P(v,w))continue;if(w==="__proto__"||w==="constructor")continue;f[w]=v[w]}}return f};i1.cache={_data:{},set:function(f,v){this._data[f]=v},get:function(f){return this._data[f]},remove:function(f){delete this._data[f]},reset:function(){this._data={}}};i1.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(v){return v[1].toUpperCase()})};i1.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();i1.hasOwnOnlyObject=function(f){var v=i1.createNullProtoObjWherePossible();for(var g in f)if(P(f,g))v[g]=f[g];return v}});var Y1=E((Lf,ff)=>{ff.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var u1=E((U1)=>{var _=(()=>({})),N=($1(),x1(w1)),j=K1(),Z1=!1,gf=Y1().version,vf="<",Cf=">",wf="%",W1="locals",$f="ejs",zf="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",X1=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],Jf=X1.concat("cache"),A1=/^\uFEFF/,x=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;U1.cache=j.cache;U1.fileLoader=_.readFileSync;U1.localsName=W1;U1.promiseImpl=new Function("return this;")().Promise;U1.resolveInclude=function(f,v,g){var{dirname:C,extname:w,resolve:$}=N,z=$(g?v:C(v),f),K=w(f);if(!K)z+=".ejs";return z};function V1(f,v){var g;if(v.some(function(C){return g=U1.resolveInclude(f,C,!0),_.existsSync(g)}))return g}function Kf(f,v){var g,C,w=v.views,$=/^[A-Za-z]+:\\|^\//.exec(f);if($&&$.length)if(f=f.replace(/^\/*/,""),Array.isArray(v.root))g=V1(f,v.root);else g=U1.resolveInclude(f,v.root||"/",!0);else{if(v.filename){if(C=U1.resolveInclude(f,v.filename),_.existsSync(C))g=C}if(!g&&Array.isArray(w))g=V1(f,w);if(!g&&typeof v.includer!=="function")throw new Error('Could not find the include file "'+v.escapeFunction(f)+'"')}return g}function R(f,v){var g,C=f.filename,w=arguments.length>1;if(f.cache){if(!C)throw new Error("cache option requires a filename");if(g=U1.cache.get(C),g)return g;if(!w)v=G1(C).toString().replace(A1,"")}else if(!w){if(!C)throw new Error("Internal EJS error: no file name or template provided");v=G1(C).toString().replace(A1,"")}if(g=U1.compile(v,f),f.cache)U1.cache.set(C,g);return g}function Yf(f,v,g){var C;if(!g)if(typeof U1.promiseImpl=="function")return new U1.promiseImpl(function(w,$){try{C=R(f)(v),w(C)}catch(z){$(z)}});else throw new Error("Please provide a callback function");else{try{C=R(f)(v)}catch(w){return g(w)}g(null,C)}}function G1(f){return U1.fileLoader(f)}function Zf(f,v){var g=j.shallowCopy(j.createNullProtoObjWherePossible(),v);if(g.filename=Kf(f,g),typeof v.includer==="function"){var C=v.includer(f,g.filename);if(C){if(C.filename)g.filename=C.filename;if(C.template)return R(g,C.template)}}return R(g)}function j1(f,v,g,C,w){var $=v.split(`
|
|
14
|
+
`),z=Math.max(C-3,0),K=Math.min($.length,C+3),A=w(g),G=$.slice(z,K).map(function(J,Y){var Z=Y+z+1;return(Z==C?" >> ":" ")+Z+"| "+J}).join(`
|
|
15
15
|
`);throw f.path=A,f.message=(A||"ejs")+":"+C+`
|
|
16
16
|
`+G+`
|
|
17
17
|
|
|
18
|
-
`+f.message,f}function Q1(f){return f.replace(/;(\s*$)/,"$1")}U1.compile=function f(v,g){var C;if(g&&g.scope){if(!Z1)console.warn("`scope` option is deprecated and will be removed in EJS 3"),Z1=!0;if(!g.context)g.context=g.scope;delete g.scope}return C=new
|
|
18
|
+
`+f.message,f}function Q1(f){return f.replace(/;(\s*$)/,"$1")}U1.compile=function f(v,g){var C;if(g&&g.scope){if(!Z1)console.warn("`scope` option is deprecated and will be removed in EJS 3"),Z1=!0;if(!g.context)g.context=g.scope;delete g.scope}return C=new W(v,g),C.compile()};U1.render=function(f,v,g){var C=v||j.createNullProtoObjWherePossible(),w=g||j.createNullProtoObjWherePossible();if(arguments.length==2)j.shallowCopyFromList(w,C,X1);return R(w,f)(C)};U1.renderFile=function(){var f=Array.prototype.slice.call(arguments),v=f.shift(),g,C={filename:v},w,$;if(typeof arguments[arguments.length-1]=="function")g=f.pop();if(f.length){if(w=f.shift(),f.length)j.shallowCopy(C,f.pop());else{if(w.settings){if(w.settings.views)C.views=w.settings.views;if(w.settings["view cache"])C.cache=!0;if($=w.settings["view options"],$)j.shallowCopy(C,$)}j.shallowCopyFromList(C,w,Jf)}C.filename=v}else w=j.createNullProtoObjWherePossible();return Yf(C,w,g)};U1.Template=W;U1.clearCache=function(){U1.cache.reset()};function W(f,v){var g=j.hasOwnOnlyObject(v),C=j.createNullProtoObjWherePossible();if(this.templateText=f,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",C.client=g.client||!1,C.escapeFunction=g.escape||g.escapeFunction||j.escapeXML,C.compileDebug=g.compileDebug!==!1,C.debug=!!g.debug,C.filename=g.filename,C.openDelimiter=g.openDelimiter||U1.openDelimiter||vf,C.closeDelimiter=g.closeDelimiter||U1.closeDelimiter||Cf,C.delimiter=g.delimiter||U1.delimiter||wf,C.strict=g.strict||!1,C.context=g.context,C.cache=g.cache||!1,C.rmWhitespace=g.rmWhitespace,C.root=g.root,C.includer=g.includer,C.outputFunctionName=g.outputFunctionName,C.localsName=g.localsName||U1.localsName||W1,C.views=g.views,C.async=g.async,C.destructuredLocals=g.destructuredLocals,C.legacyInclude=typeof g.legacyInclude!="undefined"?!!g.legacyInclude:!0,C.strict)C._with=!1;else C._with=typeof g._with!="undefined"?g._with:!0;this.opts=C,this.regex=this.createRegex()}W.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};W.prototype={createRegex:function(){var f=zf,v=j.escapeRegExpChars(this.opts.delimiter),g=j.escapeRegExpChars(this.opts.openDelimiter),C=j.escapeRegExpChars(this.opts.closeDelimiter);return f=f.replace(/%/g,v).replace(/</g,g).replace(/>/g,C),new RegExp(f)},compile:function(){var f,v,g=this.opts,C="",w="",$=g.escapeFunction,z,K=g.filename?JSON.stringify(g.filename):"undefined";if(!this.source){if(this.generateSource(),C+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
|
-
`,g.outputFunctionName){if(!
|
|
21
|
-
`}if(g.localsName&&!
|
|
22
|
-
`;for(var G=0;G<g.destructuredLocals.length;G++){var
|
|
23
|
-
`;A+=
|
|
20
|
+
`,g.outputFunctionName){if(!x.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");C+=" var "+g.outputFunctionName+` = __append;
|
|
21
|
+
`}if(g.localsName&&!x.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var A=" var __locals = ("+g.localsName+` || {}),
|
|
22
|
+
`;for(var G=0;G<g.destructuredLocals.length;G++){var J=g.destructuredLocals[G];if(!x.test(J))throw new Error("destructuredLocals["+G+"] is not a valid JS identifier.");if(G>0)A+=`,
|
|
23
|
+
`;A+=J+" = __locals."+J}C+=A+`;
|
|
24
24
|
`}if(g._with!==!1)C+=" with ("+g.localsName+` || {}) {
|
|
25
25
|
`,w+=` }
|
|
26
26
|
`;w+=` return __output;
|
|
@@ -36,34 +36,34 @@ try {
|
|
|
36
36
|
`+f}if(g.strict)f=`"use strict";
|
|
37
37
|
`+f;if(g.debug)console.log(f);if(g.compileDebug&&g.filename)f=f+`
|
|
38
38
|
//# sourceURL=`+K+`
|
|
39
|
-
`;try{if(g.async)try{
|
|
39
|
+
`;try{if(g.async)try{z=new Function("return (async function(){}).constructor;")()}catch(Q){if(Q instanceof SyntaxError)throw new Error("This environment does not support async/await");else throw Q}else z=Function;v=new z(g.localsName+", escapeFn, include, rethrow",f)}catch(Q){if(Q instanceof SyntaxError){if(g.filename)Q.message+=" in "+g.filename;if(Q.message+=` while compiling ejs
|
|
40
40
|
|
|
41
41
|
`,Q.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
42
|
`,Q.message+="https://github.com/RyanZim/EJS-Lint",!g.async)Q.message+=`
|
|
43
|
-
`,Q.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw Q}var Y=g.client?v:function Q(F){var B=function(
|
|
44
|
-
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var v=this,g=this.parseTemplateText(),C=this.opts.delimiter,w=this.opts.openDelimiter,$=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(
|
|
43
|
+
`,Q.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw Q}var Y=g.client?v:function Q(F){var B=function(X,H){var I=j.shallowCopy(j.createNullProtoObjWherePossible(),F);if(H)I=j.shallowCopy(I,H);return Zf(X,g)(I)};return v.apply(g.context,[F||j.createNullProtoObjWherePossible(),$,B,j1])};if(g.filename&&typeof Object.defineProperty==="function"){var Z=g.filename,V=N.basename(Z,N.extname(Z));try{Object.defineProperty(Y,"name",{value:V,writable:!1,enumerable:!1,configurable:!0})}catch(Q){}}return Y},generateSource:function(){var f=this.opts;if(f.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
|
+
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var v=this,g=this.parseTemplateText(),C=this.opts.delimiter,w=this.opts.openDelimiter,$=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(z,K){var A;if(z.indexOf(w+C)===0&&z.indexOf(w+C+C)!==0){if(A=g[K+2],!(A==C+$||A=="-"+C+$||A=="_"+C+$))throw new Error('Could not find matching close tag for "'+z+'".')}v.scanLine(z)})},parseTemplateText:function(){var f=this.templateText,v=this.regex,g=v.exec(f),C=[],w;while(g){if(w=g.index,w!==0)C.push(f.substring(0,w)),f=f.slice(w);C.push(g[0]),f=f.slice(g[0].length),g=v.exec(f)}if(f)C.push(f);return C},_addOutput:function(f){if(this.truncate)f=f.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!f)return f;f=f.replace(/\\/g,"\\\\"),f=f.replace(/\n/g,"\\n"),f=f.replace(/\r/g,"\\r"),f=f.replace(/"/g,"\\\""),this.source+=' ; __append("'+f+`")
|
|
45
45
|
`},scanLine:function(f){var v=this,g=this.opts.delimiter,C=this.opts.openDelimiter,w=this.opts.closeDelimiter,$=0;switch($=f.split(`
|
|
46
|
-
`).length-1,f){case C+g:case C+g+"_":this.mode=
|
|
47
|
-
`;break;case g+g+w:this.mode=
|
|
48
|
-
`;break;case g+w:case"-"+g+w:case"_"+g+w:if(this.mode==
|
|
46
|
+
`).length-1,f){case C+g:case C+g+"_":this.mode=W.modes.EVAL;break;case C+g+"=":this.mode=W.modes.ESCAPED;break;case C+g+"-":this.mode=W.modes.RAW;break;case C+g+"#":this.mode=W.modes.COMMENT;break;case C+g+g:this.mode=W.modes.LITERAL,this.source+=' ; __append("'+f.replace(C+g+g,C+g)+`")
|
|
47
|
+
`;break;case g+g+w:this.mode=W.modes.LITERAL,this.source+=' ; __append("'+f.replace(g+g+w,g+w)+`")
|
|
48
|
+
`;break;case g+w:case"-"+g+w:case"_"+g+w:if(this.mode==W.modes.LITERAL)this._addOutput(f);this.mode=null,this.truncate=f.indexOf("-")===0||f.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case W.modes.EVAL:case W.modes.ESCAPED:case W.modes.RAW:if(f.lastIndexOf("//")>f.lastIndexOf(`
|
|
49
49
|
`))f+=`
|
|
50
|
-
`}switch(this.mode){case
|
|
51
|
-
`;break;case
|
|
52
|
-
`;break;case
|
|
53
|
-
`;break;case
|
|
54
|
-
`}};U1.escapeXML=j.escapeXML;U1.__express=U1.renderFile;U1.VERSION=gf;U1.name=$f;if(typeof window!="undefined")window.ejs=U1});function
|
|
50
|
+
`}switch(this.mode){case W.modes.EVAL:this.source+=" ; "+f+`
|
|
51
|
+
`;break;case W.modes.ESCAPED:this.source+=" ; __append(escapeFn("+Q1(f)+`))
|
|
52
|
+
`;break;case W.modes.RAW:this.source+=" ; __append("+Q1(f)+`)
|
|
53
|
+
`;break;case W.modes.COMMENT:break;case W.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(v.opts.compileDebug&&$)this.currentLine+=$,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
+
`}};U1.escapeXML=j.escapeXML;U1.__express=U1.renderFile;U1.VERSION=gf;U1.name=$f;if(typeof window!="undefined")window.ejs=U1});function u(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var y=null;async function N1(){if(!y){let f=await Promise.resolve().then(() => P1(u1(),1));y=f.default||f}return y}class r{req;server;pathname;routePattern;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,v,g,C=""){this.req=f,this.server=v,this.pathname=g,this.routePattern=C}setHeader(f,v){return this.headers.set(f,v),this}removeHeader(f){return this.headers.delete(f),this}set(f,v){return this.contextData[f]=v,this}get(f){return this.contextData[f]}get ip(){return this.server.requestIP(this.req)?.address??null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=D1(this.routePattern,this.pathname)}catch(f){let v=f instanceof Error?f.message:String(f);throw new Error(`Failed to extract route parameters: ${v}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let f=await q1(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f}catch(f){throw new Error("Invalid request body format")}})();return this.parsedBody}text(f,v=200){return new Response(f,{status:v,headers:this.headers})}send(f,v=200){let g;if(f instanceof Uint8Array)g="Uint8Array";else if(f instanceof ArrayBuffer)g="ArrayBuffer";else g=typeof f;let C=g==="object"&&f!==null?JSON.stringify(f):f;return new Response(C,{status:v,headers:this.headers})}json(f,v=200){return Response.json(f,{status:v,headers:this.headers})}file(f,v,g=200){let C=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",v??u(f));return new Response(C,{status:g,headers:this.headers})}async ejs(f,v={},g=200){let C=await N1();try{let w=await Bun.file(f).text(),$=C.render(w,v),z=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response($,{status:g,headers:z})}catch(w){return console.error("EJS Rendering Error:",w),new Response("Error rendering template",{status:500})}}redirect(f,v=302){return this.headers.set("Location",f),new Response(null,{status:v,headers:this.headers})}setCookie(f,v,g={}){let C=`${encodeURIComponent(f)}=${encodeURIComponent(v)}`;if(g.maxAge)C+=`; Max-Age=${g.maxAge}`;if(g.expires)C+=`; Expires=${g.expires.toUTCString()}`;if(g.path)C+=`; Path=${g.path}`;if(g.domain)C+=`; Domain=${g.domain}`;if(g.secure)C+="; Secure";if(g.httpOnly)C+="; HttpOnly";if(g.sameSite)C+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",C),this}get cookies(){if(!this.parsedCookies){let f=this.req.headers.get("cookie");this.parsedCookies=f?R1(f):{}}return this.parsedCookies}stream(f){let v=new Headers(this.headers),g=new ReadableStream({async start(C){await f(C),C.close()}});return new Response(g,{headers:v})}yieldStream(f){return new Response}}function Bf(f,v,g,C){let w=null,$=null,z=null,K=null,A={},G=null;return{req:f,server:v,pathname:g,headers:new Headers,setHeader(J,Y){return this.headers.set(J,Y),this},removeHeader(J){return this.headers.delete(J),this},set(J,Y){return A[J]=Y,this},get(J){return A[J]},get ip(){return this.server.requestIP(f)?.address??null},get url(){if(!G)G=new URL(f.url);return G},get query(){if(!w){if(!this.url.search)return{};w=Object.fromEntries(this.url.searchParams)}return w},get params(){if(!$&&C)try{$=D1(C,g)}catch(J){let Y=J instanceof Error?J.message:String(J);throw new Error(`Failed to extract route parameters: ${Y}`)}return $??{}},get body(){if(f.method==="GET")return Promise.resolve({});if(!K)K=(async()=>{try{let J=await q1(f);if(J.error)throw new Error(J.error);return Object.keys(J).length===0?null:J}catch(J){throw new Error("Invalid request body format")}})();return K},text(J,Y=200){return new Response(J,{status:Y,headers:this.headers})},send(J,Y=200){let Z;if(J instanceof Uint8Array)Z="Uint8Array";else if(J instanceof ArrayBuffer)Z="ArrayBuffer";else Z=typeof J;let V=Z==="object"&&J!==null?JSON.stringify(J):J;return new Response(V,{status:Y,headers:this.headers})},json(J,Y=200){return Response.json(J,{status:Y,headers:this.headers})},file(J,Y,Z=200){let V=Bun.file(J);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Y??u(J));return new Response(V,{status:Z,headers:this.headers})},async ejs(J,Y={},Z=200){let V=await N1();try{let Q=await Bun.file(J).text(),F=V.render(Q,Y),B=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(F,{status:Z,headers:B})}catch(Q){return console.error("EJS Rendering Error:",Q),new Response("Error rendering template",{status:500})}},redirect(J,Y=302){return this.headers.set("Location",J),new Response(null,{status:Y,headers:this.headers})},stream(J){let Y=new Headers(this.headers),Z=new ReadableStream({async start(V){await J(V),V.close()}});return new Response(Z,{headers:Y})},yieldStream(J){return new Response("not working stream yet.")},setCookie(J,Y,Z={}){let V=`${encodeURIComponent(J)}=${encodeURIComponent(Y)}`;if(Z.maxAge)V+=`; Max-Age=${Z.maxAge}`;if(Z.expires)V+=`; Expires=${Z.expires.toUTCString()}`;if(Z.path)V+=`; Path=${Z.path}`;if(Z.domain)V+=`; Domain=${Z.domain}`;if(Z.secure)V+="; Secure";if(Z.httpOnly)V+="; HttpOnly";if(Z.sameSite)V+=`; SameSite=${Z.sameSite}`;return this.headers.append("Set-Cookie",V),this},get cookies(){if(!z){let J=this.req.headers.get("cookie");z=J?R1(J):{}}return z}}}function R1(f){return Object.fromEntries(f.split(";").map((v)=>{let[g,...C]=v.trim().split("=");return[g,decodeURIComponent(C.join("="))]}))}function D1(f,v){let g={},C=f.split("/"),[w]=v.split("?"),$=w.split("/");if(C.length!==$.length)return null;for(let z=0;z<C.length;z++){let K=C[z];if(K.charCodeAt(0)===58)g[K.slice(1)]=$[z]}return g}async function q1(f){let v=f.headers.get("Content-Type")||"";if(!v)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};if(v.startsWith("application/json"))return await f.json();if(v.startsWith("application/x-www-form-urlencoded")){let C=await f.text();return Object.fromEntries(new URLSearchParams(C))}if(v.startsWith("multipart/form-data")){let C=await f.formData(),w={};for(let[$,z]of C.entries())w[$]=z;return w}return{error:"Unknown request body type"}}async function L1(f,v,g){if(!v?.length)return;for(let C=0;C<v.length;C++){let w=v[C](...g),$=w instanceof Promise?await w:w;if($&&f!=="onRequest")return $}}async function xf(f,v,g){let C=f.globalMiddlewares;if(C.length)for(let $ of C){let z=await $(g);if(z)return z}let w=f.middlewares.get(v);if(w&&w.length)for(let $ of w){let z=await $(g);if(z)return z}return null}async function M1(f,v,g){for(let C of f){let w=await C(v,g);if(w)return w}}async function H1(f,v,g){let C=await Ff(f,v,g),w=C instanceof Promise?await C:C;if(w)return w}async function Ff(f,v,g){if(v.endsWith("/"))v=v.slice(0,-1);if(!f.filters.has(v))if(f.filterFunction.length)for(let C of f.filterFunction){let w=await C(g);if(w)return w}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function I1(f,v,g){if(f.staticPath){let w=!0;if(f.staticRequestPath)w=g.startsWith(f.staticRequestPath);if(w){let $=await bf(f,g,v);if($)return $;let z=f.trie.search("*",v.req.method);if(z?.handler)return await z.handler(v)}}let C=f.routeNotFoundFunc(v);return C instanceof Promise?await C:C||T(404,`404 Route not found for ${g}`)}function T(f,v){return new Response(JSON.stringify({error:v}),{status:f,headers:{"Content-Type":"application/json"}})}async function bf(f,v,g){if(!f.staticPath)return null;let C=`${f.staticPath}${v}`;if(await Bun.file(C).exists()){let $=u(C);return g.file(C,$,200)}return null}var M=(f)=>f.constructor.name==="AsyncFunction",k=(f,v,g,...C)=>{if(v.length>5)f.push(`
|
|
55
55
|
for (let i = 0; i < diesel.hooks.${g}.length; i++) {
|
|
56
56
|
const result = diesel.hooks.${g}[i](${C});
|
|
57
57
|
const finalResult = result instanceof Promise ? await result : result;
|
|
58
58
|
if (finalResult && '${g}' !== 'onRequest') return finalResult
|
|
59
59
|
}
|
|
60
|
-
`);else v?.forEach((w,$)=>{if(
|
|
60
|
+
`);else v?.forEach((w,$)=>{if(M(w))f.push(`
|
|
61
61
|
const ${g}${$}Result = await diesel.hooks.${g}[${$}](${C})
|
|
62
62
|
if (${g}${$}Result && '${g}' !== 'onRequest') return ${g}${$}Result
|
|
63
63
|
`);else f.push(`
|
|
64
64
|
const ${g}${$}Result = diesel.hooks.${g}[${$}](${C})
|
|
65
65
|
if (${g}${$}Result && '${g}' !== 'onRequest') return ${g}${$}Result
|
|
66
|
-
`)})},
|
|
66
|
+
`)})},uf=(f)=>{f.push(`
|
|
67
67
|
let pathname;
|
|
68
68
|
const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
|
|
69
69
|
let i = start;
|
|
@@ -81,7 +81,7 @@ try {
|
|
|
81
81
|
if (!pathname) {
|
|
82
82
|
pathname = req.url.slice(start, i);
|
|
83
83
|
}
|
|
84
|
-
`)},
|
|
84
|
+
`)},Nf=(f,v)=>{if(v.length<=5)for(let g=0;g<v.length;g++)if(M(v[g]))f.push(`
|
|
85
85
|
const resultMiddleware${g} = await globalMiddlewares[${g}](ctx);
|
|
86
86
|
if (resultMiddleware${g}) return resultMiddleware${g};
|
|
87
87
|
`);else f.push(`
|
|
@@ -92,11 +92,11 @@ try {
|
|
|
92
92
|
const result = await globalMiddlewares[i](ctx);
|
|
93
93
|
if (result) return result;
|
|
94
94
|
}
|
|
95
|
-
`)},rf=(f,v)=>{let g=[],C=v.globalMiddlewares||[],w=f?.hasOnReqHook?v.hooks.onRequest:[],$=f?.hasPreHandlerHook?v.hooks.preHandler:[],
|
|
95
|
+
`)},rf=(f,v)=>{let g=[],C=v.globalMiddlewares||[],w=f?.hasOnReqHook?v.hooks.onRequest:[],$=f?.hasPreHandlerHook?v.hooks.preHandler:[],z=f?.hasOnSendHook?v.hooks.onSend:[];if(uf(g),g.push(`
|
|
96
96
|
const routeHandler = diesel.trie.search(pathname, req.method);
|
|
97
97
|
`),w&&w.length>0)k(g,w,"onRequest","req","pathname","server");if(g.push(`
|
|
98
98
|
const ctx = new Context(req, server, pathname, routeHandler?.path)
|
|
99
|
-
`),f?.hasMiddleware){if(C.length>0)
|
|
99
|
+
`),f?.hasMiddleware){if(C.length>0)Nf(g,C);if(v.middlewares.size>0)g.push(`
|
|
100
100
|
const local = diesel.middlewares.get(pathname)
|
|
101
101
|
if (local && local.length) {
|
|
102
102
|
for (const middleware of local) {
|
|
@@ -112,7 +112,7 @@ try {
|
|
|
112
112
|
`),f.hasPreHandlerHook)k(g,$,"preHandler","ctx");if(g.push(`
|
|
113
113
|
const result = routeHandler.handler(ctx);
|
|
114
114
|
const finalResult = result instanceof Promise ? await result : result;
|
|
115
|
-
`),f.hasOnSendHook)k(g,
|
|
115
|
+
`),f.hasOnSendHook)k(g,z,"onSend","ctx","finalResult");g.push(`
|
|
116
116
|
if (finalResult instanceof Response) return finalResult;
|
|
117
117
|
return generateErrorResponse(500, "No response returned from handler.");
|
|
118
118
|
`);let K=`
|
|
@@ -120,14 +120,14 @@ try {
|
|
|
120
120
|
${g.join(`
|
|
121
121
|
`)}
|
|
122
122
|
}
|
|
123
|
-
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",K)(H1,I1,T,C,r)},Tf=(f,v,g,C,...w)=>{let $=[],
|
|
123
|
+
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",K)(H1,I1,T,C,r)},Tf=(f,v,g,C,...w)=>{let $=[],z;if(typeof w[0]==="string"||typeof w[0]==="object")z=w[0];let K=w,A=f?.hasMiddleware?v.globalMiddlewares:[],G=f?.hasMiddleware?v.middlewares.get(C)||[]:[],J=[...A,...G],Y=f?.hasOnReqHook?v.hooks.onRequest:[],Z=v.filters.has(C),V=v.filterFunction;if(Y&&Y?.length>0)$.push(`
|
|
124
124
|
const onRequestResult = await runHooks(
|
|
125
125
|
"onRequest",
|
|
126
126
|
onRequestHooks,
|
|
127
127
|
[req, "${C}", server]
|
|
128
128
|
);
|
|
129
129
|
if (onRequestResult) return onRequestResult;
|
|
130
|
-
`);if(
|
|
130
|
+
`);if(J.length)$.push(`
|
|
131
131
|
const globalMiddlewareResponse = await executeBunMiddlewares(
|
|
132
132
|
allMiddlewares,
|
|
133
133
|
req,
|
|
@@ -144,27 +144,27 @@ try {
|
|
|
144
144
|
}`)}if($.push(`
|
|
145
145
|
if ("${g}" !== req.method)
|
|
146
146
|
return new Response("Method Not Allowed", { status: 405 });
|
|
147
|
-
`),typeof
|
|
148
|
-
return new Response(${JSON.stringify(
|
|
149
|
-
`);else{let B=JSON.stringify(
|
|
147
|
+
`),typeof z!=="undefined")if(typeof z==="string")$.push(`
|
|
148
|
+
return new Response(${JSON.stringify(z)});
|
|
149
|
+
`);else{let B=JSON.stringify(z);$.push(`
|
|
150
150
|
return new Response(${JSON.stringify(B)}, {
|
|
151
151
|
headers: { "content-type": "application/json; charset=utf-8" }
|
|
152
152
|
});
|
|
153
|
-
`)}else if(K.length===1){let B=K[0];if(
|
|
153
|
+
`)}else if(K.length===1){let B=K[0];if(M(B))$.push(`
|
|
154
154
|
const response = await handlers[0](req, server);
|
|
155
155
|
if (response instanceof Response) return response;
|
|
156
156
|
`);else $.push(`
|
|
157
157
|
const response = handlers[0](req, server);
|
|
158
158
|
if (response instanceof Response) return response;
|
|
159
|
-
`)}else K.forEach((B,
|
|
160
|
-
const response${
|
|
161
|
-
if (response${
|
|
159
|
+
`)}else K.forEach((B,X)=>{if(M(B))$.push(`
|
|
160
|
+
const response${X} = await handlers[${X}](req, server);
|
|
161
|
+
if (response${X} instanceof Response) return response${X};
|
|
162
162
|
`);else $.push(`
|
|
163
|
-
const response${
|
|
164
|
-
if (response${
|
|
163
|
+
const response${X} = handlers[${X}](req, server);
|
|
164
|
+
if (response${X} instanceof Response) return response${X};
|
|
165
165
|
`)});let Q=`
|
|
166
166
|
return async function(req, server) {
|
|
167
167
|
${$.join(`
|
|
168
168
|
`)}
|
|
169
169
|
}
|
|
170
|
-
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",Q)(
|
|
170
|
+
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",Q)(M1,K,L1,V,Y,J)};export{rf as buildRequestPipeline,Tf as BunRequestPipline};
|
package/dist/types.d.ts
CHANGED
|
@@ -18,12 +18,12 @@ export interface onSend {
|
|
|
18
18
|
(ctx: ContextType, finalResult: Response): Promise<Response | undefined>;
|
|
19
19
|
}
|
|
20
20
|
export interface Hooks {
|
|
21
|
-
onRequest: onRequest[]
|
|
22
|
-
preHandler: HookFunction[]
|
|
23
|
-
postHandler: HookFunction[]
|
|
24
|
-
onSend: onSend[]
|
|
25
|
-
onError: onError[]
|
|
26
|
-
onClose: HookFunction[]
|
|
21
|
+
onRequest: onRequest[];
|
|
22
|
+
preHandler: HookFunction[];
|
|
23
|
+
postHandler: HookFunction[];
|
|
24
|
+
onSend: onSend[];
|
|
25
|
+
onError: onError[];
|
|
26
|
+
onClose: HookFunction[];
|
|
27
27
|
}
|
|
28
28
|
export interface ContextType {
|
|
29
29
|
req: Request;
|
|
@@ -94,6 +94,8 @@ export interface DieselT {
|
|
|
94
94
|
search: (pathname: string, method: string) => RouteHandlerT | undefined;
|
|
95
95
|
};
|
|
96
96
|
staticPath: string | null;
|
|
97
|
+
staticRequestPath: string | null;
|
|
98
|
+
staticFiles: Record<string, string>;
|
|
97
99
|
routeNotFoundFunc: RouteNotFoundHandler;
|
|
98
100
|
routerInstance: DieselT;
|
|
99
101
|
tempRoutes: Map<string, TempRouteEntry>;
|
|
@@ -128,7 +130,6 @@ export interface ParseBodyResult {
|
|
|
128
130
|
}
|
|
129
131
|
declare global {
|
|
130
132
|
interface Request {
|
|
131
|
-
routePattern?: string;
|
|
132
133
|
[key: string]: any;
|
|
133
134
|
}
|
|
134
135
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(e){switch(e.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}async function g(e,t,i){if(!t?.length)return;for(let n=0;n<t.length;n++){let r=t[n](...i),
|
|
1
|
+
function a(e){switch(e.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}async function g(e,t,i){if(!t?.length)return;for(let n=0;n<t.length;n++){let r=t[n](...i),s=r instanceof Promise?await r:r;if(s&&e!=="onRequest")return s}}async function m(e,t,i){let n=e.globalMiddlewares;if(n.length)for(let s of n){let o=await s(i);if(o)return o}let r=e.middlewares.get(t);if(r&&r.length)for(let s of r){let o=await s(i);if(o)return o}return null}async function d(e,t,i){for(let n of e){let r=await n(t,i);if(r)return r}}async function w(e,t,i){let n=await u(e,t,i),r=n instanceof Promise?await n:n;if(r)return r}async function u(e,t,i){if(t.endsWith("/"))t=t.slice(0,-1);if(!e.filters.has(t))if(e.filterFunction.length)for(let n of e.filterFunction){let r=await n(i);if(r)return r}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function R(e,t,i,n){if(!e.filters.has(t))if(e.filterFunction.length)for(let r of e.filterFunction){let s=await r(i,n);if(s)return s}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function h(e,t,i){if(e.staticPath){let r=!0;if(e.staticRequestPath)r=i.startsWith(e.staticRequestPath);if(r){let s=await f(e,i,t);if(s)return s;let o=e.trie.search("*",t.req.method);if(o?.handler)return await o.handler(t)}}let n=e.routeNotFoundFunc(t);return n instanceof Promise?await n:n||c(404,`404 Route not found for ${i}`)}function c(e,t){return new Response(JSON.stringify({error:t}),{status:e,headers:{"Content-Type":"application/json"}})}async function f(e,t,i){if(!e.staticPath)return null;let n=`${e.staticPath}${t}`;if(await Bun.file(n).exists()){let s=a(n);return i.file(n,s,200)}return null}export{m as runMiddlewares,g as runHooks,w as runFilter,f as handleStaticFiles,h as handleRouteNotFound,u as handleFilterRequest,R as handleBunFilterRequest,c as generateErrorResponse,d as executeBunMiddlewares};
|