@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.
- package/CHANGELOG.md +632 -293
- package/LICENSE +20 -20
- package/README.md +288 -241
- package/package.json +83 -89
- package/src/core/application.js +1070 -956
- package/src/core/context.js +1100 -830
- package/src/core/middleware.js +305 -217
- package/src/index.js +183 -278
- package/src/middleware/body-parser.js +484 -526
- package/src/middleware/cache.js +179 -170
- package/src/middleware/compression.js +179 -182
- package/src/middleware/cors.js +178 -95
- package/src/middleware/health.js +221 -218
- package/src/middleware/logger.js +197 -194
- package/src/middleware/metrics.js +341 -327
- package/src/middleware/rate-limit.js +369 -319
- package/src/middleware/security.js +444 -332
- package/src/middleware/session.js +649 -529
- package/src/middleware/static.js +406 -299
- package/src/router/layer.js +199 -117
- package/src/router/route.js +151 -123
- package/src/router/router.js +705 -755
- package/src/utils/async-handler.js +147 -144
- package/src/utils/context-pool.js +85 -82
- package/src/utils/regex-validator.js +189 -176
- package/src/utils/safe-json.js +110 -0
- package/types/index.d.ts +536 -291
- package/dist/LICENSE +0 -21
- package/dist/README.md +0 -242
- package/dist/core/application.js +0 -957
- package/dist/core/context.js +0 -831
- package/dist/core/middleware.js +0 -218
- package/dist/core/request.js +0 -333
- package/dist/core/response.js +0 -375
- package/dist/index.js +0 -278
- package/dist/middleware/body-parser.js +0 -526
- package/dist/middleware/cache.js +0 -171
- package/dist/middleware/compression.js +0 -183
- package/dist/middleware/cors.js +0 -95
- package/dist/middleware/health.js +0 -219
- package/dist/middleware/index.js +0 -21
- package/dist/middleware/logger.js +0 -195
- package/dist/middleware/metrics.js +0 -328
- package/dist/middleware/rate-limit.js +0 -320
- package/dist/middleware/security.js +0 -333
- package/dist/middleware/session.js +0 -530
- package/dist/middleware/static.js +0 -299
- package/dist/package.json +0 -62
- package/dist/router/layer.js +0 -117
- package/dist/router/route.js +0 -123
- package/dist/router/router.js +0 -756
- package/dist/types/index.d.ts +0 -291
- package/dist/utils/async-handler.js +0 -145
- package/dist/utils/cache.js +0 -441
- package/dist/utils/context-pool.js +0 -83
- package/dist/utils/error-types.js +0 -132
- package/dist/utils/http.js +0 -413
- package/dist/utils/regex-validator.js +0 -177
- package/src/core/request.js +0 -333
- package/src/core/response.js +0 -375
- package/src/middleware/index.js +0 -21
- package/src/utils/cache.js +0 -441
- package/src/utils/error-types.js +0 -132
- package/src/utils/http.js +0 -413
|
@@ -1,526 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Body parsing middleware for Spark Framework
|
|
3
|
-
* @author Spark Framework Team
|
|
4
|
-
* @since 1.0.0
|
|
5
|
-
* @version 1.0.0
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
const querystring = require('querystring');
|
|
9
|
-
const { Readable } = require('stream');
|
|
10
|
-
|
|
11
|
-
/** @constant {number} Default size limit for request bodies (1MB) */
|
|
12
|
-
const DEFAULT_LIMIT = 1024 * 1024; // 1MB
|
|
13
|
-
|
|
14
|
-
/** @constant {boolean} Default extended parsing setting */
|
|
15
|
-
const DEFAULT_EXTENDED = true;
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Create a body parsing middleware
|
|
19
|
-
*
|
|
20
|
-
* Automatically parses request bodies based on Content-Type header.
|
|
21
|
-
* Supports JSON, URL-encoded, multipart/form-data, text, and raw binary data.
|
|
22
|
-
* Provides security features like size limits and content validation.
|
|
23
|
-
*
|
|
24
|
-
* @param {Object} [options={}] - Body parser configuration options
|
|
25
|
-
* @param {number} [options.limit=1048576] - Maximum request body size in bytes (default: 1MB)
|
|
26
|
-
* @param {boolean} [options.extended=true] - Use extended URL encoding parsing
|
|
27
|
-
* @param {string} [options.type='auto'] - Force parsing type ('auto', 'json', 'urlencoded', 'multipart', 'text', 'raw')
|
|
28
|
-
* @param {string} [options.encoding='utf8'] - Text encoding for parsing
|
|
29
|
-
* @param {boolean} [options.inflate=true] - Enable gzip/deflate decompression
|
|
30
|
-
* @param {boolean} [options.strict=true] - Enable strict parsing
|
|
31
|
-
* @param {Function} [options.verify] - Custom verification function
|
|
32
|
-
* @returns {Function} Express-style middleware function
|
|
33
|
-
*
|
|
34
|
-
* @since 1.0.0
|
|
35
|
-
*
|
|
36
|
-
* @example
|
|
37
|
-
* // Auto-detect content type
|
|
38
|
-
* app.use(bodyParser());
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* // JSON only with custom limit
|
|
42
|
-
* app.use(bodyParser({
|
|
43
|
-
* type: 'json',
|
|
44
|
-
* limit: 1024 * 512 // 512KB
|
|
45
|
-
* }));
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* // With verification
|
|
49
|
-
* app.use(bodyParser({
|
|
50
|
-
* verify: (req, res, body) => {
|
|
51
|
-
* if (body.length > 1000) {
|
|
52
|
-
* throw new Error('Body too large');
|
|
53
|
-
* }
|
|
54
|
-
* }
|
|
55
|
-
* }));
|
|
56
|
-
*
|
|
57
|
-
* @example
|
|
58
|
-
* // Multiple content types
|
|
59
|
-
* app.use(bodyParser({ type: 'json' }));
|
|
60
|
-
* app.use(bodyParser({ type: 'urlencoded' }));
|
|
61
|
-
* app.use(bodyParser({ type: 'text' }));
|
|
62
|
-
*/
|
|
63
|
-
function bodyParser(options = {}) {
|
|
64
|
-
const opts = {
|
|
65
|
-
limit: options.limit || DEFAULT_LIMIT,
|
|
66
|
-
extended: options.extended !== false,
|
|
67
|
-
type: options.type || 'auto',
|
|
68
|
-
encoding: options.encoding || 'utf8',
|
|
69
|
-
inflate: options.inflate !== false,
|
|
70
|
-
strict: options.strict !== false,
|
|
71
|
-
verify: options.verify,
|
|
72
|
-
...options
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
return async (ctx, next) => {
|
|
76
|
-
if (ctx.body !== null || ctx.method === 'GET' || ctx.method === 'HEAD') {
|
|
77
|
-
return next();
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const contentType = ctx.get('content-type') || '';
|
|
81
|
-
const contentLength = parseInt(ctx.get('content-length')) || 0;
|
|
82
|
-
|
|
83
|
-
if (contentLength > opts.limit) {
|
|
84
|
-
ctx.status(413).json({ error: 'Request entity too large' });
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
try {
|
|
89
|
-
if (shouldParseJson(contentType, opts.type)) {
|
|
90
|
-
await parseJson(ctx, opts);
|
|
91
|
-
} else if (shouldParseUrlencoded(contentType, opts.type)) {
|
|
92
|
-
await parseUrlencoded(ctx, opts);
|
|
93
|
-
} else if (shouldParseMultipart(contentType, opts.type)) {
|
|
94
|
-
await parseMultipart(ctx, opts);
|
|
95
|
-
} else if (shouldParseText(contentType, opts.type)) {
|
|
96
|
-
await parseText(ctx, opts);
|
|
97
|
-
} else if (shouldParseRaw(contentType, opts.type)) {
|
|
98
|
-
await parseRaw(ctx, opts);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
if (opts.verify) {
|
|
102
|
-
await Promise.resolve(opts.verify(ctx.req, ctx.res, ctx.body));
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
await next();
|
|
106
|
-
} catch (error) {
|
|
107
|
-
ctx.status(400).json({
|
|
108
|
-
error: 'Bad Request',
|
|
109
|
-
message: error.message,
|
|
110
|
-
type: error.name
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Check if content should be parsed as JSON
|
|
118
|
-
*
|
|
119
|
-
* @param {string} contentType - Request Content-Type header
|
|
120
|
-
* @param {string} type - Parser type setting
|
|
121
|
-
* @returns {boolean} Whether to parse as JSON
|
|
122
|
-
*
|
|
123
|
-
* @private
|
|
124
|
-
* @since 1.0.0
|
|
125
|
-
*/
|
|
126
|
-
function shouldParseJson(contentType, type) {
|
|
127
|
-
if (type === 'json') return true;
|
|
128
|
-
if (type === 'auto') return contentType.includes('application/json');
|
|
129
|
-
return false;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Check if content should be parsed as URL-encoded
|
|
134
|
-
*
|
|
135
|
-
* @param {string} contentType - Request Content-Type header
|
|
136
|
-
* @param {string} type - Parser type setting
|
|
137
|
-
* @returns {boolean} Whether to parse as URL-encoded
|
|
138
|
-
*
|
|
139
|
-
* @private
|
|
140
|
-
* @since 1.0.0
|
|
141
|
-
*/
|
|
142
|
-
function shouldParseUrlencoded(contentType, type) {
|
|
143
|
-
if (type === 'urlencoded') return true;
|
|
144
|
-
if (type === 'auto') return contentType.includes('application/x-www-form-urlencoded');
|
|
145
|
-
return false;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Check if content should be parsed as multipart
|
|
150
|
-
*
|
|
151
|
-
* @param {string} contentType - Request Content-Type header
|
|
152
|
-
* @param {string} type - Parser type setting
|
|
153
|
-
* @returns {boolean} Whether to parse as multipart
|
|
154
|
-
*
|
|
155
|
-
* @private
|
|
156
|
-
* @since 1.0.0
|
|
157
|
-
*/
|
|
158
|
-
function shouldParseMultipart(contentType, type) {
|
|
159
|
-
if (type === 'multipart') return true;
|
|
160
|
-
if (type === 'auto') return contentType.includes('multipart/form-data');
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Check if content should be parsed as text
|
|
166
|
-
*
|
|
167
|
-
* @param {string} contentType - Request Content-Type header
|
|
168
|
-
* @param {string} type - Parser type setting
|
|
169
|
-
* @returns {boolean} Whether to parse as text
|
|
170
|
-
*
|
|
171
|
-
* @private
|
|
172
|
-
* @since 1.0.0
|
|
173
|
-
*/
|
|
174
|
-
function shouldParseText(contentType, type) {
|
|
175
|
-
if (type === 'text') return true;
|
|
176
|
-
if (type === 'auto') return contentType.includes('text/');
|
|
177
|
-
return false;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Check if content should be parsed as raw binary
|
|
182
|
-
*
|
|
183
|
-
* @param {string} contentType - Request Content-Type header
|
|
184
|
-
* @param {string} type - Parser type setting
|
|
185
|
-
* @returns {boolean} Whether to parse as raw binary
|
|
186
|
-
*
|
|
187
|
-
* @private
|
|
188
|
-
* @since 1.0.0
|
|
189
|
-
*/
|
|
190
|
-
function shouldParseRaw(contentType, type) {
|
|
191
|
-
return type === 'raw';
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* Parse request body as JSON
|
|
196
|
-
*
|
|
197
|
-
* @param {Context} ctx - Request context
|
|
198
|
-
* @param {Object} opts - Parser options
|
|
199
|
-
* @returns {Promise<void>}
|
|
200
|
-
*
|
|
201
|
-
* @throws {Error} When JSON parsing fails
|
|
202
|
-
*
|
|
203
|
-
* @private
|
|
204
|
-
* @since 1.0.0
|
|
205
|
-
*/
|
|
206
|
-
async function parseJson(ctx, opts) {
|
|
207
|
-
const body = await readBody(ctx.req, opts);
|
|
208
|
-
|
|
209
|
-
try {
|
|
210
|
-
ctx.body = JSON.parse(body);
|
|
211
|
-
} catch (error) {
|
|
212
|
-
throw new Error(`Invalid JSON: ${error.message}`);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Parse request body as URL-encoded form data
|
|
218
|
-
*
|
|
219
|
-
* @param {Context} ctx - Request context
|
|
220
|
-
* @param {Object} opts - Parser options
|
|
221
|
-
* @returns {Promise<void>}
|
|
222
|
-
*
|
|
223
|
-
* @private
|
|
224
|
-
* @since 1.0.0
|
|
225
|
-
*/
|
|
226
|
-
async function parseUrlencoded(ctx, opts) {
|
|
227
|
-
const body = await readBody(ctx.req, opts);
|
|
228
|
-
ctx.body = querystring.parse(body);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
async function parseMultipart(ctx, opts) {
|
|
232
|
-
const contentType = ctx.get('content-type');
|
|
233
|
-
const boundary = getBoundary(contentType);
|
|
234
|
-
|
|
235
|
-
if (!boundary) {
|
|
236
|
-
throw new Error('Invalid multipart/form-data: missing boundary');
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const chunks = [];
|
|
240
|
-
let size = 0;
|
|
241
|
-
|
|
242
|
-
await new Promise((resolve, reject) => {
|
|
243
|
-
const onData = (chunk) => {
|
|
244
|
-
size += chunk.length;
|
|
245
|
-
if (size > opts.limit) {
|
|
246
|
-
ctx.req.removeListener('data', onData);
|
|
247
|
-
ctx.req.removeListener('end', onEnd);
|
|
248
|
-
ctx.req.removeListener('error', onError);
|
|
249
|
-
return reject(new Error('Request entity too large'));
|
|
250
|
-
}
|
|
251
|
-
chunks.push(chunk);
|
|
252
|
-
};
|
|
253
|
-
|
|
254
|
-
const onEnd = () => {
|
|
255
|
-
ctx.req.removeListener('data', onData);
|
|
256
|
-
ctx.req.removeListener('error', onError);
|
|
257
|
-
resolve();
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
const onError = (error) => {
|
|
261
|
-
ctx.req.removeListener('data', onData);
|
|
262
|
-
ctx.req.removeListener('end', onEnd);
|
|
263
|
-
reject(error);
|
|
264
|
-
};
|
|
265
|
-
|
|
266
|
-
ctx.req.on('data', onData);
|
|
267
|
-
ctx.req.on('end', onEnd);
|
|
268
|
-
ctx.req.on('error', onError);
|
|
269
|
-
});
|
|
270
|
-
|
|
271
|
-
const body = Buffer.concat(chunks).toString('binary');
|
|
272
|
-
const parsed = parseMultipartData(body, boundary);
|
|
273
|
-
|
|
274
|
-
ctx.body = parsed.fields;
|
|
275
|
-
ctx.files = parsed.files;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* Parse request body as plain text
|
|
280
|
-
*
|
|
281
|
-
* @param {Context} ctx - Request context
|
|
282
|
-
* @param {Object} opts - Parser options
|
|
283
|
-
* @returns {Promise<void>}
|
|
284
|
-
*
|
|
285
|
-
* @private
|
|
286
|
-
* @since 1.0.0
|
|
287
|
-
*/
|
|
288
|
-
async function parseText(ctx, opts) {
|
|
289
|
-
ctx.body = await readBody(ctx.req, opts);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Parse request body as raw binary data
|
|
294
|
-
*
|
|
295
|
-
* @param {Context} ctx - Request context
|
|
296
|
-
* @param {Object} opts - Parser options
|
|
297
|
-
* @returns {Promise<void>}
|
|
298
|
-
*
|
|
299
|
-
* @throws {Error} When request is too large
|
|
300
|
-
*
|
|
301
|
-
* @private
|
|
302
|
-
* @since 1.0.0
|
|
303
|
-
*/
|
|
304
|
-
async function parseRaw(ctx, opts) {
|
|
305
|
-
const chunks = [];
|
|
306
|
-
|
|
307
|
-
return new Promise((resolve, reject) => {
|
|
308
|
-
let size = 0;
|
|
309
|
-
|
|
310
|
-
const onData = (chunk) => {
|
|
311
|
-
size += chunk.length;
|
|
312
|
-
if (size > opts.limit) {
|
|
313
|
-
ctx.req.removeListener('data', onData);
|
|
314
|
-
ctx.req.removeListener('end', onEnd);
|
|
315
|
-
ctx.req.removeListener('error', onError);
|
|
316
|
-
return reject(new Error('Request entity too large'));
|
|
317
|
-
}
|
|
318
|
-
chunks.push(chunk);
|
|
319
|
-
};
|
|
320
|
-
|
|
321
|
-
const onEnd = () => {
|
|
322
|
-
ctx.req.removeListener('data', onData);
|
|
323
|
-
ctx.req.removeListener('error', onError);
|
|
324
|
-
ctx.body = Buffer.concat(chunks);
|
|
325
|
-
resolve();
|
|
326
|
-
};
|
|
327
|
-
|
|
328
|
-
const onError = (error) => {
|
|
329
|
-
ctx.req.removeListener('data', onData);
|
|
330
|
-
ctx.req.removeListener('end', onEnd);
|
|
331
|
-
reject(error);
|
|
332
|
-
};
|
|
333
|
-
|
|
334
|
-
ctx.req.on('data', onData);
|
|
335
|
-
ctx.req.on('end', onEnd);
|
|
336
|
-
ctx.req.on('error', onError);
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
* Read and decode request body as text
|
|
342
|
-
*
|
|
343
|
-
* @param {http.IncomingMessage} req - HTTP request object
|
|
344
|
-
* @param {Object} opts - Parser options with encoding and limit
|
|
345
|
-
* @returns {Promise<string>} Promise resolving to decoded body text
|
|
346
|
-
*
|
|
347
|
-
* @throws {Error} When request is too large
|
|
348
|
-
*
|
|
349
|
-
* @private
|
|
350
|
-
* @since 1.0.0
|
|
351
|
-
*/
|
|
352
|
-
function readBody(req, opts) {
|
|
353
|
-
return new Promise((resolve, reject) => {
|
|
354
|
-
const chunks = [];
|
|
355
|
-
let size = 0;
|
|
356
|
-
|
|
357
|
-
const onData = (chunk) => {
|
|
358
|
-
size += chunk.length;
|
|
359
|
-
if (size > opts.limit) {
|
|
360
|
-
req.removeListener('data', onData);
|
|
361
|
-
req.removeListener('end', onEnd);
|
|
362
|
-
req.removeListener('error', onError);
|
|
363
|
-
return reject(new Error('Request entity too large'));
|
|
364
|
-
}
|
|
365
|
-
chunks.push(chunk);
|
|
366
|
-
};
|
|
367
|
-
|
|
368
|
-
const onEnd = () => {
|
|
369
|
-
req.removeListener('data', onData);
|
|
370
|
-
req.removeListener('error', onError);
|
|
371
|
-
const body = Buffer.concat(chunks).toString(opts.encoding || 'utf8');
|
|
372
|
-
resolve(body);
|
|
373
|
-
};
|
|
374
|
-
|
|
375
|
-
const onError = (error) => {
|
|
376
|
-
req.removeListener('data', onData);
|
|
377
|
-
req.removeListener('end', onEnd);
|
|
378
|
-
reject(error);
|
|
379
|
-
};
|
|
380
|
-
|
|
381
|
-
req.on('data', onData);
|
|
382
|
-
req.on('end', onEnd);
|
|
383
|
-
req.on('error', onError);
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
/**
|
|
388
|
-
* Extract boundary from multipart Content-Type header
|
|
389
|
-
*
|
|
390
|
-
* @param {string} contentType - Content-Type header value
|
|
391
|
-
* @returns {string|null} Boundary string or null if not found
|
|
392
|
-
*
|
|
393
|
-
* @private
|
|
394
|
-
* @since 1.0.0
|
|
395
|
-
*/
|
|
396
|
-
function getBoundary(contentType) {
|
|
397
|
-
const match = contentType.match(/boundary=([^;]+)/);
|
|
398
|
-
if (!match || !match[1]) return null;
|
|
399
|
-
|
|
400
|
-
// Remove quotes if present
|
|
401
|
-
return match[1].replace(/^["']|["']$/g, '');
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/**
|
|
405
|
-
* Parse multipart/form-data body content
|
|
406
|
-
*
|
|
407
|
-
* @param {string} body - Raw multipart body as binary string
|
|
408
|
-
* @param {string} boundary - Multipart boundary string
|
|
409
|
-
* @returns {Object} Object with fields and files properties
|
|
410
|
-
* @returns {Object} returns.fields - Parsed form fields
|
|
411
|
-
* @returns {Object} returns.files - Parsed file uploads with metadata
|
|
412
|
-
*
|
|
413
|
-
* @private
|
|
414
|
-
* @since 1.0.0
|
|
415
|
-
*/
|
|
416
|
-
function parseMultipartData(body, boundary) {
|
|
417
|
-
const fields = {};
|
|
418
|
-
const files = {};
|
|
419
|
-
|
|
420
|
-
const parts = body.split(`--${boundary}`);
|
|
421
|
-
|
|
422
|
-
for (let i = 1; i < parts.length - 1; i++) {
|
|
423
|
-
const part = parts[i];
|
|
424
|
-
const [headers, content] = part.split('\r\n\r\n');
|
|
425
|
-
|
|
426
|
-
if (!headers || content === undefined) continue;
|
|
427
|
-
|
|
428
|
-
const headerLines = headers.split('\r\n');
|
|
429
|
-
const contentDisposition = headerLines.find(line =>
|
|
430
|
-
line.startsWith('Content-Disposition:')
|
|
431
|
-
);
|
|
432
|
-
|
|
433
|
-
if (!contentDisposition) continue;
|
|
434
|
-
|
|
435
|
-
const nameMatch = contentDisposition.match(/name="([^"]+)"/);
|
|
436
|
-
const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
|
|
437
|
-
|
|
438
|
-
if (!nameMatch) continue;
|
|
439
|
-
|
|
440
|
-
const name = nameMatch[1];
|
|
441
|
-
const filename = filenameMatch ? filenameMatch[1] : null;
|
|
442
|
-
|
|
443
|
-
if (filename) {
|
|
444
|
-
const contentType = headerLines.find(line =>
|
|
445
|
-
line.startsWith('Content-Type:')
|
|
446
|
-
);
|
|
447
|
-
|
|
448
|
-
files[name] = {
|
|
449
|
-
filename,
|
|
450
|
-
contentType: contentType ? contentType.split(': ')[1] : 'application/octet-stream',
|
|
451
|
-
size: Buffer.byteLength(content.slice(0, -2)),
|
|
452
|
-
data: Buffer.from(content.slice(0, -2))
|
|
453
|
-
};
|
|
454
|
-
} else {
|
|
455
|
-
fields[name] = content.slice(0, -2);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
return { fields, files };
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/**
|
|
463
|
-
* Create a JSON body parser middleware
|
|
464
|
-
*
|
|
465
|
-
* @param {Object} [options] - Parser options (merged with type: 'json')
|
|
466
|
-
* @returns {Function} Middleware function for parsing JSON bodies
|
|
467
|
-
*
|
|
468
|
-
* @since 1.0.0
|
|
469
|
-
*
|
|
470
|
-
* @example
|
|
471
|
-
* app.use(json({ limit: '10mb' }));
|
|
472
|
-
*/
|
|
473
|
-
function json(options) {
|
|
474
|
-
return bodyParser({ ...options, type: 'json' });
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
/**
|
|
478
|
-
* Create a URL-encoded body parser middleware
|
|
479
|
-
*
|
|
480
|
-
* @param {Object} [options] - Parser options (merged with type: 'urlencoded')
|
|
481
|
-
* @returns {Function} Middleware function for parsing URL-encoded bodies
|
|
482
|
-
*
|
|
483
|
-
* @since 1.0.0
|
|
484
|
-
*
|
|
485
|
-
* @example
|
|
486
|
-
* app.use(urlencoded({ extended: true }));
|
|
487
|
-
*/
|
|
488
|
-
function urlencoded(options) {
|
|
489
|
-
return bodyParser({ ...options, type: 'urlencoded' });
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
/**
|
|
493
|
-
* Create a text body parser middleware
|
|
494
|
-
*
|
|
495
|
-
* @param {Object} [options] - Parser options (merged with type: 'text')
|
|
496
|
-
* @returns {Function} Middleware function for parsing text bodies
|
|
497
|
-
*
|
|
498
|
-
* @since 1.0.0
|
|
499
|
-
*
|
|
500
|
-
* @example
|
|
501
|
-
* app.use(text({ encoding: 'utf16' }));
|
|
502
|
-
*/
|
|
503
|
-
function text(options) {
|
|
504
|
-
return bodyParser({ ...options, type: 'text' });
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
/**
|
|
508
|
-
* Create a raw binary body parser middleware
|
|
509
|
-
*
|
|
510
|
-
* @param {Object} [options] - Parser options (merged with type: 'raw')
|
|
511
|
-
* @returns {Function} Middleware function for parsing raw binary bodies
|
|
512
|
-
*
|
|
513
|
-
* @since 1.0.0
|
|
514
|
-
*
|
|
515
|
-
* @example
|
|
516
|
-
* app.use(raw({ limit: '5mb' }));
|
|
517
|
-
*/
|
|
518
|
-
function raw(options) {
|
|
519
|
-
return bodyParser({ ...options, type: 'raw' });
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
module.exports = bodyParser;
|
|
523
|
-
module.exports.json = json;
|
|
524
|
-
module.exports.urlencoded = urlencoded;
|
|
525
|
-
module.exports.text = text;
|
|
526
|
-
module.exports.raw = raw;
|
package/dist/middleware/cache.js
DELETED
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cache middleware for @oxog/spark
|
|
3
|
-
* Provides response caching functionality
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Creates a cache middleware
|
|
8
|
-
* @param {Object} options - Cache configuration options
|
|
9
|
-
* @param {number} [options.maxAge=3600] - Cache max age in seconds
|
|
10
|
-
* @param {Function} [options.key] - Function to generate cache key
|
|
11
|
-
* @param {Function} [options.condition] - Function to determine if response should be cached
|
|
12
|
-
* @param {Object} [options.store] - Custom cache store (default: in-memory)
|
|
13
|
-
* @returns {Function} Cache middleware function
|
|
14
|
-
*/
|
|
15
|
-
function cache(options = {}) {
|
|
16
|
-
const {
|
|
17
|
-
maxAge = 3600,
|
|
18
|
-
key = defaultKeyGenerator,
|
|
19
|
-
condition = defaultCondition,
|
|
20
|
-
store = new Map()
|
|
21
|
-
} = options;
|
|
22
|
-
|
|
23
|
-
return async function cacheMiddleware(ctx, next) {
|
|
24
|
-
// Only cache GET and HEAD requests
|
|
25
|
-
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
|
|
26
|
-
return next();
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Check if caching should be applied
|
|
30
|
-
if (!condition(ctx)) {
|
|
31
|
-
return next();
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// Generate cache key
|
|
35
|
-
const cacheKey = key(ctx);
|
|
36
|
-
|
|
37
|
-
// Check if cached response exists
|
|
38
|
-
const cached = store.get(cacheKey);
|
|
39
|
-
if (cached && cached.expires > Date.now()) {
|
|
40
|
-
// Serve from cache
|
|
41
|
-
ctx.status = cached.status;
|
|
42
|
-
ctx.body = cached.body;
|
|
43
|
-
ctx.set(cached.headers);
|
|
44
|
-
ctx.set('X-Cache', 'HIT');
|
|
45
|
-
ctx.set('Age', Math.floor((Date.now() - cached.created) / 1000));
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// Not in cache, proceed with request
|
|
50
|
-
await next();
|
|
51
|
-
|
|
52
|
-
// Store response in cache if successful
|
|
53
|
-
if (ctx.status >= 200 && ctx.status < 300 && ctx.body) {
|
|
54
|
-
const cacheEntry = {
|
|
55
|
-
status: ctx.status,
|
|
56
|
-
body: ctx.body,
|
|
57
|
-
headers: filterHeaders(ctx.headers),
|
|
58
|
-
created: Date.now(),
|
|
59
|
-
expires: Date.now() + (maxAge * 1000)
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
store.set(cacheKey, cacheEntry);
|
|
63
|
-
|
|
64
|
-
// Set cache headers
|
|
65
|
-
ctx.set('Cache-Control', `public, max-age=${maxAge}`);
|
|
66
|
-
ctx.set('X-Cache', 'MISS');
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Default cache key generator
|
|
73
|
-
* @param {Object} ctx - Koa context
|
|
74
|
-
* @returns {string} Cache key
|
|
75
|
-
*/
|
|
76
|
-
function defaultKeyGenerator(ctx) {
|
|
77
|
-
return ctx.url;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Default condition to determine if response should be cached
|
|
82
|
-
* @param {Object} ctx - Koa context
|
|
83
|
-
* @returns {boolean} Whether to cache the response
|
|
84
|
-
*/
|
|
85
|
-
function defaultCondition(ctx) {
|
|
86
|
-
// Don't cache if no-cache header is present
|
|
87
|
-
const cacheControl = ctx.get('Cache-Control');
|
|
88
|
-
if (cacheControl && cacheControl.includes('no-cache')) {
|
|
89
|
-
return false;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Don't cache authenticated requests by default
|
|
93
|
-
if (ctx.get('Authorization')) {
|
|
94
|
-
return false;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
return true;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Filter headers to store in cache
|
|
102
|
-
* @param {Object} headers - Response headers
|
|
103
|
-
* @returns {Object} Filtered headers
|
|
104
|
-
*/
|
|
105
|
-
function filterHeaders(headers) {
|
|
106
|
-
const filtered = {};
|
|
107
|
-
const allowedHeaders = [
|
|
108
|
-
'content-type',
|
|
109
|
-
'content-encoding',
|
|
110
|
-
'content-language',
|
|
111
|
-
'vary',
|
|
112
|
-
'etag',
|
|
113
|
-
'last-modified'
|
|
114
|
-
];
|
|
115
|
-
|
|
116
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
117
|
-
if (allowedHeaders.includes(key.toLowerCase())) {
|
|
118
|
-
filtered[key] = value;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
return filtered;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Memory cache store with size limits
|
|
127
|
-
*/
|
|
128
|
-
class MemoryCacheStore {
|
|
129
|
-
constructor(maxSize = 100) {
|
|
130
|
-
this.cache = new Map();
|
|
131
|
-
this.maxSize = maxSize;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
get(key) {
|
|
135
|
-
const entry = this.cache.get(key);
|
|
136
|
-
if (entry && entry.expires > Date.now()) {
|
|
137
|
-
// Move to end (LRU)
|
|
138
|
-
this.cache.delete(key);
|
|
139
|
-
this.cache.set(key, entry);
|
|
140
|
-
return entry;
|
|
141
|
-
}
|
|
142
|
-
// Remove expired entry
|
|
143
|
-
if (entry) {
|
|
144
|
-
this.cache.delete(key);
|
|
145
|
-
}
|
|
146
|
-
return null;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
set(key, value) {
|
|
150
|
-
// Remove oldest entry if at capacity
|
|
151
|
-
if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
|
|
152
|
-
const firstKey = this.cache.keys().next().value;
|
|
153
|
-
this.cache.delete(firstKey);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
this.cache.set(key, value);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
clear() {
|
|
160
|
-
this.cache.clear();
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
size() {
|
|
164
|
-
return this.cache.size;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// Export factory function and store class
|
|
169
|
-
cache.MemoryCacheStore = MemoryCacheStore;
|
|
170
|
-
|
|
171
|
-
module.exports = cache;
|