vector-framework 0.8.2 → 0.9.0

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.
Files changed (47) hide show
  1. package/dist/cli/index.js +89 -52
  2. package/dist/cli/index.js.map +1 -1
  3. package/dist/core/config-loader.d.ts +13 -0
  4. package/dist/core/config-loader.d.ts.map +1 -0
  5. package/dist/core/config-loader.js +166 -0
  6. package/dist/core/config-loader.js.map +1 -0
  7. package/dist/core/router.d.ts +1 -0
  8. package/dist/core/router.d.ts.map +1 -1
  9. package/dist/core/router.js +3 -0
  10. package/dist/core/router.js.map +1 -1
  11. package/dist/core/vector.d.ts +10 -12
  12. package/dist/core/vector.d.ts.map +1 -1
  13. package/dist/core/vector.js +36 -25
  14. package/dist/core/vector.js.map +1 -1
  15. package/dist/dev/route-scanner.d.ts.map +1 -1
  16. package/dist/dev/route-scanner.js +12 -1
  17. package/dist/dev/route-scanner.js.map +1 -1
  18. package/dist/http.d.ts +6 -1
  19. package/dist/http.d.ts.map +1 -1
  20. package/dist/http.js +13 -4
  21. package/dist/http.js.map +1 -1
  22. package/dist/index.d.ts +4 -12
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +5 -5
  27. package/dist/middleware/manager.d.ts +2 -1
  28. package/dist/middleware/manager.d.ts.map +1 -1
  29. package/dist/middleware/manager.js +4 -0
  30. package/dist/middleware/manager.js.map +1 -1
  31. package/dist/types/index.d.ts +26 -0
  32. package/dist/types/index.d.ts.map +1 -1
  33. package/dist/utils/path.d.ts +3 -0
  34. package/dist/utils/path.d.ts.map +1 -0
  35. package/dist/utils/path.js +9 -0
  36. package/dist/utils/path.js.map +1 -0
  37. package/package.json +3 -3
  38. package/src/cli/index.ts +103 -62
  39. package/src/core/config-loader.ts +193 -0
  40. package/src/core/router.ts +4 -0
  41. package/src/core/vector.ts +38 -32
  42. package/src/dev/route-scanner.ts +12 -1
  43. package/src/http.ts +21 -5
  44. package/src/index.ts +11 -16
  45. package/src/middleware/manager.ts +16 -4
  46. package/src/types/index.ts +44 -0
  47. package/src/utils/path.ts +9 -0
package/dist/index.mjs CHANGED
@@ -1,21 +1,21 @@
1
- var fi=Object.defineProperty;var li=(i,f)=>{for(var l in f)fi(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var C=(i,f)=>()=>(i&&(f=i(i=0)),f);class F{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}}var R,v,j;var V=C(()=>{R={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},v={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},j={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class M{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=v.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 a=Date.now(),A=this.memoryCache.get(i);if(this.isCacheValid(A,a))return A.value;let E=await f();return this.setInMemoryCache(i,E,l),E}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let a=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:a}),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=v.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 X=C(()=>{V()});function $(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function m(i,f){var l="",a=0,A=-1,E=0,O;for(var _=0;_<=i.length;++_){if(_<i.length)O=i.charCodeAt(_);else if(O===47)break;else O=47;if(O===47){if(A===_-1||E===1);else if(A!==_-1&&E===2){if(l.length<2||a!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var d=l.lastIndexOf("/");if(d!==l.length-1){if(d===-1)l="",a=0;else l=l.slice(0,d),a=l.length-1-l.lastIndexOf("/");A=_,E=0;continue}}else if(l.length===2||l.length===1){l="",a=0,A=_,E=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";a=2}}else{if(l.length>0)l+="/"+i.slice(A+1,_);else l=i.slice(A+1,_);a=_-A-1}A=_,E=0}else if(O===46&&E!==-1)++E;else E=-1}return l}function ai(i,f){var l=f.dir||f.root,a=f.base||(f.name||"")+(f.ext||"");if(!l)return a;if(l===f.root)return l+a;return l+i+a}function b(){var i="",f=!1,l;for(var a=arguments.length-1;a>=-1&&!f;a--){var A;if(a>=0)A=arguments[a];else{if(l===void 0)l=process.cwd();A=l}if($(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=m(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function n(i){if($(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=m(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Ei(i){return $(i),i.length>0&&i.charCodeAt(0)===47}function J(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if($(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return n(i)}function x(i,f){if($(i),$(f),i===f)return"";if(i=b(i),f=b(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var a=i.length,A=a-l,E=1;for(;E<f.length;++E)if(f.charCodeAt(E)!==47)break;var O=f.length,_=O-E,d=A<_?A:_,I=-1,N=0;for(;N<=d;++N){if(N===d){if(_>d){if(f.charCodeAt(E+N)===47)return f.slice(E+N+1);else if(N===0)return f.slice(E+N)}else if(A>d){if(i.charCodeAt(l+N)===47)I=N;else if(N===0)I=0}break}var w=i.charCodeAt(l+N),L=f.charCodeAt(E+N);if(w!==L)break;else if(w===47)I=N}var H="";for(N=l+I+1;N<=a;++N)if(N===a||i.charCodeAt(N)===47)if(H.length===0)H+="..";else H+="/..";if(H.length>0)return H+f.slice(E+I);else{if(E+=I,f.charCodeAt(E)===47)++E;return f.slice(E)}}function Ai(i){return i}function T(i){if($(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,a=-1,A=!0;for(var E=i.length-1;E>=1;--E)if(f=i.charCodeAt(E),f===47){if(!A){a=E;break}}else A=!1;if(a===-1)return l?"/":".";if(l&&a===1)return"//";return i.slice(0,a)}function _i(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');$(i);var l=0,a=-1,A=!0,E;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var O=f.length-1,_=-1;for(E=i.length-1;E>=0;--E){var d=i.charCodeAt(E);if(d===47){if(!A){l=E+1;break}}else{if(_===-1)A=!1,_=E+1;if(O>=0)if(d===f.charCodeAt(O)){if(--O===-1)a=E}else O=-1,a=_}}if(l===a)a=_;else if(a===-1)a=i.length;return i.slice(l,a)}else{for(E=i.length-1;E>=0;--E)if(i.charCodeAt(E)===47){if(!A){l=E+1;break}}else if(a===-1)A=!1,a=E+1;if(a===-1)return"";return i.slice(l,a)}}function Oi(i){$(i);var f=-1,l=0,a=-1,A=!0,E=0;for(var O=i.length-1;O>=0;--O){var _=i.charCodeAt(O);if(_===47){if(!A){l=O+1;break}continue}if(a===-1)A=!1,a=O+1;if(_===46){if(f===-1)f=O;else if(E!==1)E=1}else if(f!==-1)E=-1}if(f===-1||a===-1||E===0||E===1&&f===a-1&&f===l+1)return"";return i.slice(f,a)}function Ni(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return ai("/",i)}function di(i){$(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),a=l===47,A;if(a)f.root="/",A=1;else A=0;var E=-1,O=0,_=-1,d=!0,I=i.length-1,N=0;for(;I>=A;--I){if(l=i.charCodeAt(I),l===47){if(!d){O=I+1;break}continue}if(_===-1)d=!1,_=I+1;if(l===46){if(E===-1)E=I;else if(N!==1)N=1}else if(E!==-1)N=-1}if(E===-1||_===-1||N===0||N===1&&E===_-1&&E===O+1){if(_!==-1)if(O===0&&a)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(O,_)}else{if(O===0&&a)f.name=i.slice(1,E),f.base=i.slice(1,_);else f.name=i.slice(O,E),f.base=i.slice(O,_);f.ext=i.slice(E,_)}if(O>0)f.dir=i.slice(0,O-1);else if(a)f.dir="/";return f}var W="/",Di=":",Gi;var z=C(()=>{Gi=((i)=>(i.posix=i,i))({resolve:b,normalize:n,isAbsolute:Ei,join:J,relative:x,_makeLong:Ai,dirname:T,basename:_i,extname:Oi,format:Ni,parse:di,sep:W,delimiter:Di,win32:null,posix:null})});var{promises:s}=(()=>({}));class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=T(this.outputPath);await s.mkdir(f,{recursive:!0});let l=[],a=new Map;for(let _ of i){if(!a.has(_.path))a.set(_.path,[]);a.get(_.path).push(_)}let A=0,E=[];for(let[_,d]of a){let I=x(T(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),N=`route_${A++}`,w=d.filter((L)=>L.name!=="default").map((L)=>L.name);if(d.some((L)=>L.name==="default"))if(w.length>0)l.push(`import ${N}, { ${w.join(", ")} } from '${I}';`);else l.push(`import ${N} from '${I}';`);else if(w.length>0)l.push(`import { ${w.join(", ")} } from '${I}';`);for(let L of d){let H=L.name==="default"?N:L.name;E.push(` ${H},`)}}let O=`// This file is auto-generated. Do not edit manually.
1
+ var li=Object.defineProperty;var ai=(i,f)=>{for(var l in f)li(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(E)=>f[l]=()=>E})};var R=(i,f)=>()=>(i&&(f=i(i=0)),f);var H=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let A=new Response(f?.(l)??l,E.url?void 0:E);return A.headers.set("content-type",i),A},hi,Hi,bi,Si,xi,Gi,k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},m=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},F=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:A,exposeHeaders:a,maxAge:d}=i,_=(w)=>{let O=w?.headers.get("origin");return f===!0?O:f instanceof RegExp?f.test(O)?O:void 0:Array.isArray(f)?f.includes(O)?O:void 0:f instanceof Function?f(O):f=="*"&&l?O:f},N=(w,O)=>{for(let[I,L]of Object.entries(O))L&&w.headers.append(I,L);return w};return{corsify:(w,O)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(w),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":a?.join?.(",")??a,"access-control-allow-headers":A?.join?.(",")??A??w.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":l})}}}};var Y=R(()=>{hi=H("application/json; charset=utf-8",JSON.stringify),Hi=H("text/plain; charset=utf-8",String),bi=H("text/html"),Si=H("image/jpeg"),xi=H("image/png"),Gi=H("image/webp")});var $,Q,j;var V=R(()=>{$={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},Q={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},j={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class c{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 X{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=Q.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(),A=this.memoryCache.get(i);if(this.isCacheValid(A,E))return A.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=Q.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 u=R(()=>{V()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function n(i,f){var l="",E=0,A=-1,a=0,d;for(var _=0;_<=i.length;++_){if(_<i.length)d=i.charCodeAt(_);else if(d===47)break;else d=47;if(d===47){if(A===_-1||a===1);else if(A!==_-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 N=l.lastIndexOf("/");if(N!==l.length-1){if(N===-1)l="",E=0;else l=l.slice(0,N),E=l.length-1-l.lastIndexOf("/");A=_,a=0;continue}}else if(l.length===2||l.length===1){l="",E=0,A=_,a=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(A+1,_);else l=i.slice(A+1,_);E=_-A-1}A=_,a=0}else if(d===46&&a!==-1)++a;else a=-1}return l}function Ei(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 x(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var A;if(E>=0)A=arguments[E];else{if(l===void 0)l=process.cwd();A=l}if(U(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=n(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function r(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=n(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Ai(i){return U(i),i.length>0&&i.charCodeAt(0)===47}function J(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(U(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return r(i)}function G(i,f){if(U(i),U(f),i===f)return"";if(i=x(i),f=x(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,A=E-l,a=1;for(;a<f.length;++a)if(f.charCodeAt(a)!==47)break;var d=f.length,_=d-a,N=A<_?A:_,w=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(f.charCodeAt(a+O)===47)return f.slice(a+O+1);else if(O===0)return f.slice(a+O)}else if(A>N){if(i.charCodeAt(l+O)===47)w=O;else if(O===0)w=0}break}var I=i.charCodeAt(l+O),L=f.charCodeAt(a+O);if(I!==L)break;else if(I===47)w=O}var P="";for(O=l+w+1;O<=E;++O)if(O===E||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+f.slice(a+w);else{if(a+=w,f.charCodeAt(a)===47)++a;return f.slice(a)}}function _i(i){return i}function M(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,A=!0;for(var a=i.length-1;a>=1;--a)if(f=i.charCodeAt(a),f===47){if(!A){E=a;break}}else A=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function di(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');U(i);var l=0,E=-1,A=!0,a;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var d=f.length-1,_=-1;for(a=i.length-1;a>=0;--a){var N=i.charCodeAt(a);if(N===47){if(!A){l=a+1;break}}else{if(_===-1)A=!1,_=a+1;if(d>=0)if(N===f.charCodeAt(d)){if(--d===-1)E=a}else d=-1,E=_}}if(l===E)E=_;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(!A){l=a+1;break}}else if(E===-1)A=!1,E=a+1;if(E===-1)return"";return i.slice(l,E)}}function Oi(i){U(i);var f=-1,l=0,E=-1,A=!0,a=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!A){l=d+1;break}continue}if(E===-1)A=!1,E=d+1;if(_===46){if(f===-1)f=d;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 Ni(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return Ei("/",i)}function Di(i){U(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,A;if(E)f.root="/",A=1;else A=0;var a=-1,d=0,_=-1,N=!0,w=i.length-1,O=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){d=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(a===-1)a=w;else if(O!==1)O=1}else if(a!==-1)O=-1}if(a===-1||_===-1||O===0||O===1&&a===_-1&&a===d+1){if(_!==-1)if(d===0&&E)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(d,_)}else{if(d===0&&E)f.name=i.slice(1,a),f.base=i.slice(1,_);else f.name=i.slice(d,a),f.base=i.slice(d,_);f.ext=i.slice(a,_)}if(d>0)f.dir=i.slice(0,d-1);else if(E)f.dir="/";return f}var W="/",wi=":",Yi;var z=R(()=>{Yi=((i)=>(i.posix=i,i))({resolve:x,normalize:r,isAbsolute:Ai,join:J,relative:G,_makeLong:_i,dirname:M,basename:di,extname:Oi,format:Ni,parse:Di,sep:W,delimiter:wi,win32:null,posix:null})});var{promises:s}=(()=>({}));class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=M(this.outputPath);await s.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let _ of i){if(!E.has(_.path))E.set(_.path,[]);E.get(_.path).push(_)}let A=0,a=[];for(let[_,N]of E){let w=G(M(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${A++}`,I=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(I.length>0)l.push(`import ${O}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${O} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?O:L.name;a.push(` ${P},`)}}let d=`// This file is auto-generated. Do not edit manually.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
5
5
  `)}
6
6
 
7
7
  export const routes = [
8
- ${E.join(`
8
+ ${a.join(`
9
9
  `)}
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await s.writeFile(this.outputPath,O,"utf-8"),console.log(`Generated routes file: ${this.outputPath}`)}async generateDynamic(i){let f=[];for(let l of i){let a=JSON.stringify({method:l.method,path:l.options.path,options:l.options});f.push(` await import('${l.path}').then(m => ({
14
- ...${a},
13
+ `;await s.writeFile(this.outputPath,d,"utf-8"),console.log(`Generated routes file: ${this.outputPath}`)}async generateDynamic(i){let f=[];for(let l of i){let E=JSON.stringify({method:l.method,path:l.options.path,options:l.options});f.push(` await import('${l.path}').then(m => ({
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
  ${f.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var r=C(()=>{z()});var{promises:y}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=b(process.cwd(),i)}async scan(){let i=[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(`Routes directory not found: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await y.readdir(i);for(let A of a){let E=J(i,A);if((await y.stat(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=x(this.routesDir,E).replace(/\.(ts|js)$/,"").split(W).join("/");try{let I=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(I.default&&typeof I.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[N,w]of Object.entries(I)){if(N==="default")continue;if(Array.isArray(w)&&w.length>=4){let[L,,,H]=w;f.push({name:N,path:E,method:L,options:{method:L,path:H,expose:!0}})}}}catch(d){console.error(`Failed to load route from ${E}:`,d)}}}}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)}}var q=C(()=>{z()});class G{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 a=await l(f);if(a instanceof Response)return a;f=a}return f}async executeFinally(i,f){let l=i;for(let a of this.finallyHandlers)l=await a(l,f);return l}clone(){let i=new G;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}}var S=(i="text/plain; charset=utf-8",f)=>(l,a={})=>{if(l===void 0||l instanceof Response)return l;let A=new Response(f?.(l)??l,a.url?void 0:a);return A.headers.set("content-type",i),A},Vi,Xi,Ji,Wi,zi,Ki,t=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},o=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,a])=>a?(f[l]=a,f):f,{})},B=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:a="*",allowHeaders:A,exposeHeaders:E,maxAge:O}=i,_=(I)=>{let N=I?.headers.get("origin");return f===!0?N:f instanceof RegExp?f.test(N)?N:void 0:Array.isArray(f)?f.includes(N)?N:void 0:f instanceof Function?f(N):f=="*"&&l?N:f},d=(I,N)=>{for(let[w,L]of Object.entries(N))L&&I.headers.append(w,L);return I};return{corsify:(I,N)=>I?.headers?.get("access-control-allow-origin")||I.status==101?I:d(I.clone(),{"access-control-allow-origin":_(N),"access-control-allow-credentials":l}),preflight:(I)=>{if(I.method=="OPTIONS"){let N=new Response(null,{status:204});return d(N,{"access-control-allow-origin":_(I),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":E?.join?.(",")??E,"access-control-allow-headers":A?.join?.(",")??A??I.headers.get("access-control-request-headers"),"access-control-max-age":O,"access-control-allow-credentials":l})}}}};var c=C(()=>{Vi=S("application/json; charset=utf-8",JSON.stringify),Xi=S("text/plain; charset=utf-8",String),Ji=S("text/html"),Wi=S("image/jpeg"),zi=S("image/png"),Ki=S("image/webp")});function Ii(i,f){let l=Ci(i,f);return[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]}function Li(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let a={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return h(i,a,l)}function h(i,f,l=j.JSON){let a=l===j.JSON?Li(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Ci(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:O=j.JSON}=i;return async(_)=>{if(!a)return P.forbidden("Forbidden");try{if(l)await Ri(_,O);if(!A)await t(_);o(_);let d=await f(_);return E?d:wi.success(d,O)}catch(d){if(d instanceof Response)return d;return P.internalServerError(String(d),O)}}}var ki,ui,wi,P,Ri=async(i,f)=>{let l=(await Promise.resolve().then(() => (g(),p))).default;if(!l.protected)throw P.unauthorized("Authentication not configured",f);try{let a=await l.protected(i);i.authUser=a}catch(a){throw P.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var Y=C(()=>{c();V();({preflight:ki,corsify:ui}=B({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));wi={success:(i,f)=>h(R.OK,i,f),created:(i,f)=>h(R.CREATED,i,f)};P={badRequest:(i="Bad Request",f)=>D(R.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D(R.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D(R.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D(R.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D(R.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D(R.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});class k{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let E=0,O=i.split("/").filter(Boolean);for(let _ of O)if(this.isStaticSegment(_))E+=1000;else if(this.isParamSegment(_))E+=10;else if(this.isWildcardSegment(_))E+=1;if(E+=i.length,this.isExactPath(i))E+=1e4;return E}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),a=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(a)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(a),this.sortRoutes(),a}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let a=l;if(!a.context)a.context={};if(!a.query&&a.url){let A=new URL(a.url),E={};for(let[O,_]of A.searchParams)E[O]=E[O]?[].concat(E[O],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(i.expose===!1)return P.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(d){return P.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 E,O=i.cache;if(O&&typeof O==="number"&&O>0){let d=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(d,()=>f(l),O)}else if(O&&typeof O==="object"&&O.ttl){let d=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(d,()=>f(l),O.ttl)}else E=await f(l);let _;if(i.rawResponse||E instanceof Response)_=E instanceof Response?E:new Response(E);else _=h(200,E,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),P.internalServerError(A instanceof Error?A.message:String(A),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[a,A,E]of this.routes)if(i.method==="OPTIONS"||i.method===a){let O=l.match(A);if(O){let _=i;if(!_.context)_.context={};_.params=O.groups||{};for(let d of E){let I=await d(_);if(I)return I}}}return P.notFound("Route not found")}}var e=C(()=>{Y()});class u{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=B(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:a}}}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(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let A=await this.router.handle(a);if(this.corsHandler)A=this.corsHandler.corsify(A,a);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}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}`}}var ii=C(()=>{c()});var p={};li(p,{default:()=>Pi,Vector:()=>U});class U{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new G,this.authManager=new F,this.cacheManager=new M,this.router=new k(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}set protected(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}get protected(){return this._protectedHandler}set cache(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}get cache(){return this._cacheHandler}route(i,f){return this.router.route(i,f)}use(...i){return this.middlewareManager.addBefore(...i),this}before(...i){return this.middlewareManager.addBefore(...i),this}finally(...i){return this.middlewareManager.addFinally(...i),this}async serve(i){if(this.config={...this.config,...i},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 u(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new Z(i);if(!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(process.platform==="win32"?`file:///${l.path.replace(/\\/g,"/")}`:l.path),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteEntry(E))this.router.addRoute(E),this.logRouteLoaded(E);else if(typeof E==="function")this.router.route(l.options,E),this.logRouteLoaded(l.options)}}catch(a){console.error(`Failed to load route ${l.name} from ${l.path}:`,a)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}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}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}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}}var $i,Pi;var g=C(()=>{X();r();q();e();ii();$i=U.getInstance(),Pi=$i});g();Y();X();Y();function Af(){return U.getInstance()}var Ui=U.getInstance(),Lf=Ui;export{Ii as route,Lf as default,Af as createVector,h as createResponse,U as Vector,G as MiddlewareManager,M as CacheManager,F as AuthManager,P as APIError};
21
+ };`}}var y=R(()=>{z()});var{promises:q}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(`Routes directory not found: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let E=await q.readdir(i);for(let A of E){let a=J(i,A);if((await q.stat(a)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(a,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,a).replace(/\.(ts|js)$/,"").split(W).join("/");try{let w=await import(process.platform==="win32"?`file:///${a.replace(/\\/g,"/")}`:a);if(w.default&&typeof w.default==="function")f.push({name:"default",path:a,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:a,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:a,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${a}:`,N)}}}}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)}}var t=R(()=>{z()});class T{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)l=await E(l,f);return l}clone(){let i=new T;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function o(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class v{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let a=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))a+=1000;else if(this.isParamSegment(_))a+=10;else if(this.isWildcardSegment(_))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),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-A})}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.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let E=l;if(!E.context)E.context={};if(!E.query&&E.url){let A=new URL(E.url),a={};for(let[d,_]of A.searchParams)a[d]=a[d]?[].concat(a[d],_):_;E.query=a}if(i.metadata)E.metadata=i.metadata;l=E;try{if(i.expose===!1)return C.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return C.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let a,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d.ttl)}else a=await f(l);let _;if(i.rawResponse||a instanceof Response)_=a instanceof Response?a:new Response(a);else _=b(200,a,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),C.internalServerError(A instanceof Error?A.message:String(A),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,a]of this.routes)if(i.method==="OPTIONS"||i.method===E){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of a){let w=await N(_);if(w)return w}}}return C.notFound("Route not found")}clearRoutes(){this.routes=[]}}var p=R(()=>{B()});class g{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=F(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 A=await this.router.handle(E);if(this.corsHandler)A=this.corsHandler.corsify(A,E);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}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}`}}var e=R(()=>{Y()});var ii={};ai(ii,{getVectorInstance:()=>Ii,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new T,this.authManager=new c,this.cacheManager=new X,this.router=new v(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.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(),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 g(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new Z(i);if(!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(o(l.path)),a=l.name==="default"?A.default:A[l.name];if(a){if(this.isRouteDefinition(a)){let d=a;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(a))this.router.addRoute(a),this.logRouteLoaded(a);else if(typeof a==="function")this.router.route(l.options,a),this.logRouteLoaded(l.options)}}catch(E){console.error(`Failed to load route ${l.name} from ${l.path}:`,E)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}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){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Ii;var fi=R(()=>{u();y();t();p();e();Ii=h.getInstance});function Li(i,f){let l=Ci(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 $i(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return b(i,E,l)}function b(i,f,l=j.JSON){let E=l===j.JSON?$i(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}function Ci(i,f){let{auth:l=!1,expose:E=!1,rawRequest:A=!1,rawResponse:a=!1,responseContentType:d=j.JSON}=i;return async(_)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Ui(_,d);if(!A)await k(_);m(_);let N=await f(_);return a?N:Ri.success(N,d)}catch(N){if(N instanceof Response)return N;return C.internalServerError(String(N),d)}}}var ff,lf,Ri,C,Ui=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (fi(),ii)),A=l().getProtectedHandler();if(!A)throw C.unauthorized("Authentication not configured",f);try{let a=await A(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var B=R(()=>{Y();V();({preflight:ff,corsify:lf}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ri={success:(i,f)=>b($.OK,i,f),created:(i,f)=>b($.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});B();B();export{Li as route,b as createResponse,C as APIError};
@@ -1,4 +1,4 @@
1
- import type { AfterMiddlewareHandler, BeforeMiddlewareHandler, DefaultVectorTypes, VectorRequest, VectorTypes } from '../types';
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;
@@ -7,5 +7,6 @@ export declare class MiddlewareManager<TTypes extends VectorTypes = DefaultVecto
7
7
  executeBefore(request: VectorRequest<TTypes>): Promise<VectorRequest<TTypes> | Response>;
8
8
  executeFinally(response: Response, request: VectorRequest<TTypes>): Promise<Response>;
9
9
  clone(): MiddlewareManager<TTypes>;
10
+ clear(): void;
10
11
  }
11
12
  //# sourceMappingURL=manager.d.ts.map
@@ -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,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;IAU3F,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC;CAMnC"}
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,CAC5B,MAAM,SAAS,WAAW,GAAG,kBAAkB;IAE/C,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,CACjB,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAC7B,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;IAgBtC,cAAc,CAClB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAC7B,OAAO,CAAC,QAAQ,CAAC;IAUpB,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC;IAOlC,KAAK,IAAI,IAAI;CAId"}
@@ -31,5 +31,9 @@ export class MiddlewareManager {
31
31
  manager.finallyHandlers = [...this.finallyHandlers];
32
32
  return manager;
33
33
  }
34
+ clear() {
35
+ this.beforeHandlers = [];
36
+ this.finallyHandlers = [];
37
+ }
34
38
  }
35
39
  //# sourceMappingURL=manager.js.map
@@ -1 +1 @@
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,IA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  autoDiscover?: boolean;
60
60
  }
61
+ export interface VectorConfigSchema<TTypes extends VectorTypes = DefaultVectorTypes> {
62
+ server?: {
63
+ port?: number;
64
+ hostname?: string;
65
+ reusePort?: boolean;
66
+ development?: boolean;
67
+ };
68
+ routes?: {
69
+ dir?: string;
70
+ autoDiscover?: boolean;
71
+ };
72
+ middleware?: {
73
+ before?: string[];
74
+ after?: string[];
75
+ };
76
+ before?: BeforeMiddlewareHandler<TTypes>[];
77
+ after?: AfterMiddlewareHandler<TTypes>[];
78
+ handlers?: {
79
+ auth?: string;
80
+ cache?: string;
81
+ };
82
+ auth?: ProtectedHandler<TTypes>;
83
+ cache?: CacheHandler;
84
+ cors?: CorsOptions | boolean;
85
+ types?: VectorTypes;
86
+ }
61
87
  export interface CorsOptions {
62
88
  origin?: string | string[] | ((origin: string) => boolean);
63
89
  credentials?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAID,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,QAAQ,CAAC,EAAE,GAAG,CAAC;CAChB;AAGD,MAAM,WAAW,kBAAmB,SAAQ,WAAW;IACrD,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC7B,KAAK,EAAE,GAAG,CAAC;I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,CAAC,GAAG,GAAG,CAAC;AAExB,MAAM,MAAM,gBAAgB,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB,IAAI,CAC9E,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,KAC3B,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;AAExD,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;AAEnG,MAAM,WAAW,eAAe,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IAC9E,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;IAC9B,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;CAC/B;AAED,MAAM,WAAW,cAAc,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;CAC/B"}
@@ -0,0 +1,3 @@
1
+ export declare function toFileUrl(path: string): string;
2
+ export declare function normalizePath(path: string): string;
3
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +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,CAI9C;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD"}
@@ -0,0 +1,9 @@
1
+ export function toFileUrl(path) {
2
+ return process.platform === 'win32'
3
+ ? `file:///${path.replace(/\\/g, '/')}`
4
+ : path;
5
+ }
6
+ export function normalizePath(path) {
7
+ return path.replace(/\\/g, '/').replace(/\/+/g, '/');
8
+ }
9
+ //# sourceMappingURL=path.js.map
@@ -0,0 +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;QACjC,CAAC,CAAC,WAAW,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE;QACvC,CAAC,CAAC,IAAI,CAAC;AACX,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vector-framework",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "author": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -73,7 +73,7 @@
73
73
  ],
74
74
  "license": "MIT",
75
75
  "scripts": {
76
- "dev": "bun --watch run src/cli/index.ts dev",
76
+ "dev": "bun run src/cli/index.ts dev",
77
77
  "start": "bun run src/cli/index.ts start",
78
78
  "build": "bun run src/cli/index.ts build",
79
79
  "example": "bun run examples/server.ts",
@@ -81,7 +81,7 @@
81
81
  "build:clean": "rm -rf dist",
82
82
  "build:ts": "tsc",
83
83
  "build:bundle": "bun build src/index.ts --format esm --minify --outfile dist/index.mjs && bun build src/index.ts --format cjs --minify --outfile dist/index.js",
84
- "test": "bun test tests/api-error.test.ts tests/cache.test.ts tests/middleware.test.ts tests/router.test.ts tests/vector.test.ts tests/autodiscover.test.ts",
84
+ "test": "bun test tests/api-error.test.ts tests/cache.test.ts tests/middleware.test.ts tests/middleware-integration.test.ts tests/router.test.ts",
85
85
  "test:unit": "bun test tests/*.test.ts",
86
86
  "test:watch": "bun test --watch tests/*.test.ts",
87
87
  "test:coverage": "bun test --coverage tests/*.test.ts",
package/src/cli/index.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  import { watch } from "node:fs";
4
- import { join } from "node:path";
5
4
  import { parseArgs } from "node:util";
6
- import vector from "../core/vector";
5
+ import { getVectorInstance } from "../core/vector";
6
+ import { ConfigLoader } from "../core/config-loader";
7
7
 
8
8
  const { values, positionals } = parseArgs({
9
9
  args: Bun.argv.slice(2),
@@ -45,92 +45,133 @@ async function runDev() {
45
45
  `\n→ Starting Vector ${isDev ? "development" : "production"} server\n`
46
46
  );
47
47
 
48
- const config: any = {
49
- port: Number.parseInt(values.port as string),
50
- hostname: values.host as string,
51
- routesDir: values.routes as string,
52
- development: isDev,
53
- autoDiscover: true,
54
- cors: values.cors
55
- ? {
48
+ let server: any = null;
49
+ let vector: any = null;
50
+
51
+ async function startServer() {
52
+ try {
53
+ // Load configuration using ConfigLoader
54
+ const configLoader = new ConfigLoader();
55
+ const config = await configLoader.load();
56
+
57
+ // Merge CLI options with loaded config
58
+ config.port = config.port || Number.parseInt(values.port as string);
59
+ config.hostname = config.hostname || (values.host as string);
60
+ config.routesDir = config.routesDir || (values.routes as string);
61
+ config.development = isDev;
62
+ config.autoDiscover = true;
63
+
64
+ // Apply CLI CORS option if not set in config
65
+ if (!config.cors && values.cors) {
66
+ config.cors = {
56
67
  origin: "*",
57
68
  credentials: true,
58
69
  allowHeaders: "Content-Type, Authorization",
59
70
  allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
60
71
  exposeHeaders: "Authorization",
61
72
  maxAge: 86400,
62
- }
63
- : undefined,
64
- };
73
+ };
74
+ }
65
75
 
66
- try {
67
- const userConfigPath = join(process.cwd(), "vector.config.ts");
68
- try {
69
- const userConfig = await import(userConfigPath);
70
- if (userConfig.default) {
71
- // Properly merge config, preserving middleware arrays
72
- const {
73
- before,
74
- finally: finallyMiddleware,
75
- ...otherConfig
76
- } = userConfig.default;
77
-
78
- // Merge non-middleware config
79
- Object.assign(config, otherConfig);
80
-
81
- // Handle middleware arrays properly - these need to be set after Object.assign
82
- // to avoid being overwritten
83
- if (before) {
84
- config.before = before;
85
- }
86
- if (finallyMiddleware) {
87
- config.finally = finallyMiddleware;
88
- }
76
+ // Get Vector instance and configure handlers
77
+ vector = getVectorInstance();
78
+
79
+ // Load and set auth handler if configured
80
+ const authHandler = await configLoader.loadAuthHandler();
81
+ if (authHandler) {
82
+ vector.setProtectedHandler(authHandler);
89
83
  }
90
- } catch {
91
- // No user config file, use defaults
92
- }
93
84
 
94
- await vector.serve(config);
85
+ // Load and set cache handler if configured
86
+ const cacheHandler = await configLoader.loadCacheHandler();
87
+ if (cacheHandler) {
88
+ vector.setCacheHandler(cacheHandler);
89
+ }
95
90
 
96
- const gray = "\x1b[90m";
97
- const reset = "\x1b[0m";
98
- const cyan = "\x1b[36m";
99
- const green = "\x1b[32m";
91
+ // Start the server
92
+ server = await vector.startServer(config);
100
93
 
101
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
102
- if (isDev && values.watch) {
103
- console.log(` ${gray}Watching${reset} All project files`);
94
+ const gray = "\x1b[90m";
95
+ const reset = "\x1b[0m";
96
+ const cyan = "\x1b[36m";
97
+ const green = "\x1b[32m";
104
98
 
99
+ console.log(` ${gray}Routes${reset} ${config.routesDir}`);
100
+ if (isDev && values.watch) {
101
+ console.log(` ${gray}Watching${reset} All project files`);
102
+ }
103
+ console.log(
104
+ ` ${gray}CORS${reset} ${values.cors ? "Enabled" : "Disabled"}`
105
+ );
106
+ console.log(
107
+ ` ${gray}Mode${reset} ${isDev ? "Development" : "Production"}\n`
108
+ );
109
+ console.log(
110
+ ` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`
111
+ );
112
+
113
+ return { server, vector, config };
114
+ } catch (error) {
115
+ console.error("[ERROR] Failed to start server:", error);
116
+ throw error;
117
+ }
118
+ }
119
+
120
+ try {
121
+ // Start the server initially
122
+ const result = await startServer();
123
+ server = result.server;
124
+
125
+ // Setup file watching for hot reload
126
+ if (isDev && values.watch) {
105
127
  try {
128
+ let reloadTimeout: any = null;
129
+
106
130
  // Watch entire project directory for changes
107
131
  watch(process.cwd(), { recursive: true }, async (_, filename) => {
108
132
  if (
109
133
  filename &&
110
134
  (filename.endsWith(".ts") ||
111
135
  filename.endsWith(".js") ||
112
- filename.endsWith(".json"))
136
+ filename.endsWith(".json")) &&
137
+ !filename.includes("node_modules") &&
138
+ !filename.includes(".git")
113
139
  ) {
114
- console.log(`\n 🔄 File changed: ${filename}`);
115
- console.log(" 🔄 Restarting server...\n");
116
-
117
- // Exit the current process, which will trigger a restart if using --watch flag
118
- process.exit(0);
140
+ // Debounce reload to avoid multiple restarts
141
+ if (reloadTimeout) {
142
+ clearTimeout(reloadTimeout);
143
+ }
144
+
145
+ reloadTimeout = setTimeout(async () => {
146
+ console.log(`\n 🔄 File changed: ${filename}`);
147
+ console.log(" 🔄 Reloading server...\n");
148
+
149
+ // Stop the current server
150
+ if (vector) {
151
+ vector.stop();
152
+ }
153
+
154
+ // Clear module cache to ensure fresh imports
155
+ for (const key in require.cache) {
156
+ if (!key.includes("node_modules")) {
157
+ delete require.cache[key];
158
+ }
159
+ }
160
+
161
+ // Restart the server
162
+ try {
163
+ const result = await startServer();
164
+ server = result.server;
165
+ } catch (error) {
166
+ console.error(" ❌ Failed to reload server:", error);
167
+ }
168
+ }, 100); // 100ms debounce
119
169
  }
120
170
  });
121
171
  } catch (err) {
122
172
  console.warn(" ⚠️ File watching not available");
123
173
  }
124
174
  }
125
- console.log(
126
- ` ${gray}CORS${reset} ${values.cors ? "Enabled" : "Disabled"}`
127
- );
128
- console.log(
129
- ` ${gray}Mode${reset} ${isDev ? "Development" : "Production"}\n`
130
- );
131
- console.log(
132
- ` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`
133
- );
134
175
  } catch (error) {
135
176
  console.error("[ERROR] Failed to start server:", error);
136
177
  process.exit(1);