vector-framework 0.9.0 → 0.9.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.
@@ -2,8 +2,10 @@ import type { CacheHandler, DefaultVectorTypes, ProtectedHandler, VectorConfig,
2
2
  export declare class ConfigLoader<TTypes extends VectorTypes = DefaultVectorTypes> {
3
3
  private configPath;
4
4
  private config;
5
+ private configSource;
5
6
  constructor(configPath?: string);
6
7
  load(): Promise<VectorConfig<TTypes>>;
8
+ getConfigSource(): 'user' | 'default';
7
9
  private buildLegacyConfig;
8
10
  private loadMiddleware;
9
11
  loadAuthHandler(): Promise<ProtectedHandler<TTypes> | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,YAAY,EAEZ,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IACvE,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,MAAM,CAA2C;gBAE7C,UAAU,SAAqB;IAIrC,IAAI,IAAI,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;YAgB7B,iBAAiB;YAoEjB,cAAc;IAuBtB,eAAe,IAAI,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IA8B3D,gBAAgB,IAAI,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IA8BtD,SAAS,IAAI,kBAAkB,CAAC,MAAM,CAAC,GAAG,IAAI;CAG/C"}
1
+ {"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAGV,YAAY,EAEZ,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IACvE,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,MAAM,CAA2C;IACzD,OAAO,CAAC,YAAY,CAAiC;gBAEzC,UAAU,SAAqB;IAKrC,IAAI,IAAI,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IA6B3C,eAAe,IAAI,MAAM,GAAG,SAAS;YAIvB,iBAAiB;YAoEjB,cAAc;IAuBtB,eAAe,IAAI,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IA8B3D,gBAAgB,IAAI,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IA8BtD,SAAS,IAAI,kBAAkB,CAAC,MAAM,CAAC,GAAG,IAAI;CAG/C"}
@@ -1,26 +1,44 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { resolve } from 'node:path';
2
3
  import { toFileUrl } from '../utils/path';
3
4
  export class ConfigLoader {
4
5
  configPath;
5
6
  config = null;
7
+ configSource = 'default';
6
8
  constructor(configPath = 'vector.config.ts') {
9
+ // Always resolve from the current working directory (user's project)
7
10
  this.configPath = resolve(process.cwd(), configPath);
8
11
  }
9
12
  async load() {
10
- try {
11
- // Try to load user config
12
- const userConfigPath = toFileUrl(this.configPath);
13
- const userConfig = await import(userConfigPath);
14
- this.config = userConfig.default || userConfig;
13
+ // Check if config file exists before attempting to load
14
+ if (existsSync(this.configPath)) {
15
+ try {
16
+ console.log(`→ Loading config from: ${this.configPath}`);
17
+ // Use explicit file:// URL to ensure correct resolution
18
+ const userConfigPath = toFileUrl(this.configPath);
19
+ const userConfig = await import(userConfigPath);
20
+ this.config = userConfig.default || userConfig;
21
+ this.configSource = 'user';
22
+ console.log(' ✓ User config loaded successfully');
23
+ }
24
+ catch (error) {
25
+ console.error(` ✗ Failed to load config from ${this.configPath}:`, error);
26
+ console.log(' → Using default configuration');
27
+ this.config = {};
28
+ }
15
29
  }
16
- catch (error) {
17
- // No config file, use defaults
18
- console.log('No vector.config.ts found, using defaults');
30
+ else {
31
+ // Config file doesn't exist, use defaults
32
+ console.log(` → No config file found at: ${this.configPath}`);
33
+ console.log(' → Using default configuration');
19
34
  this.config = {};
20
35
  }
21
36
  // Convert new config schema to legacy VectorConfig format
22
37
  return await this.buildLegacyConfig();
23
38
  }
39
+ getConfigSource() {
40
+ return this.configSource;
41
+ }
24
42
  async buildLegacyConfig() {
25
43
  const config = {};
26
44
  // Server configuration
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../src/core/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAa1C,MAAM,OAAO,YAAY;IACf,UAAU,CAAS;IACnB,MAAM,GAAsC,IAAI,CAAC;IAEzD,YAAY,UAAU,GAAG,kBAAkB;QACzC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,UAAU,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,IAAI;QACR,IAAI,CAAC;YACH,0BAA0B;YAC1B,MAAM,cAAc,GAAG,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAClD,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,cAAc,CAAC,CAAC;YAChD,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC;QACjD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,+BAA+B;YAC/B,OAAO,CAAC,GAAG,CAAC,2CAA2C,CAAC,CAAC;YACzD,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;QACnB,CAAC;QAED,0DAA0D;QAC1D,OAAO,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;IACxC,CAAC;IAEO,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C;YACzC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;YACxC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC;YAEzC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;gBAClC,OAAO,OAAuB,CAAC;YACjC,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,oBAAoB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,6BAA6B,CAAC,CAAC;gBAC1F,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,EAAE,KAAK,CAAC,CAAC;YACzF,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"route-scanner.d.ts","sourceRoot":"","sources":["../../src/dev/route-scanner.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,qBAAa,YAAY;IACvB,OAAO,CAAC,SAAS,CAAS;gBAEd,SAAS,SAAa;IAI5B,IAAI,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;YAgBzB,aAAa;IAuE3B,WAAW,CAAC,QAAQ,EAAE,MAAM,IAAI;CASjC"}
1
+ {"version":3,"file":"route-scanner.d.ts","sourceRoot":"","sources":["../../src/dev/route-scanner.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,qBAAa,YAAY;IACvB,OAAO,CAAC,SAAS,CAAS;gBAEd,SAAS,SAAa;IAK5B,IAAI,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;YA2BzB,aAAa;IAuE3B,WAAW,CAAC,QAAQ,EAAE,MAAM,IAAI;CASjC"}
@@ -1,18 +1,29 @@
1
- import { promises as fs } from 'node:fs';
1
+ import { existsSync, promises as fs } from 'node:fs';
2
2
  import { join, relative, resolve, sep } from 'node:path';
3
3
  export class RouteScanner {
4
4
  routesDir;
5
5
  constructor(routesDir = './routes') {
6
+ // Always resolve from the current working directory (user's project)
6
7
  this.routesDir = resolve(process.cwd(), routesDir);
7
8
  }
8
9
  async scan() {
9
10
  const routes = [];
11
+ // Check if routes directory exists before attempting to scan
12
+ if (!existsSync(this.routesDir)) {
13
+ console.log(` → Routes directory not found: ${this.routesDir}`);
14
+ console.log(' → No routes will be auto-discovered');
15
+ return [];
16
+ }
10
17
  try {
18
+ console.log(` → Scanning routes from: ${this.routesDir}`);
11
19
  await this.scanDirectory(this.routesDir, routes);
20
+ if (routes.length > 0) {
21
+ console.log(` ✓ Found ${routes.length} route${routes.length === 1 ? '' : 's'}`);
22
+ }
12
23
  }
13
24
  catch (error) {
14
25
  if (error.code === 'ENOENT') {
15
- console.warn(`Routes directory not found: ${this.routesDir}`);
26
+ console.warn(`Routes directory not accessible: ${this.routesDir}`);
16
27
  return [];
17
28
  }
18
29
  throw error;
@@ -1 +1 @@
1
- {"version":3,"file":"route-scanner.js","sourceRoot":"","sources":["../../src/dev/route-scanner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,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,IA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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:Y,getOwnPropertyNames:_i,getOwnPropertyDescriptor:di}=Object,Oi=Object.prototype.hasOwnProperty;var n=new WeakMap,Ni=(i)=>{var f=n.get(i),l;if(f)return f;if(f=Y({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")_i(i).map((a)=>!Oi.call(f,a)&&Y(f,a,{get:()=>i[a],enumerable:!(l=di(i,a))||l.enumerable}));return n.set(i,f),f};var r=(i,f)=>{for(var l in f)Y(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var U=(i,f)=>()=>(i&&(f=i(i=0)),f);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},Fi,ji,Mi,Ti,Bi,Yi,s=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},y=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,a])=>a?(f[l]=a,f):f,{})},F=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:a="*",allowHeaders:A,exposeHeaders:E,maxAge:d}=i,_=(w)=>{let O=w?.headers.get("origin");return f===!0?O:f instanceof RegExp?f.test(O)?O:void 0:Array.isArray(f)?f.includes(O)?O:void 0:f instanceof Function?f(O):f=="*"&&l?O:f},N=(w,O)=>{for(let[I,L]of Object.entries(O))L&&w.headers.append(I,L);return w};return{corsify:(w,O)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(w),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":E?.join?.(",")??E,"access-control-allow-headers":A?.join?.(",")??A??w.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":l})}}}};var Q=U(()=>{Fi=b("application/json; charset=utf-8",JSON.stringify),ji=b("text/plain; charset=utf-8",String),Mi=b("text/html"),Ti=b("image/jpeg"),Bi=b("image/png"),Yi=b("image/webp")});var $,V,j;var c=U(()=>{$={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 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}}class J{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 q=U(()=>{c()});function C(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function t(i,f){var l="",a=0,A=-1,E=0,d;for(var _=0;_<=i.length;++_){if(_<i.length)d=i.charCodeAt(_);else if(d===47)break;else d=47;if(d===47){if(A===_-1||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 N=l.lastIndexOf("/");if(N!==l.length-1){if(N===-1)l="",a=0;else l=l.slice(0,N),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(d===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 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(C(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=t(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function o(i){if(C(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=t(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function wi(i){return C(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(C(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return o(i)}function G(i,f){if(C(i),C(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 d=f.length,_=d-E,N=A<_?A:_,w=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(f.charCodeAt(E+O)===47)return f.slice(E+O+1);else if(O===0)return f.slice(E+O)}else if(A>N){if(i.charCodeAt(l+O)===47)w=O;else if(O===0)w=0}break}var I=i.charCodeAt(l+O),L=f.charCodeAt(E+O);if(I!==L)break;else if(I===47)w=O}var P="";for(O=l+w+1;O<=a;++O)if(O===a||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+f.slice(E+w);else{if(E+=w,f.charCodeAt(E)===47)++E;return f.slice(E)}}function Ii(i){return i}function M(i){if(C(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');C(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 d=f.length-1,_=-1;for(E=i.length-1;E>=0;--E){var N=i.charCodeAt(E);if(N===47){if(!A){l=E+1;break}}else{if(_===-1)A=!1,_=E+1;if(d>=0)if(N===f.charCodeAt(d)){if(--d===-1)a=E}else d=-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 $i(i){C(i);var f=-1,l=0,a=-1,A=!0,E=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!A){l=d+1;break}continue}if(a===-1)A=!1,a=d+1;if(_===46){if(f===-1)f=d;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 Ui(i){C(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,d=0,_=-1,N=!0,w=i.length-1,O=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){d=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(E===-1)E=w;else if(O!==1)O=1}else if(E!==-1)O=-1}if(E===-1||_===-1||O===0||O===1&&E===_-1&&E===d+1){if(_!==-1)if(d===0&&a)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(d,_)}else{if(d===0&&a)f.name=i.slice(1,E),f.base=i.slice(1,_);else f.name=i.slice(d,E),f.base=i.slice(d,_);f.ext=i.slice(E,_)}if(d>0)f.dir=i.slice(0,d-1);else if(a)f.dir="/";return f}var z="/",Ci=":",Wi;var K=U(()=>{Wi=((i)=>(i.posix=i,i))({resolve:x,normalize:o,isAbsolute:wi,join:W,relative:G,_makeLong:Ii,dirname:M,basename:Li,extname:$i,format:Ri,parse:Ui,sep:z,delimiter:Ci,win32:null,posix:null})});class v{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=M(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[_,N]of a){let w=G(M(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${A++}`,I=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(I.length>0)l.push(`import ${O}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${O} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?O:L.name;E.push(` ${P},`)}}let d=`// This file is auto-generated. Do not edit manually.
1
+ var{defineProperty:Q,getOwnPropertyNames:_i,getOwnPropertyDescriptor:di}=Object,Oi=Object.prototype.hasOwnProperty;var n=new WeakMap,Ni=(i)=>{var f=n.get(i),l;if(f)return f;if(f=Q({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")_i(i).map((a)=>!Oi.call(f,a)&&Q(f,a,{get:()=>i[a],enumerable:!(l=di(i,a))||l.enumerable}));return n.set(i,f),f};var r=(i,f)=>{for(var l in f)Q(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var U=(i,f)=>()=>(i&&(f=i(i=0)),f);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},Fi,ji,Mi,Ti,Bi,Yi,s=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},y=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,a])=>a?(f[l]=a,f):f,{})},j=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:a="*",allowHeaders:A,exposeHeaders:E,maxAge:d}=i,_=(w)=>{let O=w?.headers.get("origin");return f===!0?O:f instanceof RegExp?f.test(O)?O:void 0:Array.isArray(f)?f.includes(O)?O:void 0:f instanceof Function?f(O):f=="*"&&l?O:f},N=(w,O)=>{for(let[I,L]of Object.entries(O))L&&w.headers.append(I,L);return w};return{corsify:(w,O)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(w),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":E?.join?.(",")??E,"access-control-allow-headers":A?.join?.(",")??A??w.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":l})}}}};var V=U(()=>{Fi=b("application/json; charset=utf-8",JSON.stringify),ji=b("text/plain; charset=utf-8",String),Mi=b("text/html"),Ti=b("image/jpeg"),Bi=b("image/png"),Yi=b("image/webp")});var $,c,M;var X=U(()=>{$={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},c={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 J{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class W{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=c.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=c.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 q=U(()=>{X()});function C(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function t(i,f){var l="",a=0,A=-1,E=0,d;for(var _=0;_<=i.length;++_){if(_<i.length)d=i.charCodeAt(_);else if(d===47)break;else d=47;if(d===47){if(A===_-1||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 N=l.lastIndexOf("/");if(N!==l.length-1){if(N===-1)l="",a=0;else l=l.slice(0,N),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(d===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 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(C(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=t(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function o(i){if(C(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=t(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function wi(i){return C(i),i.length>0&&i.charCodeAt(0)===47}function z(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(C(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return o(i)}function G(i,f){if(C(i),C(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 d=f.length,_=d-E,N=A<_?A:_,w=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(f.charCodeAt(E+O)===47)return f.slice(E+O+1);else if(O===0)return f.slice(E+O)}else if(A>N){if(i.charCodeAt(l+O)===47)w=O;else if(O===0)w=0}break}var I=i.charCodeAt(l+O),L=f.charCodeAt(E+O);if(I!==L)break;else if(I===47)w=O}var P="";for(O=l+w+1;O<=a;++O)if(O===a||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+f.slice(E+w);else{if(E+=w,f.charCodeAt(E)===47)++E;return f.slice(E)}}function Ii(i){return i}function T(i){if(C(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');C(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 d=f.length-1,_=-1;for(E=i.length-1;E>=0;--E){var N=i.charCodeAt(E);if(N===47){if(!A){l=E+1;break}}else{if(_===-1)A=!1,_=E+1;if(d>=0)if(N===f.charCodeAt(d)){if(--d===-1)a=E}else d=-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 $i(i){C(i);var f=-1,l=0,a=-1,A=!0,E=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!A){l=d+1;break}continue}if(a===-1)A=!1,a=d+1;if(_===46){if(f===-1)f=d;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 Ui(i){C(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,d=0,_=-1,N=!0,w=i.length-1,O=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){d=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(E===-1)E=w;else if(O!==1)O=1}else if(E!==-1)O=-1}if(E===-1||_===-1||O===0||O===1&&E===_-1&&E===d+1){if(_!==-1)if(d===0&&a)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(d,_)}else{if(d===0&&a)f.name=i.slice(1,E),f.base=i.slice(1,_);else f.name=i.slice(d,E),f.base=i.slice(d,_);f.ext=i.slice(E,_)}if(d>0)f.dir=i.slice(0,d-1);else if(a)f.dir="/";return f}var K="/",Ci=":",Wi;var Z=U(()=>{Wi=((i)=>(i.posix=i,i))({resolve:x,normalize:o,isAbsolute:wi,join:z,relative:G,_makeLong:Ii,dirname:T,basename:Li,extname:$i,format:Ri,parse:Ui,sep:K,delimiter:Ci,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 v.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[_,N]of a){let w=G(T(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${A++}`,I=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(I.length>0)l.push(`import ${O}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${O} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?O:L.name;E.push(` ${P},`)}}let d=`// This file is auto-generated. Do not edit manually.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
@@ -10,7 +10,7 @@ ${E.join(`
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await Z.promises.writeFile(this.outputPath,d,"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 v.promises.writeFile(this.outputPath,d,"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 Z;var p=U(()=>{Z=(()=>({}));K()});class k{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 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 _=G(this.routesDir,E).replace(/\.(ts|js)$/,"").split(z).join("/");try{let w=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(w.default&&typeof w.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:E,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:E,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${E}:`,N)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}var g;var e=U(()=>{g=(()=>({}));K()});class T{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let 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 T;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function ii(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class m{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let E=0,d=i.split("/").filter(Boolean);for(let _ of d)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[d,_]of A.searchParams)E[d]=E[d]?[].concat(E[d],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(i.expose===!1)return R.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return R.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let E,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d.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),R.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 d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of E){let w=await N(_);if(w)return w}}}return R.notFound("Route not found")}clearRoutes(){this.routes=[]}}var fi=U(()=>{B()});class u{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=F(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 li=U(()=>{Q()});var ai={};r(ai,{getVectorInstance:()=>Pi,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new T,this.authManager=new X,this.cacheManager=new J,this.router=new m(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new u(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 v;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(ii(l.path)),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteDefinition(E)){let d=E;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else 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}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Pi;var Ei=U(()=>{q();p();e();fi();li();Pi=h.getInstance});function Ai(i,f){let l=Si(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function hi(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?hi(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:d=j.JSON}=i;return async(_)=>{if(!a)return R.forbidden("Forbidden");try{if(l)await bi(_,d);if(!A)await s(_);y(_);let N=await f(_);return E?N:Hi.success(N,d)}catch(N){if(N instanceof Response)return N;return R.internalServerError(String(N),d)}}}var Af,_f,Hi,R,bi=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (Ei(),ai)),A=l().getProtectedHandler();if(!A)throw R.unauthorized("Authentication not configured",f);try{let E=await A(i);i.authUser=E}catch(E){throw R.unauthorized(E instanceof Error?E.message:"Authentication failed",f)}};var B=U(()=>{Q();c();({preflight:Af,corsify:_f}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Hi={success:(i,f)=>H($.OK,i,f),created:(i,f)=>H($.CREATED,i,f)};R={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});var xi={};r(xi,{route:()=>Ai,createResponse:()=>H,APIError:()=>R});module.exports=Ni(xi);B();B();
21
+ };`}}var v;var p=U(()=>{v=(()=>({}));Z()});class k{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!F.existsSync(this.routesDir))return console.log(` → Routes directory not found: ${this.routesDir}`),console.log(" → No routes will be auto-discovered"),[];try{if(console.log(` → Scanning routes from: ${this.routesDir}`),await this.scanDirectory(this.routesDir,i),i.length>0)console.log(` ✓ Found ${i.length} route${i.length===1?"":"s"}`)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await F.promises.readdir(i);for(let A of a){let E=z(i,A);if((await F.promises.stat(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,E).replace(/\.(ts|js)$/,"").split(K).join("/");try{let w=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(w.default&&typeof w.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:E,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:E,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${E}:`,N)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}var F;var e=U(()=>{F=(()=>({}));Z()});class B{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let 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 B;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function ii(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class m{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let E=0,d=i.split("/").filter(Boolean);for(let _ of d)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[d,_]of A.searchParams)E[d]=E[d]?[].concat(E[d],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(i.expose===!1)return R.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return R.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let E,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),d.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),R.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 d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of E){let w=await N(_);if(w)return w}}}return R.notFound("Route not found")}clearRoutes(){this.routes=[]}}var fi=U(()=>{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}=j(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 li=U(()=>{V()});var ai={};r(ai,{getVectorInstance:()=>Pi,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new B,this.authManager=new J,this.cacheManager=new W,this.router=new m(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new u(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 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(ii(l.path)),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteDefinition(E)){let d=E;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else 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}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Pi;var Ei=U(()=>{q();p();e();fi();li();Pi=h.getInstance});function Ai(i,f){let l=Si(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function hi(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=M.JSON){let a=l===M.JSON?hi(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:d=M.JSON}=i;return async(_)=>{if(!a)return R.forbidden("Forbidden");try{if(l)await bi(_,d);if(!A)await s(_);y(_);let N=await f(_);return E?N:Hi.success(N,d)}catch(N){if(N instanceof Response)return N;return R.internalServerError(String(N),d)}}}var Af,_f,Hi,R,bi=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (Ei(),ai)),A=l().getProtectedHandler();if(!A)throw R.unauthorized("Authentication not configured",f);try{let E=await A(i);i.authUser=E}catch(E){throw R.unauthorized(E instanceof Error?E.message:"Authentication failed",f)}};var Y=U(()=>{V();X();({preflight:Af,corsify:_f}=j({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Hi={success:(i,f)=>H($.OK,i,f),created:(i,f)=>H($.CREATED,i,f)};R={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});var xi={};r(xi,{route:()=>Ai,createResponse:()=>H,APIError:()=>R});module.exports=Ni(xi);Y();Y();
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var li=Object.defineProperty;var ai=(i,f)=>{for(var l in f)li(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(E)=>f[l]=()=>E})};var R=(i,f)=>()=>(i&&(f=i(i=0)),f);var H=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let A=new Response(f?.(l)??l,E.url?void 0:E);return A.headers.set("content-type",i),A},hi,Hi,bi,Si,xi,Gi,k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},m=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},F=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:A,exposeHeaders:a,maxAge:d}=i,_=(w)=>{let O=w?.headers.get("origin");return f===!0?O:f instanceof RegExp?f.test(O)?O:void 0:Array.isArray(f)?f.includes(O)?O:void 0:f instanceof Function?f(O):f=="*"&&l?O:f},N=(w,O)=>{for(let[I,L]of Object.entries(O))L&&w.headers.append(I,L);return w};return{corsify:(w,O)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(w),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":a?.join?.(",")??a,"access-control-allow-headers":A?.join?.(",")??A??w.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":l})}}}};var Y=R(()=>{hi=H("application/json; charset=utf-8",JSON.stringify),Hi=H("text/plain; charset=utf-8",String),bi=H("text/html"),Si=H("image/jpeg"),xi=H("image/png"),Gi=H("image/webp")});var $,Q,j;var V=R(()=>{$={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Q={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},j={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class c{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class X{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=Q.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),A=this.memoryCache.get(i);if(this.isCacheValid(A,E))return A.value;let a=await f();return this.setInMemoryCache(i,a,l),a}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=Q.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var u=R(()=>{V()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function n(i,f){var l="",E=0,A=-1,a=0,d;for(var _=0;_<=i.length;++_){if(_<i.length)d=i.charCodeAt(_);else if(d===47)break;else d=47;if(d===47){if(A===_-1||a===1);else if(A!==_-1&&a===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var N=l.lastIndexOf("/");if(N!==l.length-1){if(N===-1)l="",E=0;else l=l.slice(0,N),E=l.length-1-l.lastIndexOf("/");A=_,a=0;continue}}else if(l.length===2||l.length===1){l="",E=0,A=_,a=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(A+1,_);else l=i.slice(A+1,_);E=_-A-1}A=_,a=0}else if(d===46&&a!==-1)++a;else a=-1}return l}function Ei(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function x(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var A;if(E>=0)A=arguments[E];else{if(l===void 0)l=process.cwd();A=l}if(U(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=n(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function r(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=n(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Ai(i){return U(i),i.length>0&&i.charCodeAt(0)===47}function J(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(U(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return r(i)}function G(i,f){if(U(i),U(f),i===f)return"";if(i=x(i),f=x(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,A=E-l,a=1;for(;a<f.length;++a)if(f.charCodeAt(a)!==47)break;var d=f.length,_=d-a,N=A<_?A:_,w=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(f.charCodeAt(a+O)===47)return f.slice(a+O+1);else if(O===0)return f.slice(a+O)}else if(A>N){if(i.charCodeAt(l+O)===47)w=O;else if(O===0)w=0}break}var I=i.charCodeAt(l+O),L=f.charCodeAt(a+O);if(I!==L)break;else if(I===47)w=O}var P="";for(O=l+w+1;O<=E;++O)if(O===E||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+f.slice(a+w);else{if(a+=w,f.charCodeAt(a)===47)++a;return f.slice(a)}}function _i(i){return i}function M(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,A=!0;for(var a=i.length-1;a>=1;--a)if(f=i.charCodeAt(a),f===47){if(!A){E=a;break}}else A=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function di(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');U(i);var l=0,E=-1,A=!0,a;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var d=f.length-1,_=-1;for(a=i.length-1;a>=0;--a){var N=i.charCodeAt(a);if(N===47){if(!A){l=a+1;break}}else{if(_===-1)A=!1,_=a+1;if(d>=0)if(N===f.charCodeAt(d)){if(--d===-1)E=a}else d=-1,E=_}}if(l===E)E=_;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(a=i.length-1;a>=0;--a)if(i.charCodeAt(a)===47){if(!A){l=a+1;break}}else if(E===-1)A=!1,E=a+1;if(E===-1)return"";return i.slice(l,E)}}function Oi(i){U(i);var f=-1,l=0,E=-1,A=!0,a=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!A){l=d+1;break}continue}if(E===-1)A=!1,E=d+1;if(_===46){if(f===-1)f=d;else if(a!==1)a=1}else if(f!==-1)a=-1}if(f===-1||E===-1||a===0||a===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function Ni(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return Ei("/",i)}function Di(i){U(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,A;if(E)f.root="/",A=1;else A=0;var a=-1,d=0,_=-1,N=!0,w=i.length-1,O=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){d=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(a===-1)a=w;else if(O!==1)O=1}else if(a!==-1)O=-1}if(a===-1||_===-1||O===0||O===1&&a===_-1&&a===d+1){if(_!==-1)if(d===0&&E)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(d,_)}else{if(d===0&&E)f.name=i.slice(1,a),f.base=i.slice(1,_);else f.name=i.slice(d,a),f.base=i.slice(d,_);f.ext=i.slice(a,_)}if(d>0)f.dir=i.slice(0,d-1);else if(E)f.dir="/";return f}var W="/",wi=":",Yi;var z=R(()=>{Yi=((i)=>(i.posix=i,i))({resolve:x,normalize:r,isAbsolute:Ai,join:J,relative:G,_makeLong:_i,dirname:M,basename:di,extname:Oi,format:Ni,parse:Di,sep:W,delimiter:wi,win32:null,posix:null})});var{promises:s}=(()=>({}));class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=M(this.outputPath);await s.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let _ of i){if(!E.has(_.path))E.set(_.path,[]);E.get(_.path).push(_)}let A=0,a=[];for(let[_,N]of E){let w=G(M(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${A++}`,I=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(I.length>0)l.push(`import ${O}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${O} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?O:L.name;a.push(` ${P},`)}}let d=`// This file is auto-generated. Do not edit manually.
1
+ var li=Object.defineProperty;var ai=(i,f)=>{for(var l in f)li(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(E)=>f[l]=()=>E})};var R=(i,f)=>()=>(i&&(f=i(i=0)),f);var H=(i="text/plain; charset=utf-8",f)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let A=new Response(f?.(l)??l,E.url?void 0:E);return A.headers.set("content-type",i),A},Hi,bi,Si,xi,Gi,Fi,k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},m=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,E])=>E?(f[l]=E,f):f,{})},F=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:E="*",allowHeaders:A,exposeHeaders:a,maxAge:d}=i,_=(w)=>{let O=w?.headers.get("origin");return f===!0?O:f instanceof RegExp?f.test(O)?O:void 0:Array.isArray(f)?f.includes(O)?O:void 0:f instanceof Function?f(O):f=="*"&&l?O:f},N=(w,O)=>{for(let[I,L]of Object.entries(O))L&&w.headers.append(I,L);return w};return{corsify:(w,O)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(w),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":a?.join?.(",")??a,"access-control-allow-headers":A?.join?.(",")??A??w.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":l})}}}};var Y=R(()=>{Hi=H("application/json; charset=utf-8",JSON.stringify),bi=H("text/plain; charset=utf-8",String),Si=H("text/html"),xi=H("image/jpeg"),Gi=H("image/png"),Fi=H("image/webp")});var $,Q,j;var V=R(()=>{$={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Q={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},j={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class c{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class X{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=Q.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let E=Date.now(),A=this.memoryCache.get(i);if(this.isCacheValid(A,E))return A.value;let a=await f();return this.setInMemoryCache(i,a,l),a}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let E=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=Q.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var u=R(()=>{V()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function n(i,f){var l="",E=0,A=-1,a=0,d;for(var _=0;_<=i.length;++_){if(_<i.length)d=i.charCodeAt(_);else if(d===47)break;else d=47;if(d===47){if(A===_-1||a===1);else if(A!==_-1&&a===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var N=l.lastIndexOf("/");if(N!==l.length-1){if(N===-1)l="",E=0;else l=l.slice(0,N),E=l.length-1-l.lastIndexOf("/");A=_,a=0;continue}}else if(l.length===2||l.length===1){l="",E=0,A=_,a=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+i.slice(A+1,_);else l=i.slice(A+1,_);E=_-A-1}A=_,a=0}else if(d===46&&a!==-1)++a;else a=-1}return l}function Ei(i,f){var l=f.dir||f.root,E=f.base||(f.name||"")+(f.ext||"");if(!l)return E;if(l===f.root)return l+E;return l+i+E}function x(){var i="",f=!1,l;for(var E=arguments.length-1;E>=-1&&!f;E--){var A;if(E>=0)A=arguments[E];else{if(l===void 0)l=process.cwd();A=l}if(U(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=n(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function r(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=n(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Ai(i){return U(i),i.length>0&&i.charCodeAt(0)===47}function J(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(U(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return r(i)}function G(i,f){if(U(i),U(f),i===f)return"";if(i=x(i),f=x(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,A=E-l,a=1;for(;a<f.length;++a)if(f.charCodeAt(a)!==47)break;var d=f.length,_=d-a,N=A<_?A:_,w=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(f.charCodeAt(a+O)===47)return f.slice(a+O+1);else if(O===0)return f.slice(a+O)}else if(A>N){if(i.charCodeAt(l+O)===47)w=O;else if(O===0)w=0}break}var I=i.charCodeAt(l+O),L=f.charCodeAt(a+O);if(I!==L)break;else if(I===47)w=O}var P="";for(O=l+w+1;O<=E;++O)if(O===E||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+f.slice(a+w);else{if(a+=w,f.charCodeAt(a)===47)++a;return f.slice(a)}}function _i(i){return i}function M(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,E=-1,A=!0;for(var a=i.length-1;a>=1;--a)if(f=i.charCodeAt(a),f===47){if(!A){E=a;break}}else A=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return i.slice(0,E)}function di(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');U(i);var l=0,E=-1,A=!0,a;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var d=f.length-1,_=-1;for(a=i.length-1;a>=0;--a){var N=i.charCodeAt(a);if(N===47){if(!A){l=a+1;break}}else{if(_===-1)A=!1,_=a+1;if(d>=0)if(N===f.charCodeAt(d)){if(--d===-1)E=a}else d=-1,E=_}}if(l===E)E=_;else if(E===-1)E=i.length;return i.slice(l,E)}else{for(a=i.length-1;a>=0;--a)if(i.charCodeAt(a)===47){if(!A){l=a+1;break}}else if(E===-1)A=!1,E=a+1;if(E===-1)return"";return i.slice(l,E)}}function Oi(i){U(i);var f=-1,l=0,E=-1,A=!0,a=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!A){l=d+1;break}continue}if(E===-1)A=!1,E=d+1;if(_===46){if(f===-1)f=d;else if(a!==1)a=1}else if(f!==-1)a=-1}if(f===-1||E===-1||a===0||a===1&&f===E-1&&f===l+1)return"";return i.slice(f,E)}function Ni(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return Ei("/",i)}function Di(i){U(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),E=l===47,A;if(E)f.root="/",A=1;else A=0;var a=-1,d=0,_=-1,N=!0,w=i.length-1,O=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){d=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(a===-1)a=w;else if(O!==1)O=1}else if(a!==-1)O=-1}if(a===-1||_===-1||O===0||O===1&&a===_-1&&a===d+1){if(_!==-1)if(d===0&&E)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(d,_)}else{if(d===0&&E)f.name=i.slice(1,a),f.base=i.slice(1,_);else f.name=i.slice(d,a),f.base=i.slice(d,_);f.ext=i.slice(a,_)}if(d>0)f.dir=i.slice(0,d-1);else if(E)f.dir="/";return f}var W="/",wi=":",Qi;var z=R(()=>{Qi=((i)=>(i.posix=i,i))({resolve:x,normalize:r,isAbsolute:Ai,join:J,relative:G,_makeLong:_i,dirname:M,basename:di,extname:Oi,format:Ni,parse:Di,sep:W,delimiter:wi,win32:null,posix:null})});var{promises:s}=(()=>({}));class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=M(this.outputPath);await s.mkdir(f,{recursive:!0});let l=[],E=new Map;for(let _ of i){if(!E.has(_.path))E.set(_.path,[]);E.get(_.path).push(_)}let A=0,a=[];for(let[_,N]of E){let w=G(M(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${A++}`,I=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(I.length>0)l.push(`import ${O}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${O} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?O:L.name;a.push(` ${P},`)}}let d=`// This file is auto-generated. Do not edit manually.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
4
  ${l.join(`
@@ -18,4 +18,4 @@ export default routes;
18
18
  ${f.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var y=R(()=>{z()});var{promises:q}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(`Routes directory not found: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let E=await q.readdir(i);for(let A of E){let a=J(i,A);if((await q.stat(a)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(a,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,a).replace(/\.(ts|js)$/,"").split(W).join("/");try{let w=await import(process.platform==="win32"?`file:///${a.replace(/\\/g,"/")}`:a);if(w.default&&typeof w.default==="function")f.push({name:"default",path:a,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:a,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:a,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${a}:`,N)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}var t=R(()=>{z()});class T{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)l=await E(l,f);return l}clone(){let i=new T;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function o(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class v{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let a=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))a+=1000;else if(this.isParamSegment(_))a+=10;else if(this.isWildcardSegment(_))a+=1;if(a+=i.length,this.isExactPath(i))a+=1e4;return a}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let E=l;if(!E.context)E.context={};if(!E.query&&E.url){let A=new URL(E.url),a={};for(let[d,_]of A.searchParams)a[d]=a[d]?[].concat(a[d],_):_;E.query=a}if(i.metadata)E.metadata=i.metadata;l=E;try{if(i.expose===!1)return C.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return C.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let a,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d.ttl)}else a=await f(l);let _;if(i.rawResponse||a instanceof Response)_=a instanceof Response?a:new Response(a);else _=b(200,a,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),C.internalServerError(A instanceof Error?A.message:String(A),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,A,a]of this.routes)if(i.method==="OPTIONS"||i.method===E){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of a){let w=await N(_);if(w)return w}}}return C.notFound("Route not found")}clearRoutes(){this.routes=[]}}var p=R(()=>{B()});class g{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=F(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let A=await this.router.handle(E);if(this.corsHandler)A=this.corsHandler.corsify(A,E);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}var e=R(()=>{Y()});var ii={};ai(ii,{getVectorInstance:()=>Ii,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new T,this.authManager=new c,this.cacheManager=new X,this.router=new v(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new g(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new Z(i);if(!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(o(l.path)),a=l.name==="default"?A.default:A[l.name];if(a){if(this.isRouteDefinition(a)){let d=a;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(a))this.router.addRoute(a),this.logRouteLoaded(a);else if(typeof a==="function")this.router.route(l.options,a),this.logRouteLoaded(l.options)}}catch(E){console.error(`Failed to load route ${l.name} from ${l.path}:`,E)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Ii;var fi=R(()=>{u();y();t();p();e();Ii=h.getInstance});function Li(i,f){let l=Ci(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function $i(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return b(i,E,l)}function b(i,f,l=j.JSON){let E=l===j.JSON?$i(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}function Ci(i,f){let{auth:l=!1,expose:E=!1,rawRequest:A=!1,rawResponse:a=!1,responseContentType:d=j.JSON}=i;return async(_)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Ui(_,d);if(!A)await k(_);m(_);let N=await f(_);return a?N:Ri.success(N,d)}catch(N){if(N instanceof Response)return N;return C.internalServerError(String(N),d)}}}var ff,lf,Ri,C,Ui=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (fi(),ii)),A=l().getProtectedHandler();if(!A)throw C.unauthorized("Authentication not configured",f);try{let a=await A(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var B=R(()=>{Y();V();({preflight:ff,corsify:lf}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ri={success:(i,f)=>b($.OK,i,f),created:(i,f)=>b($.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});B();B();export{Li as route,b as createResponse,C as APIError};
21
+ };`}}var y=R(()=>{z()});var{existsSync:Ii,promises:q}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!Ii(this.routesDir))return console.log(` → Routes directory not found: ${this.routesDir}`),console.log(" → No routes will be auto-discovered"),[];try{if(console.log(` → Scanning routes from: ${this.routesDir}`),await this.scanDirectory(this.routesDir,i),i.length>0)console.log(` ✓ Found ${i.length} route${i.length===1?"":"s"}`)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let E=await q.readdir(i);for(let A of E){let a=J(i,A);if((await q.stat(a)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(a,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=G(this.routesDir,a).replace(/\.(ts|js)$/,"").split(W).join("/");try{let w=await import(process.platform==="win32"?`file:///${a.replace(/\\/g,"/")}`:a);if(w.default&&typeof w.default==="function")f.push({name:"default",path:a,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,I]of Object.entries(w)){if(O==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:O,path:a,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:O,path:a,method:L,options:{method:L,path:P,expose:!0}})}}}catch(N){console.error(`Failed to load route from ${a}:`,N)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}var t=R(()=>{z()});class T{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let E=await l(f);if(E instanceof Response)return E;f=E}return f}async executeFinally(i,f){let l=i;for(let E of this.finallyHandlers)l=await E(l,f);return l}clone(){let i=new T;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function o(i){return process.platform==="win32"?`file:///${i.replace(/\\/g,"/")}`:i}class v{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let a=0,d=i.split("/").filter(Boolean);for(let _ of d)if(this.isStaticSegment(_))a+=1000;else if(this.isParamSegment(_))a+=10;else if(this.isWildcardSegment(_))a+=1;if(a+=i.length,this.isExactPath(i))a+=1e4;return a}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),E=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),E=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let E=l;if(!E.context)E.context={};if(!E.query&&E.url){let A=new URL(E.url),a={};for(let[d,_]of A.searchParams)a[d]=a[d]?[].concat(a[d],_):_;E.query=a}if(i.metadata)E.metadata=i.metadata;l=E;try{if(i.expose===!1)return C.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(N){return C.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let N=l.headers.get("content-type");if(N?.includes("application/json"))l.content=await l.json();else if(N?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(N?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let a,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),d.ttl)}else a=await f(l);let _;if(i.rawResponse||a instanceof Response)_=a instanceof Response?a:new Response(a);else _=b(200,a,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),C.internalServerError(A instanceof Error?A.message:String(A),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[E,A,a]of this.routes)if(i.method==="OPTIONS"||i.method===E){let d=l.match(A);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of a){let w=await N(_);if(w)return w}}}return C.notFound("Route not found")}clearRoutes(){this.routes=[]}}var p=R(()=>{B()});class g{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:E}=F(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:E}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let A=await this.router.handle(E);if(this.corsHandler)A=this.corsHandler.corsify(A,E);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}var e=R(()=>{Y()});var ii={};ai(ii,{getVectorInstance:()=>Li,Vector:()=>h});class h{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new T,this.authManager=new c,this.cacheManager=new X,this.router=new v(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}setProtectedHandler(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}getCacheHandler(){return this._cacheHandler}addRoute(i,f){return this.router.route(i,f)}async startServer(i){if(this.config={...this.config,...i},this.middlewareManager.clear(),i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new g(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new Z(i);if(!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(o(l.path)),a=l.name==="default"?A.default:A[l.name];if(a){if(this.isRouteDefinition(a)){let d=a;this.router.route(d.options,d.handler),this.logRouteLoaded(d.options)}else if(this.isRouteEntry(a))this.router.addRoute(a),this.logRouteLoaded(a);else if(typeof a==="function")this.router.route(l.options,a),this.logRouteLoaded(l.options)}}catch(E){console.error(`Failed to load route ${l.name} from ${l.path}:`,E)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT"&&f.code!=="ENOTDIR")console.error("Failed to discover routes:",f)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null;this.router.clearRoutes()}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){h.instance=null}}var Li;var fi=R(()=>{u();y();t();p();e();Li=h.getInstance});function $i(i,f){let l=Pi(i,f);return{entry:[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path],options:i,handler:f}}function Ri(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let E={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return b(i,E,l)}function b(i,f,l=j.JSON){let E=l===j.JSON?Ri(f):f;return new Response(E,{status:i,headers:{"content-type":l}})}function Pi(i,f){let{auth:l=!1,expose:E=!1,rawRequest:A=!1,rawResponse:a=!1,responseContentType:d=j.JSON}=i;return async(_)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Ci(_,d);if(!A)await k(_);m(_);let N=await f(_);return a?N:Ui.success(N,d)}catch(N){if(N instanceof Response)return N;return C.internalServerError(String(N),d)}}}var lf,af,Ui,C,Ci=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (fi(),ii)),A=l().getProtectedHandler();if(!A)throw C.unauthorized("Authentication not configured",f);try{let a=await A(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var B=R(()=>{Y();V();({preflight:lf,corsify:af}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,f)=>b($.OK,i,f),created:(i,f)=>b($.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D($.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D($.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D($.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D($.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D($.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D($.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D($.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D($.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});B();B();export{$i as route,b as createResponse,C as APIError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vector-framework",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "author": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,7 +42,7 @@
42
42
  }
43
43
  },
44
44
  "bin": {
45
- "vector": "./src/cli/index.ts"
45
+ "vector": "./dist/cli.js"
46
46
  },
47
47
  "bugs": {
48
48
  "url": "https://github.com/webhie-com/vector/issues"
@@ -77,10 +77,11 @@
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",
80
- "build:lib": "bun run build:clean && bun run build:ts && bun run build:bundle",
80
+ "build:lib": "bun run build:clean && bun run build:ts && bun run build:bundle && bun run build:cli",
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
+ "build:cli": "bun build src/cli/index.ts --target bun --outfile dist/cli.js",
84
85
  "test": "bun test tests/api-error.test.ts tests/cache.test.ts tests/middleware.test.ts tests/middleware-integration.test.ts tests/router.test.ts",
85
86
  "test:unit": "bun test tests/*.test.ts",
86
87
  "test:watch": "bun test --watch tests/*.test.ts",
package/src/cli/index.ts CHANGED
@@ -5,8 +5,11 @@ import { parseArgs } from "node:util";
5
5
  import { getVectorInstance } from "../core/vector";
6
6
  import { ConfigLoader } from "../core/config-loader";
7
7
 
8
+ // Compatibility layer for both Node and Bun
9
+ const args = typeof Bun !== 'undefined' ? Bun.argv.slice(2) : process.argv.slice(2);
10
+
8
11
  const { values, positionals } = parseArgs({
9
- args: Bun.argv.slice(2),
12
+ args,
10
13
  options: {
11
14
  port: {
12
15
  type: "string",
@@ -53,6 +56,7 @@ async function runDev() {
53
56
  // Load configuration using ConfigLoader
54
57
  const configLoader = new ConfigLoader();
55
58
  const config = await configLoader.load();
59
+ const configSource = configLoader.getConfigSource();
56
60
 
57
61
  // Merge CLI options with loaded config
58
62
  config.port = config.port || Number.parseInt(values.port as string);
@@ -96,6 +100,7 @@ async function runDev() {
96
100
  const cyan = "\x1b[36m";
97
101
  const green = "\x1b[32m";
98
102
 
103
+ console.log(` ${gray}Config${reset} ${configSource === 'user' ? 'User config loaded' : 'Using defaults'}`);
99
104
  console.log(` ${gray}Routes${reset} ${config.routesDir}`);
100
105
  if (isDev && values.watch) {
101
106
  console.log(` ${gray}Watching${reset} All project files`);
@@ -193,15 +198,25 @@ async function runBuild() {
193
198
 
194
199
  console.log(` Generated ${routes.length} routes`);
195
200
 
196
- const buildProcess = Bun.spawn([
197
- "bun",
198
- "build",
199
- "src/index.ts",
200
- "--outdir",
201
- "dist",
202
- "--minify",
203
- ]);
204
- await buildProcess.exited;
201
+ // Use spawn based on runtime
202
+ if (typeof Bun !== 'undefined') {
203
+ const buildProcess = Bun.spawn([
204
+ "bun",
205
+ "build",
206
+ "src/index.ts",
207
+ "--outdir",
208
+ "dist",
209
+ "--minify",
210
+ ]);
211
+ await buildProcess.exited;
212
+ } else {
213
+ // For Node.js, use child_process
214
+ const { spawnSync } = await import('child_process');
215
+ spawnSync('bun', ['build', 'src/index.ts', '--outdir', 'dist', '--minify'], {
216
+ stdio: 'inherit',
217
+ shell: true
218
+ });
219
+ }
205
220
 
206
221
  console.log("\n ✓ Build complete\n");
207
222
  } catch (error) {
@@ -1,3 +1,4 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { resolve } from 'node:path';
2
3
  import { toFileUrl } from '../utils/path';
3
4
  import type {
@@ -15,26 +16,45 @@ import type {
15
16
  export class ConfigLoader<TTypes extends VectorTypes = DefaultVectorTypes> {
16
17
  private configPath: string;
17
18
  private config: VectorConfigSchema<TTypes> | null = null;
19
+ private configSource: 'user' | 'default' = 'default';
18
20
 
19
21
  constructor(configPath = 'vector.config.ts') {
22
+ // Always resolve from the current working directory (user's project)
20
23
  this.configPath = resolve(process.cwd(), configPath);
21
24
  }
22
25
 
23
26
  async load(): Promise<VectorConfig<TTypes>> {
24
- try {
25
- // Try to load user config
26
- const userConfigPath = toFileUrl(this.configPath);
27
- const userConfig = await import(userConfigPath);
28
- this.config = userConfig.default || userConfig;
29
- } catch (error) {
30
- // No config file, use defaults
31
- console.log('No vector.config.ts found, using defaults');
27
+ // Check if config file exists before attempting to load
28
+ if (existsSync(this.configPath)) {
29
+ try {
30
+ console.log(`→ Loading config from: ${this.configPath}`);
31
+
32
+ // Use explicit file:// URL to ensure correct resolution
33
+ const userConfigPath = toFileUrl(this.configPath);
34
+ const userConfig = await import(userConfigPath);
35
+ this.config = userConfig.default || userConfig;
36
+ this.configSource = 'user';
37
+
38
+ console.log(' ✓ User config loaded successfully');
39
+ } catch (error) {
40
+ console.error(` ✗ Failed to load config from ${this.configPath}:`, error);
41
+ console.log(' → Using default configuration');
42
+ this.config = {};
43
+ }
44
+ } else {
45
+ // Config file doesn't exist, use defaults
46
+ console.log(` → No config file found at: ${this.configPath}`);
47
+ console.log(' → Using default configuration');
32
48
  this.config = {};
33
49
  }
34
50
 
35
51
  // Convert new config schema to legacy VectorConfig format
36
52
  return await this.buildLegacyConfig();
37
53
  }
54
+
55
+ getConfigSource(): 'user' | 'default' {
56
+ return this.configSource;
57
+ }
38
58
 
39
59
  private async buildLegacyConfig(): Promise<VectorConfig<TTypes>> {
40
60
  const config: VectorConfig<TTypes> = {};