vector-framework 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +508 -0
  3. package/dist/auth/protected.d.ts +9 -0
  4. package/dist/auth/protected.d.ts.map +1 -0
  5. package/dist/auth/protected.js +26 -0
  6. package/dist/auth/protected.js.map +1 -0
  7. package/dist/cache/manager.d.ts +21 -0
  8. package/dist/cache/manager.d.ts.map +1 -0
  9. package/dist/cache/manager.js +92 -0
  10. package/dist/cache/manager.js.map +1 -0
  11. package/dist/cli/index.d.ts +3 -0
  12. package/dist/cli/index.d.ts.map +1 -0
  13. package/dist/cli/index.js +142 -0
  14. package/dist/cli/index.js.map +1 -0
  15. package/dist/constants/index.d.ts +84 -0
  16. package/dist/constants/index.d.ts.map +1 -0
  17. package/dist/constants/index.js +88 -0
  18. package/dist/constants/index.js.map +1 -0
  19. package/dist/core/router.d.ts +26 -0
  20. package/dist/core/router.d.ts.map +1 -0
  21. package/dist/core/router.js +208 -0
  22. package/dist/core/router.js.map +1 -0
  23. package/dist/core/server.d.ts +18 -0
  24. package/dist/core/server.d.ts.map +1 -0
  25. package/dist/core/server.js +89 -0
  26. package/dist/core/server.js.map +1 -0
  27. package/dist/core/vector.d.ts +43 -0
  28. package/dist/core/vector.d.ts.map +1 -0
  29. package/dist/core/vector.js +179 -0
  30. package/dist/core/vector.js.map +1 -0
  31. package/dist/dev/route-generator.d.ts +8 -0
  32. package/dist/dev/route-generator.d.ts.map +1 -0
  33. package/dist/dev/route-generator.js +77 -0
  34. package/dist/dev/route-generator.js.map +1 -0
  35. package/dist/dev/route-scanner.d.ts +9 -0
  36. package/dist/dev/route-scanner.d.ts.map +1 -0
  37. package/dist/dev/route-scanner.js +85 -0
  38. package/dist/dev/route-scanner.js.map +1 -0
  39. package/dist/errors/index.d.ts +24 -0
  40. package/dist/errors/index.d.ts.map +1 -0
  41. package/dist/errors/index.js +73 -0
  42. package/dist/errors/index.js.map +1 -0
  43. package/dist/http.d.ts +73 -0
  44. package/dist/http.d.ts.map +1 -0
  45. package/dist/http.js +143 -0
  46. package/dist/http.js.map +1 -0
  47. package/dist/index.d.ts +13 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +21 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/index.mjs +21 -0
  52. package/dist/middleware/manager.d.ts +11 -0
  53. package/dist/middleware/manager.d.ts.map +1 -0
  54. package/dist/middleware/manager.js +35 -0
  55. package/dist/middleware/manager.js.map +1 -0
  56. package/dist/types/index.d.ts +85 -0
  57. package/dist/types/index.d.ts.map +1 -0
  58. package/dist/types/index.js +2 -0
  59. package/dist/types/index.js.map +1 -0
  60. package/dist/utils/logger.d.ts +25 -0
  61. package/dist/utils/logger.d.ts.map +1 -0
  62. package/dist/utils/logger.js +68 -0
  63. package/dist/utils/logger.js.map +1 -0
  64. package/dist/utils/validation.d.ts +5 -0
  65. package/dist/utils/validation.d.ts.map +1 -0
  66. package/dist/utils/validation.js +48 -0
  67. package/dist/utils/validation.js.map +1 -0
  68. package/package.json +110 -0
  69. package/src/auth/protected.ts +41 -0
  70. package/src/cache/manager.ts +133 -0
  71. package/src/cli/index.ts +157 -0
  72. package/src/constants/index.ts +93 -0
  73. package/src/core/router.ts +258 -0
  74. package/src/core/server.ts +107 -0
  75. package/src/core/vector.ts +228 -0
  76. package/src/dev/route-generator.ts +93 -0
  77. package/src/dev/route-scanner.ts +97 -0
  78. package/src/errors/index.ts +91 -0
  79. package/src/http.ts +331 -0
  80. package/src/index.ts +19 -0
  81. package/src/middleware/manager.ts +53 -0
  82. package/src/types/index.ts +126 -0
  83. package/src/utils/logger.ts +87 -0
  84. package/src/utils/validation.ts +58 -0
package/dist/http.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { type IRequest, type RouteEntry } from "itty-router";
2
+ import type { DefaultVectorTypes, GetAuthType, VectorRequest, VectorTypes } from "./types";
3
+ export interface ProtectedRequest<TTypes extends VectorTypes = DefaultVectorTypes> extends IRequest {
4
+ authUser?: GetAuthType<TTypes>;
5
+ }
6
+ export declare const preflight: (request: Request) => Response | undefined, corsify: (response: Response, request?: Request) => Response;
7
+ interface ExtendedApiOptions extends ApiOptions {
8
+ method: string;
9
+ path: string;
10
+ }
11
+ export declare function route<TTypes extends VectorTypes = DefaultVectorTypes>(options: ExtendedApiOptions, fn: (req: VectorRequest<TTypes>) => Promise<unknown>): RouteEntry;
12
+ declare const ApiResponse: {
13
+ success: <T>(data: T, contentType?: string) => Response;
14
+ created: <T>(data: T, contentType?: string) => Response;
15
+ };
16
+ export declare const APIError: {
17
+ badRequest: (msg?: string, contentType?: string) => Response;
18
+ unauthorized: (msg?: string, contentType?: string) => Response;
19
+ paymentRequired: (msg?: string, contentType?: string) => Response;
20
+ forbidden: (msg?: string, contentType?: string) => Response;
21
+ notFound: (msg?: string, contentType?: string) => Response;
22
+ methodNotAllowed: (msg?: string, contentType?: string) => Response;
23
+ notAcceptable: (msg?: string, contentType?: string) => Response;
24
+ requestTimeout: (msg?: string, contentType?: string) => Response;
25
+ conflict: (msg?: string, contentType?: string) => Response;
26
+ gone: (msg?: string, contentType?: string) => Response;
27
+ lengthRequired: (msg?: string, contentType?: string) => Response;
28
+ preconditionFailed: (msg?: string, contentType?: string) => Response;
29
+ payloadTooLarge: (msg?: string, contentType?: string) => Response;
30
+ uriTooLong: (msg?: string, contentType?: string) => Response;
31
+ unsupportedMediaType: (msg?: string, contentType?: string) => Response;
32
+ rangeNotSatisfiable: (msg?: string, contentType?: string) => Response;
33
+ expectationFailed: (msg?: string, contentType?: string) => Response;
34
+ imATeapot: (msg?: string, contentType?: string) => Response;
35
+ misdirectedRequest: (msg?: string, contentType?: string) => Response;
36
+ unprocessableEntity: (msg?: string, contentType?: string) => Response;
37
+ locked: (msg?: string, contentType?: string) => Response;
38
+ failedDependency: (msg?: string, contentType?: string) => Response;
39
+ tooEarly: (msg?: string, contentType?: string) => Response;
40
+ upgradeRequired: (msg?: string, contentType?: string) => Response;
41
+ preconditionRequired: (msg?: string, contentType?: string) => Response;
42
+ tooManyRequests: (msg?: string, contentType?: string) => Response;
43
+ requestHeaderFieldsTooLarge: (msg?: string, contentType?: string) => Response;
44
+ unavailableForLegalReasons: (msg?: string, contentType?: string) => Response;
45
+ internalServerError: (msg?: string, contentType?: string) => Response;
46
+ notImplemented: (msg?: string, contentType?: string) => Response;
47
+ badGateway: (msg?: string, contentType?: string) => Response;
48
+ serviceUnavailable: (msg?: string, contentType?: string) => Response;
49
+ gatewayTimeout: (msg?: string, contentType?: string) => Response;
50
+ httpVersionNotSupported: (msg?: string, contentType?: string) => Response;
51
+ variantAlsoNegotiates: (msg?: string, contentType?: string) => Response;
52
+ insufficientStorage: (msg?: string, contentType?: string) => Response;
53
+ loopDetected: (msg?: string, contentType?: string) => Response;
54
+ notExtended: (msg?: string, contentType?: string) => Response;
55
+ networkAuthenticationRequired: (msg?: string, contentType?: string) => Response;
56
+ invalidArgument: (msg?: string, contentType?: string) => Response;
57
+ rateLimitExceeded: (msg?: string, contentType?: string) => Response;
58
+ maintenance: (msg?: string, contentType?: string) => Response;
59
+ custom: (statusCode: number, msg: string, contentType?: string) => Response;
60
+ };
61
+ export declare function createResponse(statusCode: number, data?: unknown, contentType?: string): Response;
62
+ export declare const protectedRoute: <TTypes extends VectorTypes = DefaultVectorTypes>(request: VectorRequest<TTypes>, responseContentType?: string) => Promise<void>;
63
+ export interface ApiOptions {
64
+ auth?: boolean;
65
+ expose?: boolean;
66
+ rawRequest?: boolean;
67
+ rawResponse?: boolean;
68
+ cache?: number | null;
69
+ responseContentType?: string;
70
+ }
71
+ export declare function api<TTypes extends VectorTypes = DefaultVectorTypes>(options: ApiOptions, fn: (request: VectorRequest<TTypes>) => Promise<unknown>): (request: IRequest) => Promise<unknown>;
72
+ export default ApiResponse;
73
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","source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,MAAM;iDAGjB,MAAM;6CAGd,MAAM;qDAGU,MAAM;iDAGd,MAAM;0DAK9C,MAAM;wDAKN,MAAM;sDAG4C,MAAM;+CAGpB,MAAM;8CAGR,MAAM;gEAKxC,MAAM;kDAIoC,MAAM;oDAGD,MAAM;8CAGN,MAAM;yBAIhD,MAAM,OAAO,MAAM,gBAAgB,MAAM;CAE/D,CAAC;AAEF,wBAAgB,cAAc,CAC5B,UAAU,EAAE,MAAM,EAClB,IAAI,CAAC,EAAE,OAAO,EACd,WAAW,GAAE,MAA2B,GACvC,QAAQ,CAOV;AAED,eAAO,MAAM,cAAc,GACzB,MAAM,SAAS,WAAW,GAAG,kBAAkB,EAE/C,SAAS,aAAa,CAAC,MAAM,CAAC,EAC9B,sBAAsB,MAAM,kBAqB7B,CAAC;AAEF,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,wBAAgB,GAAG,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB,EACjE,OAAO,EAAE,UAAU,EACnB,EAAE,EAAE,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,IAU1C,SAAS,QAAQ,sBAkChC;AAED,eAAe,WAAW,CAAC"}
package/dist/http.js ADDED
@@ -0,0 +1,143 @@
1
+ import { cors, withContent, withCookies, } from "itty-router";
2
+ import { CONTENT_TYPES, HTTP_STATUS } from "./constants";
3
+ export const { preflight, corsify } = cors({
4
+ origin: "*",
5
+ credentials: true,
6
+ allowHeaders: "Content-Type, Authorization",
7
+ allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
8
+ exposeHeaders: "Authorization",
9
+ maxAge: 86_400,
10
+ });
11
+ export function route(options, fn) {
12
+ const handler = api(options, fn);
13
+ return [
14
+ options.method.toUpperCase(),
15
+ RegExp(`^${options.path
16
+ .replace(/\/+(\/|$)/g, "$1") // strip double & trailing splash
17
+ .replace(/(\/?\.?):(\w+)\+/g, "($1(?<$2>*))") // greedy params
18
+ .replace(/(\/?\.?):(\w+)/g, "($1(?<$2>[^$1/]+?))") // named params and image format
19
+ .replace(/\./g, "\\.") // dot in path
20
+ .replace(/(\/?)\*/g, "($1.*)?") // wildcard
21
+ }/*$`),
22
+ [handler],
23
+ options.path,
24
+ ];
25
+ }
26
+ function stringifyData(data) {
27
+ return JSON.stringify(data ?? null, (_key, value) => typeof value === "bigint" ? value.toString() : value);
28
+ }
29
+ const ApiResponse = {
30
+ success: (data, contentType) => createResponse(HTTP_STATUS.OK, data, contentType),
31
+ created: (data, contentType) => createResponse(HTTP_STATUS.CREATED, data, contentType),
32
+ };
33
+ function createErrorResponse(code, message, contentType) {
34
+ const errorBody = {
35
+ error: true,
36
+ message,
37
+ statusCode: code,
38
+ timestamp: new Date().toISOString(),
39
+ };
40
+ return createResponse(code, errorBody, contentType);
41
+ }
42
+ export const APIError = {
43
+ // 4xx Client Errors
44
+ badRequest: (msg = "Bad Request", contentType) => createErrorResponse(HTTP_STATUS.BAD_REQUEST, msg, contentType),
45
+ unauthorized: (msg = "Unauthorized", contentType) => createErrorResponse(HTTP_STATUS.UNAUTHORIZED, msg, contentType),
46
+ paymentRequired: (msg = "Payment Required", contentType) => createErrorResponse(402, msg, contentType),
47
+ forbidden: (msg = "Forbidden", contentType) => createErrorResponse(HTTP_STATUS.FORBIDDEN, msg, contentType),
48
+ notFound: (msg = "Not Found", contentType) => createErrorResponse(HTTP_STATUS.NOT_FOUND, msg, contentType),
49
+ methodNotAllowed: (msg = "Method Not Allowed", contentType) => createErrorResponse(405, msg, contentType),
50
+ notAcceptable: (msg = "Not Acceptable", contentType) => createErrorResponse(406, msg, contentType),
51
+ requestTimeout: (msg = "Request Timeout", contentType) => createErrorResponse(408, msg, contentType),
52
+ conflict: (msg = "Conflict", contentType) => createErrorResponse(HTTP_STATUS.CONFLICT, msg, contentType),
53
+ gone: (msg = "Gone", contentType) => createErrorResponse(410, msg, contentType),
54
+ lengthRequired: (msg = "Length Required", contentType) => createErrorResponse(411, msg, contentType),
55
+ preconditionFailed: (msg = "Precondition Failed", contentType) => createErrorResponse(412, msg, contentType),
56
+ payloadTooLarge: (msg = "Payload Too Large", contentType) => createErrorResponse(413, msg, contentType),
57
+ uriTooLong: (msg = "URI Too Long", contentType) => createErrorResponse(414, msg, contentType),
58
+ unsupportedMediaType: (msg = "Unsupported Media Type", contentType) => createErrorResponse(415, msg, contentType),
59
+ rangeNotSatisfiable: (msg = "Range Not Satisfiable", contentType) => createErrorResponse(416, msg, contentType),
60
+ expectationFailed: (msg = "Expectation Failed", contentType) => createErrorResponse(417, msg, contentType),
61
+ imATeapot: (msg = "I'm a teapot", contentType) => createErrorResponse(418, msg, contentType),
62
+ misdirectedRequest: (msg = "Misdirected Request", contentType) => createErrorResponse(421, msg, contentType),
63
+ unprocessableEntity: (msg = "Unprocessable Entity", contentType) => createErrorResponse(HTTP_STATUS.UNPROCESSABLE_ENTITY, msg, contentType),
64
+ locked: (msg = "Locked", contentType) => createErrorResponse(423, msg, contentType),
65
+ failedDependency: (msg = "Failed Dependency", contentType) => createErrorResponse(424, msg, contentType),
66
+ tooEarly: (msg = "Too Early", contentType) => createErrorResponse(425, msg, contentType),
67
+ upgradeRequired: (msg = "Upgrade Required", contentType) => createErrorResponse(426, msg, contentType),
68
+ preconditionRequired: (msg = "Precondition Required", contentType) => createErrorResponse(428, msg, contentType),
69
+ tooManyRequests: (msg = "Too Many Requests", contentType) => createErrorResponse(429, msg, contentType),
70
+ requestHeaderFieldsTooLarge: (msg = "Request Header Fields Too Large", contentType) => createErrorResponse(431, msg, contentType),
71
+ unavailableForLegalReasons: (msg = "Unavailable For Legal Reasons", contentType) => createErrorResponse(451, msg, contentType),
72
+ // 5xx Server Errors
73
+ internalServerError: (msg = "Internal Server Error", contentType) => createErrorResponse(HTTP_STATUS.INTERNAL_SERVER_ERROR, msg, contentType),
74
+ notImplemented: (msg = "Not Implemented", contentType) => createErrorResponse(501, msg, contentType),
75
+ badGateway: (msg = "Bad Gateway", contentType) => createErrorResponse(502, msg, contentType),
76
+ serviceUnavailable: (msg = "Service Unavailable", contentType) => createErrorResponse(503, msg, contentType),
77
+ gatewayTimeout: (msg = "Gateway Timeout", contentType) => createErrorResponse(504, msg, contentType),
78
+ httpVersionNotSupported: (msg = "HTTP Version Not Supported", contentType) => createErrorResponse(505, msg, contentType),
79
+ variantAlsoNegotiates: (msg = "Variant Also Negotiates", contentType) => createErrorResponse(506, msg, contentType),
80
+ insufficientStorage: (msg = "Insufficient Storage", contentType) => createErrorResponse(507, msg, contentType),
81
+ loopDetected: (msg = "Loop Detected", contentType) => createErrorResponse(508, msg, contentType),
82
+ notExtended: (msg = "Not Extended", contentType) => createErrorResponse(510, msg, contentType),
83
+ networkAuthenticationRequired: (msg = "Network Authentication Required", contentType) => createErrorResponse(511, msg, contentType),
84
+ // Aliases for common use cases
85
+ invalidArgument: (msg = "Invalid Argument", contentType) => createErrorResponse(HTTP_STATUS.UNPROCESSABLE_ENTITY, msg, contentType),
86
+ rateLimitExceeded: (msg = "Rate Limit Exceeded", contentType) => createErrorResponse(429, msg, contentType),
87
+ maintenance: (msg = "Service Under Maintenance", contentType) => createErrorResponse(503, msg, contentType),
88
+ // Helper to create custom error with any status code
89
+ custom: (statusCode, msg, contentType) => createErrorResponse(statusCode, msg, contentType),
90
+ };
91
+ export function createResponse(statusCode, data, contentType = CONTENT_TYPES.JSON) {
92
+ const body = contentType === CONTENT_TYPES.JSON ? stringifyData(data) : data;
93
+ return new Response(body, {
94
+ status: statusCode,
95
+ headers: { "content-type": contentType },
96
+ });
97
+ }
98
+ export const protectedRoute = async (request, responseContentType) => {
99
+ // Get the Vector instance to access the protected handler
100
+ const vector = (await import("./core/vector")).default;
101
+ if (!vector.protected) {
102
+ throw APIError.unauthorized("Authentication not configured", responseContentType);
103
+ }
104
+ try {
105
+ const authUser = await vector.protected(request);
106
+ request.authUser = authUser;
107
+ }
108
+ catch (error) {
109
+ throw APIError.unauthorized(error instanceof Error ? error.message : "Authentication failed", responseContentType);
110
+ }
111
+ };
112
+ export function api(options, fn) {
113
+ const { auth = false, expose = false, rawRequest = false, rawResponse = false, responseContentType = CONTENT_TYPES.JSON, } = options;
114
+ return async (request) => {
115
+ if (!expose) {
116
+ return APIError.forbidden("Forbidden");
117
+ }
118
+ try {
119
+ if (auth) {
120
+ await protectedRoute(request, responseContentType);
121
+ }
122
+ if (!rawRequest) {
123
+ await withContent(request);
124
+ }
125
+ withCookies(request);
126
+ // Cache handling is now done in the router
127
+ const result = await fn(request);
128
+ return rawResponse
129
+ ? result
130
+ : ApiResponse.success(result, responseContentType);
131
+ }
132
+ catch (err) {
133
+ // Ensure we return a Response object
134
+ if (err instanceof Response) {
135
+ return err;
136
+ }
137
+ // For non-Response errors, wrap them
138
+ return APIError.internalServerError(String(err), responseContentType);
139
+ }
140
+ };
141
+ }
142
+ export default ApiResponse;
143
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EAGJ,WAAW,EACX,WAAW,GACZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAczD,MAAM,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IACzC,MAAM,EAAE,GAAG;IACX,WAAW,EAAE,IAAI;IACjB,YAAY,EAAE,6BAA6B;IAC3C,YAAY,EAAE,wCAAwC;IACtD,aAAa,EAAE,eAAe;IAC9B,MAAM,EAAE,MAAM;CACf,CAAC,CAAC;AAOH,MAAM,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,IAAI,CAAC,UAAU,EAAE,CAAC;gBAChB,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;YAC7B,CAAC;YAED,WAAW,CAAC,OAAO,CAAC,CAAC;YAErB,2CAA2C;YAC3C,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,OAAuC,CAAC,CAAC;YAEjE,OAAO,WAAW;gBAChB,CAAC,CAAC,MAAM;gBACR,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACtB,qCAAqC;YACrC,IAAI,GAAG,YAAY,QAAQ,EAAE,CAAC;gBAC5B,OAAO,GAAG,CAAC;YACb,CAAC;YACD,qCAAqC;YACrC,OAAO,QAAQ,CAAC,mBAAmB,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,mBAAmB,CAAC,CAAC;QACxE,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,eAAe,WAAW,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { Vector } from './core/vector';
2
+ import { route } from './http';
3
+ import type { DefaultVectorTypes, VectorTypes } from './types';
4
+ export { route, Vector };
5
+ export { AuthManager } from './auth/protected';
6
+ export { CacheManager } from './cache/manager';
7
+ export { APIError, createResponse } from './http';
8
+ export { MiddlewareManager } from './middleware/manager';
9
+ export * from './types';
10
+ export declare function createVector<TTypes extends VectorTypes = DefaultVectorTypes>(): Vector<TTypes>;
11
+ declare const vector: Vector<DefaultVectorTypes>;
12
+ export default vector;
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE/D,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AACzB,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,cAAc,SAAS,CAAC;AAGxB,wBAAgB,YAAY,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB,KAAK,MAAM,CAAC,MAAM,CAAC,CAE9F;AAGD,QAAA,MAAM,MAAM,4BAAuB,CAAC;AACpC,eAAe,MAAM,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ var{defineProperty:v,getOwnPropertyNames:Ai,getOwnPropertyDescriptor:_i}=Object,Oi=Object.prototype.hasOwnProperty;var r=new WeakMap,Ni=(i)=>{var f=r.get(i),l;if(f)return f;if(f=v({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")Ai(i).map((a)=>!Oi.call(f,a)&&v(f,a,{get:()=>i[a],enumerable:!(l=_i(i,a))||l.enumerable}));return r.set(i,f),f};var y=(i,f)=>{for(var l in f)v(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var P=(i,f)=>()=>(i&&(f=i(i=0)),f);class b{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}var R,J,M;var W=P(()=>{R={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},J={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},M={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class G{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=J.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let a=Date.now(),A=this.memoryCache.get(i);if(this.isCacheValid(A,a))return A.value;let E=await f();return this.setInMemoryCache(i,E,l),E}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let a=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:a}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=J.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var z=P(()=>{W()});function U(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function q(i,f){var l="",a=0,A=-1,E=0,O;for(var _=0;_<=i.length;++_){if(_<i.length)O=i.charCodeAt(_);else if(O===47)break;else O=47;if(O===47){if(A===_-1||E===1);else if(A!==_-1&&E===2){if(l.length<2||a!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var d=l.lastIndexOf("/");if(d!==l.length-1){if(d===-1)l="",a=0;else l=l.slice(0,d),a=l.length-1-l.lastIndexOf("/");A=_,E=0;continue}}else if(l.length===2||l.length===1){l="",a=0,A=_,E=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";a=2}}else{if(l.length>0)l+="/"+i.slice(A+1,_);else l=i.slice(A+1,_);a=_-A-1}A=_,E=0}else if(O===46&&E!==-1)++E;else E=-1}return l}function di(i,f){var l=f.dir||f.root,a=f.base||(f.name||"")+(f.ext||"");if(!l)return a;if(l===f.root)return l+a;return l+i+a}function F(){var i="",f=!1,l;for(var a=arguments.length-1;a>=-1&&!f;a--){var A;if(a>=0)A=arguments[a];else{if(l===void 0)l=process.cwd();A=l}if(U(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=q(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function t(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=q(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function Di(i){return U(i),i.length>0&&i.charCodeAt(0)===47}function K(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if(U(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return t(i)}function j(i,f){if(U(i),U(f),i===f)return"";if(i=F(i),f=F(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var a=i.length,A=a-l,E=1;for(;E<f.length;++E)if(f.charCodeAt(E)!==47)break;var O=f.length,_=O-E,d=A<_?A:_,I=-1,N=0;for(;N<=d;++N){if(N===d){if(_>d){if(f.charCodeAt(E+N)===47)return f.slice(E+N+1);else if(N===0)return f.slice(E+N)}else if(A>d){if(i.charCodeAt(l+N)===47)I=N;else if(N===0)I=0}break}var w=i.charCodeAt(l+N),L=f.charCodeAt(E+N);if(w!==L)break;else if(w===47)I=N}var H="";for(N=l+I+1;N<=a;++N)if(N===a||i.charCodeAt(N)===47)if(H.length===0)H+="..";else H+="/..";if(H.length>0)return H+f.slice(E+I);else{if(E+=I,f.charCodeAt(E)===47)++E;return f.slice(E)}}function Ii(i){return i}function T(i){if(U(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,a=-1,A=!0;for(var E=i.length-1;E>=1;--E)if(f=i.charCodeAt(E),f===47){if(!A){a=E;break}}else A=!1;if(a===-1)return l?"/":".";if(l&&a===1)return"//";return i.slice(0,a)}function Li(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');U(i);var l=0,a=-1,A=!0,E;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var O=f.length-1,_=-1;for(E=i.length-1;E>=0;--E){var d=i.charCodeAt(E);if(d===47){if(!A){l=E+1;break}}else{if(_===-1)A=!1,_=E+1;if(O>=0)if(d===f.charCodeAt(O)){if(--O===-1)a=E}else O=-1,a=_}}if(l===a)a=_;else if(a===-1)a=i.length;return i.slice(l,a)}else{for(E=i.length-1;E>=0;--E)if(i.charCodeAt(E)===47){if(!A){l=E+1;break}}else if(a===-1)A=!1,a=E+1;if(a===-1)return"";return i.slice(l,a)}}function wi(i){U(i);var f=-1,l=0,a=-1,A=!0,E=0;for(var O=i.length-1;O>=0;--O){var _=i.charCodeAt(O);if(_===47){if(!A){l=O+1;break}continue}if(a===-1)A=!1,a=O+1;if(_===46){if(f===-1)f=O;else if(E!==1)E=1}else if(f!==-1)E=-1}if(f===-1||a===-1||E===0||E===1&&f===a-1&&f===l+1)return"";return i.slice(f,a)}function Ri(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return di("/",i)}function Ci(i){U(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),a=l===47,A;if(a)f.root="/",A=1;else A=0;var E=-1,O=0,_=-1,d=!0,I=i.length-1,N=0;for(;I>=A;--I){if(l=i.charCodeAt(I),l===47){if(!d){O=I+1;break}continue}if(_===-1)d=!1,_=I+1;if(l===46){if(E===-1)E=I;else if(N!==1)N=1}else if(E!==-1)N=-1}if(E===-1||_===-1||N===0||N===1&&E===_-1&&E===O+1){if(_!==-1)if(O===0&&a)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(O,_)}else{if(O===0&&a)f.name=i.slice(1,E),f.base=i.slice(1,_);else f.name=i.slice(O,E),f.base=i.slice(O,_);f.ext=i.slice(E,_)}if(O>0)f.dir=i.slice(0,O-1);else if(a)f.dir="/";return f}var Z="/",$i=":",Vi;var c=P(()=>{Vi=((i)=>(i.posix=i,i))({resolve:F,normalize:t,isAbsolute:Di,join:K,relative:j,_makeLong:Ii,dirname:T,basename:Li,extname:wi,format:Ri,parse:Ci,sep:Z,delimiter:$i,win32:null,posix:null})});class g{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=T(this.outputPath);await B.mkdir(f,{recursive:!0});let l=[],a=new Map;for(let _ of i){if(!a.has(_.path))a.set(_.path,[]);a.get(_.path).push(_)}let A=0,E=[];for(let[_,d]of a){let I=j(T(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),N=`route_${A++}`,w=d.filter((L)=>L.name!=="default").map((L)=>L.name);if(d.some((L)=>L.name==="default"))if(w.length>0)l.push(`import ${N}, { ${w.join(", ")} } from '${I}';`);else l.push(`import ${N} from '${I}';`);else if(w.length>0)l.push(`import { ${w.join(", ")} } from '${I}';`);for(let L of d){let H=L.name==="default"?N:L.name;E.push(` ${H},`)}}let O=`// This file is auto-generated. Do not edit manually.
2
+ // Generated at: ${new Date().toISOString()}
3
+
4
+ ${l.join(`
5
+ `)}
6
+
7
+ export const routes = [
8
+ ${E.join(`
9
+ `)}
10
+ ];
11
+
12
+ export default routes;
13
+ `;await B.writeFile(this.outputPath,O,"utf-8"),console.log(`Generated routes file: ${this.outputPath}`)}async generateDynamic(i){let f=[];for(let l of i){let a=JSON.stringify({method:l.method,path:l.options.path,options:l.options});f.push(` await import('${l.path}').then(m => ({
14
+ ...${a},
15
+ handler: m.${l.name==="default"?"default":l.name}
16
+ }))`)}return`export const loadRoutes = async () => {
17
+ return Promise.all([
18
+ ${f.join(`,
19
+ `)}
20
+ ]);
21
+ };`}}var B;var o=P(()=>{B=(()=>({}));c()});class k{routesDir;constructor(i="./routes"){this.routesDir=F(process.cwd(),i)}async scan(){let i=[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(`Routes directory not found: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await Y.readdir(i);for(let A of a){let E=K(i,A);if((await Y.stat(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=j(this.routesDir,E).replace(/\.(ts|js)$/,"").split(Z).join("/");try{let I=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(I.default&&typeof I.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[N,w]of Object.entries(I)){if(N==="default")continue;if(Array.isArray(w)&&w.length>=4){let[L,,,H]=w;f.push({name:N,path:E,method:L,options:{method:L,path:H,expose:!0}})}}}catch(d){console.error(`Failed to load route from ${E}:`,d)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}var Y;var p=P(()=>{Y=(()=>({}));c()});class h{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let a=await l(f);if(a instanceof Response)return a;f=a}return f}async executeFinally(i,f){let l=i;for(let a of this.finallyHandlers)l=await a(l,f);return l}clone(){let i=new h;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}}var x=(i="text/plain; charset=utf-8",f)=>(l,a={})=>{if(l===void 0||l instanceof Response)return l;let A=new Response(f?.(l)??l,a.url?void 0:a);return A.headers.set("content-type",i),A},Zi,ci,gi,ki,ui,mi,e=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},ii=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,a])=>a?(f[l]=a,f):f,{})},Q=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:a="*",allowHeaders:A,exposeHeaders:E,maxAge:O}=i,_=(I)=>{let N=I?.headers.get("origin");return f===!0?N:f instanceof RegExp?f.test(N)?N:void 0:Array.isArray(f)?f.includes(N)?N:void 0:f instanceof Function?f(N):f=="*"&&l?N:f},d=(I,N)=>{for(let[w,L]of Object.entries(N))L&&I.headers.append(w,L);return I};return{corsify:(I,N)=>I?.headers?.get("access-control-allow-origin")||I.status==101?I:d(I.clone(),{"access-control-allow-origin":_(N),"access-control-allow-credentials":l}),preflight:(I)=>{if(I.method=="OPTIONS"){let N=new Response(null,{status:204});return d(N,{"access-control-allow-origin":_(I),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":E?.join?.(",")??E,"access-control-allow-headers":A?.join?.(",")??A??I.headers.get("access-control-request-headers"),"access-control-max-age":O,"access-control-allow-credentials":l})}}}};var u=P(()=>{Zi=x("application/json; charset=utf-8",JSON.stringify),ci=x("text/plain; charset=utf-8",String),gi=x("text/html"),ki=x("image/jpeg"),ui=x("image/png"),mi=x("image/webp")});function fi(i,f){let l=Si(i,f);return[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path]}function Pi(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let a={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return S(i,a,l)}function S(i,f,l=M.JSON){let a=l===M.JSON?Pi(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Si(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:O=M.JSON}=i;return async(_)=>{if(!a)return C.forbidden("Forbidden");try{if(l)await Hi(_,O);if(!A)await e(_);ii(_);let d=await f(_);return E?d:Ui.success(d,O)}catch(d){if(d instanceof Response)return d;return C.internalServerError(String(d),O)}}}var yi,qi,Ui,C,Hi=async(i,f)=>{let l=(await Promise.resolve().then(() => (m(),li))).default;if(!l.protected)throw C.unauthorized("Authentication not configured",f);try{let a=await l.protected(i);i.authUser=a}catch(a){throw C.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var V=P(()=>{u();W();({preflight:yi,corsify:qi}=Q({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ui={success:(i,f)=>S(R.OK,i,f),created:(i,f)=>S(R.CREATED,i,f)};C={badRequest:(i="Bad Request",f)=>D(R.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D(R.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D(R.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D(R.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D(R.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D(R.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});class n{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let E=0,O=i.split("/").filter(Boolean);for(let _ of O)if(this.isStaticSegment(_))E+=1000;else if(this.isParamSegment(_))E+=10;else if(this.isWildcardSegment(_))E+=1;if(E+=i.length,this.isExactPath(i))E+=1e4;return E}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),a=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(a)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(a),this.sortRoutes(),a}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let a=l;if(!a.context)a.context={};if(!a.query&&a.url){let A=new URL(a.url),E={};for(let[O,_]of A.searchParams)E[O]=E[O]?[].concat(E[O],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(!i.expose)return C.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(d){return C.unauthorized(d instanceof Error?d.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let d=l.headers.get("content-type");if(d?.includes("application/json"))l.content=await l.json();else if(d?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(d?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let E,O=i.cache;if(O&&typeof O==="number"&&O>0){let d=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(d,()=>f(l),O)}else if(O&&typeof O==="object"&&O.ttl){let d=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(d,()=>f(l),O.ttl)}else E=await f(l);let _;if(i.rawResponse||E instanceof Response)_=E instanceof Response?E:new Response(E);else _=S(200,E,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),C.internalServerError(A instanceof Error?A.message:String(A),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[a,A,E]of this.routes)if(i.method==="OPTIONS"||i.method===a){let O=l.match(A);if(O){let _=i;if(!_.context)_.context={};_.params=O.groups||{};for(let d of E){let I=await d(_);if(I)return I}}}return C.notFound("Route not found")}}var ai=P(()=>{V()});class s{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=Q(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:a}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let A=await this.router.handle(a);if(this.corsHandler)A=this.corsHandler.corsify(A,a);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}var Ei=P(()=>{u()});var li={};y(li,{default:()=>xi,Vector:()=>$});class ${static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new h,this.authManager=new b,this.cacheManager=new G,this.router=new n(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!$.instance)$.instance=new $;return $.instance}set protected(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}get protected(){return this._protectedHandler}set cache(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}get cache(){return this._cacheHandler}route(i,f){return this.router.route(i,f)}use(...i){return this.middlewareManager.addBefore(...i),this}before(...i){return this.middlewareManager.addBefore(...i),this}finally(...i){return this.middlewareManager.addFinally(...i),this}async serve(i){if(this.config={...this.config,...i},i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();this.server=new s(this.router,this.config);let f=await this.server.start();if(this.config.development&&this.routeScanner)this.routeScanner.enableWatch(async()=>{await this.discoverRoutes()});return f}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new k(i);if(!this.routeGenerator)this.routeGenerator=new g;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(process.platform==="win32"?`file:///${l.path.replace(/\\/g,"/")}`:l.path),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteEntry(E))this.router.addRoute(E),this.logRouteLoaded(E);else if(typeof E==="function")this.router.route(l.options,E),this.logRouteLoaded(l.options)}}catch(a){console.error(`Failed to load route ${l.name} from ${l.path}:`,a)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT")console.error("Failed to discover routes:",f)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}}var hi,xi;var m=P(()=>{z();o();p();ai();Ei();hi=$.getInstance(),xi=hi});var Fi={};y(Fi,{route:()=>fi,default:()=>ji,createVector:()=>bi,createResponse:()=>S,Vector:()=>$,MiddlewareManager:()=>h,CacheManager:()=>G,AuthManager:()=>b,APIError:()=>C});module.exports=Ni(Fi);m();V();z();V();function bi(){return $.getInstance()}var Gi=$.getInstance(),ji=Gi;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAG/B,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AACzB,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,cAAc,SAAS,CAAC;AAExB,mDAAmD;AACnD,MAAM,UAAU,YAAY;IAC1B,OAAO,MAAM,CAAC,WAAW,EAAU,CAAC;AACtC,CAAC;AAED,qDAAqD;AACrD,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;AACpC,eAAe,MAAM,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,21 @@
1
+ var e=Object.defineProperty;var ii=(i,f)=>{for(var l in f)e(i,l,{get:f[l],enumerable:!0,configurable:!0,set:(a)=>f[l]=()=>a})};var C=(i,f)=>()=>(i&&(f=i(i=0)),f);class F{protectedHandler=null;setProtectedHandler(i){this.protectedHandler=i}async authenticate(i){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let f=await this.protectedHandler(i);return i.authUser=f,f}catch(f){throw new Error(`Authentication failed: ${f instanceof Error?f.message:String(f)}`)}}isAuthenticated(i){return!!i.authUser}getUser(i){return i.authUser||null}}var R,V,j;var v=C(()=>{R={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},V={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},j={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"}});class M{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;setCacheHandler(i){this.cacheHandler=i}async get(i,f,l=V.CACHE_TTL){if(l<=0)return f();if(this.cacheHandler)return this.cacheHandler(i,f,l);return this.getFromMemoryCache(i,f,l)}async getFromMemoryCache(i,f,l){let a=Date.now(),A=this.memoryCache.get(i);if(this.isCacheValid(A,a))return A.value;let E=await f();return this.setInMemoryCache(i,E,l),E}isCacheValid(i,f){return i!==void 0&&i.expires>f}setInMemoryCache(i,f,l){let a=Date.now()+l*1000;this.memoryCache.set(i,{value:f,expires:a}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let i=Date.now();for(let[f,l]of this.memoryCache.entries())if(l.expires<=i)this.memoryCache.delete(f);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(i,f,l=V.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(i,async()=>f,l);return}this.setInMemoryCache(i,f,l)}delete(i){return this.memoryCache.delete(i)}has(i){let f=this.memoryCache.get(i);if(!f)return!1;if(f.expires<=Date.now())return this.memoryCache.delete(i),!1;return!0}generateKey(i,f){let l=new URL(i.url);return[i.method,l.pathname,l.search,f?.authUser?.id||"anonymous"].join(":")}}var X=C(()=>{v()});function $(i){if(typeof i!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function m(i,f){var l="",a=0,A=-1,E=0,O;for(var _=0;_<=i.length;++_){if(_<i.length)O=i.charCodeAt(_);else if(O===47)break;else O=47;if(O===47){if(A===_-1||E===1);else if(A!==_-1&&E===2){if(l.length<2||a!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var d=l.lastIndexOf("/");if(d!==l.length-1){if(d===-1)l="",a=0;else l=l.slice(0,d),a=l.length-1-l.lastIndexOf("/");A=_,E=0;continue}}else if(l.length===2||l.length===1){l="",a=0,A=_,E=0;continue}}if(f){if(l.length>0)l+="/..";else l="..";a=2}}else{if(l.length>0)l+="/"+i.slice(A+1,_);else l=i.slice(A+1,_);a=_-A-1}A=_,E=0}else if(O===46&&E!==-1)++E;else E=-1}return l}function fi(i,f){var l=f.dir||f.root,a=f.base||(f.name||"")+(f.ext||"");if(!l)return a;if(l===f.root)return l+a;return l+i+a}function x(){var i="",f=!1,l;for(var a=arguments.length-1;a>=-1&&!f;a--){var A;if(a>=0)A=arguments[a];else{if(l===void 0)l=process.cwd();A=l}if($(A),A.length===0)continue;i=A+"/"+i,f=A.charCodeAt(0)===47}if(i=m(i,!f),f)if(i.length>0)return"/"+i;else return"/";else if(i.length>0)return i;else return"."}function n(i){if($(i),i.length===0)return".";var f=i.charCodeAt(0)===47,l=i.charCodeAt(i.length-1)===47;if(i=m(i,!f),i.length===0&&!f)i=".";if(i.length>0&&l)i+="/";if(f)return"/"+i;return i}function li(i){return $(i),i.length>0&&i.charCodeAt(0)===47}function J(){if(arguments.length===0)return".";var i;for(var f=0;f<arguments.length;++f){var l=arguments[f];if($(l),l.length>0)if(i===void 0)i=l;else i+="/"+l}if(i===void 0)return".";return n(i)}function b(i,f){if($(i),$(f),i===f)return"";if(i=x(i),f=x(f),i===f)return"";var l=1;for(;l<i.length;++l)if(i.charCodeAt(l)!==47)break;var a=i.length,A=a-l,E=1;for(;E<f.length;++E)if(f.charCodeAt(E)!==47)break;var O=f.length,_=O-E,d=A<_?A:_,I=-1,N=0;for(;N<=d;++N){if(N===d){if(_>d){if(f.charCodeAt(E+N)===47)return f.slice(E+N+1);else if(N===0)return f.slice(E+N)}else if(A>d){if(i.charCodeAt(l+N)===47)I=N;else if(N===0)I=0}break}var w=i.charCodeAt(l+N),L=f.charCodeAt(E+N);if(w!==L)break;else if(w===47)I=N}var H="";for(N=l+I+1;N<=a;++N)if(N===a||i.charCodeAt(N)===47)if(H.length===0)H+="..";else H+="/..";if(H.length>0)return H+f.slice(E+I);else{if(E+=I,f.charCodeAt(E)===47)++E;return f.slice(E)}}function ai(i){return i}function T(i){if($(i),i.length===0)return".";var f=i.charCodeAt(0),l=f===47,a=-1,A=!0;for(var E=i.length-1;E>=1;--E)if(f=i.charCodeAt(E),f===47){if(!A){a=E;break}}else A=!1;if(a===-1)return l?"/":".";if(l&&a===1)return"//";return i.slice(0,a)}function Ei(i,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');$(i);var l=0,a=-1,A=!0,E;if(f!==void 0&&f.length>0&&f.length<=i.length){if(f.length===i.length&&f===i)return"";var O=f.length-1,_=-1;for(E=i.length-1;E>=0;--E){var d=i.charCodeAt(E);if(d===47){if(!A){l=E+1;break}}else{if(_===-1)A=!1,_=E+1;if(O>=0)if(d===f.charCodeAt(O)){if(--O===-1)a=E}else O=-1,a=_}}if(l===a)a=_;else if(a===-1)a=i.length;return i.slice(l,a)}else{for(E=i.length-1;E>=0;--E)if(i.charCodeAt(E)===47){if(!A){l=E+1;break}}else if(a===-1)A=!1,a=E+1;if(a===-1)return"";return i.slice(l,a)}}function Ai(i){$(i);var f=-1,l=0,a=-1,A=!0,E=0;for(var O=i.length-1;O>=0;--O){var _=i.charCodeAt(O);if(_===47){if(!A){l=O+1;break}continue}if(a===-1)A=!1,a=O+1;if(_===46){if(f===-1)f=O;else if(E!==1)E=1}else if(f!==-1)E=-1}if(f===-1||a===-1||E===0||E===1&&f===a-1&&f===l+1)return"";return i.slice(f,a)}function _i(i){if(i===null||typeof i!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return fi("/",i)}function Oi(i){$(i);var f={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return f;var l=i.charCodeAt(0),a=l===47,A;if(a)f.root="/",A=1;else A=0;var E=-1,O=0,_=-1,d=!0,I=i.length-1,N=0;for(;I>=A;--I){if(l=i.charCodeAt(I),l===47){if(!d){O=I+1;break}continue}if(_===-1)d=!1,_=I+1;if(l===46){if(E===-1)E=I;else if(N!==1)N=1}else if(E!==-1)N=-1}if(E===-1||_===-1||N===0||N===1&&E===_-1&&E===O+1){if(_!==-1)if(O===0&&a)f.base=f.name=i.slice(1,_);else f.base=f.name=i.slice(O,_)}else{if(O===0&&a)f.name=i.slice(1,E),f.base=i.slice(1,_);else f.name=i.slice(O,E),f.base=i.slice(O,_);f.ext=i.slice(E,_)}if(O>0)f.dir=i.slice(0,O-1);else if(a)f.dir="/";return f}var W="/",Ni=":",ji;var z=C(()=>{ji=((i)=>(i.posix=i,i))({resolve:x,normalize:n,isAbsolute:li,join:J,relative:b,_makeLong:ai,dirname:T,basename:Ei,extname:Ai,format:_i,parse:Oi,sep:W,delimiter:Ni,win32:null,posix:null})});var{mkdir:di,writeFile:Di}=(()=>({}));class K{outputPath;constructor(i="./.vector/routes.generated.ts"){this.outputPath=i}async generate(i){let f=T(this.outputPath);await di(f,{recursive:!0});let l=[],a=new Map;for(let _ of i){if(!a.has(_.path))a.set(_.path,[]);a.get(_.path).push(_)}let A=0,E=[];for(let[_,d]of a){let I=b(T(this.outputPath),_).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),N=`route_${A++}`,w=d.filter((L)=>L.name!=="default").map((L)=>L.name);if(d.some((L)=>L.name==="default"))if(w.length>0)l.push(`import ${N}, { ${w.join(", ")} } from '${I}';`);else l.push(`import ${N} from '${I}';`);else if(w.length>0)l.push(`import { ${w.join(", ")} } from '${I}';`);for(let L of d){let H=L.name==="default"?N:L.name;E.push(` ${H},`)}}let O=`// This file is auto-generated. Do not edit manually.
2
+ // Generated at: ${new Date().toISOString()}
3
+
4
+ ${l.join(`
5
+ `)}
6
+
7
+ export const routes = [
8
+ ${E.join(`
9
+ `)}
10
+ ];
11
+
12
+ export default routes;
13
+ `;await Di(this.outputPath,O,"utf-8"),console.log(`Generated routes file: ${this.outputPath}`)}async generateDynamic(i){let f=[];for(let l of i){let a=JSON.stringify({method:l.method,path:l.options.path,options:l.options});f.push(` await import('${l.path}').then(m => ({
14
+ ...${a},
15
+ handler: m.${l.name==="default"?"default":l.name}
16
+ }))`)}return`export const loadRoutes = async () => {
17
+ return Promise.all([
18
+ ${f.join(`,
19
+ `)}
20
+ ]);
21
+ };`}}var s=C(()=>{z()});var{readdir:Ii,stat:Li}=(()=>({}));class Z{routesDir;constructor(i="./routes"){this.routesDir=x(process.cwd(),i)}async scan(){let i=[];try{await this.scanDirectory(this.routesDir,i)}catch(f){if(f.code==="ENOENT")return console.warn(`Routes directory not found: ${this.routesDir}`),[];throw f}return i}async scanDirectory(i,f,l=""){let a=await Ii(i);for(let A of a){let E=J(i,A);if((await Li(E)).isDirectory()){let _=l?`${l}/${A}`:A;await this.scanDirectory(E,f,_)}else if(A.endsWith(".ts")||A.endsWith(".js")){let _=b(this.routesDir,E).replace(/\.(ts|js)$/,"").split(W).join("/");try{let I=await import(process.platform==="win32"?`file:///${E.replace(/\\/g,"/")}`:E);if(I.default&&typeof I.default==="function")f.push({name:"default",path:E,method:"GET",options:{method:"GET",path:`/${_}`,expose:!0}});for(let[N,w]of Object.entries(I)){if(N==="default")continue;if(Array.isArray(w)&&w.length>=4){let[L,,,H]=w;f.push({name:N,path:E,method:L,options:{method:L,path:H,expose:!0}})}}}catch(d){console.error(`Failed to load route from ${E}:`,d)}}}}enableWatch(i){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await i()},1000)}}var r=C(()=>{z()});class G{beforeHandlers=[];finallyHandlers=[];addBefore(...i){this.beforeHandlers.push(...i)}addFinally(...i){this.finallyHandlers.push(...i)}async executeBefore(i){let f=i;for(let l of this.beforeHandlers){let a=await l(f);if(a instanceof Response)return a;f=a}return f}async executeFinally(i,f){let l=i;for(let a of this.finallyHandlers)l=await a(l,f);return l}clone(){let i=new G;return i.beforeHandlers=[...this.beforeHandlers],i.finallyHandlers=[...this.finallyHandlers],i}}var S=(i="text/plain; charset=utf-8",f)=>(l,a={})=>{if(l===void 0||l instanceof Response)return l;let A=new Response(f?.(l)??l,a.url?void 0:a);return A.headers.set("content-type",i),A},Ji,Wi,zi,Ki,Zi,ci,y=async(i)=>{i.content=i.body?await i.clone().json().catch(()=>i.clone().formData()).catch(()=>i.text()):void 0},q=(i)=>{i.cookies=(i.headers.get("Cookie")||"").split(/;\s*/).map((f)=>f.split(/=(.+)/)).reduce((f,[l,a])=>a?(f[l]=a,f):f,{})},B=(i={})=>{let{origin:f="*",credentials:l=!1,allowMethods:a="*",allowHeaders:A,exposeHeaders:E,maxAge:O}=i,_=(I)=>{let N=I?.headers.get("origin");return f===!0?N:f instanceof RegExp?f.test(N)?N:void 0:Array.isArray(f)?f.includes(N)?N:void 0:f instanceof Function?f(N):f=="*"&&l?N:f},d=(I,N)=>{for(let[w,L]of Object.entries(N))L&&I.headers.append(w,L);return I};return{corsify:(I,N)=>I?.headers?.get("access-control-allow-origin")||I.status==101?I:d(I.clone(),{"access-control-allow-origin":_(N),"access-control-allow-credentials":l}),preflight:(I)=>{if(I.method=="OPTIONS"){let N=new Response(null,{status:204});return d(N,{"access-control-allow-origin":_(I),"access-control-allow-methods":a?.join?.(",")??a,"access-control-expose-headers":E?.join?.(",")??E,"access-control-allow-headers":A?.join?.(",")??A??I.headers.get("access-control-request-headers"),"access-control-max-age":O,"access-control-allow-credentials":l})}}}};var c=C(()=>{Ji=S("application/json; charset=utf-8",JSON.stringify),Wi=S("text/plain; charset=utf-8",String),zi=S("text/html"),Ki=S("image/jpeg"),Zi=S("image/png"),ci=S("image/webp")});function wi(i,f){let l=Pi(i,f);return[i.method.toUpperCase(),RegExp(`^${i.path.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),[l],i.path]}function Ri(i){return JSON.stringify(i??null,(f,l)=>typeof l==="bigint"?l.toString():l)}function D(i,f,l){let a={error:!0,message:f,statusCode:i,timestamp:new Date().toISOString()};return h(i,a,l)}function h(i,f,l=j.JSON){let a=l===j.JSON?Ri(f):f;return new Response(a,{status:i,headers:{"content-type":l}})}function Pi(i,f){let{auth:l=!1,expose:a=!1,rawRequest:A=!1,rawResponse:E=!1,responseContentType:O=j.JSON}=i;return async(_)=>{if(!a)return P.forbidden("Forbidden");try{if(l)await $i(_,O);if(!A)await y(_);q(_);let d=await f(_);return E?d:Ci.success(d,O)}catch(d){if(d instanceof Response)return d;return P.internalServerError(String(d),O)}}}var mi,ni,Ci,P,$i=async(i,f)=>{let l=(await Promise.resolve().then(() => (g(),t))).default;if(!l.protected)throw P.unauthorized("Authentication not configured",f);try{let a=await l.protected(i);i.authUser=a}catch(a){throw P.unauthorized(a instanceof Error?a.message:"Authentication failed",f)}};var Y=C(()=>{c();v();({preflight:mi,corsify:ni}=B({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400}));Ci={success:(i,f)=>h(R.OK,i,f),created:(i,f)=>h(R.CREATED,i,f)};P={badRequest:(i="Bad Request",f)=>D(R.BAD_REQUEST,i,f),unauthorized:(i="Unauthorized",f)=>D(R.UNAUTHORIZED,i,f),paymentRequired:(i="Payment Required",f)=>D(402,i,f),forbidden:(i="Forbidden",f)=>D(R.FORBIDDEN,i,f),notFound:(i="Not Found",f)=>D(R.NOT_FOUND,i,f),methodNotAllowed:(i="Method Not Allowed",f)=>D(405,i,f),notAcceptable:(i="Not Acceptable",f)=>D(406,i,f),requestTimeout:(i="Request Timeout",f)=>D(408,i,f),conflict:(i="Conflict",f)=>D(R.CONFLICT,i,f),gone:(i="Gone",f)=>D(410,i,f),lengthRequired:(i="Length Required",f)=>D(411,i,f),preconditionFailed:(i="Precondition Failed",f)=>D(412,i,f),payloadTooLarge:(i="Payload Too Large",f)=>D(413,i,f),uriTooLong:(i="URI Too Long",f)=>D(414,i,f),unsupportedMediaType:(i="Unsupported Media Type",f)=>D(415,i,f),rangeNotSatisfiable:(i="Range Not Satisfiable",f)=>D(416,i,f),expectationFailed:(i="Expectation Failed",f)=>D(417,i,f),imATeapot:(i="I'm a teapot",f)=>D(418,i,f),misdirectedRequest:(i="Misdirected Request",f)=>D(421,i,f),unprocessableEntity:(i="Unprocessable Entity",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),locked:(i="Locked",f)=>D(423,i,f),failedDependency:(i="Failed Dependency",f)=>D(424,i,f),tooEarly:(i="Too Early",f)=>D(425,i,f),upgradeRequired:(i="Upgrade Required",f)=>D(426,i,f),preconditionRequired:(i="Precondition Required",f)=>D(428,i,f),tooManyRequests:(i="Too Many Requests",f)=>D(429,i,f),requestHeaderFieldsTooLarge:(i="Request Header Fields Too Large",f)=>D(431,i,f),unavailableForLegalReasons:(i="Unavailable For Legal Reasons",f)=>D(451,i,f),internalServerError:(i="Internal Server Error",f)=>D(R.INTERNAL_SERVER_ERROR,i,f),notImplemented:(i="Not Implemented",f)=>D(501,i,f),badGateway:(i="Bad Gateway",f)=>D(502,i,f),serviceUnavailable:(i="Service Unavailable",f)=>D(503,i,f),gatewayTimeout:(i="Gateway Timeout",f)=>D(504,i,f),httpVersionNotSupported:(i="HTTP Version Not Supported",f)=>D(505,i,f),variantAlsoNegotiates:(i="Variant Also Negotiates",f)=>D(506,i,f),insufficientStorage:(i="Insufficient Storage",f)=>D(507,i,f),loopDetected:(i="Loop Detected",f)=>D(508,i,f),notExtended:(i="Not Extended",f)=>D(510,i,f),networkAuthenticationRequired:(i="Network Authentication Required",f)=>D(511,i,f),invalidArgument:(i="Invalid Argument",f)=>D(R.UNPROCESSABLE_ENTITY,i,f),rateLimitExceeded:(i="Rate Limit Exceeded",f)=>D(429,i,f),maintenance:(i="Service Under Maintenance",f)=>D(503,i,f),custom:(i,f,l)=>D(i,f,l)}});class k{middlewareManager;authManager;cacheManager;routes=[];constructor(i,f,l){this.middlewareManager=i,this.authManager=f,this.cacheManager=l}getRouteSpecificity(i){let E=0,O=i.split("/").filter(Boolean);for(let _ of O)if(this.isStaticSegment(_))E+=1000;else if(this.isParamSegment(_))E+=10;else if(this.isWildcardSegment(_))E+=1;if(E+=i.length,this.isExactPath(i))E+=1e4;return E}isStaticSegment(i){return!i.startsWith(":")&&!i.includes("*")}isParamSegment(i){return i.startsWith(":")}isWildcardSegment(i){return i.includes("*")}isExactPath(i){return!i.includes(":")&&!i.includes("*")}sortRoutes(){this.routes.sort((i,f)=>{let l=this.extractPath(i),a=this.extractPath(f),A=this.getRouteSpecificity(l);return this.getRouteSpecificity(a)-A})}extractPath(i){return i[3]||""}route(i,f){let l=this.wrapHandler(i,f),a=[i.method.toUpperCase(),this.createRouteRegex(i.path),[l],i.path];return this.routes.push(a),this.sortRoutes(),a}createRouteRegex(i){return RegExp(`^${i.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}wrapHandler(i,f){return async(l)=>{let a=l;if(!a.context)a.context={};if(!a.query&&a.url){let A=new URL(a.url),E={};for(let[O,_]of A.searchParams)E[O]=E[O]?[].concat(E[O],_):_;a.query=E}if(i.metadata)a.metadata=i.metadata;l=a;try{if(!i.expose)return P.forbidden("Forbidden");let A=await this.middlewareManager.executeBefore(l);if(A instanceof Response)return A;if(l=A,i.auth)try{await this.authManager.authenticate(l)}catch(d){return P.unauthorized(d instanceof Error?d.message:"Authentication failed",i.responseContentType)}if(!i.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let d=l.headers.get("content-type");if(d?.includes("application/json"))l.content=await l.json();else if(d?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(d?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let E,O=i.cache;if(O&&typeof O==="number"&&O>0){let d=this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(d,()=>f(l),O)}else if(O&&typeof O==="object"&&O.ttl){let d=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});E=await this.cacheManager.get(d,()=>f(l),O.ttl)}else E=await f(l);let _;if(i.rawResponse||E instanceof Response)_=E instanceof Response?E:new Response(E);else _=h(200,E,i.responseContentType);return _=await this.middlewareManager.executeFinally(_,l),_}catch(A){if(A instanceof Response)return A;return console.error("Route handler error:",A),P.internalServerError(A instanceof Error?A.message:String(A),i.responseContentType)}}}addRoute(i){this.routes.push(i),this.sortRoutes()}getRoutes(){return this.routes}async handle(i){let l=new URL(i.url).pathname;for(let[a,A,E]of this.routes)if(i.method==="OPTIONS"||i.method===a){let O=l.match(A);if(O){let _=i;if(!_.context)_.context={};_.params=O.groups||{};for(let d of E){let I=await d(_);if(I)return I}}}return P.notFound("Route not found")}}var o=C(()=>{Y()});class u{server=null;router;config;corsHandler;constructor(i,f){if(this.router=i,this.config=f,f.cors){let{preflight:l,corsify:a}=B(this.normalizeCorsOptions(f.cors));this.corsHandler={preflight:l,corsify:a}}}normalizeCorsOptions(i){return{origin:i.origin||"*",credentials:i.credentials!==!1,allowHeaders:Array.isArray(i.allowHeaders)?i.allowHeaders.join(", "):i.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(i.allowMethods)?i.allowMethods.join(", "):i.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(i.exposeHeaders)?i.exposeHeaders.join(", "):i.exposeHeaders||"Authorization",maxAge:i.maxAge||86400}}async start(){let i=this.config.port||3000,f=this.config.hostname||"localhost",l=async(a)=>{try{if(this.corsHandler&&a.method==="OPTIONS")return this.corsHandler.preflight(a);let A=await this.router.handle(a);if(this.corsHandler)A=this.corsHandler.corsify(A,a);return A}catch(A){return console.error("Server error:",A),new Response("Internal Server Error",{status:500})}};return this.server=Bun.serve({port:i,hostname:f,reusePort:this.config.reusePort!==!1,fetch:l,error:(a)=>{return console.error("[ERROR] Server error:",a),new Response("Internal Server Error",{status:500})}}),console.log(`→ Vector server running at http://${f}:${i}`),this.server}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let i=this.getPort();return`http://${this.getHostname()}:${i}`}}var p=C(()=>{c()});var t={};ii(t,{default:()=>Hi,Vector:()=>U});class U{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new G,this.authManager=new F,this.cacheManager=new M,this.router=new k(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}set protected(i){this._protectedHandler=i,this.authManager.setProtectedHandler(i)}get protected(){return this._protectedHandler}set cache(i){this._cacheHandler=i,this.cacheManager.setCacheHandler(i)}get cache(){return this._cacheHandler}route(i,f){return this.router.route(i,f)}use(...i){return this.middlewareManager.addBefore(...i),this}before(...i){return this.middlewareManager.addBefore(...i),this}finally(...i){return this.middlewareManager.addFinally(...i),this}async serve(i){if(this.config={...this.config,...i},i?.before)this.middlewareManager.addBefore(...i.before);if(i?.finally)this.middlewareManager.addFinally(...i.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();this.server=new u(this.router,this.config);let f=await this.server.start();if(this.config.development&&this.routeScanner)this.routeScanner.enableWatch(async()=>{await this.discoverRoutes()});return f}async discoverRoutes(){let i=this.config.routesDir||"./routes";if(!this.routeScanner)this.routeScanner=new Z(i);if(!this.routeGenerator)this.routeGenerator=new K;try{let f=await this.routeScanner.scan();if(f.length>0){if(this.config.development)await this.routeGenerator.generate(f);for(let l of f)try{let A=await import(process.platform==="win32"?`file:///${l.path.replace(/\\/g,"/")}`:l.path),E=l.name==="default"?A.default:A[l.name];if(E){if(this.isRouteEntry(E))this.router.addRoute(E),this.logRouteLoaded(E);else if(typeof E==="function")this.router.route(l.options,E),this.logRouteLoaded(l.options)}}catch(a){console.error(`Failed to load route ${l.name} from ${l.path}:`,a)}this.router.sortRoutes(),console.log(`✅ Loaded ${f.length} routes from ${i}`)}}catch(f){if(f.code!=="ENOENT")console.error("Failed to discover routes:",f)}}async loadRoute(i){if(typeof i==="function"){let f=i();if(Array.isArray(f))this.router.addRoute(f)}else if(i&&typeof i==="object"){for(let[,f]of Object.entries(i))if(typeof f==="function"){let l=f();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(i){return Array.isArray(i)&&i.length>=3}logRouteLoaded(i){if(Array.isArray(i))console.log(` ✓ Loaded route: ${i[0]} ${i[3]||i[1]}`);else console.log(` ✓ Loaded route: ${i.method} ${i.path}`)}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}}var Ui,Hi;var g=C(()=>{X();s();r();o();p();Ui=U.getInstance(),Hi=Ui});g();Y();X();Y();function Of(){return U.getInstance()}var Si=U.getInstance(),Rf=Si;export{wi as route,Rf as default,Of as createVector,h as createResponse,U as Vector,G as MiddlewareManager,M as CacheManager,F as AuthManager,P as APIError};
@@ -0,0 +1,11 @@
1
+ import type { AfterMiddlewareHandler, BeforeMiddlewareHandler, DefaultVectorTypes, VectorRequest, VectorTypes } from '../types';
2
+ export declare class MiddlewareManager<TTypes extends VectorTypes = DefaultVectorTypes> {
3
+ private beforeHandlers;
4
+ private finallyHandlers;
5
+ addBefore(...handlers: BeforeMiddlewareHandler<TTypes>[]): void;
6
+ addFinally(...handlers: AfterMiddlewareHandler<TTypes>[]): void;
7
+ executeBefore(request: VectorRequest<TTypes>): Promise<VectorRequest<TTypes> | Response>;
8
+ executeFinally(response: Response, request: VectorRequest<TTypes>): Promise<Response>;
9
+ clone(): MiddlewareManager<TTypes>;
10
+ }
11
+ //# sourceMappingURL=manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/middleware/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,sBAAsB,EACtB,uBAAuB,EACvB,kBAAkB,EAClB,aAAa,EACb,WAAW,EACZ,MAAM,UAAU,CAAC;AAElB,qBAAa,iBAAiB,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IAC5E,OAAO,CAAC,cAAc,CAAyC;IAC/D,OAAO,CAAC,eAAe,CAAwC;IAE/D,SAAS,CAAC,GAAG,QAAQ,EAAE,uBAAuB,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI;IAI/D,UAAU,CAAC,GAAG,QAAQ,EAAE,sBAAsB,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI;IAIzD,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;IAgBxF,cAAc,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAU3F,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC;CAMnC"}
@@ -0,0 +1,35 @@
1
+ export class MiddlewareManager {
2
+ beforeHandlers = [];
3
+ finallyHandlers = [];
4
+ addBefore(...handlers) {
5
+ this.beforeHandlers.push(...handlers);
6
+ }
7
+ addFinally(...handlers) {
8
+ this.finallyHandlers.push(...handlers);
9
+ }
10
+ async executeBefore(request) {
11
+ let currentRequest = request;
12
+ for (const handler of this.beforeHandlers) {
13
+ const result = await handler(currentRequest);
14
+ if (result instanceof Response) {
15
+ return result;
16
+ }
17
+ currentRequest = result;
18
+ }
19
+ return currentRequest;
20
+ }
21
+ async executeFinally(response, request) {
22
+ let currentResponse = response;
23
+ for (const handler of this.finallyHandlers) {
24
+ currentResponse = await handler(currentResponse, request);
25
+ }
26
+ return currentResponse;
27
+ }
28
+ clone() {
29
+ const manager = new MiddlewareManager();
30
+ manager.beforeHandlers = [...this.beforeHandlers];
31
+ manager.finallyHandlers = [...this.finallyHandlers];
32
+ return manager;
33
+ }
34
+ }
35
+ //# sourceMappingURL=manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/middleware/manager.ts"],"names":[],"mappings":"AAQA,MAAM,OAAO,iBAAiB;IACpB,cAAc,GAAsC,EAAE,CAAC;IACvD,eAAe,GAAqC,EAAE,CAAC;IAE/D,SAAS,CAAC,GAAG,QAA2C;QACtD,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IACxC,CAAC;IAED,UAAU,CAAC,GAAG,QAA0C;QACtD,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,OAA8B;QAChD,IAAI,cAAc,GAAG,OAAO,CAAC;QAE7B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YAC1C,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC;YAE7C,IAAI,MAAM,YAAY,QAAQ,EAAE,CAAC;gBAC/B,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,cAAc,GAAG,MAAM,CAAC;QAC1B,CAAC;QAED,OAAO,cAAc,CAAC;IACxB,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,QAAkB,EAAE,OAA8B;QACrE,IAAI,eAAe,GAAG,QAAQ,CAAC;QAE/B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YAC3C,eAAe,GAAG,MAAM,OAAO,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;QAC5D,CAAC;QAED,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,KAAK;QACH,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAU,CAAC;QAChD,OAAO,CAAC,cAAc,GAAG,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,CAAC;QAClD,OAAO,CAAC,eAAe,GAAG,CAAC,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;QACpD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF"}
@@ -0,0 +1,85 @@
1
+ import type { IRequest } from 'itty-router';
2
+ export interface DefaultAuthUser {
3
+ id: string;
4
+ email?: string;
5
+ role?: string;
6
+ permissions?: string[];
7
+ [key: string]: any;
8
+ }
9
+ export interface VectorTypes {
10
+ auth?: any;
11
+ context?: any;
12
+ cache?: any;
13
+ metadata?: any;
14
+ }
15
+ export interface DefaultVectorTypes extends VectorTypes {
16
+ auth: DefaultAuthUser;
17
+ context: Record<string, any>;
18
+ cache: any;
19
+ metadata: Record<string, any>;
20
+ }
21
+ export type GetAuthType<T extends VectorTypes> = T['auth'] extends undefined ? DefaultAuthUser : T['auth'];
22
+ export type GetContextType<T extends VectorTypes> = T['context'] extends undefined ? Record<string, any> : T['context'];
23
+ export type GetCacheType<T extends VectorTypes> = T['cache'] extends undefined ? any : T['cache'];
24
+ export type GetMetadataType<T extends VectorTypes> = T['metadata'] extends undefined ? Record<string, any> : T['metadata'];
25
+ export type AuthUser = DefaultAuthUser;
26
+ export interface VectorRequest<TTypes extends VectorTypes = DefaultVectorTypes> extends Omit<IRequest, 'params'> {
27
+ authUser?: GetAuthType<TTypes>;
28
+ context: GetContextType<TTypes>;
29
+ metadata?: GetMetadataType<TTypes>;
30
+ content?: any;
31
+ params?: Record<string, string>;
32
+ startTime?: number;
33
+ [key: string]: any;
34
+ }
35
+ export interface CacheOptions {
36
+ key?: string;
37
+ ttl?: number;
38
+ }
39
+ export interface RouteOptions<TTypes extends VectorTypes = DefaultVectorTypes> {
40
+ method: string;
41
+ path: string;
42
+ auth?: boolean;
43
+ expose?: boolean;
44
+ cache?: CacheOptions | number;
45
+ rawRequest?: boolean;
46
+ rawResponse?: boolean;
47
+ responseContentType?: string;
48
+ metadata?: GetMetadataType<TTypes>;
49
+ }
50
+ export interface VectorConfig<TTypes extends VectorTypes = DefaultVectorTypes> {
51
+ port?: number;
52
+ hostname?: string;
53
+ reusePort?: boolean;
54
+ development?: boolean;
55
+ cors?: CorsOptions;
56
+ before?: BeforeMiddlewareHandler<TTypes>[];
57
+ finally?: AfterMiddlewareHandler<TTypes>[];
58
+ routesDir?: string;
59
+ autoDiscover?: boolean;
60
+ }
61
+ export interface CorsOptions {
62
+ origin?: string | string[] | ((origin: string) => boolean);
63
+ credentials?: boolean;
64
+ allowHeaders?: string | string[];
65
+ allowMethods?: string | string[];
66
+ exposeHeaders?: string | string[];
67
+ maxAge?: number;
68
+ }
69
+ export type BeforeMiddlewareHandler<TTypes extends VectorTypes = DefaultVectorTypes> = (request: VectorRequest<TTypes>) => Promise<VectorRequest<TTypes> | Response> | VectorRequest<TTypes> | Response;
70
+ export type AfterMiddlewareHandler<TTypes extends VectorTypes = DefaultVectorTypes> = (response: Response, request: VectorRequest<TTypes>) => Promise<Response> | Response;
71
+ export type MiddlewareHandler = BeforeMiddlewareHandler | AfterMiddlewareHandler;
72
+ export type RouteHandler<TTypes extends VectorTypes = DefaultVectorTypes> = (request: VectorRequest<TTypes>) => Promise<any> | any;
73
+ export type ProtectedHandler<TTypes extends VectorTypes = DefaultVectorTypes> = (request: VectorRequest<TTypes>) => Promise<GetAuthType<TTypes>> | GetAuthType<TTypes>;
74
+ export type CacheHandler = (key: string, factory: () => Promise<any>, ttl: number) => Promise<any>;
75
+ export interface RouteDefinition<TTypes extends VectorTypes = DefaultVectorTypes> {
76
+ options: RouteOptions<TTypes>;
77
+ handler: RouteHandler<TTypes>;
78
+ }
79
+ export interface GeneratedRoute<TTypes extends VectorTypes = DefaultVectorTypes> {
80
+ name: string;
81
+ path: string;
82
+ method: string;
83
+ options: RouteOptions<TTypes>;
84
+ }
85
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAID,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,QAAQ,CAAC,EAAE,GAAG,CAAC;CAChB;AAGD,MAAM,WAAW,kBAAmB,SAAQ,WAAW;IACrD,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CA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M,CAAC,CAAC;IAC9B,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;CAC/B;AAED,MAAM,WAAW,cAAc,CAAC,MAAM,SAAS,WAAW,GAAG,kBAAkB;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;CAC/B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,25 @@
1
+ export declare enum LogLevel {
2
+ DEBUG = 0,
3
+ INFO = 1,
4
+ WARN = 2,
5
+ ERROR = 3
6
+ }
7
+ export interface LoggerConfig {
8
+ level: LogLevel;
9
+ prefix?: string;
10
+ timestamp?: boolean;
11
+ }
12
+ export declare class Logger {
13
+ private config;
14
+ constructor(config?: Partial<LoggerConfig>);
15
+ private formatMessage;
16
+ debug(message: string, ...args: any[]): void;
17
+ info(message: string, ...args: any[]): void;
18
+ warn(message: string, ...args: any[]): void;
19
+ error(message: string, error?: Error): void;
20
+ success(message: string): void;
21
+ loading(message: string): void;
22
+ setLevel(level: LogLevel): void;
23
+ }
24
+ export declare const logger: Logger;
25
+ //# sourceMappingURL=logger.d.ts.map