@oxog/spark 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +538 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,291 +0,0 @@
1
- declare module '@oxog/spark' {
2
- // Basic types without Node.js dependencies
3
- interface IncomingMessage {
4
- url?: string;
5
- method?: string;
6
- headers: Record<string, string | string[] | undefined>;
7
- }
8
-
9
- interface ServerResponse {
10
- statusCode: number;
11
- setHeader(name: string, value: string | string[]): void;
12
- writeHead(statusCode: number, headers?: Record<string, string | string[]>): void;
13
- write(chunk: any): boolean;
14
- end(chunk?: any): void;
15
- }
16
-
17
- interface Server {
18
- listen(port?: number, hostname?: string, callback?: () => void): void;
19
- close(callback?: () => void): void;
20
- address(): { address: string; port: number } | null;
21
- }
22
-
23
- export interface AppOptions {
24
- port?: number;
25
- host?: string;
26
- cluster?: boolean;
27
- compression?: boolean;
28
- security?: {
29
- cors?: CorsOptions;
30
- rateLimit?: RateLimitOptions;
31
- csrf?: boolean;
32
- };
33
- https?: {
34
- key: string;
35
- cert: string;
36
- };
37
- }
38
-
39
- export interface Context<TState = any> {
40
- req: IncomingMessage;
41
- res: ServerResponse;
42
- app: Spark;
43
- method: string;
44
- url: string;
45
- path: string;
46
- query: Record<string, string | string[]>;
47
- params: Record<string, string>;
48
- headers: Record<string, string>;
49
- cookies: Record<string, string>;
50
- body: any;
51
- files: Record<string, UploadedFile> | null;
52
- session: any;
53
- state: TState;
54
- responded: boolean;
55
- statusCode: number;
56
-
57
- get(headerName: string): string | undefined;
58
- set(headerName: string, value: string): Context;
59
- setHeader(name: string, value: string): Context;
60
- getHeader(name: string): string | undefined;
61
- removeHeader(name: string): Context;
62
- status(code: number): Context;
63
- redirect(url: string, status?: number): Context;
64
- json(data: any): Context;
65
- text(data: string): Context;
66
- html(data: string): Context;
67
- send(data: any): Context;
68
- end(data?: any): Context;
69
- setCookie(name: string, value: string, options?: CookieOptions): Context;
70
- clearCookie(name: string, options?: CookieOptions): Context;
71
- }
72
-
73
- export interface UploadedFile {
74
- filename: string;
75
- contentType: string;
76
- size: number;
77
- data: any;
78
- }
79
-
80
- export interface CookieOptions {
81
- maxAge?: number;
82
- expires?: Date;
83
- path?: string;
84
- domain?: string;
85
- secure?: boolean;
86
- httpOnly?: boolean;
87
- sameSite?: 'strict' | 'lax' | 'none';
88
- }
89
-
90
- export type Middleware<TState = any> = (
91
- ctx: Context<TState>,
92
- next: () => Promise<void>
93
- ) => Promise<void> | void;
94
-
95
- export interface RouterOptions {
96
- prefix?: string;
97
- strict?: boolean;
98
- sensitive?: boolean;
99
- }
100
-
101
- export interface Route {
102
- method: string;
103
- path: string;
104
- middleware: Middleware[];
105
- }
106
-
107
- export class Router {
108
- constructor(options?: RouterOptions);
109
- use(...middleware: Middleware[]): Router;
110
- get(path: string, ...middleware: Middleware[]): Router;
111
- post(path: string, ...middleware: Middleware[]): Router;
112
- put(path: string, ...middleware: Middleware[]): Router;
113
- patch(path: string, ...middleware: Middleware[]): Router;
114
- delete(path: string, ...middleware: Middleware[]): Router;
115
- head(path: string, ...middleware: Middleware[]): Router;
116
- options(path: string, ...middleware: Middleware[]): Router;
117
- all(path: string, ...middleware: Middleware[]): Router;
118
- prefix(prefix: string): Router;
119
- group(prefix: string, fn: (router: Router) => void): Router;
120
- routes(): Middleware;
121
- middleware(prefix?: string): Middleware;
122
- }
123
-
124
- export class Spark {
125
- constructor(options?: AppOptions);
126
- options: AppOptions;
127
- server?: Server;
128
- listening: boolean;
129
-
130
- use(path?: string | Middleware, ...middleware: Middleware[]): Spark;
131
- get(path: string, ...middleware: Middleware[]): Spark;
132
- post(path: string, ...middleware: Middleware[]): Spark;
133
- put(path: string, ...middleware: Middleware[]): Spark;
134
- patch(path: string, ...middleware: Middleware[]): Spark;
135
- delete(path: string, ...middleware: Middleware[]): Spark;
136
- head(path: string, ...middleware: Middleware[]): Spark;
137
- options(path: string, ...middleware: Middleware[]): Spark;
138
- all(path: string, ...middleware: Middleware[]): Spark;
139
-
140
- listen(port?: number, host?: string, callback?: () => void): Promise<void>;
141
- close(): Promise<void>;
142
- handleError(error: Error, ctx?: Context): void;
143
- onShutdown(handler: () => Promise<void> | void): void;
144
-
145
- on(event: 'error', listener: (error: Error, ctx?: Context) => void): Spark;
146
- on(event: 'listening', listener: () => void): Spark;
147
- on(event: string, listener: (...args: any[]) => void): Spark;
148
-
149
- emit(event: 'error', error: Error, ctx?: Context): boolean;
150
- emit(event: 'listening'): boolean;
151
- emit(event: string, ...args: any[]): boolean;
152
- }
153
-
154
- // Middleware types
155
- export interface CorsOptions {
156
- origin?: boolean | string | string[] | ((ctx: Context) => string | boolean);
157
- credentials?: boolean;
158
- methods?: string[];
159
- allowedHeaders?: string[];
160
- exposedHeaders?: string[];
161
- maxAge?: number;
162
- }
163
-
164
- export interface RateLimitOptions {
165
- max?: number;
166
- windowMs?: number;
167
- message?: string;
168
- keyGenerator?: (ctx: Context) => string;
169
- skip?: (ctx: Context) => boolean;
170
- standardHeaders?: boolean;
171
- legacyHeaders?: boolean;
172
- }
173
-
174
- export interface SessionOptions {
175
- key?: string;
176
- secret: string;
177
- store?: any;
178
- cookie?: {
179
- maxAge?: number;
180
- httpOnly?: boolean;
181
- secure?: boolean;
182
- sameSite?: 'strict' | 'lax' | 'none';
183
- path?: string;
184
- domain?: string;
185
- };
186
- genid?: () => string;
187
- rolling?: boolean;
188
- resave?: boolean;
189
- saveUninitialized?: boolean;
190
- }
191
-
192
- export interface StaticOptions {
193
- root?: string;
194
- index?: string | string[];
195
- hidden?: boolean;
196
- extensions?: string[];
197
- redirect?: boolean;
198
- maxAge?: number;
199
- }
200
-
201
- export interface CompressionOptions {
202
- threshold?: number;
203
- level?: number;
204
- filter?: (ctx: Context) => boolean;
205
- }
206
-
207
- export interface BodyParserOptions {
208
- json?: boolean;
209
- urlencoded?: boolean;
210
- text?: boolean;
211
- multipart?: boolean;
212
- limit?: string | number;
213
- }
214
-
215
- // Middleware functions
216
- export function bodyParser(options?: BodyParserOptions): Middleware;
217
- export function cors(options?: CorsOptions): Middleware;
218
- export function compression(options?: CompressionOptions): Middleware;
219
- export function rateLimit(options?: RateLimitOptions): Middleware;
220
- export function session(options: SessionOptions): Middleware;
221
- export function security(options?: any): Middleware;
222
- export function healthCheck(options?: any): Middleware;
223
- export function metrics(options?: any): Middleware;
224
- export function logger(options?: any): Middleware;
225
-
226
- // Main exports
227
- export const Application: typeof Spark;
228
- export const App: typeof Spark;
229
-
230
- // Error handling utilities
231
- export const errorHandling: {
232
- asyncHandler: (fn: Middleware) => Middleware;
233
- errorHandler: () => Middleware;
234
- createError: (status: number, message: string) => Error;
235
- errors: {
236
- badRequest: (message?: string) => Error;
237
- unauthorized: (message?: string) => Error;
238
- forbidden: (message?: string) => Error;
239
- notFound: (message?: string) => Error;
240
- conflict: (message?: string) => Error;
241
- tooManyRequests: (message?: string) => Error;
242
- internalServerError: (message?: string) => Error;
243
- };
244
- };
245
-
246
- // Middleware collection
247
- export const middleware: {
248
- bodyParser: typeof bodyParser;
249
- cors: typeof cors;
250
- compression: typeof compression;
251
- static: (root: string, options?: StaticOptions) => Middleware;
252
- session: typeof session;
253
- rateLimit: typeof rateLimit;
254
- security: typeof security;
255
- helmet: typeof security;
256
- healthCheck: typeof healthCheck;
257
- health: typeof healthCheck;
258
- metrics: typeof metrics;
259
- logger: typeof logger;
260
- cache: (options?: any) => Middleware;
261
- compress: typeof compression;
262
- };
263
-
264
- // Utility classes
265
- export const utils: {
266
- ContextPool: any;
267
- RegexValidator: any;
268
- SafeRegexCache: any;
269
- };
270
-
271
- // Default export for ES6 compatibility
272
- export default {
273
- Spark,
274
- App,
275
- Application,
276
- Router,
277
- Context,
278
- middleware,
279
- bodyParser,
280
- cors,
281
- compression,
282
- rateLimit,
283
- session,
284
- security,
285
- healthCheck,
286
- metrics,
287
- logger,
288
- errorHandling,
289
- utils
290
- };
291
- }
@@ -1,150 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Wraps async route handlers to properly catch errors
5
- * @param {Function} fn - Async function to wrap
6
- * @returns {Function} Wrapped function that catches errors
7
- */
8
- function asyncHandler(fn) {
9
- return (ctx, next) => {
10
- const result = fn(ctx, next);
11
-
12
- // If it's a promise, catch any errors
13
- if (result && typeof result.then === 'function') {
14
- return result.catch((error) => {
15
- // Handle error appropriately
16
- if (ctx && ctx.app) {
17
- ctx.app.emit('error', error, ctx);
18
- }
19
- throw error; // Re-throw to be caught by framework
20
- });
21
- }
22
-
23
- return result;
24
- };
25
- }
26
-
27
- /**
28
- * Wraps all methods of a router or controller
29
- * @param {Object} target - Object with methods to wrap
30
- * @returns {Object} Object with wrapped methods
31
- */
32
- function wrapAsync(target) {
33
- const wrapped = {};
34
-
35
- for (const key in target) {
36
- if (typeof target[key] === 'function') {
37
- wrapped[key] = asyncHandler(target[key]);
38
- } else {
39
- wrapped[key] = target[key];
40
- }
41
- }
42
-
43
- return wrapped;
44
- }
45
-
46
- /**
47
- * Error handler middleware that can work as both regular middleware and error handler
48
- * @param {Error|Context} errOrCtx - Error object or Context (when used as regular middleware)
49
- * @param {Context|Function} ctxOrNext - Context or next function
50
- * @param {Function} [next] - Next middleware function
51
- */
52
- function errorHandler(errOrCtx, ctxOrNext, next) {
53
- // Check if this is being used as error handler (3 args) or regular middleware (2 args)
54
- if (next && typeof next === 'function') {
55
- // This is an error handler (err, ctx, next)
56
- const err = errOrCtx;
57
- const ctx = ctxOrNext;
58
-
59
- // Skip if response already sent
60
- if (ctx.responded) {
61
- return;
62
- }
63
-
64
- // Log error for debugging
65
- console.error('Error handler caught:', err);
66
-
67
- // Set status code
68
- const status = err.status || err.statusCode || 500;
69
- ctx.status(status);
70
-
71
- handleErrorResponse(err, ctx, status);
72
- } else {
73
- // This is regular middleware (ctx, next)
74
- const ctx = errOrCtx;
75
- const nextFn = ctxOrNext;
76
-
77
- // Just pass through - this shouldn't normally happen
78
- return nextFn();
79
- }
80
- }
81
-
82
- function handleErrorResponse(err, ctx, status) {
83
- // Prepare error response
84
- const isDevelopment = process.env.NODE_ENV !== 'production';
85
- const errorResponse = {
86
- error: err.message || 'Internal Server Error',
87
- status: status
88
- };
89
-
90
- // Add stack trace in development
91
- if (isDevelopment) {
92
- errorResponse.stack = err.stack;
93
- }
94
-
95
- // Add any additional error properties
96
- if (err.code) {
97
- errorResponse.code = err.code;
98
- }
99
-
100
- if (err.details) {
101
- errorResponse.details = err.details;
102
- }
103
-
104
- // Send error response
105
- ctx.json(errorResponse);
106
- }
107
-
108
- /**
109
- * Creates a custom error with status code
110
- * @param {string} message - Error message
111
- * @param {number} status - HTTP status code
112
- * @param {string} code - Error code
113
- * @returns {Error} Custom error object
114
- */
115
- function createError(message, status = 500, code = null) {
116
- const error = new Error(message);
117
- error.status = status;
118
- if (code) {
119
- error.code = code;
120
- }
121
- return error;
122
- }
123
-
124
- /**
125
- * Common HTTP errors
126
- */
127
- const errors = {
128
- badRequest: (message = 'Bad Request') => createError(message, 400, 'BAD_REQUEST'),
129
- unauthorized: (message = 'Unauthorized') => createError(message, 401, 'UNAUTHORIZED'),
130
- forbidden: (message = 'Forbidden') => createError(message, 403, 'FORBIDDEN'),
131
- notFound: (message = 'Not Found') => createError(message, 404, 'NOT_FOUND'),
132
- methodNotAllowed: (message = 'Method Not Allowed') => createError(message, 405, 'METHOD_NOT_ALLOWED'),
133
- conflict: (message = 'Conflict') => createError(message, 409, 'CONFLICT'),
134
- gone: (message = 'Gone') => createError(message, 410, 'GONE'),
135
- unprocessableEntity: (message = 'Unprocessable Entity') => createError(message, 422, 'UNPROCESSABLE_ENTITY'),
136
- tooManyRequests: (message = 'Too Many Requests') => createError(message, 429, 'TOO_MANY_REQUESTS'),
137
- internalServerError: (message = 'Internal Server Error') => createError(message, 500, 'INTERNAL_SERVER_ERROR'),
138
- notImplemented: (message = 'Not Implemented') => createError(message, 501, 'NOT_IMPLEMENTED'),
139
- badGateway: (message = 'Bad Gateway') => createError(message, 502, 'BAD_GATEWAY'),
140
- serviceUnavailable: (message = 'Service Unavailable') => createError(message, 503, 'SERVICE_UNAVAILABLE'),
141
- gatewayTimeout: (message = 'Gateway Timeout') => createError(message, 504, 'GATEWAY_TIMEOUT')
142
- };
143
-
144
- module.exports = {
145
- asyncHandler,
146
- wrapAsync,
147
- errorHandler,
148
- createError,
149
- errors
150
- };