diesel-core 1.6.7 → 1.6.9

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.
@@ -1,54 +1,84 @@
1
- var bf=Object.create;var{getPrototypeOf:Sf,defineProperty:M,getOwnPropertyNames:i,getOwnPropertyDescriptor:qf}=Object,u=Object.prototype.hasOwnProperty;var Ef=(f,w,g)=>{g=f!=null?bf(Sf(f)):{};let A=w||!f||!f.__esModule?M(g,"default",{value:f,enumerable:!0}):g;for(let $ of i(f))if(!u.call(A,$))M(A,$,{get:()=>f[$],enumerable:!0});return A},n=new WeakMap,cf=(f)=>{var w=n.get(f),g;if(w)return w;if(w=M({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")i(f).map((A)=>!u.call(w,A)&&M(w,A,{get:()=>f[A],enumerable:!(g=qf(f,A))||g.enumerable}));return n.set(f,w),w},L=(f,w)=>()=>(w||f((w={exports:{}}).exports,w),w.exports);var Tf=(f,w)=>{for(var g in w)M(f,g,{get:w[g],enumerable:!0,configurable:!0,set:(A)=>w[g]=()=>A})};var yf=(f,w)=>()=>(f&&(w=f(f=0)),w);var Pf=((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={};Tf(Af,{sep:()=>ff,resolve:()=>K,relative:()=>l,posix:()=>wf,parse:()=>e,normalize:()=>b,join:()=>d,isAbsolute:()=>m,format:()=>t,extname:()=>p,dirname:()=>s,delimiter:()=>gf,default:()=>kf,basename:()=>a,_makeLong:()=>o});function W(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function h(f,w){var g="",A=0,$=-1,j=0,z;for(var J=0;J<=f.length;++J){if(J<f.length)z=f.charCodeAt(J);else if(z===47)break;else z=47;if(z===47){if($===J-1||j===1);else if($!==J-1&&j===2){if(g.length<2||A!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var Z=g.lastIndexOf("/");if(Z!==g.length-1){if(Z===-1)g="",A=0;else g=g.slice(0,Z),A=g.length-1-g.lastIndexOf("/");$=J,j=0;continue}}else if(g.length===2||g.length===1){g="",A=0,$=J,j=0;continue}}if(w){if(g.length>0)g+="/..";else g="..";A=2}}else{if(g.length>0)g+="/"+f.slice($+1,J);else g=f.slice($+1,J);A=J-$-1}$=J,j=0}else if(z===46&&j!==-1)++j;else j=-1}return g}function _f(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 K(){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(W($),$.length===0)continue;f=$+"/"+f,w=$.charCodeAt(0)===47}if(f=h(f,!w),w)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function b(f){if(W(f),f.length===0)return".";var w=f.charCodeAt(0)===47,g=f.charCodeAt(f.length-1)===47;if(f=h(f,!w),f.length===0&&!w)f=".";if(f.length>0&&g)f+="/";if(w)return"/"+f;return f}function m(f){return W(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(W(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(W(f),W(w),f===w)return"";if(f=K(f),w=K(w),f===w)return"";var g=1;for(;g<f.length;++g)if(f.charCodeAt(g)!==47)break;var A=f.length,$=A-g,j=1;for(;j<w.length;++j)if(w.charCodeAt(j)!==47)break;var z=w.length,J=z-j,Z=$<J?$:J,B=-1,Y=0;for(;Y<=Z;++Y){if(Y===Z){if(J>Z){if(w.charCodeAt(j+Y)===47)return w.slice(j+Y+1);else if(Y===0)return w.slice(j+Y)}else if($>Z){if(f.charCodeAt(g+Y)===47)B=Y;else if(Y===0)B=0}break}var G=f.charCodeAt(g+Y),V=w.charCodeAt(j+Y);if(G!==V)break;else if(G===47)B=Y}var C="";for(Y=g+B+1;Y<=A;++Y)if(Y===A||f.charCodeAt(Y)===47)if(C.length===0)C+="..";else C+="/..";if(C.length>0)return C+w.slice(j+B);else{if(j+=B,w.charCodeAt(j)===47)++j;return w.slice(j)}}function o(f){return f}function s(f){if(W(f),f.length===0)return".";var w=f.charCodeAt(0),g=w===47,A=-1,$=!0;for(var j=f.length-1;j>=1;--j)if(w=f.charCodeAt(j),w===47){if(!$){A=j;break}}else $=!1;if(A===-1)return g?"/":".";if(g&&A===1)return"//";return f.slice(0,A)}function a(f,w){if(w!==void 0&&typeof w!=="string")throw new TypeError('"ext" argument must be a string');W(f);var g=0,A=-1,$=!0,j;if(w!==void 0&&w.length>0&&w.length<=f.length){if(w.length===f.length&&w===f)return"";var z=w.length-1,J=-1;for(j=f.length-1;j>=0;--j){var Z=f.charCodeAt(j);if(Z===47){if(!$){g=j+1;break}}else{if(J===-1)$=!1,J=j+1;if(z>=0)if(Z===w.charCodeAt(z)){if(--z===-1)A=j}else z=-1,A=J}}if(g===A)A=J;else if(A===-1)A=f.length;return f.slice(g,A)}else{for(j=f.length-1;j>=0;--j)if(f.charCodeAt(j)===47){if(!$){g=j+1;break}}else if(A===-1)$=!1,A=j+1;if(A===-1)return"";return f.slice(g,A)}}function p(f){W(f);var w=-1,g=0,A=-1,$=!0,j=0;for(var z=f.length-1;z>=0;--z){var J=f.charCodeAt(z);if(J===47){if(!$){g=z+1;break}continue}if(A===-1)$=!1,A=z+1;if(J===46){if(w===-1)w=z;else if(j!==1)j=1}else if(w!==-1)j=-1}if(w===-1||A===-1||j===0||j===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 _f("/",f)}function e(f){W(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 j=-1,z=0,J=-1,Z=!0,B=f.length-1,Y=0;for(;B>=$;--B){if(g=f.charCodeAt(B),g===47){if(!Z){z=B+1;break}continue}if(J===-1)Z=!1,J=B+1;if(g===46){if(j===-1)j=B;else if(Y!==1)Y=1}else if(j!==-1)Y=-1}if(j===-1||J===-1||Y===0||Y===1&&j===J-1&&j===z+1){if(J!==-1)if(z===0&&A)w.base=w.name=f.slice(1,J);else w.base=w.name=f.slice(z,J)}else{if(z===0&&A)w.name=f.slice(1,j),w.base=f.slice(1,J);else w.name=f.slice(z,j),w.base=f.slice(z,J);w.ext=f.slice(j,J)}if(z>0)w.dir=f.slice(0,z-1);else if(A)w.dir="/";return w}var ff="/",gf=":",wf,kf;var $f=yf(()=>{wf=((f)=>(f.posix=f,f))({resolve:K,normalize:b,isAbsolute:m,join:d,relative:l,_makeLong:o,dirname:s,basename:a,extname:p,format:t,parse:e,sep:ff,delimiter:gf,win32:null,posix:null}),kf=wf});var Jf=L((mf)=>{var If=/[|\\{}()[\]^$+*?.]/g,xf=Object.prototype.hasOwnProperty,q=function(f,w){return xf.apply(f,[w])};mf.escapeRegExpChars=function(f){if(!f)return"";return String(f).replace(If,"\\$&")};var rf={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&#34;","'":"&#39;"},nf=/[&<>'"]/g;function uf(f){return rf[f]||f}var hf=`var _ENCODE_HTML_RULES = {
2
- "&": "&amp;"
3
- , "<": "&lt;"
4
- , ">": "&gt;"
5
- , '"': "&#34;"
6
- , "'": "&#39;"
7
- }
8
- , _MATCH_HTML = /[&<>'"]/g;
9
- function encode_char(c) {
10
- return _ENCODE_HTML_RULES[c] || c;
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
11
9
  };
12
- `;mf.escapeXML=function(f){return f==null?"":String(f).replace(nf,uf)};function jf(){return Function.prototype.toString.call(this)+`;
13
- `+hf}try{if(typeof Object.defineProperty==="function")Object.defineProperty(mf.escapeXML,"toString",{value:jf});else mf.escapeXML.toString=jf}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}mf.shallowCopy=function(f,w){if(w=w||{},f!==null&&f!==void 0)for(var g in w){if(!q(w,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=w[g]}return f};mf.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(!q(w,$))continue;if($==="__proto__"||$==="constructor")continue;f[$]=w[$]}}return f};mf.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={}}};mf.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(w){return w[1].toUpperCase()})};mf.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{}}}();mf.hasOwnOnlyObject=function(f){var w=mf.createNullProtoObjWherePossible();for(var g in f)if(q(f,g))w[g]=f[g];return w}});var Yf=L((S1,tf)=>{tf.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 Hf=L((Wf)=>{var T=(()=>({})),R=($f(),cf(Af)),F=Jf(),Zf=!1,ef=Yf().version,f1="<",g1=">",w1="%",Cf="locals",A1="ejs",$1="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",Gf=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],j1=Gf.concat("cache"),Vf=/^\uFEFF/,E=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;Wf.cache=F.cache;Wf.fileLoader=T.readFileSync;Wf.localsName=Cf;Wf.promiseImpl=new Function("return this;")().Promise;Wf.resolveInclude=function(f,w,g){var{dirname:A,extname:$,resolve:j}=R,z=j(g?w:A(w),f),J=$(f);if(!J)z+=".ejs";return z};function Bf(f,w){var g;if(w.some(function(A){return g=Wf.resolveInclude(f,A,!0),T.existsSync(g)}))return g}function z1(f,w){var g,A,$=w.views,j=/^[A-Za-z]+:\\|^\//.exec(f);if(j&&j.length)if(f=f.replace(/^\/*/,""),Array.isArray(w.root))g=Bf(f,w.root);else g=Wf.resolveInclude(f,w.root||"/",!0);else{if(w.filename){if(A=Wf.resolveInclude(f,w.filename),T.existsSync(A))g=A}if(!g&&Array.isArray($))g=Bf(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=Wf.cache.get(A),g)return g;if(!$)w=Ff(A).toString().replace(Vf,"")}else if(!$){if(!A)throw new Error("Internal EJS error: no file name or template provided");w=Ff(A).toString().replace(Vf,"")}if(g=Wf.compile(w,f),f.cache)Wf.cache.set(A,g);return g}function J1(f,w,g){var A;if(!g)if(typeof Wf.promiseImpl=="function")return new Wf.promiseImpl(function($,j){try{A=U(f)(w),$(A)}catch(z){j(z)}});else throw new Error("Please provide a callback function");else{try{A=U(f)(w)}catch($){return g($)}g(null,A)}}function Ff(f){return Wf.fileLoader(f)}function Y1(f,w){var g=F.shallowCopy(F.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 Qf(f,w,g,A,$){var j=w.split(`
14
- `),z=Math.max(A-3,0),J=Math.min(j.length,A+3),Z=$(g),B=j.slice(z,J).map(function(Y,G){var V=G+z+1;return(V==A?" >> ":" ")+V+"| "+Y}).join(`
15
- `);throw f.path=Z,f.message=(Z||"ejs")+":"+A+`
16
- `+B+`
17
-
18
- `+f.message,f}function Xf(f){return f.replace(/;(\s*$)/,"$1")}Wf.compile=function f(w,g){var A;if(g&&g.scope){if(!Zf)console.warn("`scope` option is deprecated and will be removed in EJS 3"),Zf=!0;if(!g.context)g.context=g.scope;delete g.scope}return A=new Q(w,g),A.compile()};Wf.render=function(f,w,g){var A=w||F.createNullProtoObjWherePossible(),$=g||F.createNullProtoObjWherePossible();if(arguments.length==2)F.shallowCopyFromList($,A,Gf);return U($,f)(A)};Wf.renderFile=function(){var f=Array.prototype.slice.call(arguments),w=f.shift(),g,A={filename:w},$,j;if(typeof arguments[arguments.length-1]=="function")g=f.pop();if(f.length){if($=f.shift(),f.length)F.shallowCopy(A,f.pop());else{if($.settings){if($.settings.views)A.views=$.settings.views;if($.settings["view cache"])A.cache=!0;if(j=$.settings["view options"],j)F.shallowCopy(A,j)}F.shallowCopyFromList(A,$,j1)}A.filename=w}else $=F.createNullProtoObjWherePossible();return J1(A,$,g)};Wf.Template=Q;Wf.clearCache=function(){Wf.cache.reset()};function Q(f,w){var g=F.hasOwnOnlyObject(w),A=F.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||F.escapeXML,A.compileDebug=g.compileDebug!==!1,A.debug=!!g.debug,A.filename=g.filename,A.openDelimiter=g.openDelimiter||Wf.openDelimiter||f1,A.closeDelimiter=g.closeDelimiter||Wf.closeDelimiter||g1,A.delimiter=g.delimiter||Wf.delimiter||w1,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||Wf.localsName||Cf,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=$1,w=F.escapeRegExpChars(this.opts.delimiter),g=F.escapeRegExpChars(this.opts.openDelimiter),A=F.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="",$="",j=g.escapeFunction,z,J=g.filename?JSON.stringify(g.filename):"undefined";if(!this.source){if(this.generateSource(),A+=` var __output = "";
19
- function __append(s) { if (s !== undefined && s !== null) __output += s }
20
- `,g.outputFunctionName){if(!E.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");A+=" var "+g.outputFunctionName+` = __append;
21
- `}if(g.localsName&&!E.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var Z=" var __locals = ("+g.localsName+` || {}),
22
- `;for(var B=0;B<g.destructuredLocals.length;B++){var Y=g.destructuredLocals[B];if(!E.test(Y))throw new Error("destructuredLocals["+B+"] is not a valid JS identifier.");if(B>0)Z+=`,
23
- `;Z+=Y+" = __locals."+Y}A+=Z+`;
24
- `}if(g._with!==!1)A+=" with ("+g.localsName+` || {}) {
25
- `,$+=` }
26
- `;$+=` return __output;
27
- `,this.source=A+this.source+$}if(g.compileDebug)f=`var __line = 1
28
- , __lines = `+JSON.stringify(this.templateText)+`
29
- , __filename = `+J+`;
30
- try {
31
- `+this.source+`} catch (e) {
32
- rethrow(e, __lines, __filename, __line, escapeFn);
10
+ import { Context } from "./ctx";
11
+ import { tryDecodeURI } from "./utils/urls";
12
+ import { generateErrorResponse, handleRouteNotFound, runFilter, runHooks, runMiddlewares } from "./utils/request.util";
13
+ import { isPromise } from "./utils/promise";
14
+ export default function handleRequest(req, server, diesel, env, executionContext) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ let pathname;
17
+ const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
18
+ let i = start;
19
+ for (; i < req.url.length; i++) {
20
+ const charCode = req.url.charCodeAt(i);
21
+ if (charCode === 37) { // percent-encoded
22
+ const queryIndex = req.url.indexOf('?', i);
23
+ const path = req.url.slice(start, queryIndex === -1 ? undefined : queryIndex);
24
+ pathname = tryDecodeURI(path.includes('%25') ? path.replace(/%25/g, '%2525') : path);
25
+ break;
26
+ }
27
+ else if (charCode === 63) {
28
+ break;
29
+ }
30
+ }
31
+ if (!pathname) {
32
+ pathname = req.url.slice(start, i);
33
+ }
34
+ const matchedRouteHandler = diesel.router.find(req.method, pathname);
35
+ const ctx = new Context(req, server, pathname, matchedRouteHandler === null || matchedRouteHandler === void 0 ? void 0 : matchedRouteHandler.path, env, executionContext);
36
+ // const ctx = createCtx(req,server,pathname,routeHandler?.path)
37
+ // PipeLines such as filters , middlewares, hooks
38
+ // if (diesel.hasOnReqHook)
39
+ // await runHooks('onRequest', diesel.hooks.onRequest, [req, pathname, server])
40
+ // middleware execution
41
+ if (diesel.hasMiddleware) {
42
+ const mwResult = yield runMiddlewares(diesel, pathname, ctx);
43
+ if (mwResult)
44
+ return mwResult;
45
+ }
46
+ // filter execution
47
+ if (diesel.hasFilterEnabled) {
48
+ const filterResponse = yield runFilter(diesel, pathname, ctx);
49
+ if (filterResponse)
50
+ return filterResponse;
51
+ }
52
+ // if route not found
53
+ // if (!routeHandler) return await handleRouteNotFound(diesel, ctx, pathname)
54
+ // pre-handler
55
+ if (diesel.hasPreHandlerHook) {
56
+ const result = yield runHooks('preHandler', diesel.hooks.preHandler, [ctx]);
57
+ if (result)
58
+ return result;
59
+ }
60
+ let finalResult;
61
+ const handlers = matchedRouteHandler === null || matchedRouteHandler === void 0 ? void 0 : matchedRouteHandler.handler;
62
+ if (handlers.length === 1) {
63
+ const result = handlers[0](ctx);
64
+ finalResult = isPromise(result) ? yield result : result;
65
+ }
66
+ else {
67
+ for (let i = 0; i < handlers.length; i++) {
68
+ const result = handlers[i](ctx);
69
+ finalResult = isPromise(result) ? yield result : result;
70
+ if (finalResult)
71
+ break;
72
+ }
73
+ }
74
+ // onSend
75
+ if (diesel.hasOnSendHook) {
76
+ const response = yield runHooks('onSend', diesel.hooks.onSend, [ctx, finalResult]);
77
+ if (response)
78
+ return response;
79
+ }
80
+ return finalResult !== null && finalResult !== void 0 ? finalResult : yield handleRouteNotFound(diesel, ctx, pathname);
81
+ // if we dont return a response then by default Bun shows a err
82
+ return generateErrorResponse(500, "No response returned from handler.");
83
+ });
33
84
  }
34
- `;else f=this.source;if(g.client){if(f="escapeFn = escapeFn || "+j.toString()+`;
35
- `+f,g.compileDebug)f="rethrow = rethrow || "+Qf.toString()+`;
36
- `+f}if(g.strict)f=`"use strict";
37
- `+f;if(g.debug)console.log(f);if(g.compileDebug&&g.filename)f=f+`
38
- //# sourceURL=`+J+`
39
- `;try{if(g.async)try{z=new Function("return (async function(){}).constructor;")()}catch(X){if(X instanceof SyntaxError)throw new Error("This environment does not support async/await");else throw X}else z=Function;w=new z(g.localsName+", escapeFn, include, rethrow",f)}catch(X){if(X instanceof SyntaxError){if(g.filename)X.message+=" in "+g.filename;if(X.message+=` while compiling ejs
40
-
41
- `,X.message+=`If the above error is not helpful, you may want to try EJS-Lint:
42
- `,X.message+="https://github.com/RyanZim/EJS-Lint",!g.async)X.message+=`
43
- `,X.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw X}var G=g.client?w:function X(x){var Of=function(Lf,r){var O=F.shallowCopy(F.createNullProtoObjWherePossible(),x);if(r)O=F.shallowCopy(O,r);return Y1(Lf,g)(O)};return w.apply(g.context,[x||F.createNullProtoObjWherePossible(),j,Of,Qf])};if(g.filename&&typeof Object.defineProperty==="function"){var V=g.filename,C=R.basename(V,R.extname(V));try{Object.defineProperty(G,"name",{value:C,writable:!1,enumerable:!1,configurable:!0})}catch(X){}}return G},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 w=this,g=this.parseTemplateText(),A=this.opts.delimiter,$=this.opts.openDelimiter,j=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(z,J){var Z;if(z.indexOf($+A)===0&&z.indexOf($+A+A)!==0){if(Z=g[J+2],!(Z==A+j||Z=="-"+A+j||Z=="_"+A+j))throw new Error('Could not find matching close tag for "'+z+'".')}w.scanLine(z)})},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
- `},scanLine:function(f){var w=this,g=this.opts.delimiter,A=this.opts.openDelimiter,$=this.opts.closeDelimiter,j=0;switch(j=f.split(`
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)+`")
47
- `;break;case g+g+$:this.mode=Q.modes.LITERAL,this.source+=' ; __append("'+f.replace(g+g+$,g+$)+`")
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
- `))f+=`
50
- `}switch(this.mode){case Q.modes.EVAL:this.source+=" ; "+f+`
51
- `;break;case Q.modes.ESCAPED:this.source+=" ; __append(escapeFn("+Xf(f)+`))
52
- `;break;case Q.modes.RAW:this.source+=" ; __append("+Xf(f)+`)
53
- `;break;case Q.modes.COMMENT:break;case Q.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(w.opts.compileDebug&&j)this.currentLine+=j,this.source+=" ; __line = "+this.currentLine+`
54
- `}};Wf.escapeXML=F.escapeXML;Wf.__express=Wf.renderFile;Wf.VERSION=ef;Wf.name=A1;if(typeof window!="undefined")window.ejs=Wf});function D(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 W1(){if(!y){let f=await Promise.resolve().then(() => Ef(Hf(),1));y=f.default||f}return y}var M1={string:"text/plain; charset=utf-8",object:"application/json; charset=utf-8",Uint8Array:"application/octet-stream",ArrayBuffer:"application/octet-stream"};class P{req;server;path;routePattern;paramNames;env;executionContext;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,w,g,A,$,j,z){this.req=f,this.server=w,this.path=g,this.routePattern=A,this.executionContext=z,this.env=j,this.paramNames=$}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(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||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(!Array.isArray(this.paramNames))return this.paramNames;if(!this.parsedParams)try{this.parsedParams=U1(this.paramNames,this.path)}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 H1(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;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",M1[g]??"text/plain; charset=utf-8");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??D(f));return new Response(A,{status:g,headers:this.headers})}async ejs(f,w={},g=200){let A=await W1();try{let $=await Bun.file(f).text(),j=A.render($,w),z=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(j,{status:g,headers:z})}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?R1(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){return Object.fromEntries(f.split(";").map((w)=>{let[g,...A]=w.trim().split("=");return[g,decodeURIComponent(A.join("="))]}))}function U1(f,w){let g={},[A]=w.split("?"),$=A.split("/").filter((z)=>z!==""),j=$.length-f.length;for(let z=0;z<f.length;z++)g[f[z]]=$[j+z];return g}function P1(f,w){let g={},A=f.split("/"),[$]=w.split("?"),j=$.split("/");if(A.length!==j.length)return null;for(let z=0;z<A.length;z++){let J=A[z];if(J.charCodeAt(0)===58)g[J.slice(1)]=j[z]}return g}async function H1(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[j,z]of A.entries())$[j]=z;return $}return{error:"Unknown request body type"}}var D1=(f,w)=>{try{return w(f)}catch{return f.replace(/(?:%[0-9A-Fa-f]{2})+/g,(g)=>{try{return w(g)}catch{return g}})}},_=(f)=>D1(f,decodeURI),k1=(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),j=f.slice(w,$===-1?void 0:$);return _(j.includes("%25")?j.replace(/%25/g,"%2525"):j)}else if(A===63)break}return f.slice(w,g)};var H=(f)=>f!==null&&typeof f==="object"&&typeof f.then==="function",Df=(f)=>f!==null&&typeof f==="object"&&typeof f.status==="number"&&typeof f.headers==="object";async function k(f,w,g){if(!w?.length)return;for(let A=0;A<w.length;A++){let $=w[A](...g),j=$ instanceof Promise?await $:$;if(j&&f!=="onRequest")return j}}async function Kf(f,w,g){let A=f.globalMiddlewares;if(A.length)for(let j of A){let z=await j(g);if(z)return z}let $=f.middlewares.get(w);if($&&$.length)for(let j of $){let z=await j(g);if(z)return z}return null}async function i1(f,w,g){for(let A of f){let $=await A(w,g);if($)return $}}async function vf(f,w,g){let A=await K1(f,w,g),$=H(A)?await A:A;if($)return $}async function K1(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 Nf(f,w,g){if(f.staticPath){let J=!0;if(f.staticRequestPath)J=g.startsWith(f.staticRequestPath);if(J){let Z=await v1(f,g,w);if(Z)return Z}}let j=(f.router.find(w.req.method,"*")?.handler).slice(-1);if(j.length>0){let J=await j[0](w);if(Df(J))return J}let z=f.routeNotFoundFunc(w);return z instanceof Promise?await z:z||I(404,`404 Route not found for ${g}`)}function I(f,w){return new Response(JSON.stringify({error:w}),{status:f,headers:{"Content-Type":"application/json"}})}async function v1(f,w,g){if(!f.staticPath)return null;let A=`${f.staticPath}${w}`;if(await Bun.file(A).exists()){let j=D(A);return g.file(A,j,200)}return null}async function N1(f,w,g,A,$){let j,z=f.url.indexOf("/",f.url.indexOf(":")+4),J=z;for(;J<f.url.length;J++){let V=f.url.charCodeAt(J);if(V===37){let C=f.url.indexOf("?",J),X=f.url.slice(z,C===-1?void 0:C);j=_(X.includes("%25")?X.replace(/%25/g,"%2525"):X);break}else if(V===63)break}if(!j)j=f.url.slice(z,J);let Z=g.router.find(f.method,j),B=new P(f,w,j,Z?.path,A,$);if(g.hasMiddleware){let V=await Kf(g,j,B);if(V)return V}if(g.hasFilterEnabled){let V=await vf(g,j,B);if(V)return V}if(g.hasPreHandlerHook){let V=await k("preHandler",g.hooks.preHandler,[B]);if(V)return V}let Y,G=Z?.handler;if(G.length===1){let V=G[0](B);Y=H(V)?await V:V}else for(let V=0;V<G.length;V++){let C=G[V](B);if(Y=H(C)?await C:C,Y)break}if(g.hasOnSendHook){let V=await k("onSend",g.hooks.onSend,[B,Y]);if(V)return V}return Y??await Nf(g,B,j)}export{N1 as default};
@@ -1 +1,20 @@
1
- var p=Object.create;var{getPrototypeOf:c,defineProperty:r,getOwnPropertyNames:u,getOwnPropertyDescriptor:h}=Object,i=Object.prototype.hasOwnProperty;var T=(s,e,t)=>{t=s!=null?p(c(s)):{};let n=e||!s||!s.__esModule?r(t,"default",{value:s,enumerable:!0}):t;for(let o of u(s))if(!i.call(n,o))r(n,o,{get:()=>s[o],enumerable:!0});return n},a=new WeakMap,d=(s)=>{var e=a.get(s),t;if(e)return e;if(e=r({},"__esModule",{value:!0}),s&&typeof s==="object"||typeof s==="function")u(s).map((n)=>!i.call(e,n)&&r(e,n,{get:()=>s[n],enumerable:!(t=h(s,n))||t.enumerable}));return a.set(s,e),e},m=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var x=(s,e)=>{for(var t in e)r(s,t,{get:e[t],enumerable:!0,configurable:!0,set:(n)=>e[t]=()=>n})};var g=(s,e)=>()=>(s&&(e=s(s=0)),e);var w=((s)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(s,{get:(e,t)=>(typeof require!=="undefined"?require:e)[t]}):s)(function(s){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});class R extends Error{res;status;constructor(s=500,e){super(e?.message,{cause:e?.cause});this.name="HTTPException",this.res=e?.res,this.status=s}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}export{R as HTTPException};
1
+ export class HTTPException extends Error {
2
+ constructor(status = 500, options) {
3
+ super(options === null || options === void 0 ? void 0 : options.message, { cause: options === null || options === void 0 ? void 0 : options.cause });
4
+ this.name = 'HTTPException';
5
+ this.res = options === null || options === void 0 ? void 0 : options.res;
6
+ this.status = status;
7
+ }
8
+ getResponse() {
9
+ if (this.res) {
10
+ const newResponse = new Response(this.res.body, {
11
+ status: this.status,
12
+ headers: this.res.headers,
13
+ });
14
+ return newResponse;
15
+ }
16
+ return new Response(this.message, {
17
+ status: this.status,
18
+ });
19
+ }
20
+ }
@@ -0,0 +1,50 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { describe, expect, it } from 'bun:test';
11
+ import { HTTPException } from './http-exception';
12
+ describe('HTTPException', () => {
13
+ it('Should be 401 HTTP exception object', () => __awaiter(void 0, void 0, void 0, function* () {
14
+ // We should throw an exception if is not authorized
15
+ // because next handlers should not be fired.
16
+ const exception = new HTTPException(401, {
17
+ message: 'Unauthorized',
18
+ });
19
+ const res = exception.getResponse();
20
+ expect(res.status).toBe(401);
21
+ expect(yield res.text()).toBe('Unauthorized');
22
+ expect(exception.status).toBe(401);
23
+ expect(exception.message).toBe('Unauthorized');
24
+ }));
25
+ it('Should be accessible to the object causing the exception', () => __awaiter(void 0, void 0, void 0, function* () {
26
+ // We should pass the cause of the error to the cause option
27
+ // because it makes debugging easier.
28
+ const error = new Error('Server Error');
29
+ const exception = new HTTPException(500, {
30
+ message: 'Internal Server Error',
31
+ cause: error,
32
+ });
33
+ const res = exception.getResponse();
34
+ expect(res.status).toBe(500);
35
+ expect(yield res.text()).toBe('Internal Server Error');
36
+ expect(exception.status).toBe(500);
37
+ expect(exception.message).toBe('Internal Server Error');
38
+ expect(exception.cause).toBe(error);
39
+ }));
40
+ it('Should prioritize the status code over the code in the response', () => __awaiter(void 0, void 0, void 0, function* () {
41
+ const exception = new HTTPException(400, {
42
+ res: new Response('An exception', {
43
+ status: 200,
44
+ }),
45
+ });
46
+ const res = exception.getResponse();
47
+ expect(res.status).toBe(400);
48
+ expect(yield res.text()).toBe('An exception');
49
+ }));
50
+ });