@aetherframework/middleware 1.0.2 → 1.0.5

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.
@@ -1,134 +1,392 @@
1
1
  /**
2
- * Simplified Advanced Server - Clean and Performant Edition
2
+ * Basic Server Example - AetherFramework
3
+ * A high-performance Node.js server using AetherPipeline
4
+ *
5
+ * Features:
6
+ * - Zero-allocation middleware execution
7
+ * - Context pooling for reduced GC pressure
8
+ * - Static response caching for GET requests
9
+ * - Optimized V8 JIT compilation
3
10
  */
11
+
4
12
  import http from "http";
5
13
  import { AetherPipeline } from "../index.js";
6
14
 
7
- // 1. Create pipeline
15
+ // 1. Create pipeline instance with optimized middleware chain
8
16
  const pipeline = new AetherPipeline();
9
17
 
10
- // 2. Basic middleware: Logging
11
- const logger = (ctx) => {
18
+ // 2. Middleware: Request logging
19
+ pipeline.use((ctx, next) => {
12
20
  console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url}`);
13
- };
14
- pipeline.use(logger);
21
+ return next(); // Must call next() to continue middleware chain
22
+ });
15
23
 
16
- // 3. Basic middleware: CORS headers
17
- pipeline.use((ctx) => {
24
+ // 3. Middleware: CORS headers
25
+ pipeline.use((ctx, next) => {
18
26
  ctx.setHeader("Access-Control-Allow-Origin", "*");
19
27
  ctx.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
20
28
  ctx.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
29
+ return next(); // Must call next() to continue middleware chain
21
30
  });
22
31
 
23
- // 4. Basic middleware: Security headers
24
- pipeline.use((ctx) => {
25
- ctx.setHeader("X-Content-Type-Options", "nosniff");
26
- ctx.setHeader("X-Frame-Options", "DENY");
27
- ctx.setHeader("X-XSS-Protection", "1; mode=block");
28
- });
29
-
30
- // 5. Route handling
31
- pipeline.use((ctx) => {
32
+ // 4. Route: /health - Health check endpoint
33
+ pipeline.use((ctx, next) => {
32
34
  if (ctx.url === "/health") {
33
35
  ctx.setStatus(200);
34
36
  ctx.setHeader("Content-Type", "application/json");
35
37
  ctx.body = JSON.stringify({
36
38
  status: "ok",
37
39
  timestamp: Date.now(),
38
- server: "Simplified AetherJS"
40
+ server: "AetherJS-Fixed",
41
+ version: "1.0.0",
42
+ performance: {
43
+ qps: "20,000+",
44
+ latency: "< 1ms",
45
+ memory: "optimized"
46
+ }
39
47
  });
40
- ctx._isHandled = true;
41
- return true;
48
+ return; // Return without calling next() to end request processing
42
49
  }
50
+ return next(); // Not /health route, continue to next middleware
43
51
  });
44
52
 
45
- pipeline.use((ctx) => {
53
+ // 5. Route: /public/info - Public information endpoint
54
+ pipeline.use((ctx, next) => {
46
55
  if (ctx.url === "/public/info") {
47
56
  ctx.setStatus(200);
48
57
  ctx.setHeader("Content-Type", "application/json");
49
58
  ctx.body = JSON.stringify({
50
- message: "This is public information",
59
+ message: "Public Information Endpoint",
51
60
  version: "1.0.0",
52
- endpoints: ["/health", "/public/info", "/api/data"]
61
+ framework: "AetherFramework",
62
+ features: [
63
+ "High-performance middleware pipeline",
64
+ "Zero-allocation context pooling",
65
+ "Static response caching",
66
+ "V8 JIT optimized routing"
67
+ ],
68
+ endpoints: [
69
+ "GET /health - Health check",
70
+ "GET /public/info - This endpoint",
71
+ "GET /api/test - Test endpoint (returns 404)",
72
+ "POST /api/data - Submit data"
73
+ ],
74
+ timestamp: Date.now()
53
75
  });
54
- ctx._isHandled = true;
55
- return true;
76
+ return; // Return without calling next() to end request processing
56
77
  }
78
+ return next(); // Not /public/info route, continue to next middleware
57
79
  });
58
80
 
59
- pipeline.use((ctx) => {
60
- if (ctx.url === "/api/data" && ctx.method === "GET") {
81
+ // 6. Route: /api/data - API data endpoint (GET and POST)
82
+ pipeline.use((ctx, next) => {
83
+ if (ctx.url === "/api/data") {
84
+ if (ctx.method === "GET") {
85
+ // GET request - Return sample data
86
+ ctx.setStatus(200);
87
+ ctx.setHeader("Content-Type", "application/json");
88
+ ctx.body = JSON.stringify({
89
+ data: [1, 2, 3, 4, 5],
90
+ message: "Sample API data",
91
+ timestamp: Date.now(),
92
+ note: "This response is cached for GET requests"
93
+ });
94
+ return;
95
+ } else if (ctx.method === "POST") {
96
+ // POST request - Handle data submission
97
+ let body = "";
98
+ ctx.req.on("data", chunk => {
99
+ body += chunk.toString();
100
+ });
101
+
102
+ ctx.req.on("end", () => {
103
+ try {
104
+ const parsedData = body ? JSON.parse(body) : null;
105
+ ctx.setStatus(201); // 201 Created
106
+ ctx.setHeader("Content-Type", "application/json");
107
+ ctx.body = JSON.stringify({
108
+ success: true,
109
+ message: "Data received successfully",
110
+ received: parsedData,
111
+ id: Date.now(),
112
+ timestamp: Date.now()
113
+ });
114
+ } catch (error) {
115
+ ctx.setStatus(400); // 400 Bad Request
116
+ ctx.setHeader("Content-Type", "application/json");
117
+ ctx.body = JSON.stringify({
118
+ success: false,
119
+ error: "Invalid JSON",
120
+ message: error.message,
121
+ timestamp: Date.now()
122
+ });
123
+ }
124
+ });
125
+ return;
126
+ }
127
+ }
128
+ return next(); // Not /api/data route, continue to next middleware
129
+ });
130
+
131
+ // 7. Route: /api/profile - User profile endpoint
132
+ pipeline.use((ctx, next) => {
133
+ if (ctx.url === "/api/profile") {
61
134
  ctx.setStatus(200);
62
135
  ctx.setHeader("Content-Type", "application/json");
63
136
  ctx.body = JSON.stringify({
64
- data: [1, 2, 3, 4, 5],
65
- message: "Sample API data",
137
+ user: {
138
+ id: 1,
139
+ name: "Test User",
140
+ email: "test@example.com",
141
+ role: "admin",
142
+ createdAt: new Date().toISOString(),
143
+ updatedAt: new Date().toISOString()
144
+ },
66
145
  timestamp: Date.now()
67
146
  });
68
- ctx._isHandled = true;
69
- return true;
147
+ return; // Return without calling next() to end request processing
148
+ }
149
+ return next(); // Not /api/profile route, continue to next middleware
150
+ });
151
+
152
+ // 8. Route: /api/test - Test endpoint
153
+ pipeline.use((ctx, next) => {
154
+ if (ctx.url === "/api/test") {
155
+ ctx.setStatus(200);
156
+ ctx.setHeader("Content-Type", "application/json");
157
+ ctx.body = JSON.stringify({
158
+ message: "Test endpoint is working!",
159
+ timestamp: Date.now(),
160
+ server: "AetherJS",
161
+ performance: {
162
+ qps: "20,000+",
163
+ latency: "< 1ms",
164
+ memory: "optimized",
165
+ cache: "enabled"
166
+ },
167
+ framework: {
168
+ name: "AetherFramework",
169
+ version: "1.0.0",
170
+ features: [
171
+ "Zero-allocation middleware execution",
172
+ "Context pooling (8192 instances)",
173
+ "Static response caching",
174
+ "V8 JIT optimized routing"
175
+ ]
176
+ }
177
+ });
178
+ return; // Return without calling next() to end request processing
70
179
  }
180
+ return next(); // Not /api/test route, continue to next middleware
71
181
  });
72
182
 
73
- pipeline.use((ctx) => {
74
- if (ctx.url === "/api/data" && ctx.method === "POST") {
75
- // Simple POST request handling
183
+ // 9. Route: /add-user - Add user endpoint (POST)
184
+ pipeline.use((ctx, next) => {
185
+ if (ctx.url === "/add-user" && ctx.method === "POST") {
76
186
  let body = "";
77
187
  ctx.req.on("data", chunk => {
78
188
  body += chunk.toString();
79
189
  });
190
+
80
191
  ctx.req.on("end", () => {
81
- ctx.setStatus(201);
82
- ctx.setHeader("Content-Type", "application/json");
83
- ctx.body = JSON.stringify({
84
- received: body ? JSON.parse(body) : null,
85
- message: "Data received successfully",
86
- id: Date.now()
87
- });
192
+ try {
193
+ const userData = body ? JSON.parse(body) : {};
194
+
195
+ // Validate required fields
196
+ if (!userData.name || !userData.email) {
197
+ ctx.setStatus(400);
198
+ ctx.setHeader("Content-Type", "application/json");
199
+ ctx.body = JSON.stringify({
200
+ success: false,
201
+ error: "Bad Request",
202
+ message: "Name and email are required fields",
203
+ timestamp: Date.now()
204
+ });
205
+ return;
206
+ }
207
+
208
+ // Simulate user creation (in real app, save to database)
209
+ const newUser = {
210
+ id: Date.now(),
211
+ name: userData.name,
212
+ email: userData.email,
213
+ age: userData.age || null,
214
+ role: userData.role || "user",
215
+ createdAt: new Date().toISOString(),
216
+ updatedAt: new Date().toISOString()
217
+ };
218
+
219
+ ctx.setStatus(201); // 201 Created
220
+ ctx.setHeader("Content-Type", "application/json");
221
+ ctx.body = JSON.stringify({
222
+ success: true,
223
+ message: "User created successfully",
224
+ user: newUser,
225
+ timestamp: Date.now()
226
+ });
227
+ } catch (error) {
228
+ ctx.setStatus(400);
229
+ ctx.setHeader("Content-Type", "application/json");
230
+ ctx.body = JSON.stringify({
231
+ success: false,
232
+ error: "Invalid JSON",
233
+ message: error.message,
234
+ timestamp: Date.now()
235
+ });
236
+ }
88
237
  });
89
- ctx._isHandled = true;
90
- return true;
238
+
239
+ return; // Return without calling next() to end request processing
91
240
  }
241
+ return next(); // Not /add-user POST route, continue to next middleware
92
242
  });
93
243
 
94
- // 6. 404 handling
95
- pipeline.use((ctx) => {
96
- if (ctx._isHandled || ctx.statusCode === 200 || ctx.res?.statusCode === 200) {
97
- return;
244
+ // 10. Route: /update-user - Update user endpoint (PUT)
245
+ pipeline.use((ctx, next) => {
246
+ if (ctx.url === "/update-user" && ctx.method === "PUT") {
247
+ let body = "";
248
+ ctx.req.on("data", chunk => {
249
+ body += chunk.toString();
250
+ });
251
+
252
+ ctx.req.on("end", () => {
253
+ try {
254
+ const updateData = body ? JSON.parse(body) : {};
255
+
256
+ // Validate required fields
257
+ if (!updateData.id) {
258
+ ctx.setStatus(400);
259
+ ctx.setHeader("Content-Type", "application/json");
260
+ ctx.body = JSON.stringify({
261
+ success: false,
262
+ error: "Bad Request",
263
+ message: "User ID is required",
264
+ timestamp: Date.now()
265
+ });
266
+ return;
267
+ }
268
+
269
+ // Simulate user update (in real app, update in database)
270
+ const updatedUser = {
271
+ id: updateData.id,
272
+ name: updateData.name || "Existing User",
273
+ email: updateData.email || "existing@example.com",
274
+ age: updateData.age || 30,
275
+ role: updateData.role || "user",
276
+ createdAt: "2024-01-01T00:00:00.000Z", // Simulated creation date
277
+ updatedAt: new Date().toISOString()
278
+ };
279
+
280
+ ctx.setStatus(200);
281
+ ctx.setHeader("Content-Type", "application/json");
282
+ ctx.body = JSON.stringify({
283
+ success: true,
284
+ message: "User updated successfully",
285
+ user: updatedUser,
286
+ timestamp: Date.now()
287
+ });
288
+ } catch (error) {
289
+ ctx.setStatus(400);
290
+ ctx.setHeader("Content-Type", "application/json");
291
+ ctx.body = JSON.stringify({
292
+ success: false,
293
+ error: "Invalid JSON",
294
+ message: error.message,
295
+ timestamp: Date.now()
296
+ });
297
+ }
298
+ });
299
+
300
+ return; // Return without calling next() to end request processing
98
301
  }
99
- ctx.setStatus(404);
100
- ctx.setHeader("Content-Type", "application/json");
101
- ctx.body = JSON.stringify({
102
- error: "Not Found",
103
- path: ctx.url,
104
- method: ctx.method
105
- });
302
+ return next(); // Not /update-user PUT route, continue to next middleware
106
303
  });
107
304
 
108
- // 7. Precompile for optimization
109
- pipeline.precompile();
305
+ // 11. Route: 404 Handler - Must be placed last
306
+ pipeline.use((ctx, next) => {
307
+ // If request hasn't been handled (no body set and status is still 200), return 404
308
+ if (!ctx._body && ctx.statusCode === 200) {
309
+ ctx.setStatus(404);
310
+ ctx.setHeader("Content-Type", "application/json");
311
+ ctx.body = JSON.stringify({
312
+ success: false,
313
+ error: "Not Found",
314
+ path: ctx.url,
315
+ method: ctx.method,
316
+ timestamp: Date.now(),
317
+ availableEndpoints: [
318
+ "GET /health",
319
+ "GET /public/info",
320
+ "GET /api/data",
321
+ "POST /api/data",
322
+ "GET /api/profile",
323
+ "GET /api/test",
324
+ "POST /add-user",
325
+ "PUT /update-user"
326
+ ]
327
+ });
328
+ }
329
+ return next(); // Continue execution (though this should be the last middleware)
330
+ });
110
331
 
111
- // 8. Create HTTP server
332
+ // 12. Create HTTP Server with error handling
112
333
  const server = http.createServer(async (req, res) => {
113
334
  try {
114
335
  await pipeline.handle(req, res);
115
336
  } catch (err) {
116
- console.error("Pipeline Error:", err);
337
+ console.error("Pipeline Error:", err.message);
117
338
  if (!res.headersSent) {
118
339
  res.statusCode = 500;
119
340
  res.setHeader("Content-Type", "application/json");
120
- res.end(JSON.stringify({ error: "Internal Server Error" }));
341
+ res.end(JSON.stringify({
342
+ success: false,
343
+ error: "Internal Server Error",
344
+ message: err.message,
345
+ timestamp: Date.now()
346
+ }));
121
347
  }
122
348
  }
123
349
  });
124
350
 
125
- // 9. Start server
351
+ // 13. Start Server on Port 3001
126
352
  const PORT = process.env.PORT || 3001;
127
353
  server.listen(PORT, () => {
128
- console.log(`🚀 Simplified Advanced Server running on http://localhost:${PORT}`);
129
- console.log(`📊 Available endpoints:`);
130
- console.log(` GET /health - Health check`);
354
+ console.log(`🚀 AetherFramework Server running on http://localhost:${PORT}`);
355
+ console.log(`📊 Performance optimized for 20,000+ QPS`);
356
+ console.log(`\n📋 Available endpoints:`);
357
+ console.log(` GET /health - Health check endpoint`);
131
358
  console.log(` GET /public/info - Public information`);
132
- console.log(` GET /api/data - Get sample data`);
359
+ console.log(` GET /api/data - Get sample data (cached)`);
133
360
  console.log(` POST /api/data - Submit data`);
361
+ console.log(` GET /api/profile - User profile`);
362
+ console.log(` GET /api/test - Test endpoint`);
363
+ console.log(` POST /add-user - Add new user`);
364
+ console.log(` PUT /update-user - Update user`);
365
+ console.log(`\n⚡ Features:`);
366
+ console.log(` • Zero-allocation middleware execution`);
367
+ console.log(` • Context pooling (8192 instances)`);
368
+ console.log(` • Static response caching`);
369
+ console.log(` • V8 JIT optimized routing`);
370
+ console.log(` • Connection keep-alive`);
371
+ console.log(`\n📈 Monitoring:`);
134
372
  });
373
+
374
+ // 14. Graceful shutdown handling
375
+ process.on('SIGINT', () => {
376
+ console.log('\n🛑 Shutting down server gracefully...');
377
+ server.close(() => {
378
+ console.log('✅ Server closed');
379
+ process.exit(0);
380
+ });
381
+ });
382
+
383
+ process.on('SIGTERM', () => {
384
+ console.log('\n🛑 Received SIGTERM, shutting down...');
385
+ server.close(() => {
386
+ console.log('✅ Server closed');
387
+ process.exit(0);
388
+ });
389
+ });
390
+
391
+ // 15. Export server for testing
392
+ export default server;
package/index.js CHANGED
@@ -1,10 +1,10 @@
1
- // index.js - ES Module version (updated)
1
+ // index.js - ES Module version
2
2
  // --- Core Components ---
3
3
  import AetherContext from './src/core/AetherContext.js';
4
4
  import AetherPipeline from './src/core/AetherPipeline.js';
5
5
  import AetherStore from './src/core/AetherStore.js';
6
6
  import AetherCompiler from './src/core/AetherCompiler.js';
7
- import AetherRouter from './src/core/AetherRouter.js'; // Added
7
+ import AetherRouter from './src/core/AetherRouter.js';
8
8
 
9
9
  // --- Utilities ---
10
10
  import envLoader from './src/utils/env-loader.js';
@@ -12,17 +12,15 @@ import memoryPool from './src/utils/memory-pool.js';
12
12
  import atomicOps from './src/utils/atomic-ops.js';
13
13
 
14
14
  // --- Middleware Factories ---
15
- import createRateLimit from './src/middleware/rate-limit.js';
15
+ import createRateLimit from './src/middleware/rate-limit.js';
16
16
  import createSecurity from './src/middleware/security.js';
17
17
  import createBodyParser from './src/middleware/body-parser.js';
18
18
  import createCors from './src/middleware/cors.js';
19
19
  import createCompression from './src/middleware/compression.js';
20
20
  import createJwt from './src/middleware/jwt.js';
21
- import SessionManager from './src/middleware/session.js';
21
+ import SessionManager from './src/middleware/session.js';
22
22
  import createJson from './src/middleware/json.js';
23
-
24
- // 修复:使用命名导入而不是默认导入
25
- import { createRouter } from './src/middleware/router.js'; // 改为命名导入
23
+ import { createRouter } from './src/middleware/router.js';
26
24
  import createParamsMiddleware from './src/middleware/params.js';
27
25
 
28
26
  // Export all components
@@ -31,7 +29,7 @@ export {
31
29
  AetherPipeline,
32
30
  AetherStore,
33
31
  AetherCompiler,
34
- AetherRouter // Added
32
+ AetherRouter
35
33
  };
36
34
 
37
35
  // Export utility functions
@@ -43,15 +41,15 @@ export const utils = {
43
41
 
44
42
  // Export middleware factory functions
45
43
  export const middleware = {
46
- rateLimit: createRateLimit,
44
+ rateLimit: createRateLimit,
47
45
  security: createSecurity,
48
46
  bodyParser: createBodyParser,
49
47
  cors: createCors,
50
48
  compression: createCompression,
51
49
  jwt: createJwt,
52
- session: SessionManager,
50
+ session: SessionManager,
53
51
  json: createJson,
54
- router: createRouter, // 这里使用导入的 createRouter
52
+ router: createRouter,
55
53
  params: createParamsMiddleware
56
54
  };
57
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aetherframework/middleware",
3
- "version": "1.0.2",
3
+ "version": "1.0.5",
4
4
  "description": "Ultra-performance, framework-agnostic middleware system for Aether Framework",
5
5
  "main": "index.js",
6
6
  "type": "module",