vector-framework 0.9.6 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -47,61 +47,75 @@ async function runDev() {
47
47
  let server = null;
48
48
  let vector = null;
49
49
  async function startServer() {
50
- try {
51
- // Load configuration using ConfigLoader
52
- const configLoader = new ConfigLoader(values.config);
53
- const config = await configLoader.load();
54
- const configSource = configLoader.getConfigSource();
55
- // Merge CLI options with loaded config
56
- // Only use CLI values if config doesn't have them
57
- config.port = config.port ?? Number.parseInt(values.port);
58
- config.hostname = config.hostname ?? values.host;
59
- config.routesDir = config.routesDir ?? values.routes;
60
- config.development = config.development ?? isDev;
61
- config.autoDiscover = true; // Always auto-discover routes
62
- // Apply CLI CORS option if not set in config
63
- if (!config.cors && values.cors) {
64
- config.cors = {
65
- origin: "*",
66
- credentials: true,
67
- allowHeaders: "Content-Type, Authorization",
68
- allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
69
- exposeHeaders: "Authorization",
70
- maxAge: 86400,
71
- };
72
- }
73
- // Get Vector instance and configure handlers
74
- vector = getVectorInstance();
75
- // Load and set auth handler if configured
76
- const authHandler = await configLoader.loadAuthHandler();
77
- if (authHandler) {
78
- vector.setProtectedHandler(authHandler);
79
- }
80
- // Load and set cache handler if configured
81
- const cacheHandler = await configLoader.loadCacheHandler();
82
- if (cacheHandler) {
83
- vector.setCacheHandler(cacheHandler);
50
+ // Create a timeout promise that rejects after 10 seconds
51
+ const timeoutPromise = new Promise((_, reject) => {
52
+ setTimeout(() => {
53
+ reject(new Error("Server startup timed out (10s)"));
54
+ }, 10000);
55
+ });
56
+ // Create the actual server start promise
57
+ const serverStartPromise = (async () => {
58
+ try {
59
+ // Load configuration using ConfigLoader
60
+ const configLoader = new ConfigLoader(values.config);
61
+ const config = await configLoader.load();
62
+ const configSource = configLoader.getConfigSource();
63
+ // Merge CLI options with loaded config
64
+ // Only use CLI values if config doesn't have them
65
+ config.port = config.port ?? Number.parseInt(values.port);
66
+ config.hostname = config.hostname ?? values.host;
67
+ config.routesDir = config.routesDir ?? values.routes;
68
+ config.development = config.development ?? isDev;
69
+ config.autoDiscover = true; // Always auto-discover routes
70
+ // Apply CLI CORS option if not set in config
71
+ if (!config.cors && values.cors) {
72
+ config.cors = {
73
+ origin: "*",
74
+ credentials: true,
75
+ allowHeaders: "Content-Type, Authorization",
76
+ allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
77
+ exposeHeaders: "Authorization",
78
+ maxAge: 86400,
79
+ };
80
+ }
81
+ // Get Vector instance and configure handlers
82
+ vector = getVectorInstance();
83
+ // Load and set auth handler if configured
84
+ const authHandler = await configLoader.loadAuthHandler();
85
+ if (authHandler) {
86
+ vector.setProtectedHandler(authHandler);
87
+ }
88
+ // Load and set cache handler if configured
89
+ const cacheHandler = await configLoader.loadCacheHandler();
90
+ if (cacheHandler) {
91
+ vector.setCacheHandler(cacheHandler);
92
+ }
93
+ // Start the server
94
+ server = await vector.startServer(config);
95
+ // Verify the server is actually running
96
+ if (!server || !server.port) {
97
+ throw new Error("Server started but is not responding correctly");
98
+ }
99
+ const gray = "\x1b[90m";
100
+ const reset = "\x1b[0m";
101
+ const cyan = "\x1b[36m";
102
+ const green = "\x1b[32m";
103
+ console.log(` ${gray}Config${reset} ${configSource === "user" ? "User config loaded" : "Using defaults"}`);
104
+ console.log(` ${gray}Routes${reset} ${config.routesDir}`);
105
+ if (isDev && values.watch) {
106
+ console.log(` ${gray}Watching${reset} All project files`);
107
+ }
108
+ console.log(` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`);
109
+ console.log(` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}\n`);
110
+ console.log(` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`);
111
+ return { server, vector, config };
84
112
  }
85
- // Start the server
86
- server = await vector.startServer(config);
87
- const gray = "\x1b[90m";
88
- const reset = "\x1b[0m";
89
- const cyan = "\x1b[36m";
90
- const green = "\x1b[32m";
91
- console.log(` ${gray}Config${reset} ${configSource === "user" ? "User config loaded" : "Using defaults"}`);
92
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
93
- if (isDev && values.watch) {
94
- console.log(` ${gray}Watching${reset} All project files`);
113
+ catch (error) {
114
+ throw error;
95
115
  }
96
- console.log(` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`);
97
- console.log(` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}\n`);
98
- console.log(` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`);
99
- return { server, vector, config };
100
- }
101
- catch (error) {
102
- console.error("[ERROR] Failed to start server:", error);
103
- throw error;
104
- }
116
+ })();
117
+ // Race between server startup and timeout
118
+ return await Promise.race([serverStartPromise, timeoutPromise]);
105
119
  }
106
120
  try {
107
121
  // Start the server initially
@@ -163,7 +177,8 @@ async function runDev() {
163
177
  vector = result.vector;
164
178
  }
165
179
  catch (error) {
166
- console.error(" Failed to reload server:", error);
180
+ console.error("\n[Reload Error]", error.message || error);
181
+ // Don't exit the process on reload failures, just continue watching
167
182
  }
168
183
  finally {
169
184
  // Reset flag after a delay
@@ -181,7 +196,22 @@ async function runDev() {
181
196
  }
182
197
  }
183
198
  catch (error) {
184
- console.error("[ERROR] Failed to start server:", error);
199
+ const red = "\x1b[31m";
200
+ const reset = "\x1b[0m";
201
+ console.error(`\n${red}[ERROR] Failed to start server${reset}\n`);
202
+ // Always show the error message and stack trace
203
+ if (error.message) {
204
+ console.error(`Message: ${error.message}`);
205
+ }
206
+ if (error.stack) {
207
+ console.error(`\nStack trace:`);
208
+ console.error(error.stack);
209
+ }
210
+ else if (!error.message) {
211
+ // If no message or stack, show the raw error
212
+ console.error(`Raw error:`, error);
213
+ }
214
+ // Ensure we exit with error code
185
215
  process.exit(1);
186
216
  }
187
217
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["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AAC;QAC7C,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;CAef,CAAC,CAAC;QACC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC"}
package/dist/cli.js CHANGED
@@ -799,19 +799,36 @@ class VectorServer {
799
799
  return new Response("Internal Server Error", { status: 500 });
800
800
  }
801
801
  };
802
- this.server = Bun.serve({
803
- port,
804
- hostname,
805
- reusePort: this.config.reusePort !== false,
806
- fetch,
807
- idleTimeout: this.config.idleTimeout || 60,
808
- error: (error) => {
809
- console.error("[ERROR] Server error:", error);
810
- return new Response("Internal Server Error", { status: 500 });
802
+ try {
803
+ this.server = Bun.serve({
804
+ port,
805
+ hostname,
806
+ reusePort: this.config.reusePort !== false,
807
+ fetch,
808
+ idleTimeout: this.config.idleTimeout || 60,
809
+ error: (error) => {
810
+ console.error("[ERROR] Server error:", error);
811
+ return new Response("Internal Server Error", { status: 500 });
812
+ }
813
+ });
814
+ if (!this.server || !this.server.port) {
815
+ throw new Error(`Failed to start server on ${hostname}:${port} - server object is invalid`);
811
816
  }
812
- });
813
- console.log(`\u2192 Vector server running at http://${hostname}:${port}`);
814
- return this.server;
817
+ console.log(`\u2192 Vector server running at http://${hostname}:${port}`);
818
+ return this.server;
819
+ } catch (error) {
820
+ if (error.code === "EADDRINUSE" || error.message?.includes("address already in use")) {
821
+ error.message = `Port ${port} is already in use`;
822
+ error.port = port;
823
+ } else if (error.code === "EACCES" || error.message?.includes("permission denied")) {
824
+ error.message = `Permission denied to bind to port ${port}`;
825
+ error.port = port;
826
+ } else if (error.message?.includes("EADDRNOTAVAIL")) {
827
+ error.message = `Cannot bind to hostname ${hostname}`;
828
+ error.hostname = hostname;
829
+ }
830
+ throw error;
831
+ }
815
832
  }
816
833
  stop() {
817
834
  if (this.server) {
@@ -1127,54 +1144,64 @@ async function runDev() {
1127
1144
  let server = null;
1128
1145
  let vector = null;
1129
1146
  async function startServer() {
1130
- try {
1131
- const configLoader = new ConfigLoader(values.config);
1132
- const config = await configLoader.load();
1133
- const configSource = configLoader.getConfigSource();
1134
- config.port = config.port ?? Number.parseInt(values.port);
1135
- config.hostname = config.hostname ?? values.host;
1136
- config.routesDir = config.routesDir ?? values.routes;
1137
- config.development = config.development ?? isDev;
1138
- config.autoDiscover = true;
1139
- if (!config.cors && values.cors) {
1140
- config.cors = {
1141
- origin: "*",
1142
- credentials: true,
1143
- allowHeaders: "Content-Type, Authorization",
1144
- allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1145
- exposeHeaders: "Authorization",
1146
- maxAge: 86400
1147
- };
1148
- }
1149
- vector = getVectorInstance();
1150
- const authHandler = await configLoader.loadAuthHandler();
1151
- if (authHandler) {
1152
- vector.setProtectedHandler(authHandler);
1153
- }
1154
- const cacheHandler = await configLoader.loadCacheHandler();
1155
- if (cacheHandler) {
1156
- vector.setCacheHandler(cacheHandler);
1157
- }
1158
- server = await vector.startServer(config);
1159
- const gray = "\x1B[90m";
1160
- const reset = "\x1B[0m";
1161
- const cyan = "\x1B[36m";
1162
- const green = "\x1B[32m";
1163
- console.log(` ${gray}Config${reset} ${configSource === "user" ? "User config loaded" : "Using defaults"}`);
1164
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
1165
- if (isDev && values.watch) {
1166
- console.log(` ${gray}Watching${reset} All project files`);
1167
- }
1168
- console.log(` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`);
1169
- console.log(` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}
1147
+ const timeoutPromise = new Promise((_, reject) => {
1148
+ setTimeout(() => {
1149
+ reject(new Error("Server startup timed out (10s)"));
1150
+ }, 1e4);
1151
+ });
1152
+ const serverStartPromise = (async () => {
1153
+ try {
1154
+ const configLoader = new ConfigLoader(values.config);
1155
+ const config = await configLoader.load();
1156
+ const configSource = configLoader.getConfigSource();
1157
+ config.port = config.port ?? Number.parseInt(values.port);
1158
+ config.hostname = config.hostname ?? values.host;
1159
+ config.routesDir = config.routesDir ?? values.routes;
1160
+ config.development = config.development ?? isDev;
1161
+ config.autoDiscover = true;
1162
+ if (!config.cors && values.cors) {
1163
+ config.cors = {
1164
+ origin: "*",
1165
+ credentials: true,
1166
+ allowHeaders: "Content-Type, Authorization",
1167
+ allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1168
+ exposeHeaders: "Authorization",
1169
+ maxAge: 86400
1170
+ };
1171
+ }
1172
+ vector = getVectorInstance();
1173
+ const authHandler = await configLoader.loadAuthHandler();
1174
+ if (authHandler) {
1175
+ vector.setProtectedHandler(authHandler);
1176
+ }
1177
+ const cacheHandler = await configLoader.loadCacheHandler();
1178
+ if (cacheHandler) {
1179
+ vector.setCacheHandler(cacheHandler);
1180
+ }
1181
+ server = await vector.startServer(config);
1182
+ if (!server || !server.port) {
1183
+ throw new Error("Server started but is not responding correctly");
1184
+ }
1185
+ const gray = "\x1B[90m";
1186
+ const reset = "\x1B[0m";
1187
+ const cyan = "\x1B[36m";
1188
+ const green = "\x1B[32m";
1189
+ console.log(` ${gray}Config${reset} ${configSource === "user" ? "User config loaded" : "Using defaults"}`);
1190
+ console.log(` ${gray}Routes${reset} ${config.routesDir}`);
1191
+ if (isDev && values.watch) {
1192
+ console.log(` ${gray}Watching${reset} All project files`);
1193
+ }
1194
+ console.log(` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`);
1195
+ console.log(` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}
1170
1196
  `);
1171
- console.log(` ${green}Ready${reset} \u2192 ${cyan}http://${config.hostname}:${config.port}${reset}
1197
+ console.log(` ${green}Ready${reset} \u2192 ${cyan}http://${config.hostname}:${config.port}${reset}
1172
1198
  `);
1173
- return { server, vector, config };
1174
- } catch (error) {
1175
- console.error("[ERROR] Failed to start server:", error);
1176
- throw error;
1177
- }
1199
+ return { server, vector, config };
1200
+ } catch (error) {
1201
+ throw error;
1202
+ }
1203
+ })();
1204
+ return await Promise.race([serverStartPromise, timeoutPromise]);
1178
1205
  }
1179
1206
  try {
1180
1207
  const result = await startServer();
@@ -1214,7 +1241,8 @@ async function runDev() {
1214
1241
  server = result2.server;
1215
1242
  vector = result2.vector;
1216
1243
  } catch (error) {
1217
- console.error(" \u274C Failed to reload server:", error);
1244
+ console.error(`
1245
+ [Reload Error]`, error.message || error);
1218
1246
  } finally {
1219
1247
  setTimeout(() => {
1220
1248
  isReloading = false;
@@ -1228,7 +1256,21 @@ async function runDev() {
1228
1256
  }
1229
1257
  }
1230
1258
  } catch (error) {
1231
- console.error("[ERROR] Failed to start server:", error);
1259
+ const red = "\x1B[31m";
1260
+ const reset = "\x1B[0m";
1261
+ console.error(`
1262
+ ${red}[ERROR] Failed to start server${reset}
1263
+ `);
1264
+ if (error.message) {
1265
+ console.error(`Message: ${error.message}`);
1266
+ }
1267
+ if (error.stack) {
1268
+ console.error(`
1269
+ Stack trace:`);
1270
+ console.error(error.stack);
1271
+ } else if (!error.message) {
1272
+ console.error(`Raw error:`, error);
1273
+ }
1232
1274
  process.exit(1);
1233
1275
  }
1234
1276
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/core/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAElC,OAAO,KAAK,EAEV,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACZ,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,qBAAa,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IACvE,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,WAAW,CAAM;gBAEb,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC;IAYtE,OAAO,CAAC,oBAAoB;IAiBtB,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;IA4C9B,IAAI;IAQJ,SAAS,IAAI,MAAM,GAAG,IAAI;IAI1B,OAAO,IAAI,MAAM;IAIjB,WAAW,IAAI,MAAM;IAIrB,MAAM,IAAI,MAAM;CAKjB"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/core/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAElC,OAAO,KAAK,EAEV,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACZ,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,qBAAa,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IACvE,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,WAAW,CAAM;gBAEb,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC;IAYtE,OAAO,CAAC,oBAAoB;IAiBtB,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;IAiE9B,IAAI;IAQJ,SAAS,IAAI,MAAM,GAAG,IAAI;IAI1B,OAAO,IAAI,MAAM;IAIjB,WAAW,IAAI,MAAM;IAIrB,MAAM,IAAI,MAAM;CAKjB"}
@@ -50,20 +50,42 @@ export class VectorServer {
50
50
  return new Response("Internal Server Error", { status: 500 });
51
51
  }
52
52
  };
53
- this.server = Bun.serve({
54
- port,
55
- hostname,
56
- reusePort: this.config.reusePort !== false,
57
- fetch,
58
- idleTimeout: this.config.idleTimeout || 60,
59
- error: (error) => {
60
- console.error("[ERROR] Server error:", error);
61
- return new Response("Internal Server Error", { status: 500 });
62
- },
63
- });
64
- // Server logs are handled by CLI, keep this minimal
65
- console.log(`→ Vector server running at http://${hostname}:${port}`);
66
- return this.server;
53
+ try {
54
+ this.server = Bun.serve({
55
+ port,
56
+ hostname,
57
+ reusePort: this.config.reusePort !== false,
58
+ fetch,
59
+ idleTimeout: this.config.idleTimeout || 60,
60
+ error: (error) => {
61
+ console.error("[ERROR] Server error:", error);
62
+ return new Response("Internal Server Error", { status: 500 });
63
+ },
64
+ });
65
+ // Validate that the server actually started
66
+ if (!this.server || !this.server.port) {
67
+ throw new Error(`Failed to start server on ${hostname}:${port} - server object is invalid`);
68
+ }
69
+ // Server logs are handled by CLI, keep this minimal
70
+ console.log(`→ Vector server running at http://${hostname}:${port}`);
71
+ return this.server;
72
+ }
73
+ catch (error) {
74
+ // Enhance error message with context for common issues
75
+ if (error.code === 'EADDRINUSE' || error.message?.includes('address already in use')) {
76
+ error.message = `Port ${port} is already in use`;
77
+ error.port = port;
78
+ }
79
+ else if (error.code === 'EACCES' || error.message?.includes('permission denied')) {
80
+ error.message = `Permission denied to bind to port ${port}`;
81
+ error.port = port;
82
+ }
83
+ else if (error.message?.includes('EADDRNOTAVAIL')) {
84
+ error.message = `Cannot bind to hostname ${hostname}`;
85
+ error.hostname = hostname;
86
+ }
87
+ throw error;
88
+ }
67
89
  }
68
90
  stop() {
69
91
  if (this.server) {
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/core/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AASnC,MAAM,OAAO,YAAY;IACf,MAAM,GAAkB,IAAI,CAAC;IAC7B,MAAM,CAAuB;IAC7B,MAAM,CAAuB;IAC7B,WAAW,CAAM;IAEzB,YAAY,MAA4B,EAAE,MAA4B;QACpE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;YAChB,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,IAAI,CACjC,IAAI,CAAC,o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,CAAC,MAAM,CAAC,QAAQ,IAAI,WAAW,CAAC;IACtE,CAAC;IAED,MAAM;QACJ,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACpC,OAAO,UAAU,QAAQ,IAAI,IAAI,EAAE,CAAC;IACtC,CAAC;CACF"}
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
- var{defineProperty:Q,getOwnPropertyNames:_i,getOwnPropertyDescriptor:Oi}=Object,di=Object.prototype.hasOwnProperty;var r=new WeakMap,Ni=(i)=>{var f=r.get(i),l;if(f)return f;if(f=Q({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")_i(i).map((a)=>!di.call(f,a)&&Q(f,a,{get:()=>i[a],enumerable:!(l=Oi(i,a))||l.enumerable}));return r.set(i,f),f};var n=(i,f)=>{for(var l in f)Q(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var $=(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:O}=i,_=(w)=>{let d=w?.headers.get("origin");return f===!0?d:f instanceof RegExp?f.test(d)?d:void 0:Array.isArray(f)?f.includes(d)?d:void 0:f instanceof Function?f(d):f=="*"&&l?d:f},N=(w,d)=>{for(let[I,L]of Object.entries(d))L&&w.headers.append(I,L);return w};return{corsify:(w,d)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(d),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let d=new Response(null,{status:204});return N(d,{"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":O,"access-control-allow-credentials":l})}}}};var V=$(()=>{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 R,X,M;var J=$(()=>{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},X={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 W{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class z{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=X.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let 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=X.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var q=$(()=>{J()});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,O;for(var _=0;_<=i.length;++_){if(_<i.length)O=i.charCodeAt(_);else if(O===47)break;else O=47;if(O===47){if(A===_-1||E===1);else if(A!==_-1&&E===2){if(l.length<2||a!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var 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(O===46&&E!==-1)++E;else E=-1}return l}function Di(i,f){var l=f.dir||f.root,a=f.base||(f.name||"")+(f.ext||"");if(!l)return a;if(l===f.root)return l+a;return l+i+a}function 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 c(){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 O=f.length,_=O-E,N=A<_?A:_,w=-1,d=0;for(;d<=N;++d){if(d===N){if(_>N){if(f.charCodeAt(E+d)===47)return f.slice(E+d+1);else if(d===0)return f.slice(E+d)}else if(A>N){if(i.charCodeAt(l+d)===47)w=d;else if(d===0)w=0}break}var I=i.charCodeAt(l+d),L=f.charCodeAt(E+d);if(I!==L)break;else if(I===47)w=d}var P="";for(d=l+w+1;d<=a;++d)if(d===a||i.charCodeAt(d)===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 O=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(O>=0)if(N===f.charCodeAt(O)){if(--O===-1)a=E}else O=-1,a=_}}if(l===a)a=_;else if(a===-1)a=i.length;return i.slice(l,a)}else{for(E=i.length-1;E>=0;--E)if(i.charCodeAt(E)===47){if(!A){l=E+1;break}}else if(a===-1)A=!1,a=E+1;if(a===-1)return"";return i.slice(l,a)}}function Ri(i){C(i);var f=-1,l=0,a=-1,A=!0,E=0;for(var O=i.length-1;O>=0;--O){var _=i.charCodeAt(O);if(_===47){if(!A){l=O+1;break}continue}if(a===-1)A=!1,a=O+1;if(_===46){if(f===-1)f=O;else if(E!==1)E=1}else if(f!==-1)E=-1}if(f===-1||a===-1||E===0||E===1&&f===a-1&&f===l+1)return"";return i.slice(f,a)}function Ui(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 $i(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,O=0,_=-1,N=!0,w=i.length-1,d=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){O=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(E===-1)E=w;else if(d!==1)d=1}else if(E!==-1)d=-1}if(E===-1||_===-1||d===0||d===1&&E===_-1&&E===O+1){if(_!==-1)if(O===0&&a)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(O,_)}else{if(O===0&&a)f.name=i.slice(1,E),f.base=i.slice(1,_);else f.name=i.slice(O,E),f.base=i.slice(O,_);f.ext=i.slice(E,_)}if(O>0)f.dir=i.slice(0,O-1);else if(a)f.dir="/";return f}var K="/",Ci=":",zi;var Z=$(()=>{zi=((i)=>(i.posix=i,i))({resolve:x,normalize:o,isAbsolute:wi,join:c,relative:G,_makeLong:Ii,dirname:T,basename:Li,extname:Ri,format:Ui,parse:$i,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)$/,""),d=`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 ${d}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${d} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?d:L.name;E.push(` ${P},`)}}let O=`// 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 l=n.get(i),f;if(l)return l;if(l=Q({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")_i(i).map((a)=>!Oi.call(l,a)&&Q(l,a,{get:()=>i[a],enumerable:!(f=di(i,a))||f.enumerable}));return n.set(i,l),l};var s=(i,l)=>{for(var f in l)Q(i,f,{get:l[f],enumerable:!0,configurable:!0,set:(a)=>l[f]=()=>a})};var U=(i,l)=>()=>(i&&(l=i(i=0)),l);var h=(i="text/plain; charset=utf-8",l)=>(f,a={})=>{if(f===void 0||f instanceof Response)return f;let E=new Response(l?.(f)??f,a.url?void 0:a);return E.headers.set("content-type",i),E},Fi,ji,Mi,Ti,Bi,Yi,r=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((l)=>l.split(/=(.+)/)).reduce((l,[f,a])=>a?(l[f]=a,l):l,{})},j=(i={})=>{let{origin:l="*",credentials:f=!1,allowMethods:a="*",allowHeaders:E,exposeHeaders:A,maxAge:d}=i,_=(I)=>{let O=I?.headers.get("origin");return l===!0?O:l instanceof RegExp?l.test(O)?O:void 0:Array.isArray(l)?l.includes(O)?O:void 0:l instanceof Function?l(O):l=="*"&&f?O:l},N=(I,O)=>{for(let[w,L]of Object.entries(O))L&&I.headers.append(w,L);return I};return{corsify:(I,O)=>I?.headers?.get("access-control-allow-origin")||I.status==101?I:N(I.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":f}),preflight:(I)=>{if(I.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(I),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":E?.join?.(",")??E??I.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":f})}}}};var V=U(()=>{Fi=h("application/json; charset=utf-8",JSON.stringify),ji=h("text/plain; charset=utf-8",String),Mi=h("text/html"),Ti=h("image/jpeg"),Bi=h("image/png"),Yi=h("image/webp")});var C,X,M;var J=U(()=>{C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},X={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},M={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class W{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let l=await this.protectedHandler(i);return i.authUser=l,l}catch(l){throw new Error(`Authentication failed: ${l instanceof Error?l.message:String(l)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}class z{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,l,f=X.CACHE_TTL){if(f<=0)return l();if(this.cacheHandler)return this.cacheHandler(i,l,f);return this.getFromMemoryCache(i,l,f)}async getFromMemoryCache(i,l,f){let a=Date.now(),E=this.memoryCache.get(i);if(this.isCacheValid(E,a))return E.value;let A=await l();return this.setInMemoryCache(i,A,f),A}isCacheValid(i,l){return i!==void 0&&i.expires>l}setInMemoryCache(i,l,f){let a=Date.now()+f*1000;this.memoryCache.set(i,{value:l,expires:a}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[l,f]of this.memoryCache.entries())if(f.expires<=i)this.memoryCache.delete(l);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,l,f=X.CACHE_TTL){if(f<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>l,f);return}this.setInMemoryCache(i,l,f)}delete(i){return this.memoryCache.delete(i)}has(i){let l=this.memoryCache.get(i);if(!l)return!1;if(l.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,l){let f=new URL(i.url);return[i.method,f.pathname,f.search,l?.authUser?.id||"anonymous"].join(":")}}var q=U(()=>{J()});function $(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function t(i,l){var f="",a=0,E=-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(E===_-1||A===1);else if(E!==_-1&&A===2){if(f.length<2||a!==2||f.charCodeAt(f.length-1)!==46||f.charCodeAt(f.length-2)!==46){if(f.length>2){var N=f.lastIndexOf("/");if(N!==f.length-1){if(N===-1)f="",a=0;else f=f.slice(0,N),a=f.length-1-f.lastIndexOf("/");E=_,A=0;continue}}else if(f.length===2||f.length===1){f="",a=0,E=_,A=0;continue}}if(l){if(f.length>0)f+="/..";else f="..";a=2}}else{if(f.length>0)f+="/"+i.slice(E+1,_);else f=i.slice(E+1,_);a=_-E-1}E=_,A=0}else if(d===46&&A!==-1)++A;else A=-1}return f}function Di(i,l){var f=l.dir||l.root,a=l.base||(l.name||"")+(l.ext||"");if(!f)return a;if(f===l.root)return f+a;return f+i+a}function x(){var i="",l=!1,f;for(var a=arguments.length-1;a>=-1&&!l;a--){var E;if(a>=0)E=arguments[a];else{if(f===void 0)f=process.cwd();E=f}if($(E),E.length===0)continue;i=E+"/"+i,l=E.charCodeAt(0)===47}if(i=t(i,!l),l)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function o(i){if($(i),i.length===0)return".";var l=i.charCodeAt(0)===47,f=i.charCodeAt(i.length-1)===47;if(i=t(i,!l),i.length===0&&!l)i=".";if(i.length>0&&f)i+="/";if(l)return"/"+i;return i}function Ii(i){return $(i),i.length>0&&i.charCodeAt(0)===47}function K(){if(arguments.length===0)return".";var i;for(var l=0;l<arguments.length;++l){var f=arguments[l];if($(f),f.length>0)if(i===void 0)i=f;else i+="/"+f}if(i===void 0)return".";return o(i)}function G(i,l){if($(i),$(l),i===l)return"";if(i=x(i),l=x(l),i===l)return"";var f=1;for(;f<i.length;++f)if(i.charCodeAt(f)!==47)break;var a=i.length,E=a-f,A=1;for(;A<l.length;++A)if(l.charCodeAt(A)!==47)break;var d=l.length,_=d-A,N=E<_?E:_,I=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(l.charCodeAt(A+O)===47)return l.slice(A+O+1);else if(O===0)return l.slice(A+O)}else if(E>N){if(i.charCodeAt(f+O)===47)I=O;else if(O===0)I=0}break}var w=i.charCodeAt(f+O),L=l.charCodeAt(A+O);if(w!==L)break;else if(w===47)I=O}var P="";for(O=f+I+1;O<=a;++O)if(O===a||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+l.slice(A+I);else{if(A+=I,l.charCodeAt(A)===47)++A;return l.slice(A)}}function wi(i){return i}function T(i){if($(i),i.length===0)return".";var l=i.charCodeAt(0),f=l===47,a=-1,E=!0;for(var A=i.length-1;A>=1;--A)if(l=i.charCodeAt(A),l===47){if(!E){a=A;break}}else E=!1;if(a===-1)return f?"/":".";if(f&&a===1)return"//";return i.slice(0,a)}function Li(i,l){if(l!==void 0&&typeof l!=="string")throw new TypeError('"ext" argument must be a string');$(i);var f=0,a=-1,E=!0,A;if(l!==void 0&&l.length>0&&l.length<=i.length){if(l.length===i.length&&l===i)return"";var d=l.length-1,_=-1;for(A=i.length-1;A>=0;--A){var N=i.charCodeAt(A);if(N===47){if(!E){f=A+1;break}}else{if(_===-1)E=!1,_=A+1;if(d>=0)if(N===l.charCodeAt(d)){if(--d===-1)a=A}else d=-1,a=_}}if(f===a)a=_;else if(a===-1)a=i.length;return i.slice(f,a)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!E){f=A+1;break}}else if(a===-1)E=!1,a=A+1;if(a===-1)return"";return i.slice(f,a)}}function Ci(i){$(i);var l=-1,f=0,a=-1,E=!0,A=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!E){f=d+1;break}continue}if(a===-1)E=!1,a=d+1;if(_===46){if(l===-1)l=d;else if(A!==1)A=1}else if(l!==-1)A=-1}if(l===-1||a===-1||A===0||A===1&&l===a-1&&l===f+1)return"";return i.slice(l,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){$(i);var l={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return l;var f=i.charCodeAt(0),a=f===47,E;if(a)l.root="/",E=1;else E=0;var A=-1,d=0,_=-1,N=!0,I=i.length-1,O=0;for(;I>=E;--I){if(f=i.charCodeAt(I),f===47){if(!N){d=I+1;break}continue}if(_===-1)N=!1,_=I+1;if(f===46){if(A===-1)A=I;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&&a)l.base=l.name=i.slice(1,_);else l.base=l.name=i.slice(d,_)}else{if(d===0&&a)l.name=i.slice(1,A),l.base=i.slice(1,_);else l.name=i.slice(d,A),l.base=i.slice(d,_);l.ext=i.slice(A,_)}if(d>0)l.dir=i.slice(0,d-1);else if(a)l.dir="/";return l}var Z="/",$i=":",zi;var c=U(()=>{zi=((i)=>(i.posix=i,i))({resolve:x,normalize:o,isAbsolute:Ii,join:K,relative:G,_makeLong:wi,dirname:T,basename:Li,extname:Ci,format:Ri,parse:Ui,sep:Z,delimiter:$i,win32:null,posix:null})});class g{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let l=T(this.outputPath);await v.promises.mkdir(l,{recursive:!0});let f=[],a=new Map;for(let _ of i){if(!a.has(_.path))a.set(_.path,[]);a.get(_.path).push(_)}let E=0,A=[];for(let[_,N]of a){let I=G(T(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${E++}`,w=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(w.length>0)f.push(`import ${O}, { ${w.join(", ")} } from '${I}';`);else f.push(`import ${O} from '${I}';`);else if(w.length>0)f.push(`import { ${w.join(", ")} } from '${I}';`);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
- ${l.join(`
4
+ ${f.join(`
5
5
  `)}
6
6
 
7
7
  export const routes = [
8
- ${E.join(`
8
+ ${A.join(`
9
9
  `)}
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await v.promises.writeFile(this.outputPath,O,"utf-8")}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")}async generateDynamic(i){let l=[];for(let f of i){let a=JSON.stringify({method:f.method,path:f.options.path,options:f.options});l.push(` await import('${f.path}').then(m => ({
14
14
  ...${a},
15
- handler: m.${l.name==="default"?"default":l.name}
15
+ handler: m.${f.name==="default"?"default":f.name}
16
16
  }))`)}return`export const loadRoutes = async () => {
17
17
  return Promise.all([
18
- ${f.join(`,
18
+ ${l.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var v;var p=$(()=>{v=(()=>({}));Z()});class k{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!F.existsSync(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await F.promises.readdir(i);for(let A of a){let E=c(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[d,I]of Object.entries(w)){if(d==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:d,path:E,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:d,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=$(()=>{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,O=i.split("/").filter(Boolean);for(let _ of O)if(this.isStaticSegment(_))E+=1000;else if(this.isParamSegment(_))E+=10;else if(this.isWildcardSegment(_))E+=1;if(E+=i.length,this.isExactPath(i))E+=1e4;return E}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),a=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(a)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(a),this.sortRoutes(),a}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let a=l;if(!a.context)a.context={};if(!a.query&&a.url){let A=new URL(a.url),E={};for(let[O,_]of A.searchParams)E[O]=E[O]?[].concat(E[O],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(i.expose===!1)return U.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 U.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,O=i.cache;if(O&&typeof O==="number"&&O>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),O)}else if(O&&typeof O==="object"&&O.ttl){let N=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(N,()=>f(l),O.ttl)}else E=await f(l);let _;if(i.rawResponse||E instanceof Response)_=E instanceof Response?E:new Response(E);else _=H(200,E,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),U.internalServerError(A instanceof Error?A.message:String(A),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[a,A,E]of this.routes)if(i.method==="OPTIONS"||i.method===a){let O=l.match(A);if(O){let _=i;if(!_.context)_.context={};_.params=O.groups||{};for(let N of E){let w=await N(_);if(w)return w}}}return U.notFound("Route not found")}clearRoutes(){this.routes=[]}}var fi=$(()=>{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,idleTimeout:this.config.idleTimeout||60,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=$(()=>{V()});var ai={};n(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 W,this.cacheManager=new z,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=new k(i),!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 O=E;this.router.route(O.options,O.handler),this.logRouteLoaded(O.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()}}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){}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=$(()=>{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:O=M.JSON}=i;return async(_)=>{if(!a)return U.forbidden("Forbidden");try{if(l)await bi(_,O);if(!A)await s(_);y(_);let N=await f(_);return E?N:Hi.success(N,O)}catch(N){if(N instanceof Response)return N;return U.internalServerError(String(N),O)}}}var Af,_f,Hi,U,bi=async(i,f)=>{let{getVectorInstance:l}=await Promise.resolve().then(() => (Ei(),ai)),A=l().getProtectedHandler();if(!A)throw U.unauthorized("Authentication not configured",f);try{let E=await A(i);i.authUser=E}catch(E){throw U.unauthorized(E instanceof Error?E.message:"Authentication failed",f)}};var Y=$(()=>{V();J();({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(R.OK,i,f),created:(i,f)=>H(R.CREATED,i,f)};U={badRequest:(i="Bad Request",f)=>D(R.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D(R.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D(R.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D(R.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D(R.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D(R.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});var xi={};n(xi,{route:()=>Ai,createResponse:()=>H,APIError:()=>U});module.exports=Ni(xi);Y();Y();
21
+ };`}}var v;var p=U(()=>{v=(()=>({}));c()});class k{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!F.existsSync(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(l){if(l.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw l}return i}async scanDirectory(i,l,f=""){let a=await F.promises.readdir(i);for(let E of a){let A=K(i,E);if((await F.promises.stat(A)).isDirectory()){let _=f?`${f}/${E}`:E;await this.scanDirectory(A,l,_)}else if(E.endsWith(".ts")||E.endsWith(".js")){let _=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(Z).join("/");try{let I=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(I.default&&typeof I.default==="function")l.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,w]of Object.entries(I)){if(O==="default")continue;if(w&&typeof w==="object"&&"entry"in w&&"options"in w&&"handler"in w){let L=w;l.push({name:O,path:A,method:L.options.method,options:L.options})}else if(Array.isArray(w)&&w.length>=4){let[L,,,P]=w;l.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 F;var e=U(()=>{F=(()=>({}));c()});class B{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let l=i;for(let f of this.beforeHandlers){let a=await f(l);if(a instanceof Response)return a;l=a}return l}async executeFinally(i,l){let f=i;for(let a of this.finallyHandlers)f=await a(f,l);return f}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 u{middlewareManager;authManager;cacheManager;routes=[];constructor(i,l,f){this.middlewareManager=i,this.authManager=l,this.cacheManager=f}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,l)=>{let f=this.extractPath(i),a=this.extractPath(l),E=this.getRouteSpecificity(f);return this.getRouteSpecificity(a)-E})}extractPath(i){return i[3]||""}route(i,l){let f=this.wrapHandler(i,l),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[f],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,l){return async(f)=>{let a=f;if(!a.context)a.context={};if(!a.query&&a.url){let E=new URL(a.url),A={};for(let[d,_]of E.searchParams)A[d]=A[d]?[].concat(A[d],_):_;a.query=A}if(i.metadata)a.metadata=i.metadata;f=a;try{if(i.expose===!1)return R.forbidden("Forbidden");let E=await this.middlewareManager.executeBefore(f);if(E instanceof Response)return E;if(f=E,i.auth)try{await this.authManager.authenticate(f)}catch(N){return R.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&f.method!=="GET"&&f.method!=="HEAD")try{let N=f.headers.get("content-type");if(N?.includes("application/json"))f.content=await f.json();else if(N?.includes("application/x-www-form-urlencoded"))f.content=Object.fromEntries(await f.formData());else if(N?.includes("multipart/form-data"))f.content=await f.formData();else f.content=await f.text()}catch{f.content=null}let A,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(f,{authUser:f.authUser});A=await this.cacheManager.get(N,()=>l(f),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(f,{authUser:f.authUser});A=await this.cacheManager.get(N,()=>l(f),d.ttl)}else A=await l(f);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(_,f),_}catch(E){if(E instanceof Response)return E;return console.error("Route handler error:",E),R.internalServerError(E instanceof Error?E.message:String(E),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let f=new URL(i.url).pathname;for(let[a,E,A]of this.routes)if(i.method==="OPTIONS"||i.method===a){let d=f.match(E);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of A){let I=await N(_);if(I)return I}}}return R.notFound("Route not found")}clearRoutes(){this.routes=[]}}var li=U(()=>{Y()});class m{server=null;router;config;corsHandler;constructor(i,l){if(this.router=i,this.config=l,l.cors){let{preflight:f,corsify:a}=j(this.normalizeCorsOptions(l.cors));this.corsHandler={preflight:f,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,l=this.config.hostname||"localhost",f=async(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let E=await this.router.handle(a);if(this.corsHandler)E=this.corsHandler.corsify(E,a);return E}catch(E){return console.error("Server error:",E),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:l,reusePort:this.config.reusePort!==!1,fetch:f,idleTimeout:this.config.idleTimeout||60,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${l}:${i} - server object is invalid`);return console.log(`→ Vector server running at http://${l}:${i}`),this.server}catch(a){if(a.code==="EADDRINUSE"||a.message?.includes("address already in use"))a.message=`Port ${i} is already in use`,a.port=i;else if(a.code==="EACCES"||a.message?.includes("permission denied"))a.message=`Permission denied to bind to port ${i}`,a.port=i;else if(a.message?.includes("EADDRNOTAVAIL"))a.message=`Cannot bind to hostname ${l}`,a.hostname=l;throw a}}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 fi=U(()=>{V()});var ai={};s(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 W,this.cacheManager=new z,this.router=new u(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,l){return this.router.route(i,l)}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 m(this.router,this.config),await this.server.start()}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(this.routeScanner=new k(i),!this.routeGenerator)this.routeGenerator=new g;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let f of l)try{let E=await import(ii(f.path)),A=f.name==="default"?E.default:E[f.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(f.options,A),this.logRouteLoaded(f.options)}}catch(a){console.error(`Failed to load route ${f.name} from ${f.path}:`,a)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let l=i();if(Array.isArray(l))this.router.addRoute(l)}else if(i&&typeof i==="object"){for(let[,l]of Object.entries(i))if(typeof l==="function"){let f=l();if(Array.isArray(f))this.router.addRoute(f)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null;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 Ai=U(()=>{q();p();e();li();fi();Pi=H.getInstance});function Ei(i,l){let f=Si(i,l);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.*)?")}/*$`),[f],i.path],options:i,handler:l}}function Hi(i){return JSON.stringify(i??null,(l,f)=>typeof f==="bigint"?f.toString():f)}function D(i,l,f){let a={error:!0,message:l,statusCode:i,timestamp:new Date().toISOString()};return b(i,a,f)}function b(i,l,f=M.JSON){let a=f===M.JSON?Hi(l):l;return new Response(a,{status:i,headers:{"content-type":f}})}function Si(i,l){let{auth:f=!1,expose:a=!1,rawRequest:E=!1,rawResponse:A=!1,responseContentType:d=M.JSON}=i;return async(_)=>{if(!a)return R.forbidden("Forbidden");try{if(f)await hi(_,d);if(!E)await r(_);y(_);let N=await l(_);return A?N:bi.success(N,d)}catch(N){if(N instanceof Response)return N;return R.internalServerError(String(N),d)}}}var Al,El,bi,R,hi=async(i,l)=>{let{getVectorInstance:f}=await Promise.resolve().then(() => (Ai(),ai)),E=f().getProtectedHandler();if(!E)throw R.unauthorized("Authentication not configured",l);try{let A=await E(i);i.authUser=A}catch(A){throw R.unauthorized(A instanceof Error?A.message:"Authentication failed",l)}};var Y=U(()=>{V();J();({preflight:Al,corsify:El}=j({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));bi={success:(i,l)=>b(C.OK,i,l),created:(i,l)=>b(C.CREATED,i,l)};R={badRequest:(i="Bad Request",l)=>D(C.BAD_REQUEST,i,l),unauthorized:(i="Unauthorized",l)=>D(C.UNAUTHORIZED,i,l),paymentRequired:(i="Payment Required",l)=>D(402,i,l),forbidden:(i="Forbidden",l)=>D(C.FORBIDDEN,i,l),notFound:(i="Not Found",l)=>D(C.NOT_FOUND,i,l),methodNotAllowed:(i="Method Not Allowed",l)=>D(405,i,l),notAcceptable:(i="Not Acceptable",l)=>D(406,i,l),requestTimeout:(i="Request Timeout",l)=>D(408,i,l),conflict:(i="Conflict",l)=>D(C.CONFLICT,i,l),gone:(i="Gone",l)=>D(410,i,l),lengthRequired:(i="Length Required",l)=>D(411,i,l),preconditionFailed:(i="Precondition Failed",l)=>D(412,i,l),payloadTooLarge:(i="Payload Too Large",l)=>D(413,i,l),uriTooLong:(i="URI Too Long",l)=>D(414,i,l),unsupportedMediaType:(i="Unsupported Media Type",l)=>D(415,i,l),rangeNotSatisfiable:(i="Range Not Satisfiable",l)=>D(416,i,l),expectationFailed:(i="Expectation Failed",l)=>D(417,i,l),imATeapot:(i="I'm a teapot",l)=>D(418,i,l),misdirectedRequest:(i="Misdirected Request",l)=>D(421,i,l),unprocessableEntity:(i="Unprocessable Entity",l)=>D(C.UNPROCESSABLE_ENTITY,i,l),locked:(i="Locked",l)=>D(423,i,l),failedDependency:(i="Failed Dependency",l)=>D(424,i,l),tooEarly:(i="Too Early",l)=>D(425,i,l),upgradeRequired:(i="Upgrade Required",l)=>D(426,i,l),preconditionRequired:(i="Precondition Required",l)=>D(428,i,l),tooManyRequests:(i="Too Many Requests",l)=>D(429,i,l),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",l)=>D(431,i,l),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",l)=>D(451,i,l),internalServerError:(i="Internal Server Error",l)=>D(C.INTERNAL_SERVER_ERROR,i,l),notImplemented:(i="Not Implemented",l)=>D(501,i,l),badGateway:(i="Bad Gateway",l)=>D(502,i,l),serviceUnavailable:(i="Service Unavailable",l)=>D(503,i,l),gatewayTimeout:(i="Gateway Timeout",l)=>D(504,i,l),httpVersionNotSupported:(i="HTTP Version Not Supported",l)=>D(505,i,l),variantAlsoNegotiates:(i="Variant Also Negotiates",l)=>D(506,i,l),insufficientStorage:(i="Insufficient Storage",l)=>D(507,i,l),loopDetected:(i="Loop Detected",l)=>D(508,i,l),notExtended:(i="Not Extended",l)=>D(510,i,l),networkAuthenticationRequired:(i="Network Authentication Required",l)=>D(511,i,l),invalidArgument:(i="Invalid Argument",l)=>D(C.UNPROCESSABLE_ENTITY,i,l),rateLimitExceeded:(i="Rate Limit Exceeded",l)=>D(429,i,l),maintenance:(i="Service Under Maintenance",l)=>D(503,i,l),custom:(i,l,f)=>D(i,l,f)}});var xi={};s(xi,{route:()=>Ei,createResponse:()=>b,APIError:()=>R});module.exports=Ni(xi);Y();Y();
package/dist/index.mjs CHANGED
@@ -1,21 +1,21 @@
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 U=(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:O}=i,_=(w)=>{let d=w?.headers.get("origin");return f===!0?d:f instanceof RegExp?f.test(d)?d:void 0:Array.isArray(f)?f.includes(d)?d:void 0:f instanceof Function?f(d):f=="*"&&l?d:f},N=(w,d)=>{for(let[I,L]of Object.entries(d))L&&w.headers.append(I,L);return w};return{corsify:(w,d)=>w?.headers?.get("access-control-allow-origin")||w.status==101?w:N(w.clone(),{"access-control-allow-origin":_(d),"access-control-allow-credentials":l}),preflight:(w)=>{if(w.method=="OPTIONS"){let d=new Response(null,{status:204});return N(d,{"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":O,"access-control-allow-credentials":l})}}}};var Y=U(()=>{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 R,Q,j;var V=U(()=>{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 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=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=U(()=>{V()});function $(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function r(i,f){var l="",E=0,A=-1,a=0,O;for(var _=0;_<=i.length;++_){if(_<i.length)O=i.charCodeAt(_);else if(O===47)break;else O=47;if(O===47){if(A===_-1||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(O===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($(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=r(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function n(i){if($(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=r(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Ai(i){return $(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($(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return n(i)}function G(i,f){if($(i),$(f),i===f)return"";if(i=x(i),f=x(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var E=i.length,A=E-l,a=1;for(;a<f.length;++a)if(f.charCodeAt(a)!==47)break;var O=f.length,_=O-a,N=A<_?A:_,w=-1,d=0;for(;d<=N;++d){if(d===N){if(_>N){if(f.charCodeAt(a+d)===47)return f.slice(a+d+1);else if(d===0)return f.slice(a+d)}else if(A>N){if(i.charCodeAt(l+d)===47)w=d;else if(d===0)w=0}break}var I=i.charCodeAt(l+d),L=f.charCodeAt(a+d);if(I!==L)break;else if(I===47)w=d}var P="";for(d=l+w+1;d<=E;++d)if(d===E||i.charCodeAt(d)===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($(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 Oi(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');$(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 O=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(O>=0)if(N===f.charCodeAt(O)){if(--O===-1)E=a}else O=-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 di(i){$(i);var f=-1,l=0,E=-1,A=!0,a=0;for(var O=i.length-1;O>=0;--O){var _=i.charCodeAt(O);if(_===47){if(!A){l=O+1;break}continue}if(E===-1)A=!1,E=O+1;if(_===46){if(f===-1)f=O;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){$(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,O=0,_=-1,N=!0,w=i.length-1,d=0;for(;w>=A;--w){if(l=i.charCodeAt(w),l===47){if(!N){O=w+1;break}continue}if(_===-1)N=!1,_=w+1;if(l===46){if(a===-1)a=w;else if(d!==1)d=1}else if(a!==-1)d=-1}if(a===-1||_===-1||d===0||d===1&&a===_-1&&a===O+1){if(_!==-1)if(O===0&&E)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(O,_)}else{if(O===0&&E)f.name=i.slice(1,a),f.base=i.slice(1,_);else f.name=i.slice(O,a),f.base=i.slice(O,_);f.ext=i.slice(a,_)}if(O>0)f.dir=i.slice(0,O-1);else if(E)f.dir="/";return f}var z="/",wi=":",Qi;var c=U(()=>{Qi=((i)=>(i.posix=i,i))({resolve:x,normalize:n,isAbsolute:Ai,join:W,relative:G,_makeLong:_i,dirname:M,basename:Oi,extname:di,format:Ni,parse:Di,sep:z,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)$/,""),d=`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 ${d}, { ${I.join(", ")} } from '${w}';`);else l.push(`import ${d} from '${w}';`);else if(I.length>0)l.push(`import { ${I.join(", ")} } from '${w}';`);for(let L of N){let P=L.name==="default"?d:L.name;a.push(` ${P},`)}}let O=`// This file is auto-generated. Do not edit manually.
1
+ var fi=Object.defineProperty;var ai=(i,l)=>{for(var f in l)fi(i,f,{get:l[f],enumerable:!0,configurable:!0,set:(a)=>l[f]=()=>a})};var R=(i,l)=>()=>(i&&(l=i(i=0)),l);var b=(i="text/plain; charset=utf-8",l)=>(f,a={})=>{if(f===void 0||f instanceof Response)return f;let E=new Response(l?.(f)??f,a.url?void 0:a);return E.headers.set("content-type",i),E},bi,hi,Si,xi,Gi,Fi,k=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},u=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((l)=>l.split(/=(.+)/)).reduce((l,[f,a])=>a?(l[f]=a,l):l,{})},F=(i={})=>{let{origin:l="*",credentials:f=!1,allowMethods:a="*",allowHeaders:E,exposeHeaders:A,maxAge:d}=i,_=(I)=>{let O=I?.headers.get("origin");return l===!0?O:l instanceof RegExp?l.test(O)?O:void 0:Array.isArray(l)?l.includes(O)?O:void 0:l instanceof Function?l(O):l=="*"&&f?O:l},N=(I,O)=>{for(let[w,L]of Object.entries(O))L&&I.headers.append(w,L);return I};return{corsify:(I,O)=>I?.headers?.get("access-control-allow-origin")||I.status==101?I:N(I.clone(),{"access-control-allow-origin":_(O),"access-control-allow-credentials":f}),preflight:(I)=>{if(I.method=="OPTIONS"){let O=new Response(null,{status:204});return N(O,{"access-control-allow-origin":_(I),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":E?.join?.(",")??E??I.headers.get("access-control-request-headers"),"access-control-max-age":d,"access-control-allow-credentials":f})}}}};var Y=R(()=>{bi=b("application/json; charset=utf-8",JSON.stringify),hi=b("text/plain; charset=utf-8",String),Si=b("text/html"),xi=b("image/jpeg"),Gi=b("image/png"),Fi=b("image/webp")});var C,Q,j;var V=R(()=>{C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},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 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 l=await this.protectedHandler(i);return i.authUser=l,l}catch(l){throw new Error(`Authentication failed: ${l instanceof Error?l.message:String(l)}`)}}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,l,f=Q.CACHE_TTL){if(f<=0)return l();if(this.cacheHandler)return this.cacheHandler(i,l,f);return this.getFromMemoryCache(i,l,f)}async getFromMemoryCache(i,l,f){let a=Date.now(),E=this.memoryCache.get(i);if(this.isCacheValid(E,a))return E.value;let A=await l();return this.setInMemoryCache(i,A,f),A}isCacheValid(i,l){return i!==void 0&&i.expires>l}setInMemoryCache(i,l,f){let a=Date.now()+f*1000;this.memoryCache.set(i,{value:l,expires:a}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[l,f]of this.memoryCache.entries())if(f.expires<=i)this.memoryCache.delete(l);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,l,f=Q.CACHE_TTL){if(f<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>l,f);return}this.setInMemoryCache(i,l,f)}delete(i){return this.memoryCache.delete(i)}has(i){let l=this.memoryCache.get(i);if(!l)return!1;if(l.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,l){let f=new URL(i.url);return[i.method,f.pathname,f.search,l?.authUser?.id||"anonymous"].join(":")}}var m=R(()=>{V()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function n(i,l){var f="",a=0,E=-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(E===_-1||A===1);else if(E!==_-1&&A===2){if(f.length<2||a!==2||f.charCodeAt(f.length-1)!==46||f.charCodeAt(f.length-2)!==46){if(f.length>2){var N=f.lastIndexOf("/");if(N!==f.length-1){if(N===-1)f="",a=0;else f=f.slice(0,N),a=f.length-1-f.lastIndexOf("/");E=_,A=0;continue}}else if(f.length===2||f.length===1){f="",a=0,E=_,A=0;continue}}if(l){if(f.length>0)f+="/..";else f="..";a=2}}else{if(f.length>0)f+="/"+i.slice(E+1,_);else f=i.slice(E+1,_);a=_-E-1}E=_,A=0}else if(d===46&&A!==-1)++A;else A=-1}return f}function Ai(i,l){var f=l.dir||l.root,a=l.base||(l.name||"")+(l.ext||"");if(!f)return a;if(f===l.root)return f+a;return f+i+a}function x(){var i="",l=!1,f;for(var a=arguments.length-1;a>=-1&&!l;a--){var E;if(a>=0)E=arguments[a];else{if(f===void 0)f=process.cwd();E=f}if(U(E),E.length===0)continue;i=E+"/"+i,l=E.charCodeAt(0)===47}if(i=n(i,!l),l)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function s(i){if(U(i),i.length===0)return".";var l=i.charCodeAt(0)===47,f=i.charCodeAt(i.length-1)===47;if(i=n(i,!l),i.length===0&&!l)i=".";if(i.length>0&&f)i+="/";if(l)return"/"+i;return i}function Ei(i){return U(i),i.length>0&&i.charCodeAt(0)===47}function W(){if(arguments.length===0)return".";var i;for(var l=0;l<arguments.length;++l){var f=arguments[l];if(U(f),f.length>0)if(i===void 0)i=f;else i+="/"+f}if(i===void 0)return".";return s(i)}function G(i,l){if(U(i),U(l),i===l)return"";if(i=x(i),l=x(l),i===l)return"";var f=1;for(;f<i.length;++f)if(i.charCodeAt(f)!==47)break;var a=i.length,E=a-f,A=1;for(;A<l.length;++A)if(l.charCodeAt(A)!==47)break;var d=l.length,_=d-A,N=E<_?E:_,I=-1,O=0;for(;O<=N;++O){if(O===N){if(_>N){if(l.charCodeAt(A+O)===47)return l.slice(A+O+1);else if(O===0)return l.slice(A+O)}else if(E>N){if(i.charCodeAt(f+O)===47)I=O;else if(O===0)I=0}break}var w=i.charCodeAt(f+O),L=l.charCodeAt(A+O);if(w!==L)break;else if(w===47)I=O}var P="";for(O=f+I+1;O<=a;++O)if(O===a||i.charCodeAt(O)===47)if(P.length===0)P+="..";else P+="/..";if(P.length>0)return P+l.slice(A+I);else{if(A+=I,l.charCodeAt(A)===47)++A;return l.slice(A)}}function _i(i){return i}function M(i){if(U(i),i.length===0)return".";var l=i.charCodeAt(0),f=l===47,a=-1,E=!0;for(var A=i.length-1;A>=1;--A)if(l=i.charCodeAt(A),l===47){if(!E){a=A;break}}else E=!1;if(a===-1)return f?"/":".";if(f&&a===1)return"//";return i.slice(0,a)}function di(i,l){if(l!==void 0&&typeof l!=="string")throw new TypeError('"ext" argument must be a string');U(i);var f=0,a=-1,E=!0,A;if(l!==void 0&&l.length>0&&l.length<=i.length){if(l.length===i.length&&l===i)return"";var d=l.length-1,_=-1;for(A=i.length-1;A>=0;--A){var N=i.charCodeAt(A);if(N===47){if(!E){f=A+1;break}}else{if(_===-1)E=!1,_=A+1;if(d>=0)if(N===l.charCodeAt(d)){if(--d===-1)a=A}else d=-1,a=_}}if(f===a)a=_;else if(a===-1)a=i.length;return i.slice(f,a)}else{for(A=i.length-1;A>=0;--A)if(i.charCodeAt(A)===47){if(!E){f=A+1;break}}else if(a===-1)E=!1,a=A+1;if(a===-1)return"";return i.slice(f,a)}}function Oi(i){U(i);var l=-1,f=0,a=-1,E=!0,A=0;for(var d=i.length-1;d>=0;--d){var _=i.charCodeAt(d);if(_===47){if(!E){f=d+1;break}continue}if(a===-1)E=!1,a=d+1;if(_===46){if(l===-1)l=d;else if(A!==1)A=1}else if(l!==-1)A=-1}if(l===-1||a===-1||A===0||A===1&&l===a-1&&l===f+1)return"";return i.slice(l,a)}function Ni(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return Ai("/",i)}function Di(i){U(i);var l={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return l;var f=i.charCodeAt(0),a=f===47,E;if(a)l.root="/",E=1;else E=0;var A=-1,d=0,_=-1,N=!0,I=i.length-1,O=0;for(;I>=E;--I){if(f=i.charCodeAt(I),f===47){if(!N){d=I+1;break}continue}if(_===-1)N=!1,_=I+1;if(f===46){if(A===-1)A=I;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&&a)l.base=l.name=i.slice(1,_);else l.base=l.name=i.slice(d,_)}else{if(d===0&&a)l.name=i.slice(1,A),l.base=i.slice(1,_);else l.name=i.slice(d,A),l.base=i.slice(d,_);l.ext=i.slice(A,_)}if(d>0)l.dir=i.slice(0,d-1);else if(a)l.dir="/";return l}var z="/",Ii=":",Qi;var K=R(()=>{Qi=((i)=>(i.posix=i,i))({resolve:x,normalize:s,isAbsolute:Ei,join:W,relative:G,_makeLong:_i,dirname:M,basename:di,extname:Oi,format:Ni,parse:Di,sep:z,delimiter:Ii,win32:null,posix:null})});var{promises:r}=(()=>({}));class Z{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let l=M(this.outputPath);await r.mkdir(l,{recursive:!0});let f=[],a=new Map;for(let _ of i){if(!a.has(_.path))a.set(_.path,[]);a.get(_.path).push(_)}let E=0,A=[];for(let[_,N]of a){let I=G(M(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),O=`route_${E++}`,w=N.filter((L)=>L.name!=="default").map((L)=>L.name);if(N.some((L)=>L.name==="default"))if(w.length>0)f.push(`import ${O}, { ${w.join(", ")} } from '${I}';`);else f.push(`import ${O} from '${I}';`);else if(w.length>0)f.push(`import { ${w.join(", ")} } from '${I}';`);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
- ${l.join(`
4
+ ${f.join(`
5
5
  `)}
6
6
 
7
7
  export const routes = [
8
- ${a.join(`
8
+ ${A.join(`
9
9
  `)}
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await s.writeFile(this.outputPath,O,"utf-8")}async generateDynamic(i){let f=[];for(let l of i){let E=JSON.stringify({method:l.method,path:l.options.path,options:l.options});f.push(` await import('${l.path}').then(m => ({
14
- ...${E},
15
- handler: m.${l.name==="default"?"default":l.name}
13
+ `;await r.writeFile(this.outputPath,d,"utf-8")}async generateDynamic(i){let l=[];for(let f of i){let a=JSON.stringify({method:f.method,path:f.options.path,options:f.options});l.push(` await import('${f.path}').then(m => ({
14
+ ...${a},
15
+ handler: m.${f.name==="default"?"default":f.name}
16
16
  }))`)}return`export const loadRoutes = async () => {
17
17
  return Promise.all([
18
- ${f.join(`,
18
+ ${l.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var y=U(()=>{c()});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[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let E=await q.readdir(i);for(let A of E){let a=W(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(z).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[d,I]of Object.entries(w)){if(d==="default")continue;if(I&&typeof I==="object"&&"entry"in I&&"options"in I&&"handler"in I){let L=I;f.push({name:d,path:a,method:L.options.method,options:L.options})}else if(Array.isArray(I)&&I.length>=4){let[L,,,P]=I;f.push({name:d,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=U(()=>{c()});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,O=i.split("/").filter(Boolean);for(let _ of O)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[O,_]of A.searchParams)a[O]=a[O]?[].concat(a[O],_):_;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,O=i.cache;if(O&&typeof O==="number"&&O>0){let N=this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),O)}else if(O&&typeof O==="object"&&O.ttl){let N=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});a=await this.cacheManager.get(N,()=>f(l),O.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 O=l.match(A);if(O){let _=i;if(!_.context)_.context={};_.params=O.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=U(()=>{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,idleTimeout:this.config.idleTimeout||60,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=U(()=>{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 X,this.cacheManager=new J,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=new Z(i),!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 O=a;this.router.route(O.options,O.handler),this.logRouteLoaded(O.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()}}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){}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=U(()=>{u();y();t();p();e();Li=h.getInstance});function Ri(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 Ui(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?Ui(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:O=j.JSON}=i;return async(_)=>{if(!E)return C.forbidden("Forbidden");try{if(l)await Ci(_,O);if(!A)await k(_);m(_);let N=await f(_);return a?N:$i.success(N,O)}catch(N){if(N instanceof Response)return N;return C.internalServerError(String(N),O)}}}var lf,af,$i,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=U(()=>{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}));$i={success:(i,f)=>b(R.OK,i,f),created:(i,f)=>b(R.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D(R.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D(R.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D(R.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D(R.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D(R.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D(R.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});B();B();export{Ri as route,b as createResponse,C as APIError};
21
+ };`}}var y=R(()=>{K()});var{existsSync:wi,promises:q}=(()=>({}));class c{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];if(!wi(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,i)}catch(l){if(l.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw l}return i}async scanDirectory(i,l,f=""){let a=await q.readdir(i);for(let E of a){let A=W(i,E);if((await q.stat(A)).isDirectory()){let _=f?`${f}/${E}`:E;await this.scanDirectory(A,l,_)}else if(E.endsWith(".ts")||E.endsWith(".js")){let _=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(z).join("/");try{let I=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(I.default&&typeof I.default==="function")l.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[O,w]of Object.entries(I)){if(O==="default")continue;if(w&&typeof w==="object"&&"entry"in w&&"options"in w&&"handler"in w){let L=w;l.push({name:O,path:A,method:L.options.method,options:L.options})}else if(Array.isArray(w)&&w.length>=4){let[L,,,P]=w;l.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(()=>{K()});class T{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let l=i;for(let f of this.beforeHandlers){let a=await f(l);if(a instanceof Response)return a;l=a}return l}async executeFinally(i,l){let f=i;for(let a of this.finallyHandlers)f=await a(f,l);return f}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,l,f){this.middlewareManager=i,this.authManager=l,this.cacheManager=f}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,l)=>{let f=this.extractPath(i),a=this.extractPath(l),E=this.getRouteSpecificity(f);return this.getRouteSpecificity(a)-E})}extractPath(i){return i[3]||""}route(i,l){let f=this.wrapHandler(i,l),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[f],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,l){return async(f)=>{let a=f;if(!a.context)a.context={};if(!a.query&&a.url){let E=new URL(a.url),A={};for(let[d,_]of E.searchParams)A[d]=A[d]?[].concat(A[d],_):_;a.query=A}if(i.metadata)a.metadata=i.metadata;f=a;try{if(i.expose===!1)return $.forbidden("Forbidden");let E=await this.middlewareManager.executeBefore(f);if(E instanceof Response)return E;if(f=E,i.auth)try{await this.authManager.authenticate(f)}catch(N){return $.unauthorized(N instanceof Error?N.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&f.method!=="GET"&&f.method!=="HEAD")try{let N=f.headers.get("content-type");if(N?.includes("application/json"))f.content=await f.json();else if(N?.includes("application/x-www-form-urlencoded"))f.content=Object.fromEntries(await f.formData());else if(N?.includes("multipart/form-data"))f.content=await f.formData();else f.content=await f.text()}catch{f.content=null}let A,d=i.cache;if(d&&typeof d==="number"&&d>0){let N=this.cacheManager.generateKey(f,{authUser:f.authUser});A=await this.cacheManager.get(N,()=>l(f),d)}else if(d&&typeof d==="object"&&d.ttl){let N=d.key||this.cacheManager.generateKey(f,{authUser:f.authUser});A=await this.cacheManager.get(N,()=>l(f),d.ttl)}else A=await l(f);let _;if(i.rawResponse||A instanceof Response)_=A instanceof Response?A:new Response(A);else _=h(200,A,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,f),_}catch(E){if(E instanceof Response)return E;return console.error("Route handler error:",E),$.internalServerError(E instanceof Error?E.message:String(E),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let f=new URL(i.url).pathname;for(let[a,E,A]of this.routes)if(i.method==="OPTIONS"||i.method===a){let d=f.match(E);if(d){let _=i;if(!_.context)_.context={};_.params=d.groups||{};for(let N of A){let I=await N(_);if(I)return I}}}return $.notFound("Route not found")}clearRoutes(){this.routes=[]}}var p=R(()=>{B()});class g{server=null;router;config;corsHandler;constructor(i,l){if(this.router=i,this.config=l,l.cors){let{preflight:f,corsify:a}=F(this.normalizeCorsOptions(l.cors));this.corsHandler={preflight:f,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,l=this.config.hostname||"localhost",f=async(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let E=await this.router.handle(a);if(this.corsHandler)E=this.corsHandler.corsify(E,a);return E}catch(E){return console.error("Server error:",E),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:i,hostname:l,reusePort:this.config.reusePort!==!1,fetch:f,idleTimeout:this.config.idleTimeout||60,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${l}:${i} - server object is invalid`);return console.log(`→ Vector server running at http://${l}:${i}`),this.server}catch(a){if(a.code==="EADDRINUSE"||a.message?.includes("address already in use"))a.message=`Port ${i} is already in use`,a.port=i;else if(a.code==="EACCES"||a.message?.includes("permission denied"))a.message=`Permission denied to bind to port ${i}`,a.port=i;else if(a.message?.includes("EADDRNOTAVAIL"))a.message=`Cannot bind to hostname ${l}`,a.hostname=l;throw a}}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 X,this.cacheManager=new J,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,l){return this.router.route(i,l)}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=new c(i),!this.routeGenerator)this.routeGenerator=new Z;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let f of l)try{let E=await import(o(f.path)),A=f.name==="default"?E.default:E[f.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(f.options,A),this.logRouteLoaded(f.options)}}catch(a){console.error(`Failed to load route ${f.name} from ${f.path}:`,a)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(i){if(typeof i==="function"){let l=i();if(Array.isArray(l))this.router.addRoute(l)}else if(i&&typeof i==="object"){for(let[,l]of Object.entries(i))if(typeof l==="function"){let f=l();if(Array.isArray(f))this.router.addRoute(f)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}isRouteDefinition(i){return i&&typeof i==="object"&&"entry"in i&&"options"in i&&"handler"in i}logRouteLoaded(i){}stop(){if(this.server)this.server.stop(),this.server=null;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 li=R(()=>{m();y();t();p();e();Li=H.getInstance});function Ci(i,l){let f=Pi(i,l);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.*)?")}/*$`),[f],i.path],options:i,handler:l}}function Ri(i){return JSON.stringify(i??null,(l,f)=>typeof f==="bigint"?f.toString():f)}function D(i,l,f){let a={error:!0,message:l,statusCode:i,timestamp:new Date().toISOString()};return h(i,a,f)}function h(i,l,f=j.JSON){let a=f===j.JSON?Ri(l):l;return new Response(a,{status:i,headers:{"content-type":f}})}function Pi(i,l){let{auth:f=!1,expose:a=!1,rawRequest:E=!1,rawResponse:A=!1,responseContentType:d=j.JSON}=i;return async(_)=>{if(!a)return $.forbidden("Forbidden");try{if(f)await $i(_,d);if(!E)await k(_);u(_);let N=await l(_);return A?N:Ui.success(N,d)}catch(N){if(N instanceof Response)return N;return $.internalServerError(String(N),d)}}}var ll,fl,Ui,$,$i=async(i,l)=>{let{getVectorInstance:f}=await Promise.resolve().then(() => (li(),ii)),E=f().getProtectedHandler();if(!E)throw $.unauthorized("Authentication not configured",l);try{let A=await E(i);i.authUser=A}catch(A){throw $.unauthorized(A instanceof Error?A.message:"Authentication failed",l)}};var B=R(()=>{Y();V();({preflight:ll,corsify:fl}=F({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,l)=>h(C.OK,i,l),created:(i,l)=>h(C.CREATED,i,l)};$={badRequest:(i="Bad Request",l)=>D(C.BAD_REQUEST,i,l),unauthorized:(i="Unauthorized",l)=>D(C.UNAUTHORIZED,i,l),paymentRequired:(i="Payment Required",l)=>D(402,i,l),forbidden:(i="Forbidden",l)=>D(C.FORBIDDEN,i,l),notFound:(i="Not Found",l)=>D(C.NOT_FOUND,i,l),methodNotAllowed:(i="Method Not Allowed",l)=>D(405,i,l),notAcceptable:(i="Not Acceptable",l)=>D(406,i,l),requestTimeout:(i="Request Timeout",l)=>D(408,i,l),conflict:(i="Conflict",l)=>D(C.CONFLICT,i,l),gone:(i="Gone",l)=>D(410,i,l),lengthRequired:(i="Length Required",l)=>D(411,i,l),preconditionFailed:(i="Precondition Failed",l)=>D(412,i,l),payloadTooLarge:(i="Payload Too Large",l)=>D(413,i,l),uriTooLong:(i="URI Too Long",l)=>D(414,i,l),unsupportedMediaType:(i="Unsupported Media Type",l)=>D(415,i,l),rangeNotSatisfiable:(i="Range Not Satisfiable",l)=>D(416,i,l),expectationFailed:(i="Expectation Failed",l)=>D(417,i,l),imATeapot:(i="I'm a teapot",l)=>D(418,i,l),misdirectedRequest:(i="Misdirected Request",l)=>D(421,i,l),unprocessableEntity:(i="Unprocessable Entity",l)=>D(C.UNPROCESSABLE_ENTITY,i,l),locked:(i="Locked",l)=>D(423,i,l),failedDependency:(i="Failed Dependency",l)=>D(424,i,l),tooEarly:(i="Too Early",l)=>D(425,i,l),upgradeRequired:(i="Upgrade Required",l)=>D(426,i,l),preconditionRequired:(i="Precondition Required",l)=>D(428,i,l),tooManyRequests:(i="Too Many Requests",l)=>D(429,i,l),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",l)=>D(431,i,l),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",l)=>D(451,i,l),internalServerError:(i="Internal Server Error",l)=>D(C.INTERNAL_SERVER_ERROR,i,l),notImplemented:(i="Not Implemented",l)=>D(501,i,l),badGateway:(i="Bad Gateway",l)=>D(502,i,l),serviceUnavailable:(i="Service Unavailable",l)=>D(503,i,l),gatewayTimeout:(i="Gateway Timeout",l)=>D(504,i,l),httpVersionNotSupported:(i="HTTP Version Not Supported",l)=>D(505,i,l),variantAlsoNegotiates:(i="Variant Also Negotiates",l)=>D(506,i,l),insufficientStorage:(i="Insufficient Storage",l)=>D(507,i,l),loopDetected:(i="Loop Detected",l)=>D(508,i,l),notExtended:(i="Not Extended",l)=>D(510,i,l),networkAuthenticationRequired:(i="Network Authentication Required",l)=>D(511,i,l),invalidArgument:(i="Invalid Argument",l)=>D(C.UNPROCESSABLE_ENTITY,i,l),rateLimitExceeded:(i="Rate Limit Exceeded",l)=>D(429,i,l),maintenance:(i="Service Under Maintenance",l)=>D(503,i,l),custom:(i,l,f)=>D(i,l,f)}});B();B();export{Ci as route,h as createResponse,$ as APIError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vector-framework",
3
- "version": "0.9.6",
3
+ "version": "0.9.7",
4
4
  "author": "",
5
5
  "repository": {
6
6
  "type": "git",
package/src/cli/index.ts CHANGED
@@ -56,80 +56,97 @@ async function runDev() {
56
56
  let server: any = null;
57
57
  let vector: any = null;
58
58
 
59
- async function startServer() {
60
- try {
61
- // Load configuration using ConfigLoader
62
- const configLoader = new ConfigLoader(values.config as string | undefined);
63
- const config = await configLoader.load();
64
- const configSource = configLoader.getConfigSource();
65
-
66
- // Merge CLI options with loaded config
67
- // Only use CLI values if config doesn't have them
68
- config.port = config.port ?? Number.parseInt(values.port as string);
69
- config.hostname = config.hostname ?? (values.host as string);
70
- config.routesDir = config.routesDir ?? (values.routes as string);
71
- config.development = config.development ?? isDev;
72
- config.autoDiscover = true; // Always auto-discover routes
73
-
74
- // Apply CLI CORS option if not set in config
75
- if (!config.cors && values.cors) {
76
- config.cors = {
77
- origin: "*",
78
- credentials: true,
79
- allowHeaders: "Content-Type, Authorization",
80
- allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
81
- exposeHeaders: "Authorization",
82
- maxAge: 86400,
83
- };
84
- }
59
+ async function startServer(): Promise<{ server: any; vector: any; config: any }> {
60
+ // Create a timeout promise that rejects after 10 seconds
61
+ const timeoutPromise = new Promise<never>((_, reject) => {
62
+ setTimeout(() => {
63
+ reject(new Error("Server startup timed out (10s)"));
64
+ }, 10000);
65
+ });
66
+
67
+ // Create the actual server start promise
68
+ const serverStartPromise = (async (): Promise<{ server: any; vector: any; config: any }> => {
69
+ try {
70
+ // Load configuration using ConfigLoader
71
+ const configLoader = new ConfigLoader(values.config as string | undefined);
72
+ const config = await configLoader.load();
73
+ const configSource = configLoader.getConfigSource();
74
+
75
+ // Merge CLI options with loaded config
76
+ // Only use CLI values if config doesn't have them
77
+ config.port = config.port ?? Number.parseInt(values.port as string);
78
+ config.hostname = config.hostname ?? (values.host as string);
79
+ config.routesDir = config.routesDir ?? (values.routes as string);
80
+ config.development = config.development ?? isDev;
81
+ config.autoDiscover = true; // Always auto-discover routes
82
+
83
+ // Apply CLI CORS option if not set in config
84
+ if (!config.cors && values.cors) {
85
+ config.cors = {
86
+ origin: "*",
87
+ credentials: true,
88
+ allowHeaders: "Content-Type, Authorization",
89
+ allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
90
+ exposeHeaders: "Authorization",
91
+ maxAge: 86400,
92
+ };
93
+ }
85
94
 
86
- // Get Vector instance and configure handlers
87
- vector = getVectorInstance();
95
+ // Get Vector instance and configure handlers
96
+ vector = getVectorInstance();
88
97
 
89
- // Load and set auth handler if configured
90
- const authHandler = await configLoader.loadAuthHandler();
91
- if (authHandler) {
92
- vector.setProtectedHandler(authHandler);
93
- }
98
+ // Load and set auth handler if configured
99
+ const authHandler = await configLoader.loadAuthHandler();
100
+ if (authHandler) {
101
+ vector.setProtectedHandler(authHandler);
102
+ }
94
103
 
95
- // Load and set cache handler if configured
96
- const cacheHandler = await configLoader.loadCacheHandler();
97
- if (cacheHandler) {
98
- vector.setCacheHandler(cacheHandler);
99
- }
104
+ // Load and set cache handler if configured
105
+ const cacheHandler = await configLoader.loadCacheHandler();
106
+ if (cacheHandler) {
107
+ vector.setCacheHandler(cacheHandler);
108
+ }
100
109
 
101
- // Start the server
102
- server = await vector.startServer(config);
110
+ // Start the server
111
+ server = await vector.startServer(config);
103
112
 
104
- const gray = "\x1b[90m";
105
- const reset = "\x1b[0m";
106
- const cyan = "\x1b[36m";
107
- const green = "\x1b[32m";
113
+ // Verify the server is actually running
114
+ if (!server || !server.port) {
115
+ throw new Error("Server started but is not responding correctly");
116
+ }
108
117
 
109
- console.log(
110
- ` ${gray}Config${reset} ${
111
- configSource === "user" ? "User config loaded" : "Using defaults"
112
- }`
113
- );
114
- console.log(` ${gray}Routes${reset} ${config.routesDir}`);
115
- if (isDev && values.watch) {
116
- console.log(` ${gray}Watching${reset} All project files`);
118
+ const gray = "\x1b[90m";
119
+ const reset = "\x1b[0m";
120
+ const cyan = "\x1b[36m";
121
+ const green = "\x1b[32m";
122
+
123
+ console.log(
124
+ ` ${gray}Config${reset} ${
125
+ configSource === "user" ? "User config loaded" : "Using defaults"
126
+ }`
127
+ );
128
+ console.log(` ${gray}Routes${reset} ${config.routesDir}`);
129
+ if (isDev && values.watch) {
130
+ console.log(` ${gray}Watching${reset} All project files`);
131
+ }
132
+ console.log(
133
+ ` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`
134
+ );
135
+ console.log(
136
+ ` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}\n`
137
+ );
138
+ console.log(
139
+ ` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`
140
+ );
141
+
142
+ return { server, vector, config };
143
+ } catch (error) {
144
+ throw error;
117
145
  }
118
- console.log(
119
- ` ${gray}CORS${reset} ${config.cors ? "Enabled" : "Disabled"}`
120
- );
121
- console.log(
122
- ` ${gray}Mode${reset} ${config.development ? "Development" : "Production"}\n`
123
- );
124
- console.log(
125
- ` ${green}Ready${reset} → ${cyan}http://${config.hostname}:${config.port}${reset}\n`
126
- );
146
+ })();
127
147
 
128
- return { server, vector, config };
129
- } catch (error) {
130
- console.error("[ERROR] Failed to start server:", error);
131
- throw error;
132
- }
148
+ // Race between server startup and timeout
149
+ return await Promise.race([serverStartPromise, timeoutPromise]);
133
150
  }
134
151
 
135
152
  try {
@@ -200,8 +217,9 @@ async function runDev() {
200
217
  const result = await startServer();
201
218
  server = result.server;
202
219
  vector = result.vector;
203
- } catch (error) {
204
- console.error(" Failed to reload server:", error);
220
+ } catch (error: any) {
221
+ console.error("\n[Reload Error]", error.message || error);
222
+ // Don't exit the process on reload failures, just continue watching
205
223
  } finally {
206
224
  // Reset flag after a delay
207
225
  setTimeout(() => {
@@ -215,8 +233,26 @@ async function runDev() {
215
233
  console.warn(" ⚠️ File watching not available");
216
234
  }
217
235
  }
218
- } catch (error) {
219
- console.error("[ERROR] Failed to start server:", error);
236
+ } catch (error: any) {
237
+ const red = "\x1b[31m";
238
+ const reset = "\x1b[0m";
239
+
240
+ console.error(`\n${red}[ERROR] Failed to start server${reset}\n`);
241
+
242
+ // Always show the error message and stack trace
243
+ if (error.message) {
244
+ console.error(`Message: ${error.message}`);
245
+ }
246
+
247
+ if (error.stack) {
248
+ console.error(`\nStack trace:`);
249
+ console.error(error.stack);
250
+ } else if (!error.message) {
251
+ // If no message or stack, show the raw error
252
+ console.error(`Raw error:`, error);
253
+ }
254
+
255
+ // Ensure we exit with error code
220
256
  process.exit(1);
221
257
  }
222
258
  }
@@ -69,22 +69,43 @@ export class VectorServer<TTypes extends VectorTypes = DefaultVectorTypes> {
69
69
  }
70
70
  };
71
71
 
72
- this.server = Bun.serve({
73
- port,
74
- hostname,
75
- reusePort: this.config.reusePort !== false,
76
- fetch,
77
- idleTimeout: this.config.idleTimeout || 60,
78
- error: (error) => {
79
- console.error("[ERROR] Server error:", error);
80
- return new Response("Internal Server Error", { status: 500 });
81
- },
82
- });
72
+ try {
73
+ this.server = Bun.serve({
74
+ port,
75
+ hostname,
76
+ reusePort: this.config.reusePort !== false,
77
+ fetch,
78
+ idleTimeout: this.config.idleTimeout || 60,
79
+ error: (error) => {
80
+ console.error("[ERROR] Server error:", error);
81
+ return new Response("Internal Server Error", { status: 500 });
82
+ },
83
+ });
84
+
85
+ // Validate that the server actually started
86
+ if (!this.server || !this.server.port) {
87
+ throw new Error(`Failed to start server on ${hostname}:${port} - server object is invalid`);
88
+ }
83
89
 
84
- // Server logs are handled by CLI, keep this minimal
85
- console.log(`→ Vector server running at http://${hostname}:${port}`);
90
+ // Server logs are handled by CLI, keep this minimal
91
+ console.log(`→ Vector server running at http://${hostname}:${port}`);
92
+
93
+ return this.server;
94
+ } catch (error: any) {
95
+ // Enhance error message with context for common issues
96
+ if (error.code === 'EADDRINUSE' || error.message?.includes('address already in use')) {
97
+ error.message = `Port ${port} is already in use`;
98
+ error.port = port;
99
+ } else if (error.code === 'EACCES' || error.message?.includes('permission denied')) {
100
+ error.message = `Permission denied to bind to port ${port}`;
101
+ error.port = port;
102
+ } else if (error.message?.includes('EADDRNOTAVAIL')) {
103
+ error.message = `Cannot bind to hostname ${hostname}`;
104
+ error.hostname = hostname;
105
+ }
86
106
 
87
- return this.server;
107
+ throw error;
108
+ }
88
109
  }
89
110
 
90
111
  stop() {