vector-framework 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
1
+ import { promises as fs } from 'node:fs';
2
2
  import { dirname, relative } from 'node:path';
3
3
  export class RouteGenerator {
4
4
  outputPath;
@@ -7,7 +7,7 @@ export class RouteGenerator {
7
7
  }
8
8
  async generate(routes) {
9
9
  const outputDir = dirname(this.outputPath);
10
- await mkdir(outputDir, { recursive: true });
10
+ await fs.mkdir(outputDir, { recursive: true });
11
11
  const imports = [];
12
12
  const groupedByFile = new Map();
13
13
  for (const route of routes) {
@@ -51,7 +51,7 @@ ${routeEntries.join('\n')}
51
51
 
52
52
  export default routes;
53
53
  `;
54
- await writeFile(this.outputPath, content, 'utf-8');
54
+ await fs.writeFile(this.outputPath, content, 'utf-8');
55
55
  console.log(`Generated routes file: ${this.outputPath}`);
56
56
  }
57
57
  async generateDynamic(routes) {
@@ -1 +1 @@
1
- {"version":3,"file":"route-generator.js","sourceRoot":"","sources":["../../src/dev/route-generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAG9C,MAAM,OAAO,cAAc;IACjB,UAAU,CAAS;IAE3B,YAAY,UAAU,GAAG,+BAA+B;QACtD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,MAAwB;QACrC,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC3C,MAAM,KAAK,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAE5C,MAAM,OAAO,GAAa,EAAE,CAAC;QAC7B,MAAM,aAAa,GAAG,IAA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KAAK,CAAC,IAAI,CAAC;gBACpE,YAAY,CAAC,IAAI,CAAC,KAAK,QAAQ,GAAG,CAAC,CAAC;YACtC,CAAC;QACH,CAAC;QAED,MAAM,OAAO,GAAG;mBACD,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;;EAEzC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;;;EAGlB,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;;;;CAIxB,CAAC;QAEE,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QACtD,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;IAC3D,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,MAAwB;QAC5C,MAAM,YAAY,GAAa,EAAE,CAAC;QAElC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;gBAC9B,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI;gBACxB,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;YAEH,YAAY,CAAC,IAAI,CAAC,mBAAmB,KAAK,CAAC,IAAI;aACxC,QAAQ;qBACA,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI;UAC5D,CAAC,CAAC;QACR,CAAC;QAED,OAAO;;EAET,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC;;GAEvB,CAAC;IACF,CAAC;CACF"}
@@ -1,4 +1,4 @@
1
- import { readdir, stat } from 'node:fs/promises';
1
+ import { promises as fs } from 'node:fs';
2
2
  import { join, relative, resolve, sep } from 'node:path';
3
3
  export class RouteScanner {
4
4
  routesDir;
@@ -20,10 +20,10 @@ export class RouteScanner {
20
20
  return routes;
21
21
  }
22
22
  async scanDirectory(dir, routes, basePath = '') {
23
- const entries = await readdir(dir);
23
+ const entries = await fs.readdir(dir);
24
24
  for (const entry of entries) {
25
25
  const fullPath = join(dir, entry);
26
- const stats = await stat(fullPath);
26
+ const stats = await fs.stat(fullPath);
27
27
  if (stats.isDirectory()) {
28
28
  const newBasePath = basePath ? `${basePath}/${entry}` : entry;
29
29
  await this.scanDirectory(fullPath, routes, newBasePath);
@@ -1 +1 @@
1
- {"version":3,"file":"route-scanner.js","sourceRoot":"","sources":["../../src/dev/route-scanner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGzD,MAAM,OAAO,YAAY;IACf,SAAS,CAAS;IAE1B,YAAY,SAAS,GAAG,UAAU;QAChC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,SAAS,CAAC,CAAC;IACrD,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,MAAM,GAAqB,EAAE,CAAC;QAEpC,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QACnD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAK,KAAa,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACrC,OAAO,CAAC,IAAI,CAAC,+BAA+B,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;gBAC9D,OAAO,EAAE,CAAC;YACZ,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,KAAK,CAAC,aAAa,CAAC,GAAW,EAAE,MAAwB,EAAE,QAAQ,GAAG,EAAE;QAC9E,MAAM,OAAO,GAAG,MAAM,O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AAC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;4BAC9C,MAAM,CAAC,MAAM,EAAE,AAAD,EAAG,AAAD,EAAG,IAAI,CAAC,GAAG,KAAK,CAAC;4BACjC,MAAM,CAAC,IAAI,CAAC;gCACV,IAAI;gCACJ,IAAI,EAAE,QAAQ;gCACd,MAAM,EAAE,MAAgB;gCACxB,OAAO,EAAE;oCACP,MAAM,EAAE,MAAgB;oCACxB,IAAI,EAAE,IAAc;oCACpB,MAAM,EAAE,IAAI;iCACb;6BACF,CAAC,CAAC;wBACL,CAAC;oBACH,CAAC;gBACH,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO,CAAC,KAAK,CAAC,6BAA6B,QAAQ,GAAG,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,WAAW,CAAC,QAAoB;QAC9B,IAAI,OAAO,GAAG,KAAK,WAAW,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;YACrE,OAAO,CAAC,GAAG,CAAC,iCAAiC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;YAE/D,WAAW,CAAC,KAAK,IAAI,EAAE;gBACrB,MAAM,QAAQ,EAAE,CAAC;YACnB,CAAC,EAAE,IAAI,CAAC,CAAC;QACX,CAAC;IACH,CAAC;CACF"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var{defineProperty:v,getOwnPropertyNames:Ai,getOwnPropertyDescriptor:_i}=Object,Oi=Object.prototype.hasOwnProperty;var r=new WeakMap,Ni=(i)=>{var f=r.get(i),l;if(f)return f;if(f=v({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")Ai(i).map((a)=>!Oi.call(f,a)&&v(f,a,{get:()=>i[a],enumerable:!(l=_i(i,a))||l.enumerable}));return r.set(i,f),f};var y=(i,f)=>{for(var l in f)v(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var P=(i,f)=>()=>(i&&(f=i(i=0)),f);class b{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,J,M;var W=P(()=>{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},J={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},M={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class G{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 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=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 z=P(()=>{W()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function q(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 di(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 F(){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(U(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=q(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function t(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=q(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Di(i){return U(i),i.length>0&&i.charCodeAt(0)===47}function K(){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 t(i)}function j(i,f){if(U(i),U(f),i===f)return"";if(i=F(i),f=F(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 Ii(i){return i}function T(i){if(U(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 Li(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');U(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 wi(i){U(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 Ri(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return di("/",i)}function Ci(i){U(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 Z="/",$i=":",Vi;var c=P(()=>{Vi=((i)=>(i.posix=i,i))({resolve:F,normalize:t,isAbsolute:Di,join:K,relative:j,_makeLong:Ii,dirname:T,basename:Li,extname:wi,format:Ri,parse:Ci,sep:Z,delimiter:$i,win32:null,posix:null})});class g{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=T(this.outputPath);await B.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=j(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{defineProperty:Q,getOwnPropertyNames:Ai,getOwnPropertyDescriptor:_i}=Object,Oi=Object.prototype.hasOwnProperty;var r=new WeakMap,Ni=(i)=>{var f=r.get(i),l;if(f)return f;if(f=Q({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")Ai(i).map((a)=>!Oi.call(f,a)&&Q(f,a,{get:()=>i[a],enumerable:!(l=_i(i,a))||l.enumerable}));return r.set(i,f),f};var y=(i,f)=>{for(var l in f)Q(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var P=(i,f)=>()=>(i&&(f=i(i=0)),f);class x{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,M;var X=P(()=>{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},M={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class G{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 J=P(()=>{X()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function q(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 di(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 F(){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(U(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=q(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function t(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=q(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Di(i){return U(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(U(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return t(i)}function j(i,f){if(U(i),U(f),i===f)return"";if(i=F(i),f=F(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 Ii(i){return i}function T(i){if(U(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 Li(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');U(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 wi(i){U(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 Ri(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return di("/",i)}function Ci(i){U(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 z="/",$i=":",vi;var K=P(()=>{vi=((i)=>(i.posix=i,i))({resolve:F,normalize:t,isAbsolute:Di,join:W,relative:j,_makeLong:Ii,dirname:T,basename:Li,extname:wi,format:Ri,parse:Ci,sep:z,delimiter:$i,win32:null,posix:null})});class c{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=T(this.outputPath);await Z.promises.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=j(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.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
@@ -10,7 +10,7 @@ ${E.join(`
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await B.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 => ({
13
+ `;await Z.promises.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
14
  ...${a},
15
15
  handler: m.${l.name==="default"?"default":l.name}
16
16
  }))`)}return`export const loadRoutes = async () => {
@@ -18,4 +18,4 @@ export default routes;
18
18
  ${f.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var B;var o=P(()=>{B=(()=>({}));c()});class k{routesDir;constructor(i="./routes"){this.routesDir=F(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=K(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 _=j(this.routesDir,E).replace(/\.(ts|js)$/,"").split(Z).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 Y;var p=P(()=>{Y=(()=>({}));c()});class h{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 h;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}}var x=(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},Zi,ci,gi,ki,ui,mi,e=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},ii=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,a])=>a?(f[l]=a,f):f,{})},Q=(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 u=P(()=>{Zi=x("application/json; charset=utf-8",JSON.stringify),ci=x("text/plain; charset=utf-8",String),gi=x("text/html"),ki=x("image/jpeg"),ui=x("image/png"),mi=x("image/webp")});function fi(i,f){let l=Si(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 Pi(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 S(i,a,l)}function S(i,f,l=M.JSON){let a=l===M.JSON?Pi(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Si(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:O=M.JSON}=i;return async(_)=>{if(!a)return C.forbidden("Forbidden");try{if(l)await Hi(_,O);if(!A)await e(_);ii(_);let d=await f(_);return E?d:Ui.success(d,O)}catch(d){if(d instanceof Response)return d;return C.internalServerError(String(d),O)}}}var yi,qi,Ui,C,Hi=async(i,f)=>{let l=(await Promise.resolve().then(() => (m(),li))).default;if(!l.protected)throw C.unauthorized("Authentication not configured",f);try{let a=await l.protected(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var V=P(()=>{u();W();({preflight:yi,corsify:qi}=Q({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,f)=>S(R.OK,i,f),created:(i,f)=>S(R.CREATED,i,f)};C={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 n{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)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(d){return C.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 _=S(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),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[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 C.notFound("Route not found")}}var ai=P(()=>{V()});class s{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=Q(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 Ei=P(()=>{u()});var li={};y(li,{default:()=>xi,Vector:()=>$});class ${static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new h,this.authManager=new b,this.cacheManager=new G,this.router=new n(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!$.instance)$.instance=new $;return $.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();this.server=new s(this.router,this.config);let f=await this.server.start();if(this.config.development&&this.routeScanner)this.routeScanner.enableWatch(async()=>{await this.discoverRoutes()});return f}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new k(i);if(!this.routeGenerator)this.routeGenerator=new g;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")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 hi,xi;var m=P(()=>{z();o();p();ai();Ei();hi=$.getInstance(),xi=hi});var Fi={};y(Fi,{route:()=>fi,default:()=>ji,createVector:()=>bi,createResponse:()=>S,Vector:()=>$,MiddlewareManager:()=>h,CacheManager:()=>G,AuthManager:()=>b,APIError:()=>C});module.exports=Ni(Fi);m();V();z();V();function bi(){return $.getInstance()}var Gi=$.getInstance(),ji=Gi;
21
+ };`}}var Z;var o=P(()=>{Z=(()=>({}));K()});class k{routesDir;constructor(i="./routes"){this.routesDir=F(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 g.promises.readdir(i);for(let A of a){let E=W(i,A);if((await g.promises.stat(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=j(this.routesDir,E).replace(/\.(ts|js)$/,"").split(z).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 g;var p=P(()=>{g=(()=>({}));K()});class h{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 h;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}}var b=(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},Zi,ci,gi,ki,ui,mi,e=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},ii=(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 u=P(()=>{Zi=b("application/json; charset=utf-8",JSON.stringify),ci=b("text/plain; charset=utf-8",String),gi=b("text/html"),ki=b("image/jpeg"),ui=b("image/png"),mi=b("image/webp")});function fi(i,f){let l=Si(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 Pi(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 S(i,a,l)}function S(i,f,l=M.JSON){let a=l===M.JSON?Pi(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Si(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:O=M.JSON}=i;return async(_)=>{if(!a)return C.forbidden("Forbidden");try{if(l)await Hi(_,O);if(!A)await e(_);ii(_);let d=await f(_);return E?d:Ui.success(d,O)}catch(d){if(d instanceof Response)return d;return C.internalServerError(String(d),O)}}}var yi,qi,Ui,C,Hi=async(i,f)=>{let l=(await Promise.resolve().then(() => (m(),li))).default;if(!l.protected)throw C.unauthorized("Authentication not configured",f);try{let a=await l.protected(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var Y=P(()=>{u();X();({preflight:yi,corsify:qi}=B({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,f)=>S(R.OK,i,f),created:(i,f)=>S(R.CREATED,i,f)};C={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 n{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 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(d){return C.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 _=S(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),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[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 C.notFound("Route not found")}}var ai=P(()=>{Y()});class s{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 Ei=P(()=>{u()});var li={};y(li,{default:()=>bi,Vector:()=>$});class ${static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new h,this.authManager=new x,this.cacheManager=new G,this.router=new n(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!$.instance)$.instance=new $;return $.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 s(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new k(i);if(!this.routeGenerator)this.routeGenerator=new c;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 hi,bi;var m=P(()=>{J();o();p();ai();Ei();hi=$.getInstance(),bi=hi});var Fi={};y(Fi,{route:()=>fi,default:()=>ji,createVector:()=>xi,createResponse:()=>S,Vector:()=>$,MiddlewareManager:()=>h,CacheManager:()=>G,AuthManager:()=>x,APIError:()=>C});module.exports=Ni(Fi);m();Y();J();Y();function xi(){return $.getInstance()}var Gi=$.getInstance(),ji=Gi;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var e=Object.defineProperty;var ii=(i,f)=>{for(var l in f)e(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 fi(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 x(){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 li(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 b(i,f){if($(i),$(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 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 Ei(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 Ai(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 _i(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return fi("/",i)}function Oi(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="/",Ni=":",ji;var z=C(()=>{ji=((i)=>(i.posix=i,i))({resolve:x,normalize:n,isAbsolute:li,join:J,relative:b,_makeLong:ai,dirname:T,basename:Ei,extname:Ai,format:_i,parse:Oi,sep:W,delimiter:Ni,win32:null,posix:null})});var{mkdir:di,writeFile:Di}=(()=>({}));class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=T(this.outputPath);await di(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=b(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 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.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
@@ -10,7 +10,7 @@ ${E.join(`
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await Di(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 => ({
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
14
  ...${a},
15
15
  handler: m.${l.name==="default"?"default":l.name}
16
16
  }))`)}return`export const loadRoutes = async () => {
@@ -18,4 +18,4 @@ export default routes;
18
18
  ${f.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var s=C(()=>{z()});var{readdir:Ii,stat:Li}=(()=>({}));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 a=await Ii(i);for(let A of a){let E=J(i,A);if((await Li(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=b(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 r=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},Ji,Wi,zi,Ki,Zi,ci,y=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},q=(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(()=>{Ji=S("application/json; charset=utf-8",JSON.stringify),Wi=S("text/plain; charset=utf-8",String),zi=S("text/html"),Ki=S("image/jpeg"),Zi=S("image/png"),ci=S("image/webp")});function wi(i,f){let l=Pi(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 Ri(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?Ri(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Pi(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 $i(_,O);if(!A)await y(_);q(_);let d=await f(_);return E?d:Ci.success(d,O)}catch(d){if(d instanceof Response)return d;return P.internalServerError(String(d),O)}}}var mi,ni,Ci,P,$i=async(i,f)=>{let l=(await Promise.resolve().then(() => (g(),t))).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:mi,corsify:ni}=B({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ci={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)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 o=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 p=C(()=>{c()});var t={};ii(t,{default:()=>Hi,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();this.server=new u(this.router,this.config);let f=await this.server.start();if(this.config.development&&this.routeScanner)this.routeScanner.enableWatch(async()=>{await this.discoverRoutes()});return f}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")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 Ui,Hi;var g=C(()=>{X();s();r();o();p();Ui=U.getInstance(),Hi=Ui});g();Y();X();Y();function Of(){return U.getInstance()}var Si=U.getInstance(),Rf=Si;export{wi as route,Rf as default,Of as createVector,h as createResponse,U as Vector,G as MiddlewareManager,M as CacheManager,F as AuthManager,P as APIError};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vector-framework",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
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 run src/cli/index.ts dev",
76
+ "dev": "bun --watch 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",
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",
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",
@@ -1,5 +1,10 @@
1
- import { DEFAULT_CONFIG } from '../constants';
2
- import type { CacheHandler, DefaultVectorTypes, GetCacheType, VectorTypes } from '../types';
1
+ import { DEFAULT_CONFIG } from "../constants";
2
+ import type {
3
+ CacheHandler,
4
+ DefaultVectorTypes,
5
+ GetCacheType,
6
+ VectorTypes,
7
+ } from "../types";
3
8
 
4
9
  interface CacheEntry<T = any> {
5
10
  value: T;
@@ -126,8 +131,13 @@ export class CacheManager<TTypes extends VectorTypes = DefaultVectorTypes> {
126
131
 
127
132
  generateKey(request: Request, options?: { authUser?: any }): string {
128
133
  const url = new URL(request.url);
129
- const parts = [request.method, url.pathname, url.search, options?.authUser?.id || 'anonymous'];
130
-
131
- return parts.join(':');
134
+ const parts = [
135
+ request.method,
136
+ url.pathname,
137
+ url.search,
138
+ options?.authUser?.id || "anonymous",
139
+ ];
140
+
141
+ return parts.join(":");
132
142
  }
133
143
  }