@oxog/spark 1.1.0 → 1.2.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 +632 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
package/types/index.d.ts CHANGED
@@ -1,291 +1,536 @@
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
+ // Type definitions for @oxog/spark.
2
+ // The runtime is a single CommonJS module that also serves ESM `import`.
3
+ // Node's own types are not required: request/response objects are typed
4
+ // structurally below.
5
+
6
+ /** Incoming HTTP request (structural subset of http.IncomingMessage). */
7
+ export interface IncomingMessage {
8
+ url?: string;
9
+ method?: string;
10
+ httpVersion?: string;
11
+ headers: Record<string, string | string[] | undefined>;
12
+ [key: string]: any;
13
+ }
14
+
15
+ /** HTTP response (structural subset of http.ServerResponse). */
16
+ export interface ServerResponse {
17
+ statusCode: number;
18
+ headersSent: boolean;
19
+ setHeader(name: string, value: number | string | readonly string[]): any;
20
+ getHeader(name: string): number | string | string[] | undefined;
21
+ end(chunk?: any): any;
22
+ [key: string]: any;
23
+ }
24
+
25
+ /** HTTP server (structural subset of http.Server). */
26
+ export interface Server {
27
+ listening: boolean;
28
+ close(callback?: (error?: Error) => void): any;
29
+ address(): { address: string; family: string; port: number } | string | null;
30
+ [key: string]: any;
31
+ }
32
+
33
+ /** Parsed request URL (a WHATWG URL instance). */
34
+ export interface RequestURL {
35
+ href: string;
36
+ origin: string;
37
+ protocol: string;
38
+ host: string;
39
+ hostname: string;
40
+ port: string;
41
+ pathname: string;
42
+ search: string;
43
+ hash: string;
44
+ searchParams: { get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean };
45
+ toString(): string;
46
+ }
47
+
48
+ /** A readable stream that can be piped to the response. */
49
+ export interface ReadableLike {
50
+ pipe(destination: any, options?: { end?: boolean }): any;
51
+ destroy(error?: Error): any;
52
+ }
53
+
54
+ export interface AppSettings {
55
+ /** Trust X-Forwarded-For / X-Real-IP in ctx.ip() and ctx.ips(). */
56
+ trustProxy?: boolean;
57
+ /** Hosts ctx.redirect() may send clients to (subdomains included). */
58
+ allowedRedirectDomains?: Array<string | RegExp>;
59
+ /** Allow redirects to any external host (not recommended). */
60
+ allowOpenRedirects?: boolean;
61
+ [key: string]: unknown;
62
+ }
63
+
64
+ export interface AppOptions {
65
+ port?: number | string;
66
+ host?: string;
67
+ cluster?: boolean;
68
+ https?: Record<string, unknown>;
69
+ settings?: AppSettings;
70
+ /** Milliseconds close() waits for in-flight requests (default 10000). */
71
+ shutdownTimeout?: number;
72
+ /** Close gracefully on SIGTERM/SIGINT while listening (default true). */
73
+ handleSignals?: boolean;
74
+ /** Exit (code 1) on uncaught exceptions while listening (default true). */
75
+ exitOnUncaughtException?: boolean;
76
+ /** Exit (code 1) on unhandled rejections while listening (default false). */
77
+ exitOnUnhandledRejection?: boolean;
78
+ [key: string]: unknown;
79
+ }
80
+
81
+ export interface CookieOptions {
82
+ maxAge?: number;
83
+ expires?: Date;
84
+ path?: string;
85
+ domain?: string;
86
+ secure?: boolean;
87
+ httpOnly?: boolean;
88
+ sameSite?: 'strict' | 'lax' | 'none' | 'Strict' | 'Lax' | 'None';
89
+ }
90
+
91
+ export interface UploadedFile {
92
+ filename: string;
93
+ contentType: string;
94
+ size: number;
95
+ data: Uint8Array;
96
+ }
97
+
98
+ export interface SessionData {
99
+ readonly id: string;
100
+ readonly isNew: boolean;
101
+ readonly destroyed: boolean | undefined;
102
+ modified: boolean | undefined;
103
+ destroy(): Promise<void>;
104
+ regenerate(): Promise<void>;
105
+ reload(): Promise<void>;
106
+ save(): Promise<void>;
107
+ touch(): Promise<void>;
108
+ [key: string]: any;
109
+ }
110
+
111
+ export declare class Context<TState = any> {
112
+ constructor(req: IncomingMessage, res: ServerResponse, app?: Spark);
113
+ req: IncomingMessage;
114
+ res: ServerResponse;
115
+ app: Spark;
116
+ method: string;
117
+ url: RequestURL | null;
118
+ originalUrl: string;
119
+ path: string;
120
+ mountpath?: string;
121
+ query: Record<string, string | string[]>;
122
+ params: Record<string, string>;
123
+ headers: Record<string, string | string[] | undefined>;
124
+ responseHeaders: Record<string, string | string[]>;
125
+ cookies: Record<string, string | true>;
126
+ /** Parsed request body (set by bodyParser). */
127
+ body: any;
128
+ files: Record<string, UploadedFile> | null;
129
+ session: SessionData | null;
130
+ state: TState;
131
+ responded: boolean;
132
+ statusCode: number;
133
+ /** Set by the csrf() middleware. */
134
+ csrfToken?: () => string;
135
+ [key: string]: any;
136
+
137
+ /** Read a request header (case-insensitive). */
138
+ get(headerName: string): string | undefined;
139
+ /** Set a response header. Rejects CR/LF/NUL in values. */
140
+ set(headerName: string, value: string | number): this;
141
+ setHeader(name: string, value: string | number): this;
142
+ getHeader(name: string): string | string[] | undefined;
143
+ removeHeader(name: string): this;
144
+ status(code: number | string): this;
145
+ redirect(url: string, status?: number): this;
146
+ json(data: unknown): this;
147
+ text(data: string): this;
148
+ html(data: string): this;
149
+ send(data?: unknown): this;
150
+ end(data?: unknown): this;
151
+ /** Pipe a readable stream as the response body (with backpressure). */
152
+ stream(readable: ReadableLike): Promise<void>;
153
+ setCookie(name: string, value: string | number | boolean | null | undefined, options?: CookieOptions): this;
154
+ clearCookie(name: string, options?: CookieOptions): this;
155
+ is(type: string): boolean;
156
+ accepts(types: string | string[]): string | false;
157
+ fresh(): boolean;
158
+ stale(): boolean;
159
+ secure(): boolean;
160
+ xhr(): boolean;
161
+ ip(): string;
162
+ ips(): string[];
163
+ protocol(): 'http' | 'https';
164
+ host(): string;
165
+ hostname(): string;
166
+ port(): number;
167
+ subdomains(): string[];
168
+ type(): string;
169
+ charset(): string;
170
+ length(): number;
171
+ toJSON(): Record<string, unknown>;
172
+ }
173
+
174
+ export type Next = (error?: unknown) => Promise<void>;
175
+
176
+ /** Middleware or route handler. The return value is ignored (it may be awaited). */
177
+ export type Middleware<TState = any> = (ctx: Context<TState>, next: Next) => unknown;
178
+
179
+ export interface RouterOptions {
180
+ caseSensitive?: boolean;
181
+ /** Alias of caseSensitive. */
182
+ sensitive?: boolean;
183
+ /** Trailing slash is significant. */
184
+ strict?: boolean;
185
+ }
186
+
187
+ export declare class Route {
188
+ constructor(path: string);
189
+ path: string;
190
+ get(...handlers: Middleware[]): this;
191
+ post(...handlers: Middleware[]): this;
192
+ put(...handlers: Middleware[]): this;
193
+ delete(...handlers: Middleware[]): this;
194
+ patch(...handlers: Middleware[]): this;
195
+ head(...handlers: Middleware[]): this;
196
+ options(...handlers: Middleware[]): this;
197
+ all(...handlers: Middleware[]): this;
198
+ }
199
+
200
+ type RouteRegistrar<T> = (path: string | RegExp | Array<string | RegExp>, ...handlers: Middleware[]) => T;
201
+
202
+ export declare class Router {
203
+ constructor(options?: RouterOptions);
204
+ /** Router configuration; also callable to register OPTIONS routes. */
205
+ options: RouterOptions & RouteRegistrar<Router>;
206
+ use(...middleware: Array<Middleware | Router>): this;
207
+ use(path: string, ...middleware: Array<Middleware | Router>): this;
208
+ get: RouteRegistrar<this>;
209
+ post: RouteRegistrar<this>;
210
+ put: RouteRegistrar<this>;
211
+ patch: RouteRegistrar<this>;
212
+ delete: RouteRegistrar<this>;
213
+ head: RouteRegistrar<this>;
214
+ all: RouteRegistrar<this>;
215
+ route(path: string, method: string | null, ...handlers: Middleware[]): Route;
216
+ param(name: string, handler: (ctx: Context, next: () => void, value: string, name: string) => unknown): this;
217
+ group(prefix: string, fn: (router: Router) => void): this;
218
+ version(version: string | number, fn: (router: Router) => void): this;
219
+ mount(path: string, router: Router): this;
220
+ routes(): Middleware;
221
+ middleware(prefix?: string): Middleware;
222
+ handle(ctx: Context, next: Next): Promise<void>;
223
+ }
224
+
225
+ export declare class Spark {
226
+ constructor(options?: AppOptions);
227
+ /** Application configuration; also callable to register OPTIONS routes. */
228
+ options: AppOptions & RouteRegistrar<Spark>;
229
+ settings: AppSettings;
230
+ router: Router;
231
+ server: Server | null;
232
+ listening: boolean;
233
+
234
+ use(middleware: Middleware | Router): this;
235
+ use(path: string, middleware: Middleware | Router): this;
236
+ get: RouteRegistrar<this>;
237
+ post: RouteRegistrar<this>;
238
+ put: RouteRegistrar<this>;
239
+ patch: RouteRegistrar<this>;
240
+ delete: RouteRegistrar<this>;
241
+ head: RouteRegistrar<this>;
242
+ all: RouteRegistrar<this>;
243
+
244
+ /** Start listening; the callback runs once the server is bound. */
245
+ listen(callback?: () => void): this;
246
+ listen(port: number | string, callback?: () => void): this;
247
+ listen(port: number | string, host: string, callback?: () => void): this;
248
+ /** Stop accepting connections and resolve once the server is closed. */
249
+ close(): Promise<void>;
250
+ handleError(error: unknown, ctx: Context): Promise<void>;
251
+ onShutdown(handler: () => unknown): this;
252
+ gracefulShutdown(exitCode?: number): Promise<void>;
253
+
254
+ on(event: 'error', listener: (error: Error, ctx?: Context) => void): this;
255
+ on(event: 'listening' | 'close', listener: () => void): this;
256
+ on(event: string, listener: (...args: any[]) => void): this;
257
+ once(event: string, listener: (...args: any[]) => void): this;
258
+ off(event: string, listener: (...args: any[]) => void): this;
259
+ emit(event: string, ...args: any[]): boolean;
260
+ }
261
+
262
+ /** @deprecated Use Spark. */
263
+ export declare const App: typeof Spark;
264
+ export declare const Application: typeof Spark;
265
+
266
+ // Middleware option types
267
+
268
+ export interface CorsOptions {
269
+ origin?: boolean | string | Array<string | RegExp> | ((ctx: Context) => string | boolean | Promise<string | boolean>);
270
+ credentials?: boolean;
271
+ methods?: string[];
272
+ allowedHeaders?: string[] | string | ((ctx: Context) => string[] | string);
273
+ exposedHeaders?: string[];
274
+ maxAge?: number;
275
+ preflightContinue?: boolean;
276
+ optionsSuccessStatus?: number;
277
+ }
278
+
279
+ export interface RateLimitStore {
280
+ incr(key: string, windowMs: number): Promise<{ totalHits: number; resetTime: number }>;
281
+ decrement(key: string): Promise<void>;
282
+ reset(key: string): Promise<void>;
283
+ cleanup?(): void;
284
+ }
285
+
286
+ export interface RateLimitOptions {
287
+ max?: number;
288
+ windowMs?: number;
289
+ message?: string;
290
+ statusCode?: number;
291
+ /** Send X-RateLimit-* headers (default true). */
292
+ headers?: boolean;
293
+ keyGenerator?: (ctx: Context) => string;
294
+ skip?: (ctx: Context) => boolean | Promise<boolean>;
295
+ handler?: (ctx: Context, options: RateLimitOptions, resetTime?: number) => unknown;
296
+ onLimitReached?: (ctx: Context, options: RateLimitOptions) => void;
297
+ skipSuccessfulRequests?: boolean;
298
+ skipFailedRequests?: boolean;
299
+ store?: RateLimitStore;
300
+ maxKeys?: number;
301
+ }
302
+
303
+ export interface SessionStore {
304
+ get(id: string): Promise<Record<string, any> | null>;
305
+ set(id: string, data: Record<string, any>, maxAge: number): Promise<void>;
306
+ destroy(id: string): Promise<void>;
307
+ touch(id: string, data: Record<string, any>, maxAge: number): Promise<void>;
308
+ }
309
+
310
+ export interface SessionOptions {
311
+ secret: string;
312
+ key?: string;
313
+ store?: SessionStore;
314
+ cookie?: CookieOptions;
315
+ genid?: () => string;
316
+ rolling?: boolean;
317
+ resave?: boolean;
318
+ saveUninitialized?: boolean;
319
+ }
320
+
321
+ export interface StaticOptions {
322
+ maxAge?: number;
323
+ index?: string | string[] | false;
324
+ dotfiles?: 'ignore' | 'deny' | 'allow';
325
+ /** Legacy alias for dotfiles: 'allow'. */
326
+ hidden?: boolean;
327
+ etag?: boolean;
328
+ lastModified?: boolean;
329
+ extensions?: string[];
330
+ fallthrough?: boolean;
331
+ redirect?: boolean;
332
+ setHeaders?: (ctx: Context, fileName: string, stats: unknown) => void;
333
+ }
334
+
335
+ export interface CompressionOptions {
336
+ threshold?: number;
337
+ level?: number;
338
+ encodings?: Array<'br' | 'gzip' | 'deflate'>;
339
+ filter?: (ctx: Context, body: unknown) => boolean;
340
+ }
341
+
342
+ export interface BodyParserOptions {
343
+ /** Maximum body size in bytes, or a string such as '100kb' / '5mb' (default 1mb). */
344
+ limit?: number | string;
345
+ type?: 'auto' | 'json' | 'urlencoded' | 'multipart' | 'text' | 'raw';
346
+ encoding?: string;
347
+ /** Decompress gzip/deflate/br request bodies (default true). */
348
+ inflate?: boolean;
349
+ verify?: (req: IncomingMessage, res: ServerResponse, body: unknown) => unknown;
350
+ }
351
+
352
+ export interface CsrfOptions {
353
+ secret: string;
354
+ cookieName?: string;
355
+ cookieOptions?: CookieOptions;
356
+ headerName?: string;
357
+ bodyName?: string;
358
+ sessionKey?: string;
359
+ ignoreMethods?: string[];
360
+ }
361
+
362
+ export interface SecurityOptions {
363
+ contentSecurityPolicy?: boolean | Record<string, string | string[] | false>;
364
+ crossOriginEmbedderPolicy?: boolean;
365
+ crossOriginOpenerPolicy?: boolean;
366
+ crossOriginResourcePolicy?: boolean;
367
+ dnsPrefetchControl?: boolean;
368
+ frameguard?: boolean | string | { action?: string; domain?: string };
369
+ hidePoweredBy?: boolean;
370
+ hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean };
371
+ ieNoOpen?: boolean;
372
+ noSniff?: boolean;
373
+ originAgentCluster?: boolean;
374
+ permittedCrossDomainPolicies?: boolean;
375
+ referrerPolicy?: boolean | string;
376
+ xssFilter?: boolean;
377
+ }
378
+
379
+ export interface CacheOptions {
380
+ maxAge?: number;
381
+ maxEntries?: number;
382
+ key?: (ctx: Context) => string;
383
+ condition?: (ctx: Context) => boolean;
384
+ store?: { get(key: string): any; set(key: string, value: any): void };
385
+ }
386
+
387
+ // Middleware factories
388
+
389
+ export interface BodyParser {
390
+ (options?: BodyParserOptions): Middleware;
391
+ json(options?: BodyParserOptions): Middleware;
392
+ urlencoded(options?: BodyParserOptions): Middleware;
393
+ text(options?: BodyParserOptions): Middleware;
394
+ raw(options?: BodyParserOptions): Middleware;
395
+ }
396
+
397
+ export interface Security {
398
+ (options?: SecurityOptions): Middleware;
399
+ csrf(options: CsrfOptions): Middleware;
400
+ csrfToken(ctx: Context, options?: Partial<CsrfOptions>): string;
401
+ xssProtection(options?: { escapeHtml?: boolean; escapeJson?: boolean }): Middleware;
402
+ requestSizeLimit(options?: { limit?: number; message?: string; statusCode?: number }): Middleware;
403
+ }
404
+
405
+ export interface RateLimit {
406
+ (options?: RateLimitOptions): Middleware & { cleanup(): void; store: RateLimitStore };
407
+ slowDown(options?: Record<string, unknown>): Middleware;
408
+ tokenBucket(options?: Record<string, unknown>): Middleware;
409
+ MemoryStore: new (options?: { maxKeys?: number }) => RateLimitStore;
410
+ }
411
+
412
+ export interface SessionFactory {
413
+ (options: SessionOptions): Middleware;
414
+ MemoryStore: new () => SessionStore;
415
+ FileStore: new (options?: { path?: string; ttl?: number }) => SessionStore;
416
+ }
417
+
418
+ export interface StaticFactory {
419
+ (root: string, options?: StaticOptions): Middleware;
420
+ serveStatic(root: string, options?: StaticOptions): Middleware;
421
+ }
422
+
423
+ export interface CompressionFactory {
424
+ (options?: CompressionOptions): Middleware;
425
+ gzip(options?: CompressionOptions): Middleware;
426
+ deflate(options?: CompressionOptions): Middleware;
427
+ brotli(options?: CompressionOptions): Middleware;
428
+ }
429
+
430
+ export declare const bodyParser: BodyParser;
431
+ export declare const cors: (options?: CorsOptions) => Middleware;
432
+ export declare const compression: CompressionFactory;
433
+ export declare const rateLimit: RateLimit;
434
+ export declare const session: SessionFactory;
435
+ export declare const security: Security;
436
+ export declare const csrf: Security['csrf'];
437
+ export declare const csrfToken: Security['csrfToken'];
438
+ export declare const serveStatic: StaticFactory;
439
+ export declare const healthCheck: (options?: Record<string, unknown>) => Middleware;
440
+ export declare const metrics: (options?: Record<string, unknown>) => Middleware;
441
+ export declare const logger: (options?: Record<string, unknown>) => Middleware;
442
+ export declare const cache: (options?: CacheOptions) => Middleware;
443
+ declare const staticMiddleware: StaticFactory;
444
+ export { staticMiddleware as static };
445
+
446
+ // Error handling
447
+
448
+ export interface HttpError extends Error {
449
+ status: number;
450
+ code?: string;
451
+ }
452
+
453
+ export declare function asyncHandler(fn: Middleware): Middleware;
454
+ export declare function createError(message: string, status?: number, code?: string | null): HttpError;
455
+ export declare const errors: {
456
+ badRequest(message?: string): HttpError;
457
+ unauthorized(message?: string): HttpError;
458
+ forbidden(message?: string): HttpError;
459
+ notFound(message?: string): HttpError;
460
+ methodNotAllowed(message?: string): HttpError;
461
+ conflict(message?: string): HttpError;
462
+ gone(message?: string): HttpError;
463
+ unprocessableEntity(message?: string): HttpError;
464
+ tooManyRequests(message?: string): HttpError;
465
+ internalServerError(message?: string): HttpError;
466
+ notImplemented(message?: string): HttpError;
467
+ badGateway(message?: string): HttpError;
468
+ serviceUnavailable(message?: string): HttpError;
469
+ gatewayTimeout(message?: string): HttpError;
470
+ };
471
+
472
+ export declare const errorHandling: {
473
+ asyncHandler: typeof asyncHandler;
474
+ errorHandler: (...args: any[]) => unknown;
475
+ createError: typeof createError;
476
+ errors: typeof errors;
477
+ };
478
+
479
+ export declare const middleware: {
480
+ bodyParser: BodyParser;
481
+ cors: typeof cors;
482
+ compression: CompressionFactory;
483
+ compress: CompressionFactory;
484
+ static: StaticFactory;
485
+ session: SessionFactory;
486
+ rateLimit: RateLimit;
487
+ security: Security;
488
+ helmet: Security;
489
+ healthCheck: typeof healthCheck;
490
+ health: typeof healthCheck;
491
+ metrics: typeof metrics;
492
+ logger: typeof logger;
493
+ cache: typeof cache;
494
+ };
495
+
496
+ export declare const utils: {
497
+ ContextPool: new (maxSize?: number) => {
498
+ acquire(req: IncomingMessage, res: ServerResponse, app: Spark): Context;
499
+ release(ctx: Context): void;
500
+ };
501
+ RegexValidator: any;
502
+ SafeRegexCache: any;
503
+ };
504
+
505
+ /** Package version. */
506
+ export declare const version: string;
507
+
508
+ declare const spark: {
509
+ Spark: typeof Spark;
510
+ App: typeof Spark;
511
+ Application: typeof Spark;
512
+ Router: typeof Router;
513
+ Context: typeof Context;
514
+ middleware: typeof middleware;
515
+ bodyParser: BodyParser;
516
+ cors: typeof cors;
517
+ compression: CompressionFactory;
518
+ static: StaticFactory;
519
+ serveStatic: StaticFactory;
520
+ session: SessionFactory;
521
+ rateLimit: RateLimit;
522
+ security: Security;
523
+ csrf: typeof csrf;
524
+ csrfToken: typeof csrfToken;
525
+ healthCheck: typeof healthCheck;
526
+ metrics: typeof metrics;
527
+ logger: typeof logger;
528
+ cache: typeof cache;
529
+ errorHandling: typeof errorHandling;
530
+ asyncHandler: typeof asyncHandler;
531
+ createError: typeof createError;
532
+ errors: typeof errors;
533
+ utils: typeof utils;
534
+ version: string;
535
+ };
536
+ export default spark;