vector-framework 0.9.9 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/dist/cache/manager.d.ts +5 -2
- package/dist/cache/manager.d.ts.map +1 -1
- package/dist/cache/manager.js +21 -7
- package/dist/cache/manager.js.map +1 -1
- package/dist/cli/index.js +76 -98
- package/dist/cli/index.js.map +1 -1
- package/dist/cli.js +134 -69
- package/dist/core/config-loader.d.ts +2 -2
- package/dist/core/config-loader.d.ts.map +1 -1
- package/dist/core/config-loader.js +16 -21
- package/dist/core/config-loader.js.map +1 -1
- package/dist/core/router.d.ts +2 -0
- package/dist/core/router.d.ts.map +1 -1
- package/dist/core/router.js +52 -16
- package/dist/core/router.js.map +1 -1
- package/dist/core/server.d.ts +4 -3
- package/dist/core/server.d.ts.map +1 -1
- package/dist/core/server.js +40 -20
- package/dist/core/server.js.map +1 -1
- package/dist/core/vector.d.ts +7 -7
- package/dist/core/vector.d.ts.map +1 -1
- package/dist/core/vector.js +20 -21
- package/dist/core/vector.js.map +1 -1
- package/dist/dev/route-scanner.d.ts +1 -1
- package/dist/dev/route-scanner.d.ts.map +1 -1
- package/dist/dev/route-scanner.js +40 -42
- package/dist/dev/route-scanner.js.map +1 -1
- package/dist/http.d.ts +2 -2
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +70 -63
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/dist/middleware/manager.d.ts +1 -1
- package/dist/middleware/manager.d.ts.map +1 -1
- package/dist/middleware/manager.js.map +1 -1
- package/dist/utils/path.d.ts +1 -0
- package/dist/utils/path.d.ts.map +1 -1
- package/dist/utils/path.js +9 -3
- package/dist/utils/path.js.map +1 -1
- package/package.json +14 -9
- package/src/cache/manager.ts +23 -14
- package/src/cli/index.ts +83 -117
- package/src/core/config-loader.ts +19 -27
- package/src/core/router.ts +52 -18
- package/src/core/server.ts +43 -30
- package/src/core/vector.ts +25 -35
- package/src/dev/route-scanner.ts +41 -47
- package/src/http.ts +82 -112
- package/src/index.ts +3 -3
- package/src/middleware/manager.ts +4 -11
- package/src/utils/path.ts +13 -4
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var{defineProperty:z,getOwnPropertyNames:n,getOwnPropertyDescriptor:s}=Object,p=Object.prototype.hasOwnProperty;var T=new WeakMap,r=(i)=>{var f=T.get(i),l;if(f)return f;if(f=z({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")n(i).map((E)=>!p.call(f,E)&&z(f,E,{get:()=>i[E],enumerable:!(l=s(i,E))||l.enumerable}));return T.set(i,f),f};var o=(i,f)=>{for(var l in f)z(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(E)=>f[l]=()=>E})};var Li={};o(Li,{route:()=>y,createResponse:()=>P,APIError:()=>S});module.exports=r(Li);var G=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(f?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",i),_},$i=G("application/json; charset=utf-8",JSON.stringify);var wi=G("text/plain; charset=utf-8",String),Ci=G("text/html"),Si=G("image/jpeg"),bi=G("image/png"),Ri=G("image/webp"),k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},g=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},H=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:N}=i,O=(D)=>{let I=D?.headers.get("origin");return f===!0?I:f instanceof RegExp?f.test(I)?I:void 0:Array.isArray(f)?f.includes(I)?I:void 0:f instanceof Function?f(I):f=="*"&&l?I:f},U=(D,I)=>{for(let[$,w]of Object.entries(I))w&&D.headers.append($,w);return D};return{corsify:(D,I)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:U(D.clone(),{"access-control-allow-origin":O(I),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let I=new Response(null,{status:204});return U(I,{"access-control-allow-origin":O(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":N,"access-control-allow-credentials":l})}}}};var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},J={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},F={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class W{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class h{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=J.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),_=this.memoryCache.get(i);if(this.isCacheValid(_,E))return _.value;let A=await f();return this.setInMemoryCache(i,A,l),A}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=J.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var V=(()=>({}));function b(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function c(i,f){var l="",E=0,_=-1,A=0,N;for(var O=0;O<=i.length;++O){if(O<i.length)N=i.charCodeAt(O);else if(N===47)break;else N=47;if(N===47){if(_===O-1||A===1);else if(_!==O-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var U=l.lastIndexOf("/");if(U!==l.length-1){if(U===-1)l="",E=0;else l=l.slice(0,U),E=l.length-1-l.lastIndexOf("/");_=O,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=O,A=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(_+1,O);else l=i.slice(_+1,O);E=O-_-1}_=O,A=0}else if(N===46&&A!==-1)++A;else A=-1}return l}function t(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function j(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(b(_),_.length===0)continue;i=_+"/"+i,f=_.charCodeAt(0)===47}if(i=c(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function m(i){if(b(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=c(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function e(i){return b(i),i.length>0&&i.charCodeAt(0)===47}function M(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(b(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return m(i)}function a(i,f){if(b(i),b(f),i===f)return"";if(i=j(i),f=j(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,_=E-l,A=1;for(;A<f.length;++A)if(f.charCodeAt(A)!==47)break;var N=f.length,O=N-A,U=_<O?_:O,D=-1,I=0;for(;I<=U;++I){if(I===U){if(O>U){if(f.charCodeAt(A+I)===47)return f.slice(A+I+1);else if(I===0)return f.slice(A+I)}else if(_>U){if(i.charCodeAt(l+I)===47)D=I;else if(I===0)D=0}break}var $=i.charCodeAt(l+I),w=f.charCodeAt(A+I);if($!==w)break;else if($===47)D=I}var R="";for(I=l+D+1;I<=E;++I)if(I===E||i.charCodeAt(I)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+f.slice(A+D);else{if(A+=D,f.charCodeAt(A)===47)++A;return f.slice(A)}}function ii(i){return i}function Y(i){if(b(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,_=!0;for(var A=i.length-1;A>=1;--A)if(f=i.charCodeAt(A),f===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function fi(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');b(i);var l=0,E=-1,_=!0,A;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var N=f.length-1,O=-1;for(A=i.length-1;A>=0;--A){var U=i.charCodeAt(A);if(U===47){if(!_){l=A+1;break}}else{if(O===-1)_=!1,O=A+1;if(N>=0)if(U===f.charCodeAt(N)){if(--N===-1)E=A}else N=-1,E=O}}if(l===E)E=O;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return i.slice(l,E)}}function li(i){b(i);var f=-1,l=0,E=-1,_=!0,A=0;for(var N=i.length-1;N>=0;--N){var O=i.charCodeAt(N);if(O===47){if(!_){l=N+1;break}continue}if(E===-1)_=!1,E=N+1;if(O===46){if(f===-1)f=N;else if(A!==1)A=1}else if(f!==-1)A=-1}if(f===-1||E===-1||A===0||A===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function Ei(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return t("/",i)}function Ai(i){b(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,_;if(E)f.root="/",_=1;else _=0;var A=-1,N=0,O=-1,U=!0,D=i.length-1,I=0;for(;D>=_;--D){if(l=i.charCodeAt(D),l===47){if(!U){N=D+1;break}continue}if(O===-1)U=!1,O=D+1;if(l===46){if(A===-1)A=D;else if(I!==1)I=1}else if(A!==-1)I=-1}if(A===-1||O===-1||I===0||I===1&&A===O-1&&A===N+1){if(O!==-1)if(N===0&&E)f.base=f.name=i.slice(1,O);else f.base=f.name=i.slice(N,O)}else{if(N===0&&E)f.name=i.slice(1,A),f.base=i.slice(1,O);else f.name=i.slice(N,A),f.base=i.slice(N,O);f.ext=i.slice(A,O)}if(N>0)f.dir=i.slice(0,N-1);else if(E)f.dir="/";return f}var Q="/",_i=":",xi=((i)=>(i.posix=i,i))({resolve:j,normalize:m,isAbsolute:e,join:M,relative:a,_makeLong:ii,dirname:Y,basename:fi,extname:li,format:Ei,parse:Ai,sep:Q,delimiter:_i,win32:null,posix:null});class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=Y(this.outputPath);await V.promises.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let O of i){if(!E.has(O.path))E.set(O.path,[]);E.get(O.path).push(O)}let _=0,A=[];for(let[O,U]of E){let D=a(Y(this.outputPath),O).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),I=`route_${_++}`,$=U.filter((w)=>w.name!=="default").map((w)=>w.name);if(U.some((w)=>w.name==="default"))if($.length>0)l.push(`import ${I}, { ${$.join(", ")} } from '${D}';`);else l.push(`import ${I} from '${D}';`);else if($.length>0)l.push(`import { ${$.join(", ")} } from '${D}';`);for(let w of U){let R=w.name==="default"?I:w.name;A.push(` ${R},`)}}let N=`// This file is auto-generated. Do not edit manually.
|
|
1
|
+
var{defineProperty:V,getOwnPropertyNames:s,getOwnPropertyDescriptor:p}=Object,r=Object.prototype.hasOwnProperty;var v=new WeakMap,o=(f)=>{var i=v.get(f),l;if(i)return i;if(i=V({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")s(f).map((E)=>!r.call(i,E)&&V(i,E,{get:()=>f[E],enumerable:!(l=p(f,E))||l.enumerable}));return v.set(f,i),i};var t=(f,i)=>{for(var l in i)V(f,l,{get:i[l],enumerable:!0,configurable:!0,set:(E)=>i[l]=()=>E})};var wf={};t(wf,{route:()=>y,createResponse:()=>P,APIError:()=>C});module.exports=o(wf);var G=(f="text/plain; charset=utf-8",i)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(i?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",f),_},Cf=G("application/json; charset=utf-8",JSON.stringify);var bf=G("text/plain; charset=utf-8",String),Sf=G("text/html"),Rf=G("image/jpeg"),Pf=G("image/png"),jf=G("image/webp"),k=async(f)=>{f.content=f.body?await f.clone().json().catch(()=>f.clone().formData()).catch(()=>f.text()):void 0};var d=(f={})=>{let{origin:i="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:O}=f,N=(D)=>{let $=D?.headers.get("origin");return i===!0?$:i instanceof RegExp?i.test($)?$:void 0:Array.isArray(i)?i.includes($)?$:void 0:i instanceof Function?i($):i=="*"&&l?$:i},L=(D,$)=>{for(let[w,U]of Object.entries($))U&&D.headers.append(w,U);return D};return{corsify:(D,$)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:L(D.clone(),{"access-control-allow-origin":N($),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let $=new Response(null,{status:204});return L($,{"access-control-allow-origin":N(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":O,"access-control-allow-credentials":l})}}}};function c(f){return process.platform==="win32"?`file:///${f.replace(/\\/g,"/")}`:f}function Q(f){return RegExp(`^${f.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>[\\s\\S]+))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}var b={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},K={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},H={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class Z{protectedHandler=null;setProtectedHandler(f){this.protectedHandler=f}async authenticate(f){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let i=await this.protectedHandler(f);return f.authUser=i,i}catch(i){throw new Error(`Authentication failed: ${i instanceof Error?i.message:String(i)}`)}}isAuthenticated(f){return!!f.authUser}getUser(f){return f.authUser||null}}class W{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;inflight=new Map;setCacheHandler(f){this.cacheHandler=f}async get(f,i,l=K.CACHE_TTL){if(l<=0)return i();if(this.cacheHandler)return this.cacheHandler(f,i,l);return this.getFromMemoryCache(f,i,l)}async getFromMemoryCache(f,i,l){let E=Date.now(),_=this.memoryCache.get(f);if(this.isCacheValid(_,E))return _.value;if(this.inflight.has(f))return await this.inflight.get(f);let A=(async()=>{let O=await i();return this.setInMemoryCache(f,O,l),O})();this.inflight.set(f,A);try{return await A}finally{this.inflight.delete(f)}}isCacheValid(f,i){return f!==void 0&&f.expires>i}setInMemoryCache(f,i,l){let E=Date.now()+l*1000;this.memoryCache.set(f,{value:i,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let f=Date.now();for(let[i,l]of this.memoryCache.entries())if(l.expires<=f)this.memoryCache.delete(i);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(f,i,l=K.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(f,async()=>i,l);return}this.setInMemoryCache(f,i,l)}delete(f){return this.memoryCache.delete(f)}has(f){let i=this.memoryCache.get(f);if(!i)return!1;if(i.expires<=Date.now())return this.memoryCache.delete(f),!1;return!0}generateKey(f,i){let l=f._parsedUrl??new URL(f.url);return[f.method,l.pathname,l.search,i?.authUser?.id!=null?String(i.authUser.id):"anonymous"].join(":")}}var M=(()=>({}));function S(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function m(f,i){var l="",E=0,_=-1,A=0,O;for(var N=0;N<=f.length;++N){if(N<f.length)O=f.charCodeAt(N);else if(O===47)break;else O=47;if(O===47){if(_===N-1||A===1);else if(_!==N-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var L=l.lastIndexOf("/");if(L!==l.length-1){if(L===-1)l="",E=0;else l=l.slice(0,L),E=l.length-1-l.lastIndexOf("/");_=N,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=N,A=0;continue}}if(i){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+f.slice(_+1,N);else l=f.slice(_+1,N);E=N-_-1}_=N,A=0}else if(O===46&&A!==-1)++A;else A=-1}return l}function e(f,i){var l=i.dir||i.root,E=i.base||(i.name||"")+(i.ext||"");if(!l)return E;if(l===i.root)return l+E;return l+f+E}function F(){var f="",i=!1,l;for(var E=arguments.length-1;E>=-1&&!i;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(S(_),_.length===0)continue;f=_+"/"+f,i=_.charCodeAt(0)===47}if(f=m(f,!i),i)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function u(f){if(S(f),f.length===0)return".";var i=f.charCodeAt(0)===47,l=f.charCodeAt(f.length-1)===47;if(f=m(f,!i),f.length===0&&!i)f=".";if(f.length>0&&l)f+="/";if(i)return"/"+f;return f}function ff(f){return S(f),f.length>0&&f.charCodeAt(0)===47}function a(){if(arguments.length===0)return".";var f;for(var i=0;i<arguments.length;++i){var l=arguments[i];if(S(l),l.length>0)if(f===void 0)f=l;else f+="/"+l}if(f===void 0)return".";return u(f)}function x(f,i){if(S(f),S(i),f===i)return"";if(f=F(f),i=F(i),f===i)return"";var l=1;for(;l<f.length;++l)if(f.charCodeAt(l)!==47)break;var E=f.length,_=E-l,A=1;for(;A<i.length;++A)if(i.charCodeAt(A)!==47)break;var O=i.length,N=O-A,L=_<N?_:N,D=-1,$=0;for(;$<=L;++$){if($===L){if(N>L){if(i.charCodeAt(A+$)===47)return i.slice(A+$+1);else if($===0)return i.slice(A+$)}else if(_>L){if(f.charCodeAt(l+$)===47)D=$;else if($===0)D=0}break}var w=f.charCodeAt(l+$),U=i.charCodeAt(A+$);if(w!==U)break;else if(w===47)D=$}var R="";for($=l+D+1;$<=E;++$)if($===E||f.charCodeAt($)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+i.slice(A+D);else{if(A+=D,i.charCodeAt(A)===47)++A;return i.slice(A)}}function lf(f){return f}function X(f){if(S(f),f.length===0)return".";var i=f.charCodeAt(0),l=i===47,E=-1,_=!0;for(var A=f.length-1;A>=1;--A)if(i=f.charCodeAt(A),i===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return f.slice(0,E)}function Ef(f,i){if(i!==void 0&&typeof i!=="string")throw new TypeError('"ext" argument must be a string');S(f);var l=0,E=-1,_=!0,A;if(i!==void 0&&i.length>0&&i.length<=f.length){if(i.length===f.length&&i===f)return"";var O=i.length-1,N=-1;for(A=f.length-1;A>=0;--A){var L=f.charCodeAt(A);if(L===47){if(!_){l=A+1;break}}else{if(N===-1)_=!1,N=A+1;if(O>=0)if(L===i.charCodeAt(O)){if(--O===-1)E=A}else O=-1,E=N}}if(l===E)E=N;else if(E===-1)E=f.length;return f.slice(l,E)}else{for(A=f.length-1;A>=0;--A)if(f.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return f.slice(l,E)}}function Af(f){S(f);var i=-1,l=0,E=-1,_=!0,A=0;for(var O=f.length-1;O>=0;--O){var N=f.charCodeAt(O);if(N===47){if(!_){l=O+1;break}continue}if(E===-1)_=!1,E=O+1;if(N===46){if(i===-1)i=O;else if(A!==1)A=1}else if(i!==-1)A=-1}if(i===-1||E===-1||A===0||A===1&&i===E-1&&i===l+1)return"";return f.slice(i,E)}function _f(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return e("/",f)}function Of(f){S(f);var i={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return i;var l=f.charCodeAt(0),E=l===47,_;if(E)i.root="/",_=1;else _=0;var A=-1,O=0,N=-1,L=!0,D=f.length-1,$=0;for(;D>=_;--D){if(l=f.charCodeAt(D),l===47){if(!L){O=D+1;break}continue}if(N===-1)L=!1,N=D+1;if(l===46){if(A===-1)A=D;else if($!==1)$=1}else if(A!==-1)$=-1}if(A===-1||N===-1||$===0||$===1&&A===N-1&&A===O+1){if(N!==-1)if(O===0&&E)i.base=i.name=f.slice(1,N);else i.base=i.name=f.slice(O,N)}else{if(O===0&&E)i.name=f.slice(1,A),i.base=f.slice(1,N);else i.name=f.slice(O,A),i.base=f.slice(O,N);i.ext=f.slice(A,N)}if(O>0)i.dir=f.slice(0,O-1);else if(E)i.dir="/";return i}var z="/",Nf=":",Hf=((f)=>(f.posix=f,f))({resolve:F,normalize:u,isAbsolute:ff,join:a,relative:x,_makeLong:lf,dirname:X,basename:Ef,extname:Af,format:_f,parse:Of,sep:z,delimiter:Nf,win32:null,posix:null});class h{outputPath;constructor(f="./.vector/routes.generated.ts"){this.outputPath=f}async generate(f){let i=X(this.outputPath);await M.promises.mkdir(i,{recursive:!0});let l=[],E=new Map;for(let N of f){if(!E.has(N.path))E.set(N.path,[]);E.get(N.path).push(N)}let _=0,A=[];for(let[N,L]of E){let D=x(X(this.outputPath),N).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),$=`route_${_++}`,w=L.filter((U)=>U.name!=="default").map((U)=>U.name);if(L.some((U)=>U.name==="default"))if(w.length>0)l.push(`import ${$}, { ${w.join(", ")} } from '${D}';`);else l.push(`import ${$} from '${D}';`);else if(w.length>0)l.push(`import { ${w.join(", ")} } from '${D}';`);for(let U of L){let R=U.name==="default"?$:U.name;A.push(` ${R},`)}}let O=`// This file is auto-generated. Do not edit manually.
|
|
2
2
|
// Generated at: ${new Date().toISOString()}
|
|
3
3
|
|
|
4
4
|
${l.join(`
|
|
@@ -10,12 +10,12 @@ ${A.join(`
|
|
|
10
10
|
];
|
|
11
11
|
|
|
12
12
|
export default routes;
|
|
13
|
-
`;await
|
|
13
|
+
`;await M.promises.writeFile(this.outputPath,O,"utf-8")}async generateDynamic(f){let i=[];for(let l of f){let E=JSON.stringify({method:l.method,path:l.options.path,options:l.options});i.push(` await import('${l.path}').then(m => ({
|
|
14
14
|
...${E},
|
|
15
15
|
handler: m.${l.name==="default"?"default":l.name}
|
|
16
16
|
}))`)}return`export const loadRoutes = async () => {
|
|
17
17
|
return Promise.all([
|
|
18
|
-
${
|
|
18
|
+
${i.join(`,
|
|
19
19
|
`)}
|
|
20
20
|
]);
|
|
21
|
-
};`}}var x=(()=>({}));class B{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(i="./routes",f){this.routesDir=j(process.cwd(),i),this.excludePatterns=f||B.DEFAULT_EXCLUDE_PATTERNS}async scan(){let i=[];if(!x.existsSync(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}isExcluded(i){let f=a(this.routesDir,i);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*/g,"[^/]*").replace(/\*\*/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=f.split(Q).pop()||"";if(_.test(f)||_.test(A))return!0}return!1}async scanDirectory(i,f,l=""){let E=await x.promises.readdir(i);for(let _ of E){let A=M(i,_);if((await x.promises.stat(A)).isDirectory()){let O=l?`${l}/${_}`:_;await this.scanDirectory(A,f,O)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let O=a(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Q).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")f.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${O}`,expose:!0}});for(let[I,$]of Object.entries(D)){if(I==="default")continue;if($&&typeof $==="object"&&"entry"in $&&"options"in $&&"handler"in $){let w=$;f.push({name:I,path:A,method:w.options.method,options:w.options})}else if(Array.isArray($)&&$.length>=4){let[w,,,R]=$;f.push({name:I,path:A,method:w,options:{method:w,path:R,expose:!0}})}}}catch(U){console.error(`Failed to load route from ${A}:`,U)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}class X{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)try{l=await E(l,f)}catch(_){console.error("After middleware error:",_)}return l}clone(){let i=new X;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function u(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class Z{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let A=0,N=i.split("/").filter(Boolean);for(let O of N)if(this.isStaticSegment(O))A+=1000;else if(this.isParamSegment(O))A+=10;else if(this.isWildcardSegment(O))A+=1;if(A+=i.length,this.isExactPath(i))A+=1e4;return A}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}prepareRequest(i,f){if(!i.context)i.context={};if(f?.params!==void 0)i.params=f.params;if(f?.route!==void 0)i.route=f.route;if(f?.metadata!==void 0)i.metadata=f.metadata;if(!i.query&&i.url){let l=new URL(i.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;i.query=E}if(!i.cookies)g(i)}wrapHandler(i,f){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:i.metadata}),l=E;try{if(i.expose===!1)return S.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,i.auth)try{await this.authManager.authenticate(l)}catch(D){return S.unauthorized(D instanceof Error?D.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,N=i.cache,O=async()=>{let D=await f(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(N&&typeof N==="number"&&N>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N)}else if(N&&typeof N==="object"&&N.ttl){let D=N.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N.ttl)}else A=await f(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let U;if(i.rawResponse||A instanceof Response)U=A instanceof Response?A:new Response(A);else U=P(200,A,i.responseContentType);return U=await this.middlewareManager.executeFinally(U,l),U}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),S.internalServerError(_ instanceof Error?_.message:String(_),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,_,A,N]of this.routes)if(i.method==="OPTIONS"||i.method===E){let O=l.match(_);if(O){let U=i;this.prepareRequest(U,{params:O.groups||{},route:N||l});for(let D of A){let I=await D(U);if(I)return I}}}return S.notFound("Route not found")}clearRoutes(){this.routes=[]}}class v{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=H(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${f}:${i} - server object is invalid`);return console.log(`→ Vector server running at http://${f}:${i}`),this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${i} is already in use`,E.port=i;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${i}`,E.port=i;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${f}`,E.hostname=f;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}class d{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new X,this.authManager=new W,this.cacheManager=new h,this.router=new Z(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!d.instance)d.instance=new d;return d.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new v(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes",f=this.config.routeExcludePatterns;if(this.routeScanner=new B(i,f),!this.routeGenerator)this.routeGenerator=new K;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(u(E.path)),N=E.name==="default"?A.default:A[E.name];if(N){if(this.isRouteDefinition(N)){let O=N;this.router.route(O.options,O.handler),this.logRouteLoaded(O.options)}else if(this.isRouteEntry(N))this.router.addRoute(N),this.logRouteLoaded(N);else if(typeof N==="function")this.router.route(E.options,N),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){d.instance=null}}var q=d.getInstance;var{preflight:si,corsify:pi}=H({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function y(i,f){let l=Ii(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function Oi(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}var Ni={success:(i,f)=>P(C.OK,i,f),created:(i,f)=>P(C.CREATED,i,f)};function L(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return P(i,E,l)}var S={badRequest:(i="Bad Request",f)=>L(C.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>L(C.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>L(402,i,f),forbidden:(i="Forbidden",f)=>L(C.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>L(C.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>L(405,i,f),notAcceptable:(i="Not Acceptable",f)=>L(406,i,f),requestTimeout:(i="Request Timeout",f)=>L(408,i,f),conflict:(i="Conflict",f)=>L(C.CONFLICT,i,f),gone:(i="Gone",f)=>L(410,i,f),lengthRequired:(i="Length Required",f)=>L(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>L(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>L(413,i,f),uriTooLong:(i="URI Too Long",f)=>L(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>L(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>L(416,i,f),expectationFailed:(i="Expectation Failed",f)=>L(417,i,f),imATeapot:(i="I'm a teapot",f)=>L(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>L(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>L(423,i,f),failedDependency:(i="Failed Dependency",f)=>L(424,i,f),tooEarly:(i="Too Early",f)=>L(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>L(426,i,f),preconditionRequired:(i="Precondition Required",f)=>L(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>L(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>L(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>L(451,i,f),internalServerError:(i="Internal Server Error",f)=>L(C.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>L(501,i,f),badGateway:(i="Bad Gateway",f)=>L(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>L(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>L(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>L(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>L(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>L(507,i,f),loopDetected:(i="Loop Detected",f)=>L(508,i,f),notExtended:(i="Not Extended",f)=>L(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>L(511,i,f),invalidArgument:(i="Invalid Argument",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>L(429,i,f),maintenance:(i="Service Under Maintenance",f)=>L(503,i,f),custom:(i,f,l)=>L(i,f,l)};function P(i,f,l=F.JSON){let E=l===F.JSON?Oi(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}var Di=async(i,f)=>{let E=q().getProtectedHandler();if(!E)throw S.unauthorized("Authentication not configured",f);try{let _=await E(i);i.authUser=_}catch(_){throw S.unauthorized(_ instanceof Error?_.message:"Authentication failed",f)}};function Ii(i,f){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:N=F.JSON}=i;return async(O)=>{if(!E)return S.forbidden("Forbidden");try{if(l)await Di(O,N);if(!_)await k(O);let U=await f(O);return A?U:Ni.success(U,N)}catch(U){if(U instanceof Response)return U;return S.internalServerError(String(U),N)}}}
|
|
21
|
+
};`}}var Y=(()=>({}));class B{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(f="./routes",i){this.routesDir=F(process.cwd(),f),this.excludePatterns=i||B.DEFAULT_EXCLUDE_PATTERNS}async scan(){let f=[];if(!Y.existsSync(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,f)}catch(i){if(i.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw i}return f}isExcluded(f){let i=x(this.routesDir,f);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/__GLOBSTAR__/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=i.split(z).pop()||"";if(_.test(i)||_.test(A))return!0}return!1}async scanDirectory(f,i,l=""){let E=await Y.promises.readdir(f);for(let _ of E){let A=a(f,_);if((await Y.promises.stat(A)).isDirectory()){let N=l?`${l}/${_}`:_;await this.scanDirectory(A,i,N)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let N=x(this.routesDir,A).replace(/\.(ts|js)$/,"").split(z).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")i.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${N}`,expose:!0}});for(let[$,w]of Object.entries(D)){if($==="default")continue;if(w&&typeof w==="object"&&"entry"in w&&"options"in w&&"handler"in w){let U=w;i.push({name:$,path:A,method:U.options.method,options:U.options})}else if(Array.isArray(w)&&w.length>=4){let[U,,,R]=w;i.push({name:$,path:A,method:U,options:{method:U,path:R,expose:!0}})}}}catch(L){console.error(`Failed to load route from ${A}:`,L)}}}}enableWatch(f){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await f()},1000)}}class J{beforeHandlers=[];finallyHandlers=[];addBefore(...f){this.beforeHandlers.push(...f)}addFinally(...f){this.finallyHandlers.push(...f)}async executeBefore(f){let i=f;for(let l of this.beforeHandlers){let E=await l(i);if(E instanceof Response)return E;i=E}return i}async executeFinally(f,i){let l=f;for(let E of this.finallyHandlers)try{l=await E(l,i)}catch(_){console.error("After middleware error:",_)}return l}clone(){let f=new J;return f.beforeHandlers=[...this.beforeHandlers],f.finallyHandlers=[...this.finallyHandlers],f}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}class g{middlewareManager;authManager;cacheManager;routes=[];specificityCache=new Map;constructor(f,i,l){this.middlewareManager=f,this.authManager=i,this.cacheManager=l}getRouteSpecificity(f){let i=this.specificityCache.get(f);if(i!==void 0)return i;let l=1000,E=10,_=1,A=1e4,O=0,N=f.split("/").filter(Boolean);for(let L of N)if(this.isStaticSegment(L))O+=l;else if(this.isParamSegment(L))O+=E;else if(this.isWildcardSegment(L))O+=_;if(O+=f.length,this.isExactPath(f))O+=A;return this.specificityCache.set(f,O),O}isStaticSegment(f){return!f.startsWith(":")&&!f.includes("*")}isParamSegment(f){return f.startsWith(":")}isWildcardSegment(f){return f.includes("*")}isExactPath(f){return!f.includes(":")&&!f.includes("*")}sortRoutes(){this.routes.sort((f,i)=>{let l=this.extractPath(f),E=this.extractPath(i),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(f){return f[3]||""}route(f,i){let l=this.wrapHandler(f,i),E=[f.method.toUpperCase(),this.createRouteRegex(f.path),[l],f.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(f){return Q(f)}prepareRequest(f,i){if(!f.context)f.context={};if(i?.params!==void 0)f.params=i.params;if(i?.route!==void 0)f.route=i.route;if(i?.metadata!==void 0)f.metadata=i.metadata;if(!f.query&&f.url){let l=f._parsedUrl??new URL(f.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;f.query=E}if(!Object.getOwnPropertyDescriptor(f,"cookies"))Object.defineProperty(f,"cookies",{get(){let l=this.headers.get("cookie")??"",E={};if(l)for(let _ of l.split(";")){let A=_.indexOf("=");if(A>0)E[_.slice(0,A).trim()]=_.slice(A+1).trim()}return Object.defineProperty(this,"cookies",{value:E,writable:!0,configurable:!0,enumerable:!0}),E},configurable:!0,enumerable:!0})}wrapHandler(f,i){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:f.metadata}),l=E;try{if(f.expose===!1)return C.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,f.auth)try{await this.authManager.authenticate(l)}catch(D){return C.unauthorized(D instanceof Error?D.message:"Authentication failed",f.responseContentType)}if(!f.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,O=f.cache,N=async()=>{let D=await i(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(O&&typeof O==="number"&&O>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,N,O)}else if(O&&typeof O==="object"&&O.ttl){let D=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,N,O.ttl)}else A=await i(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let L;if(f.rawResponse||A instanceof Response)L=A instanceof Response?A:new Response(A);else L=P(200,A,f.responseContentType);return L=await this.middlewareManager.executeFinally(L,l),L}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),C.internalServerError(_ instanceof Error?_.message:String(_),f.responseContentType)}}}addRoute(f){this.routes.push(f),this.sortRoutes()}bulkAddRoutes(f){for(let i of f)this.routes.push(i);this.sortRoutes()}getRoutes(){return this.routes}async handle(f){let i;try{i=new URL(f.url)}catch{return C.badRequest("Malformed request URL")}f._parsedUrl=i;let l=i.pathname;for(let[E,_,A,O]of this.routes)if(f.method==="OPTIONS"||f.method===E){let N=l.match(_);if(N){let L=f;this.prepareRequest(L,{params:N.groups||{},route:O||l});for(let D of A){let $=await D(L);if($)return $}}}return C.notFound("Route not found")}clearRoutes(){this.routes=[],this.specificityCache.clear()}}class T{server=null;router;config;corsHandler;corsHeaders=null;constructor(f,i){if(this.router=f,this.config=i,i.cors){let l=this.normalizeCorsOptions(i.cors),{preflight:E,corsify:_}=d(l);if(this.corsHandler={preflight:E,corsify:_},typeof l.origin==="string"){if(this.corsHeaders={"access-control-allow-origin":l.origin,"access-control-allow-methods":l.allowMethods,"access-control-allow-headers":l.allowHeaders,"access-control-expose-headers":l.exposeHeaders,"access-control-max-age":String(l.maxAge)},l.credentials)this.corsHeaders["access-control-allow-credentials"]="true"}}}normalizeCorsOptions(f){return{origin:f.origin||"*",credentials:f.credentials!==!1,allowHeaders:Array.isArray(f.allowHeaders)?f.allowHeaders.join(", "):f.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(f.allowMethods)?f.allowMethods.join(", "):f.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(f.exposeHeaders)?f.exposeHeaders.join(", "):f.exposeHeaders||"Authorization",maxAge:f.maxAge||86400}}async start(){let f=this.config.port||3000,i=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHeaders)for(let[A,O]of Object.entries(this.corsHeaders))_.headers.set(A,O);else if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:f,hostname:i,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${i}:${f} - server object is invalid`);return this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${f} is already in use`,E.port=f;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${f}`,E.port=f;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${i}`,E.hostname=i;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let f=this.getPort();return`http://${this.getHostname()}:${f}`}}class j{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new J,this.authManager=new Z,this.cacheManager=new W,this.router=new g(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!j.instance)j.instance=new j;return j.instance}setProtectedHandler(f){this._protectedHandler=f,this.authManager.setProtectedHandler(f)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(f){this._cacheHandler=f,this.cacheManager.setCacheHandler(f)}getCacheHandler(){return this._cacheHandler}addRoute(f,i){return this.router.route(f,i)}async startServer(f){if(this.config={...this.config,...f},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(f?.before)this.middlewareManager.addBefore(...f.before);if(f?.finally)this.middlewareManager.addFinally(...f.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new T(this.router,this.config),await this.server.start()}async discoverRoutes(){let f=this.config.routesDir||"./routes",i=this.config.routeExcludePatterns;if(this.routeScanner=new B(f,i),!this.routeGenerator)this.routeGenerator=new h;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(c(E.path)),O=E.name==="default"?A.default:A[E.name];if(O){if(this.isRouteDefinition(O)){let N=O;this.router.route(N.options,N.handler),this.logRouteLoaded(N.options)}else if(this.isRouteEntry(O))this.router.addRoute(O),this.logRouteLoaded(O);else if(typeof O==="function")this.router.route(E.options,O),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(f){if(typeof f==="function"){let i=f();if(Array.isArray(i))this.router.addRoute(i)}else if(f&&typeof f==="object"){for(let[,i]of Object.entries(f))if(typeof i==="function"){let l=i();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(f){return Array.isArray(f)&&f.length>=3}isRouteDefinition(f){return f&&typeof f==="object"&&"entry"in f&&"options"in f&&"handler"in f}logRouteLoaded(f){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){j.instance=null}}var q=j.getInstance;var{preflight:of,corsify:tf}=d({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function y(f,i){let l=If(f,i);return{entry:[f.method.toUpperCase(),Q(f.path),[l],f.path],options:f,handler:i}}function n(f,i=0){if(typeof f==="bigint")return!0;if(i>4||f===null||typeof f!=="object")return!1;for(let l of Object.values(f))if(n(l,i+1))return!0;return!1}function Df(f){let i=f??null;if(!n(i))return JSON.stringify(i);return JSON.stringify(i,(l,E)=>typeof E==="bigint"?E.toString():E)}var $f={success:(f,i)=>P(b.OK,f,i),created:(f,i)=>P(b.CREATED,f,i)};function I(f,i,l){let E={error:!0,message:i,statusCode:f,timestamp:new Date().toISOString()};return P(f,E,l)}var C={badRequest:(f="Bad Request",i)=>I(b.BAD_REQUEST,f,i),unauthorized:(f="Unauthorized",i)=>I(b.UNAUTHORIZED,f,i),paymentRequired:(f="Payment Required",i)=>I(402,f,i),forbidden:(f="Forbidden",i)=>I(b.FORBIDDEN,f,i),notFound:(f="Not Found",i)=>I(b.NOT_FOUND,f,i),methodNotAllowed:(f="Method Not Allowed",i)=>I(405,f,i),notAcceptable:(f="Not Acceptable",i)=>I(406,f,i),requestTimeout:(f="Request Timeout",i)=>I(408,f,i),conflict:(f="Conflict",i)=>I(b.CONFLICT,f,i),gone:(f="Gone",i)=>I(410,f,i),lengthRequired:(f="Length Required",i)=>I(411,f,i),preconditionFailed:(f="Precondition Failed",i)=>I(412,f,i),payloadTooLarge:(f="Payload Too Large",i)=>I(413,f,i),uriTooLong:(f="URI Too Long",i)=>I(414,f,i),unsupportedMediaType:(f="Unsupported Media Type",i)=>I(415,f,i),rangeNotSatisfiable:(f="Range Not Satisfiable",i)=>I(416,f,i),expectationFailed:(f="Expectation Failed",i)=>I(417,f,i),imATeapot:(f="I'm a teapot",i)=>I(418,f,i),misdirectedRequest:(f="Misdirected Request",i)=>I(421,f,i),unprocessableEntity:(f="Unprocessable Entity",i)=>I(b.UNPROCESSABLE_ENTITY,f,i),locked:(f="Locked",i)=>I(423,f,i),failedDependency:(f="Failed Dependency",i)=>I(424,f,i),tooEarly:(f="Too Early",i)=>I(425,f,i),upgradeRequired:(f="Upgrade Required",i)=>I(426,f,i),preconditionRequired:(f="Precondition Required",i)=>I(428,f,i),tooManyRequests:(f="Too Many Requests",i)=>I(429,f,i),requestHeaderFieldsTooLarge:(f="Request Header Fields Too Large",i)=>I(431,f,i),unavailableForLegalReasons:(f="Unavailable For Legal Reasons",i)=>I(451,f,i),internalServerError:(f="Internal Server Error",i)=>I(b.INTERNAL_SERVER_ERROR,f,i),notImplemented:(f="Not Implemented",i)=>I(501,f,i),badGateway:(f="Bad Gateway",i)=>I(502,f,i),serviceUnavailable:(f="Service Unavailable",i)=>I(503,f,i),gatewayTimeout:(f="Gateway Timeout",i)=>I(504,f,i),httpVersionNotSupported:(f="HTTP Version Not Supported",i)=>I(505,f,i),variantAlsoNegotiates:(f="Variant Also Negotiates",i)=>I(506,f,i),insufficientStorage:(f="Insufficient Storage",i)=>I(507,f,i),loopDetected:(f="Loop Detected",i)=>I(508,f,i),notExtended:(f="Not Extended",i)=>I(510,f,i),networkAuthenticationRequired:(f="Network Authentication Required",i)=>I(511,f,i),invalidArgument:(f="Invalid Argument",i)=>I(b.UNPROCESSABLE_ENTITY,f,i),rateLimitExceeded:(f="Rate Limit Exceeded",i)=>I(429,f,i),maintenance:(f="Service Under Maintenance",i)=>I(503,f,i),custom:(f,i,l)=>I(f,i,l)};function P(f,i,l=H.JSON){let E=l===H.JSON?Df(i):i;return new Response(E,{status:f,headers:{"content-type":l}})}var Lf=async(f,i)=>{let E=q().getProtectedHandler();if(!E)throw C.unauthorized("Authentication not configured",i);try{let _=await E(f);f.authUser=_}catch(_){throw C.unauthorized(_ instanceof Error?_.message:"Authentication failed",i)}};function If(f,i){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:O=H.JSON}=f;return async(N)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Lf(N,O);if(!_)await k(N);let L=await i(N);return A?L:$f.success(L,O)}catch(L){if(L instanceof Response)return L;return C.internalServerError(String(L),O)}}}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var d=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(f?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",i),_},Ai=d("application/json; charset=utf-8",JSON.stringify);var _i=d("text/plain; charset=utf-8",String),Oi=d("text/html"),Ni=d("image/jpeg"),Di=d("image/png"),Ii=d("image/webp"),K=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},Z=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},x=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:N}=i,O=(D)=>{let I=D?.headers.get("origin");return f===!0?I:f instanceof RegExp?f.test(I)?I:void 0:Array.isArray(f)?f.includes(I)?I:void 0:f instanceof Function?f(I):f=="*"&&l?I:f},U=(D,I)=>{for(let[$,w]of Object.entries(I))w&&D.headers.append($,w);return D};return{corsify:(D,I)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:U(D.clone(),{"access-control-allow-origin":O(I),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let I=new Response(null,{status:204});return U(I,{"access-control-allow-origin":O(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":N,"access-control-allow-credentials":l})}}}};var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},X={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},H={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class z{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class J{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=X.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),_=this.memoryCache.get(i);if(this.isCacheValid(_,E))return _.value;let A=await f();return this.setInMemoryCache(i,A,l),A}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=X.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var{promises:k}=(()=>({}));function S(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function v(i,f){var l="",E=0,_=-1,A=0,N;for(var O=0;O<=i.length;++O){if(O<i.length)N=i.charCodeAt(O);else if(N===47)break;else N=47;if(N===47){if(_===O-1||A===1);else if(_!==O-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var U=l.lastIndexOf("/");if(U!==l.length-1){if(U===-1)l="",E=0;else l=l.slice(0,U),E=l.length-1-l.lastIndexOf("/");_=O,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=O,A=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(_+1,O);else l=i.slice(_+1,O);E=O-_-1}_=O,A=0}else if(N===46&&A!==-1)++A;else A=-1}return l}function u(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function j(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(S(_),_.length===0)continue;i=_+"/"+i,f=_.charCodeAt(0)===47}if(i=v(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function T(i){if(S(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=v(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function q(i){return S(i),i.length>0&&i.charCodeAt(0)===47}function W(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(S(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return T(i)}function G(i,f){if(S(i),S(f),i===f)return"";if(i=j(i),f=j(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,_=E-l,A=1;for(;A<f.length;++A)if(f.charCodeAt(A)!==47)break;var N=f.length,O=N-A,U=_<O?_:O,D=-1,I=0;for(;I<=U;++I){if(I===U){if(O>U){if(f.charCodeAt(A+I)===47)return f.slice(A+I+1);else if(I===0)return f.slice(A+I)}else if(_>U){if(i.charCodeAt(l+I)===47)D=I;else if(I===0)D=0}break}var $=i.charCodeAt(l+I),w=f.charCodeAt(A+I);if($!==w)break;else if($===47)D=I}var R="";for(I=l+D+1;I<=E;++I)if(I===E||i.charCodeAt(I)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+f.slice(A+D);else{if(A+=D,f.charCodeAt(A)===47)++A;return f.slice(A)}}function y(i){return i}function F(i){if(S(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,_=!0;for(var A=i.length-1;A>=1;--A)if(f=i.charCodeAt(A),f===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function n(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');S(i);var l=0,E=-1,_=!0,A;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var N=f.length-1,O=-1;for(A=i.length-1;A>=0;--A){var U=i.charCodeAt(A);if(U===47){if(!_){l=A+1;break}}else{if(O===-1)_=!1,O=A+1;if(N>=0)if(U===f.charCodeAt(N)){if(--N===-1)E=A}else N=-1,E=O}}if(l===E)E=O;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return i.slice(l,E)}}function s(i){S(i);var f=-1,l=0,E=-1,_=!0,A=0;for(var N=i.length-1;N>=0;--N){var O=i.charCodeAt(N);if(O===47){if(!_){l=N+1;break}continue}if(E===-1)_=!1,E=N+1;if(O===46){if(f===-1)f=N;else if(A!==1)A=1}else if(f!==-1)A=-1}if(f===-1||E===-1||A===0||A===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function p(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return u("/",i)}function r(i){S(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,_;if(E)f.root="/",_=1;else _=0;var A=-1,N=0,O=-1,U=!0,D=i.length-1,I=0;for(;D>=_;--D){if(l=i.charCodeAt(D),l===47){if(!U){N=D+1;break}continue}if(O===-1)U=!1,O=D+1;if(l===46){if(A===-1)A=D;else if(I!==1)I=1}else if(A!==-1)I=-1}if(A===-1||O===-1||I===0||I===1&&A===O-1&&A===N+1){if(O!==-1)if(N===0&&E)f.base=f.name=i.slice(1,O);else f.base=f.name=i.slice(N,O)}else{if(N===0&&E)f.name=i.slice(1,A),f.base=i.slice(1,O);else f.name=i.slice(N,A),f.base=i.slice(N,O);f.ext=i.slice(A,O)}if(N>0)f.dir=i.slice(0,N-1);else if(E)f.dir="/";return f}var Y="/",o=":",Si=((i)=>(i.posix=i,i))({resolve:j,normalize:T,isAbsolute:q,join:W,relative:G,_makeLong:y,dirname:F,basename:n,extname:s,format:p,parse:r,sep:Y,delimiter:o,win32:null,posix:null});class h{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=F(this.outputPath);await k.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let O of i){if(!E.has(O.path))E.set(O.path,[]);E.get(O.path).push(O)}let _=0,A=[];for(let[O,U]of E){let D=G(F(this.outputPath),O).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),I=`route_${_++}`,$=U.filter((w)=>w.name!=="default").map((w)=>w.name);if(U.some((w)=>w.name==="default"))if($.length>0)l.push(`import ${I}, { ${$.join(", ")} } from '${D}';`);else l.push(`import ${I} from '${D}';`);else if($.length>0)l.push(`import { ${$.join(", ")} } from '${D}';`);for(let w of U){let R=w.name==="default"?I:w.name;A.push(` ${R},`)}}let N=`// This file is auto-generated. Do not edit manually.
|
|
1
|
+
var j=(f="text/plain; charset=utf-8",i)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(i?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",f),_},Of=j("application/json; charset=utf-8",JSON.stringify);var Nf=j("text/plain; charset=utf-8",String),Df=j("text/html"),$f=j("image/jpeg"),Lf=j("image/png"),If=j("image/webp"),h=async(f)=>{f.content=f.body?await f.clone().json().catch(()=>f.clone().formData()).catch(()=>f.text()):void 0};var Y=(f={})=>{let{origin:i="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:O}=f,N=(D)=>{let $=D?.headers.get("origin");return i===!0?$:i instanceof RegExp?i.test($)?$:void 0:Array.isArray(i)?i.includes($)?$:void 0:i instanceof Function?i($):i=="*"&&l?$:i},L=(D,$)=>{for(let[w,U]of Object.entries($))U&&D.headers.append(w,U);return D};return{corsify:(D,$)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:L(D.clone(),{"access-control-allow-origin":N($),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let $=new Response(null,{status:204});return L($,{"access-control-allow-origin":N(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":O,"access-control-allow-credentials":l})}}}};function g(f){return process.platform==="win32"?`file:///${f.replace(/\\/g,"/")}`:f}function d(f){return RegExp(`^${f.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>[\\s\\S]+))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},J={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},Q={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class V{protectedHandler=null;setProtectedHandler(f){this.protectedHandler=f}async authenticate(f){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let i=await this.protectedHandler(f);return f.authUser=i,i}catch(i){throw new Error(`Authentication failed: ${i instanceof Error?i.message:String(i)}`)}}isAuthenticated(f){return!!f.authUser}getUser(f){return f.authUser||null}}class K{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;inflight=new Map;setCacheHandler(f){this.cacheHandler=f}async get(f,i,l=J.CACHE_TTL){if(l<=0)return i();if(this.cacheHandler)return this.cacheHandler(f,i,l);return this.getFromMemoryCache(f,i,l)}async getFromMemoryCache(f,i,l){let E=Date.now(),_=this.memoryCache.get(f);if(this.isCacheValid(_,E))return _.value;if(this.inflight.has(f))return await this.inflight.get(f);let A=(async()=>{let O=await i();return this.setInMemoryCache(f,O,l),O})();this.inflight.set(f,A);try{return await A}finally{this.inflight.delete(f)}}isCacheValid(f,i){return f!==void 0&&f.expires>i}setInMemoryCache(f,i,l){let E=Date.now()+l*1000;this.memoryCache.set(f,{value:i,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let f=Date.now();for(let[i,l]of this.memoryCache.entries())if(l.expires<=f)this.memoryCache.delete(i);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(f,i,l=J.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(f,async()=>i,l);return}this.setInMemoryCache(f,i,l)}delete(f){return this.memoryCache.delete(f)}has(f){let i=this.memoryCache.get(f);if(!i)return!1;if(i.expires<=Date.now())return this.memoryCache.delete(f),!1;return!0}generateKey(f,i){let l=f._parsedUrl??new URL(f.url);return[f.method,l.pathname,l.search,i?.authUser?.id!=null?String(i.authUser.id):"anonymous"].join(":")}}var{promises:k}=(()=>({}));function S(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function T(f,i){var l="",E=0,_=-1,A=0,O;for(var N=0;N<=f.length;++N){if(N<f.length)O=f.charCodeAt(N);else if(O===47)break;else O=47;if(O===47){if(_===N-1||A===1);else if(_!==N-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var L=l.lastIndexOf("/");if(L!==l.length-1){if(L===-1)l="",E=0;else l=l.slice(0,L),E=l.length-1-l.lastIndexOf("/");_=N,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=N,A=0;continue}}if(i){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+f.slice(_+1,N);else l=f.slice(_+1,N);E=N-_-1}_=N,A=0}else if(O===46&&A!==-1)++A;else A=-1}return l}function q(f,i){var l=i.dir||i.root,E=i.base||(i.name||"")+(i.ext||"");if(!l)return E;if(l===i.root)return l+E;return l+f+E}function F(){var f="",i=!1,l;for(var E=arguments.length-1;E>=-1&&!i;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(S(_),_.length===0)continue;f=_+"/"+f,i=_.charCodeAt(0)===47}if(f=T(f,!i),i)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function v(f){if(S(f),f.length===0)return".";var i=f.charCodeAt(0)===47,l=f.charCodeAt(f.length-1)===47;if(f=T(f,!i),f.length===0&&!i)f=".";if(f.length>0&&l)f+="/";if(i)return"/"+f;return f}function y(f){return S(f),f.length>0&&f.charCodeAt(0)===47}function Z(){if(arguments.length===0)return".";var f;for(var i=0;i<arguments.length;++i){var l=arguments[i];if(S(l),l.length>0)if(f===void 0)f=l;else f+="/"+l}if(f===void 0)return".";return v(f)}function G(f,i){if(S(f),S(i),f===i)return"";if(f=F(f),i=F(i),f===i)return"";var l=1;for(;l<f.length;++l)if(f.charCodeAt(l)!==47)break;var E=f.length,_=E-l,A=1;for(;A<i.length;++A)if(i.charCodeAt(A)!==47)break;var O=i.length,N=O-A,L=_<N?_:N,D=-1,$=0;for(;$<=L;++$){if($===L){if(N>L){if(i.charCodeAt(A+$)===47)return i.slice(A+$+1);else if($===0)return i.slice(A+$)}else if(_>L){if(f.charCodeAt(l+$)===47)D=$;else if($===0)D=0}break}var w=f.charCodeAt(l+$),U=i.charCodeAt(A+$);if(w!==U)break;else if(w===47)D=$}var R="";for($=l+D+1;$<=E;++$)if($===E||f.charCodeAt($)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+i.slice(A+D);else{if(A+=D,i.charCodeAt(A)===47)++A;return i.slice(A)}}function n(f){return f}function H(f){if(S(f),f.length===0)return".";var i=f.charCodeAt(0),l=i===47,E=-1,_=!0;for(var A=f.length-1;A>=1;--A)if(i=f.charCodeAt(A),i===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return f.slice(0,E)}function s(f,i){if(i!==void 0&&typeof i!=="string")throw new TypeError('"ext" argument must be a string');S(f);var l=0,E=-1,_=!0,A;if(i!==void 0&&i.length>0&&i.length<=f.length){if(i.length===f.length&&i===f)return"";var O=i.length-1,N=-1;for(A=f.length-1;A>=0;--A){var L=f.charCodeAt(A);if(L===47){if(!_){l=A+1;break}}else{if(N===-1)_=!1,N=A+1;if(O>=0)if(L===i.charCodeAt(O)){if(--O===-1)E=A}else O=-1,E=N}}if(l===E)E=N;else if(E===-1)E=f.length;return f.slice(l,E)}else{for(A=f.length-1;A>=0;--A)if(f.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return f.slice(l,E)}}function p(f){S(f);var i=-1,l=0,E=-1,_=!0,A=0;for(var O=f.length-1;O>=0;--O){var N=f.charCodeAt(O);if(N===47){if(!_){l=O+1;break}continue}if(E===-1)_=!1,E=O+1;if(N===46){if(i===-1)i=O;else if(A!==1)A=1}else if(i!==-1)A=-1}if(i===-1||E===-1||A===0||A===1&&i===E-1&&i===l+1)return"";return f.slice(i,E)}function r(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return q("/",f)}function o(f){S(f);var i={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return i;var l=f.charCodeAt(0),E=l===47,_;if(E)i.root="/",_=1;else _=0;var A=-1,O=0,N=-1,L=!0,D=f.length-1,$=0;for(;D>=_;--D){if(l=f.charCodeAt(D),l===47){if(!L){O=D+1;break}continue}if(N===-1)L=!1,N=D+1;if(l===46){if(A===-1)A=D;else if($!==1)$=1}else if(A!==-1)$=-1}if(A===-1||N===-1||$===0||$===1&&A===N-1&&A===O+1){if(N!==-1)if(O===0&&E)i.base=i.name=f.slice(1,N);else i.base=i.name=f.slice(O,N)}else{if(O===0&&E)i.name=f.slice(1,A),i.base=f.slice(1,N);else i.name=f.slice(O,A),i.base=f.slice(O,N);i.ext=f.slice(A,N)}if(O>0)i.dir=f.slice(0,O-1);else if(E)i.dir="/";return i}var X="/",t=":",Pf=((f)=>(f.posix=f,f))({resolve:F,normalize:v,isAbsolute:y,join:Z,relative:G,_makeLong:n,dirname:H,basename:s,extname:p,format:r,parse:o,sep:X,delimiter:t,win32:null,posix:null});class W{outputPath;constructor(f="./.vector/routes.generated.ts"){this.outputPath=f}async generate(f){let i=H(this.outputPath);await k.mkdir(i,{recursive:!0});let l=[],E=new Map;for(let N of f){if(!E.has(N.path))E.set(N.path,[]);E.get(N.path).push(N)}let _=0,A=[];for(let[N,L]of E){let D=G(H(this.outputPath),N).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),$=`route_${_++}`,w=L.filter((U)=>U.name!=="default").map((U)=>U.name);if(L.some((U)=>U.name==="default"))if(w.length>0)l.push(`import ${$}, { ${w.join(", ")} } from '${D}';`);else l.push(`import ${$} from '${D}';`);else if(w.length>0)l.push(`import { ${w.join(", ")} } from '${D}';`);for(let U of L){let R=U.name==="default"?$:U.name;A.push(` ${R},`)}}let O=`// This file is auto-generated. Do not edit manually.
|
|
2
2
|
// Generated at: ${new Date().toISOString()}
|
|
3
3
|
|
|
4
4
|
${l.join(`
|
|
@@ -10,12 +10,12 @@ ${A.join(`
|
|
|
10
10
|
];
|
|
11
11
|
|
|
12
12
|
export default routes;
|
|
13
|
-
`;await k.writeFile(this.outputPath,
|
|
13
|
+
`;await k.writeFile(this.outputPath,O,"utf-8")}async generateDynamic(f){let i=[];for(let l of f){let E=JSON.stringify({method:l.method,path:l.options.path,options:l.options});i.push(` await import('${l.path}').then(m => ({
|
|
14
14
|
...${E},
|
|
15
15
|
handler: m.${l.name==="default"?"default":l.name}
|
|
16
16
|
}))`)}return`export const loadRoutes = async () => {
|
|
17
17
|
return Promise.all([
|
|
18
|
-
${
|
|
18
|
+
${i.join(`,
|
|
19
19
|
`)}
|
|
20
20
|
]);
|
|
21
|
-
};`}}var{existsSync:t,promises:g}=(()=>({}));class Q{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(i="./routes",f){this.routesDir=j(process.cwd(),i),this.excludePatterns=f||Q.DEFAULT_EXCLUDE_PATTERNS}async scan(){let i=[];if(!t(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}isExcluded(i){let f=G(this.routesDir,i);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*/g,"[^/]*").replace(/\*\*/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=f.split(Y).pop()||"";if(_.test(f)||_.test(A))return!0}return!1}async scanDirectory(i,f,l=""){let E=await g.readdir(i);for(let _ of E){let A=W(i,_);if((await g.stat(A)).isDirectory()){let O=l?`${l}/${_}`:_;await this.scanDirectory(A,f,O)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let O=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Y).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")f.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${O}`,expose:!0}});for(let[I,$]of Object.entries(D)){if(I==="default")continue;if($&&typeof $==="object"&&"entry"in $&&"options"in $&&"handler"in $){let w=$;f.push({name:I,path:A,method:w.options.method,options:w.options})}else if(Array.isArray($)&&$.length>=4){let[w,,,R]=$;f.push({name:I,path:A,method:w,options:{method:w,path:R,expose:!0}})}}}catch(U){console.error(`Failed to load route from ${A}:`,U)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}class B{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)try{l=await E(l,f)}catch(_){console.error("After middleware error:",_)}return l}clone(){let i=new B;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function c(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class M{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let A=0,N=i.split("/").filter(Boolean);for(let O of N)if(this.isStaticSegment(O))A+=1000;else if(this.isParamSegment(O))A+=10;else if(this.isWildcardSegment(O))A+=1;if(A+=i.length,this.isExactPath(i))A+=1e4;return A}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}prepareRequest(i,f){if(!i.context)i.context={};if(f?.params!==void 0)i.params=f.params;if(f?.route!==void 0)i.route=f.route;if(f?.metadata!==void 0)i.metadata=f.metadata;if(!i.query&&i.url){let l=new URL(i.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;i.query=E}if(!i.cookies)Z(i)}wrapHandler(i,f){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:i.metadata}),l=E;try{if(i.expose===!1)return b.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,i.auth)try{await this.authManager.authenticate(l)}catch(D){return b.unauthorized(D instanceof Error?D.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,N=i.cache,O=async()=>{let D=await f(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(N&&typeof N==="number"&&N>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N)}else if(N&&typeof N==="object"&&N.ttl){let D=N.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,O,N.ttl)}else A=await f(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let U;if(i.rawResponse||A instanceof Response)U=A instanceof Response?A:new Response(A);else U=a(200,A,i.responseContentType);return U=await this.middlewareManager.executeFinally(U,l),U}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),b.internalServerError(_ instanceof Error?_.message:String(_),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,_,A,N]of this.routes)if(i.method==="OPTIONS"||i.method===E){let O=l.match(_);if(O){let U=i;this.prepareRequest(U,{params:O.groups||{},route:N||l});for(let D of A){let I=await D(U);if(I)return I}}}return b.notFound("Route not found")}clearRoutes(){this.routes=[]}}class V{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=x(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${f}:${i} - server object is invalid`);return console.log(`→ Vector server running at http://${f}:${i}`),this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${i} is already in use`,E.port=i;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${i}`,E.port=i;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${f}`,E.hostname=f;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}class P{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new B,this.authManager=new z,this.cacheManager=new J,this.router=new M(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new V(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes",f=this.config.routeExcludePatterns;if(this.routeScanner=new Q(i,f),!this.routeGenerator)this.routeGenerator=new h;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(c(E.path)),N=E.name==="default"?A.default:A[E.name];if(N){if(this.isRouteDefinition(N)){let O=N;this.router.route(O.options,O.handler),this.logRouteLoaded(O.options)}else if(this.isRouteEntry(N))this.router.addRoute(N),this.logRouteLoaded(N);else if(typeof N==="function")this.router.route(E.options,N),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){P.instance=null}}var m=P.getInstance;var{preflight:ci,corsify:mi}=x({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function e(i,f){let l=Ei(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function ii(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}var fi={success:(i,f)=>a(C.OK,i,f),created:(i,f)=>a(C.CREATED,i,f)};function L(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return a(i,E,l)}var b={badRequest:(i="Bad Request",f)=>L(C.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>L(C.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>L(402,i,f),forbidden:(i="Forbidden",f)=>L(C.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>L(C.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>L(405,i,f),notAcceptable:(i="Not Acceptable",f)=>L(406,i,f),requestTimeout:(i="Request Timeout",f)=>L(408,i,f),conflict:(i="Conflict",f)=>L(C.CONFLICT,i,f),gone:(i="Gone",f)=>L(410,i,f),lengthRequired:(i="Length Required",f)=>L(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>L(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>L(413,i,f),uriTooLong:(i="URI Too Long",f)=>L(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>L(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>L(416,i,f),expectationFailed:(i="Expectation Failed",f)=>L(417,i,f),imATeapot:(i="I'm a teapot",f)=>L(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>L(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>L(423,i,f),failedDependency:(i="Failed Dependency",f)=>L(424,i,f),tooEarly:(i="Too Early",f)=>L(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>L(426,i,f),preconditionRequired:(i="Precondition Required",f)=>L(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>L(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>L(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>L(451,i,f),internalServerError:(i="Internal Server Error",f)=>L(C.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>L(501,i,f),badGateway:(i="Bad Gateway",f)=>L(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>L(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>L(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>L(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>L(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>L(507,i,f),loopDetected:(i="Loop Detected",f)=>L(508,i,f),notExtended:(i="Not Extended",f)=>L(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>L(511,i,f),invalidArgument:(i="Invalid Argument",f)=>L(C.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>L(429,i,f),maintenance:(i="Service Under Maintenance",f)=>L(503,i,f),custom:(i,f,l)=>L(i,f,l)};function a(i,f,l=H.JSON){let E=l===H.JSON?ii(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}var li=async(i,f)=>{let E=m().getProtectedHandler();if(!E)throw b.unauthorized("Authentication not configured",f);try{let _=await E(i);i.authUser=_}catch(_){throw b.unauthorized(_ instanceof Error?_.message:"Authentication failed",f)}};function Ei(i,f){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:N=H.JSON}=i;return async(O)=>{if(!E)return b.forbidden("Forbidden");try{if(l)await li(O,N);if(!_)await K(O);let U=await f(O);return A?U:fi.success(U,N)}catch(U){if(U instanceof Response)return U;return b.internalServerError(String(U),N)}}}export{e as route,a as createResponse,b as APIError};
|
|
21
|
+
};`}}var{existsSync:e,promises:c}=(()=>({}));class z{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(f="./routes",i){this.routesDir=F(process.cwd(),f),this.excludePatterns=i||z.DEFAULT_EXCLUDE_PATTERNS}async scan(){let f=[];if(!e(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,f)}catch(i){if(i.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw i}return f}isExcluded(f){let i=G(this.routesDir,f);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/__GLOBSTAR__/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=i.split(X).pop()||"";if(_.test(i)||_.test(A))return!0}return!1}async scanDirectory(f,i,l=""){let E=await c.readdir(f);for(let _ of E){let A=Z(f,_);if((await c.stat(A)).isDirectory()){let N=l?`${l}/${_}`:_;await this.scanDirectory(A,i,N)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let N=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(X).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")i.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${N}`,expose:!0}});for(let[$,w]of Object.entries(D)){if($==="default")continue;if(w&&typeof w==="object"&&"entry"in w&&"options"in w&&"handler"in w){let U=w;i.push({name:$,path:A,method:U.options.method,options:U.options})}else if(Array.isArray(w)&&w.length>=4){let[U,,,R]=w;i.push({name:$,path:A,method:U,options:{method:U,path:R,expose:!0}})}}}catch(L){console.error(`Failed to load route from ${A}:`,L)}}}}enableWatch(f){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await f()},1000)}}class B{beforeHandlers=[];finallyHandlers=[];addBefore(...f){this.beforeHandlers.push(...f)}addFinally(...f){this.finallyHandlers.push(...f)}async executeBefore(f){let i=f;for(let l of this.beforeHandlers){let E=await l(i);if(E instanceof Response)return E;i=E}return i}async executeFinally(f,i){let l=f;for(let E of this.finallyHandlers)try{l=await E(l,i)}catch(_){console.error("After middleware error:",_)}return l}clone(){let f=new B;return f.beforeHandlers=[...this.beforeHandlers],f.finallyHandlers=[...this.finallyHandlers],f}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}class a{middlewareManager;authManager;cacheManager;routes=[];specificityCache=new Map;constructor(f,i,l){this.middlewareManager=f,this.authManager=i,this.cacheManager=l}getRouteSpecificity(f){let i=this.specificityCache.get(f);if(i!==void 0)return i;let l=1000,E=10,_=1,A=1e4,O=0,N=f.split("/").filter(Boolean);for(let L of N)if(this.isStaticSegment(L))O+=l;else if(this.isParamSegment(L))O+=E;else if(this.isWildcardSegment(L))O+=_;if(O+=f.length,this.isExactPath(f))O+=A;return this.specificityCache.set(f,O),O}isStaticSegment(f){return!f.startsWith(":")&&!f.includes("*")}isParamSegment(f){return f.startsWith(":")}isWildcardSegment(f){return f.includes("*")}isExactPath(f){return!f.includes(":")&&!f.includes("*")}sortRoutes(){this.routes.sort((f,i)=>{let l=this.extractPath(f),E=this.extractPath(i),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(f){return f[3]||""}route(f,i){let l=this.wrapHandler(f,i),E=[f.method.toUpperCase(),this.createRouteRegex(f.path),[l],f.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(f){return d(f)}prepareRequest(f,i){if(!f.context)f.context={};if(i?.params!==void 0)f.params=i.params;if(i?.route!==void 0)f.route=i.route;if(i?.metadata!==void 0)f.metadata=i.metadata;if(!f.query&&f.url){let l=f._parsedUrl??new URL(f.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;f.query=E}if(!Object.getOwnPropertyDescriptor(f,"cookies"))Object.defineProperty(f,"cookies",{get(){let l=this.headers.get("cookie")??"",E={};if(l)for(let _ of l.split(";")){let A=_.indexOf("=");if(A>0)E[_.slice(0,A).trim()]=_.slice(A+1).trim()}return Object.defineProperty(this,"cookies",{value:E,writable:!0,configurable:!0,enumerable:!0}),E},configurable:!0,enumerable:!0})}wrapHandler(f,i){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:f.metadata}),l=E;try{if(f.expose===!1)return b.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,f.auth)try{await this.authManager.authenticate(l)}catch(D){return b.unauthorized(D instanceof Error?D.message:"Authentication failed",f.responseContentType)}if(!f.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,O=f.cache,N=async()=>{let D=await i(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(O&&typeof O==="number"&&O>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,N,O)}else if(O&&typeof O==="object"&&O.ttl){let D=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,N,O.ttl)}else A=await i(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let L;if(f.rawResponse||A instanceof Response)L=A instanceof Response?A:new Response(A);else L=x(200,A,f.responseContentType);return L=await this.middlewareManager.executeFinally(L,l),L}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),b.internalServerError(_ instanceof Error?_.message:String(_),f.responseContentType)}}}addRoute(f){this.routes.push(f),this.sortRoutes()}bulkAddRoutes(f){for(let i of f)this.routes.push(i);this.sortRoutes()}getRoutes(){return this.routes}async handle(f){let i;try{i=new URL(f.url)}catch{return b.badRequest("Malformed request URL")}f._parsedUrl=i;let l=i.pathname;for(let[E,_,A,O]of this.routes)if(f.method==="OPTIONS"||f.method===E){let N=l.match(_);if(N){let L=f;this.prepareRequest(L,{params:N.groups||{},route:O||l});for(let D of A){let $=await D(L);if($)return $}}}return b.notFound("Route not found")}clearRoutes(){this.routes=[],this.specificityCache.clear()}}class M{server=null;router;config;corsHandler;corsHeaders=null;constructor(f,i){if(this.router=f,this.config=i,i.cors){let l=this.normalizeCorsOptions(i.cors),{preflight:E,corsify:_}=Y(l);if(this.corsHandler={preflight:E,corsify:_},typeof l.origin==="string"){if(this.corsHeaders={"access-control-allow-origin":l.origin,"access-control-allow-methods":l.allowMethods,"access-control-allow-headers":l.allowHeaders,"access-control-expose-headers":l.exposeHeaders,"access-control-max-age":String(l.maxAge)},l.credentials)this.corsHeaders["access-control-allow-credentials"]="true"}}}normalizeCorsOptions(f){return{origin:f.origin||"*",credentials:f.credentials!==!1,allowHeaders:Array.isArray(f.allowHeaders)?f.allowHeaders.join(", "):f.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(f.allowMethods)?f.allowMethods.join(", "):f.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(f.exposeHeaders)?f.exposeHeaders.join(", "):f.exposeHeaders||"Authorization",maxAge:f.maxAge||86400}}async start(){let f=this.config.port||3000,i=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHeaders)for(let[A,O]of Object.entries(this.corsHeaders))_.headers.set(A,O);else if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:f,hostname:i,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${i}:${f} - server object is invalid`);return this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${f} is already in use`,E.port=f;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${f}`,E.port=f;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${i}`,E.hostname=i;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let f=this.getPort();return`http://${this.getHostname()}:${f}`}}class P{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new B,this.authManager=new V,this.cacheManager=new K,this.router=new a(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}setProtectedHandler(f){this._protectedHandler=f,this.authManager.setProtectedHandler(f)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(f){this._cacheHandler=f,this.cacheManager.setCacheHandler(f)}getCacheHandler(){return this._cacheHandler}addRoute(f,i){return this.router.route(f,i)}async startServer(f){if(this.config={...this.config,...f},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(f?.before)this.middlewareManager.addBefore(...f.before);if(f?.finally)this.middlewareManager.addFinally(...f.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new M(this.router,this.config),await this.server.start()}async discoverRoutes(){let f=this.config.routesDir||"./routes",i=this.config.routeExcludePatterns;if(this.routeScanner=new z(f,i),!this.routeGenerator)this.routeGenerator=new W;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(g(E.path)),O=E.name==="default"?A.default:A[E.name];if(O){if(this.isRouteDefinition(O)){let N=O;this.router.route(N.options,N.handler),this.logRouteLoaded(N.options)}else if(this.isRouteEntry(O))this.router.addRoute(O),this.logRouteLoaded(O);else if(typeof O==="function")this.router.route(E.options,O),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(f){if(typeof f==="function"){let i=f();if(Array.isArray(i))this.router.addRoute(i)}else if(f&&typeof f==="object"){for(let[,i]of Object.entries(f))if(typeof i==="function"){let l=i();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(f){return Array.isArray(f)&&f.length>=3}isRouteDefinition(f){return f&&typeof f==="object"&&"entry"in f&&"options"in f&&"handler"in f}logRouteLoaded(f){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){P.instance=null}}var m=P.getInstance;var{preflight:qf,corsify:yf}=Y({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function ff(f,i){let l=_f(f,i);return{entry:[f.method.toUpperCase(),d(f.path),[l],f.path],options:f,handler:i}}function u(f,i=0){if(typeof f==="bigint")return!0;if(i>4||f===null||typeof f!=="object")return!1;for(let l of Object.values(f))if(u(l,i+1))return!0;return!1}function lf(f){let i=f??null;if(!u(i))return JSON.stringify(i);return JSON.stringify(i,(l,E)=>typeof E==="bigint"?E.toString():E)}var Ef={success:(f,i)=>x(C.OK,f,i),created:(f,i)=>x(C.CREATED,f,i)};function I(f,i,l){let E={error:!0,message:i,statusCode:f,timestamp:new Date().toISOString()};return x(f,E,l)}var b={badRequest:(f="Bad Request",i)=>I(C.BAD_REQUEST,f,i),unauthorized:(f="Unauthorized",i)=>I(C.UNAUTHORIZED,f,i),paymentRequired:(f="Payment Required",i)=>I(402,f,i),forbidden:(f="Forbidden",i)=>I(C.FORBIDDEN,f,i),notFound:(f="Not Found",i)=>I(C.NOT_FOUND,f,i),methodNotAllowed:(f="Method Not Allowed",i)=>I(405,f,i),notAcceptable:(f="Not Acceptable",i)=>I(406,f,i),requestTimeout:(f="Request Timeout",i)=>I(408,f,i),conflict:(f="Conflict",i)=>I(C.CONFLICT,f,i),gone:(f="Gone",i)=>I(410,f,i),lengthRequired:(f="Length Required",i)=>I(411,f,i),preconditionFailed:(f="Precondition Failed",i)=>I(412,f,i),payloadTooLarge:(f="Payload Too Large",i)=>I(413,f,i),uriTooLong:(f="URI Too Long",i)=>I(414,f,i),unsupportedMediaType:(f="Unsupported Media Type",i)=>I(415,f,i),rangeNotSatisfiable:(f="Range Not Satisfiable",i)=>I(416,f,i),expectationFailed:(f="Expectation Failed",i)=>I(417,f,i),imATeapot:(f="I'm a teapot",i)=>I(418,f,i),misdirectedRequest:(f="Misdirected Request",i)=>I(421,f,i),unprocessableEntity:(f="Unprocessable Entity",i)=>I(C.UNPROCESSABLE_ENTITY,f,i),locked:(f="Locked",i)=>I(423,f,i),failedDependency:(f="Failed Dependency",i)=>I(424,f,i),tooEarly:(f="Too Early",i)=>I(425,f,i),upgradeRequired:(f="Upgrade Required",i)=>I(426,f,i),preconditionRequired:(f="Precondition Required",i)=>I(428,f,i),tooManyRequests:(f="Too Many Requests",i)=>I(429,f,i),requestHeaderFieldsTooLarge:(f="Request Header Fields Too Large",i)=>I(431,f,i),unavailableForLegalReasons:(f="Unavailable For Legal Reasons",i)=>I(451,f,i),internalServerError:(f="Internal Server Error",i)=>I(C.INTERNAL_SERVER_ERROR,f,i),notImplemented:(f="Not Implemented",i)=>I(501,f,i),badGateway:(f="Bad Gateway",i)=>I(502,f,i),serviceUnavailable:(f="Service Unavailable",i)=>I(503,f,i),gatewayTimeout:(f="Gateway Timeout",i)=>I(504,f,i),httpVersionNotSupported:(f="HTTP Version Not Supported",i)=>I(505,f,i),variantAlsoNegotiates:(f="Variant Also Negotiates",i)=>I(506,f,i),insufficientStorage:(f="Insufficient Storage",i)=>I(507,f,i),loopDetected:(f="Loop Detected",i)=>I(508,f,i),notExtended:(f="Not Extended",i)=>I(510,f,i),networkAuthenticationRequired:(f="Network Authentication Required",i)=>I(511,f,i),invalidArgument:(f="Invalid Argument",i)=>I(C.UNPROCESSABLE_ENTITY,f,i),rateLimitExceeded:(f="Rate Limit Exceeded",i)=>I(429,f,i),maintenance:(f="Service Under Maintenance",i)=>I(503,f,i),custom:(f,i,l)=>I(f,i,l)};function x(f,i,l=Q.JSON){let E=l===Q.JSON?lf(i):i;return new Response(E,{status:f,headers:{"content-type":l}})}var Af=async(f,i)=>{let E=m().getProtectedHandler();if(!E)throw b.unauthorized("Authentication not configured",i);try{let _=await E(f);f.authUser=_}catch(_){throw b.unauthorized(_ instanceof Error?_.message:"Authentication failed",i)}};function _f(f,i){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:O=Q.JSON}=f;return async(N)=>{if(!E)return b.forbidden("Forbidden");try{if(l)await Af(N,O);if(!_)await h(N);let L=await i(N);return A?L:Ef.success(L,O)}catch(L){if(L instanceof Response)return L;return b.internalServerError(String(L),O)}}}export{ff as route,x as createResponse,b as APIError};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AfterMiddlewareHandler, BeforeMiddlewareHandler, DefaultVectorTypes, VectorRequest, VectorTypes } from
|
|
1
|
+
import type { AfterMiddlewareHandler, BeforeMiddlewareHandler, DefaultVectorTypes, VectorRequest, VectorTypes } from '../types';
|
|
2
2
|
export declare class MiddlewareManager<TTypes extends VectorTypes = DefaultVectorTypes> {
|
|
3
3
|
private beforeHandlers;
|
|
4
4
|
private finallyHandlers;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/middleware/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,sBAAsB,EACtB,uBAAuB,EACvB,kBAAkB,EAClB,aAAa,EACb,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,iBAAiB,
|
|
1
|
+
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/middleware/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,sBAAsB,EACtB,uBAAuB,EACvB,kBAAkB,EAClB,aAAa,EACb,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,iBAAiB,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IAC5E,OAAO,CAAC,cAAc,CAAyC;IAC/D,OAAO,CAAC,eAAe,CAAwC;IAE/D,SAAS,CAAC,GAAG,QAAQ,EAAE,uBAAuB,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI;IAI/D,UAAU,CAAC,GAAG,QAAQ,EAAE,sBAAsB,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI;IAIzD,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;IAgBxF,cAAc,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgB3F,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC;IAOlC,KAAK,IAAI,IAAI;CAId"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/middleware/manager.ts"],"names":[],"mappings":"AAQA,MAAM,OAAO,iBAAiB;
|
|
1
|
+
{"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/middleware/manager.ts"],"names":[],"mappings":"AAQA,MAAM,OAAO,iBAAiB;IACpB,cAAc,GAAsC,EAAE,CAAC;IACvD,eAAe,GAAqC,EAAE,CAAC;IAE/D,SAAS,CAAC,GAAG,QAA2C;QACtD,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IACxC,CAAC;IAED,UAAU,CAAC,GAAG,QAA0C;QACtD,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,OAA8B;QAChD,IAAI,cAAc,GAAG,OAAO,CAAC;QAE7B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YAC1C,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC;YAE7C,IAAI,MAAM,YAAY,QAAQ,EAAE,CAAC;gBAC/B,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,cAAc,GAAG,MAAM,CAAC;QAC1B,CAAC;QAED,OAAO,cAAc,CAAC;IACxB,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,QAAkB,EAAE,OAA8B;QACrE,IAAI,eAAe,GAAG,QAAQ,CAAC;QAE/B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YAC3C,IAAI,CAAC;gBACH,eAAe,GAAG,MAAM,OAAO,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;YAC5D,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,kEAAkE;gBAClE,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;gBAChD,qCAAqC;YACvC,CAAC;QACH,CAAC;QAED,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,KAAK;QACH,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAU,CAAC;QAChD,OAAO,CAAC,cAAc,GAAG,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,CAAC;QAClD,OAAO,CAAC,eAAe,GAAG,CAAC,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;QACpD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;IAC5B,CAAC;CACF"}
|
package/dist/utils/path.d.ts
CHANGED
package/dist/utils/path.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../src/utils/path.ts"],"names":[],"mappings":"AAAA,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../src/utils/path.ts"],"names":[],"mappings":"AAAA,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CASpD"}
|
package/dist/utils/path.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
export function toFileUrl(path) {
|
|
2
|
-
return process.platform === 'win32'
|
|
3
|
-
? `file:///${path.replace(/\\/g, '/')}`
|
|
4
|
-
: path;
|
|
2
|
+
return process.platform === 'win32' ? `file:///${path.replace(/\\/g, '/')}` : path;
|
|
5
3
|
}
|
|
6
4
|
export function normalizePath(path) {
|
|
7
5
|
return path.replace(/\\/g, '/').replace(/\/+/g, '/');
|
|
8
6
|
}
|
|
7
|
+
export function buildRouteRegex(path) {
|
|
8
|
+
return RegExp(`^${path
|
|
9
|
+
.replace(/\/+(\/|$)/g, '$1')
|
|
10
|
+
.replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>[\\s\\S]+))')
|
|
11
|
+
.replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))')
|
|
12
|
+
.replace(/\./g, '\\.')
|
|
13
|
+
.replace(/(\/?)\*/g, '($1.*)?')}/*$`);
|
|
14
|
+
}
|
|
9
15
|
//# sourceMappingURL=path.js.map
|
package/dist/utils/path.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.js","sourceRoot":"","sources":["../../src/utils/path.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO
|
|
1
|
+
{"version":3,"file":"path.js","sourceRoot":"","sources":["../../src/utils/path.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACrF,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,OAAO,MAAM,CACX,IAAI,IAAI;SACL,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC;SAC3B,OAAO,CAAC,mBAAmB,EAAE,sBAAsB,CAAC;SACpD,OAAO,CAAC,iBAAiB,EAAE,qBAAqB,CAAC;SACjD,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,UAAU,EAAE,SAAS,CAAC,KAAK,CACvC,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vector-framework",
|
|
3
|
-
"version": "
|
|
4
|
-
"author": "",
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"author": "webhie-com",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/webhie-com/vector.git"
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
"itty-router": "^5.0.0"
|
|
13
13
|
},
|
|
14
14
|
"devDependencies": {
|
|
15
|
+
"@biomejs/biome": "^2.4.6",
|
|
16
|
+
"@biomejs/cli-darwin-arm64": "^2.4.6",
|
|
15
17
|
"@types/bun": "latest",
|
|
16
18
|
"oxlint": "^1.15.0",
|
|
17
19
|
"typescript": "^5.0.0"
|
|
@@ -76,6 +78,7 @@
|
|
|
76
78
|
"dev": "bun run src/cli/index.ts dev",
|
|
77
79
|
"start": "bun run src/cli/index.ts start",
|
|
78
80
|
"build": "bun run src/cli/index.ts build",
|
|
81
|
+
"build:app": "bun run src/cli/index.ts build",
|
|
79
82
|
"build:lib": "bun run build:clean && bun run build:ts && bun run build:bundle && bun run build:cli",
|
|
80
83
|
"build:clean": "rm -rf dist",
|
|
81
84
|
"build:ts": "tsc",
|
|
@@ -93,13 +96,15 @@
|
|
|
93
96
|
"test:perf": "bun run test:load && bun run test:soak && bun run test:benchmark",
|
|
94
97
|
"docker:build": "docker build -t vector:latest .",
|
|
95
98
|
"docker:build:test": "docker build -t vector:test --target test .",
|
|
96
|
-
"docker:run": "docker
|
|
97
|
-
"docker:run:dev": "docker
|
|
98
|
-
"docker:test": "docker
|
|
99
|
-
"docker:test:unit": "docker
|
|
100
|
-
"docker:test:e2e": "docker
|
|
101
|
-
"docker:test:load": "docker
|
|
102
|
-
"docker:test:benchmark": "docker
|
|
99
|
+
"docker:run": "docker compose up",
|
|
100
|
+
"docker:run:dev": "docker compose --profile dev up",
|
|
101
|
+
"docker:test": "docker compose -f docker-compose.test.yml run test-all",
|
|
102
|
+
"docker:test:unit": "docker compose -f docker-compose.test.yml run test-unit",
|
|
103
|
+
"docker:test:e2e": "docker compose -f docker-compose.test.yml run test-e2e",
|
|
104
|
+
"docker:test:load": "docker compose -f docker-compose.test.yml run test-load",
|
|
105
|
+
"docker:test:benchmark": "docker compose -f docker-compose.test.yml run test-benchmark",
|
|
106
|
+
"format": "biome format --write .",
|
|
107
|
+
"format:check": "biome format .",
|
|
103
108
|
"lint": "oxlint .",
|
|
104
109
|
"lint:fix": "oxlint . --fix",
|
|
105
110
|
"typecheck": "tsc --noEmit",
|
package/src/cache/manager.ts
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
|
-
import { DEFAULT_CONFIG } from
|
|
2
|
-
import type {
|
|
3
|
-
CacheHandler,
|
|
4
|
-
DefaultVectorTypes,
|
|
5
|
-
GetCacheType,
|
|
6
|
-
VectorTypes,
|
|
7
|
-
} from "../types";
|
|
1
|
+
import { DEFAULT_CONFIG } from '../constants';
|
|
2
|
+
import type { CacheHandler, DefaultVectorTypes, GetCacheType, VectorTypes } from '../types';
|
|
8
3
|
|
|
9
4
|
interface CacheEntry<T = any> {
|
|
10
5
|
value: T;
|
|
@@ -15,6 +10,7 @@ export class CacheManager<TTypes extends VectorTypes = DefaultVectorTypes> {
|
|
|
15
10
|
private cacheHandler: CacheHandler | null = null;
|
|
16
11
|
private memoryCache: Map<string, CacheEntry> = new Map();
|
|
17
12
|
private cleanupInterval: Timer | null = null;
|
|
13
|
+
private inflight: Map<string, Promise<any>> = new Map();
|
|
18
14
|
|
|
19
15
|
setCacheHandler(handler: CacheHandler) {
|
|
20
16
|
this.cacheHandler = handler;
|
|
@@ -48,10 +44,23 @@ export class CacheManager<TTypes extends VectorTypes = DefaultVectorTypes> {
|
|
|
48
44
|
return cached!.value as T;
|
|
49
45
|
}
|
|
50
46
|
|
|
51
|
-
|
|
52
|
-
this.
|
|
47
|
+
// Deduplicate concurrent requests for the same key (cache stampede prevention)
|
|
48
|
+
if (this.inflight.has(key)) {
|
|
49
|
+
return (await this.inflight.get(key)!) as T;
|
|
50
|
+
}
|
|
53
51
|
|
|
54
|
-
|
|
52
|
+
const promise = (async () => {
|
|
53
|
+
const value = await factory();
|
|
54
|
+
this.setInMemoryCache(key, value, ttl);
|
|
55
|
+
return value;
|
|
56
|
+
})();
|
|
57
|
+
|
|
58
|
+
this.inflight.set(key, promise);
|
|
59
|
+
try {
|
|
60
|
+
return await promise;
|
|
61
|
+
} finally {
|
|
62
|
+
this.inflight.delete(key);
|
|
63
|
+
}
|
|
55
64
|
}
|
|
56
65
|
|
|
57
66
|
private isCacheValid(entry: CacheEntry | undefined, now: number): boolean {
|
|
@@ -129,15 +138,15 @@ export class CacheManager<TTypes extends VectorTypes = DefaultVectorTypes> {
|
|
|
129
138
|
return true;
|
|
130
139
|
}
|
|
131
140
|
|
|
132
|
-
generateKey(request: Request, options?: { authUser?: any }): string {
|
|
133
|
-
const url = new URL(request.url);
|
|
141
|
+
generateKey(request: Request & { _parsedUrl?: URL }, options?: { authUser?: any }): string {
|
|
142
|
+
const url = request._parsedUrl ?? new URL(request.url);
|
|
134
143
|
const parts = [
|
|
135
144
|
request.method,
|
|
136
145
|
url.pathname,
|
|
137
146
|
url.search,
|
|
138
|
-
options?.authUser?.id
|
|
147
|
+
options?.authUser?.id != null ? String(options.authUser.id) : 'anonymous',
|
|
139
148
|
];
|
|
140
149
|
|
|
141
|
-
return parts.join(
|
|
150
|
+
return parts.join(':');
|
|
142
151
|
}
|
|
143
152
|
}
|