te.js 2.0.1 → 2.0.3

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,168 +0,0 @@
1
- ---
2
- name: Tejas Framework Test Suite
3
- overview: Create a comprehensive test suite using Vitest for all core features of the Tejas framework, including unit tests, integration tests, edge cases, and error scenarios.
4
- todos:
5
- - id: setup-vitest
6
- content: Set up Vitest configuration and install dependencies
7
- status: completed
8
- - id: test-helpers
9
- content: Create test helper utilities and HTTP mocks
10
- status: pending
11
- - id: test-ammo
12
- content: Write unit tests for Ammo class (fire, throw, redirect, shortcuts)
13
- status: pending
14
- - id: test-target-registry
15
- content: Write tests for Target class and TargetRegistry route matching
16
- status: pending
17
- - id: test-body-parser
18
- content: Write tests for body parser (JSON, URL-encoded, multipart)
19
- status: pending
20
- - id: test-rate-limiting
21
- content: Write tests for all 3 rate limiting algorithms
22
- status: pending
23
- - id: test-file-uploader
24
- content: Write tests for file upload middleware
25
- status: pending
26
- - id: test-configuration
27
- content: Write tests for configuration loading and standardization
28
- status: pending
29
- - id: test-handler-integration
30
- content: Write integration tests for request handler and middleware chain
31
- status: pending
32
- ---
33
-
34
- # Tejas Framework Test Suite Plan
35
-
36
- Create comprehensive tests using Vitest for all core features of the Tejas framework, organized by module with unit, integration, and error scenario coverage.
37
-
38
- ## Test Infrastructure Setup
39
-
40
- Install Vitest and configure for ES modules. Create test utilities and mocks for HTTP requests, database connections, and file system operations.**Files to create:**
41
-
42
- - `vitest.config.js` - Vitest configuration with ESM support
43
- - `tests/helpers/mock-http.js` - HTTP request/response mocks
44
- - `tests/helpers/test-utils.js` - Common test utilities
45
-
46
- ## Core Module Tests
47
-
48
- ### 1. Ammo Class ([server/ammo.js](server/ammo.js))
49
-
50
- Unit tests for the request/response handler:
51
-
52
- - HTTP method flag initialization (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
53
- - `fire()` response dispatch with various argument patterns (status only, data only, status+data, status+data+content-type)
54
- - `redirect()` with default and custom status codes
55
- - `throw()` error handling (TejError, Error instances, status codes, strings)
56
- - `notFound()`, `notAllowed()`, `unauthorized()` shortcuts
57
- - `enhance()` method populating request properties
58
-
59
- ### 2. Target & Registry ([server/target.js](server/target.js), [server/targets/registry.js](server/targets/registry.js))
60
-
61
- Unit tests for routing:
62
-
63
- - Target constructor with base path
64
- - `midair()` middleware registration
65
- - `register()` endpoint registration with path + handler + optional middlewares
66
- - TargetRegistry singleton pattern
67
- - `aim()` exact path matching
68
- - `aim()` parameterized route matching (`/users/:id`, `/api/:category/:id`)
69
- - `getAllEndpoints()` listing (flat and grouped)
70
-
71
- ### 3. Request Handler ([server/handler.js](server/handler.js))
72
-
73
- Integration tests for request processing:
74
-
75
- - Middleware chain execution order
76
- - Global + target + route middleware composition
77
- - Async middleware handling
78
- - Error propagation through chain
79
- - 404 handling for unmatched routes
80
- - Response already sent detection
81
-
82
- ### 4. Body Parser ([server/ammo/body-parser.js](server/ammo/body-parser.js))
83
-
84
- Unit tests for request body parsing:
85
-
86
- - JSON body parsing (valid, invalid, empty)
87
- - URL-encoded body parsing
88
- - Multipart form data parsing with boundary extraction
89
- - Body size limit enforcement (413 errors)
90
- - Request timeout handling (408 errors)
91
- - Missing content-type handling
92
-
93
- ### 5. Rate Limiting ([rate-limit/](rate-limit/))
94
-
95
- Unit tests for each algorithm:
96
-
97
- - **Fixed Window:** Counter increments, window reset, strict mode alignment
98
- - **Sliding Window:** Weighted counts, timestamp pruning, window transitions
99
- - **Token Bucket:** Token consumption, refill rate, burst handling
100
- - Storage interface (memory operations)
101
- - Rate limit header generation (standard, legacy, draft7, draft8)
102
- - `onRateLimited` callback
103
-
104
- ### 6. File Uploader ([server/files/uploader.js](server/files/uploader.js))
105
-
106
- Unit tests for file handling:
107
-
108
- - Single file upload with `file()` middleware
109
- - Multiple file upload with `files()` middleware
110
- - File size validation (413 errors for oversized files)
111
- - File metadata extraction (extension, mimetype, path)
112
- - Non-multipart request passthrough
113
- - Directory creation
114
-
115
- ### 7. Configuration ([utils/configuration.js](utils/configuration.js))
116
-
117
- Unit tests for config processing:
118
-
119
- - `loadConfigFile()` file reading and JSON parsing
120
- - `standardizeObj()` key uppercasing and flattening
121
- - Missing config file handling
122
- - Nested object flattening with underscores
123
-
124
- ### 8. TejError ([server/error.js](server/error.js))
125
-
126
- Unit tests for custom error:
127
-
128
- - Constructor with code and message
129
- - Error inheritance
130
- - Name property
131
-
132
- ### 9. Database Manager ([database/index.js](database/index.js))
133
-
134
- Unit tests (mocked connections):
135
-
136
- - Singleton pattern enforcement
137
- - Connection initialization tracking
138
- - `hasConnection()` status checking
139
- - `getConnection()` retrieval
140
- - Connection not found error
141
-
142
- ## Test File Structure
143
-
144
- ```javascript
145
- tests/
146
- helpers/
147
- mock-http.js
148
- test-utils.js
149
- unit/
150
- ammo.test.js
151
- target.test.js
152
- registry.test.js
153
- body-parser.test.js
154
- rate-limit/
155
- fixed-window.test.js
156
- sliding-window.test.js
157
- token-bucket.test.js
158
- file-uploader.test.js
159
- configuration.test.js
160
- tej-error.test.js
161
- database-manager.test.js
162
- integration/
163
- handler.test.js
164
- middleware-chain.test.js
165
- rate-limit-middleware.test.js
166
-
167
-
168
- ```
package/.prettierignore DELETED
@@ -1,31 +0,0 @@
1
- # Dependencies
2
- node_modules/
3
- package-lock.json
4
- yarn.lock
5
-
6
- # Build output
7
- dist/
8
- build/
9
- *.min.js
10
-
11
- # Coverage directory
12
- coverage/
13
-
14
- # Cache directories
15
- .cache/
16
- .npm/
17
-
18
- # Logs
19
- logs/
20
- *.log
21
- npm-debug.log*
22
-
23
- # IDE specific files
24
- .idea/
25
- .vscode/
26
- *.swp
27
- *.swo
28
-
29
- # System Files
30
- .DS_Store
31
- Thumbs.db
package/.prettierrc DELETED
@@ -1,5 +0,0 @@
1
- {
2
- "singleQuote": true,
3
- "printWidth": 80,
4
- "semi": true
5
- }
@@ -1,77 +0,0 @@
1
- # API Documentation
2
-
3
- **Version:** 1.0.0
4
-
5
- ## Project Summary
6
-
7
- This API provides a lightweight service combining user account management, a Redis-backed caching layer, and system introspection utilities. It supports full CRUD operations on user resources—including file uploads for profile images and bulk documents—offers key-value caching with optional TTL, and exposes health-check and route discovery endpoints for operational monitoring and API introspection. User data is maintained in-memory for demonstration purposes, and uploaded files are stored on disk with configurable size limits.
8
-
9
- ---
10
-
11
- ## APIs Available
12
-
13
- ### Users
14
- Manages user accounts with full CRUD operations: create, retrieve, update, and delete users. Additionally supports profile image uploads and bulk document uploads, with files stored on disk and configurable size limits.
15
-
16
- ### Cache
17
- Provides a key-value caching layer backed by Redis. Store arbitrary values with an optional time-to-live (TTL) and retrieve them by key. A middleware guard ensures the Redis service is available before processing any cache request.
18
-
19
- ### System & Discovery
20
- Core application utilities including a default landing endpoint, a health-check endpoint reporting server status with a current timestamp, and a route discovery endpoint that lists all registered endpoints grouped by source for API introspection.
21
-
22
- ---
23
-
24
- ## Key Endpoints
25
-
26
- ### Getting Started
27
-
28
- | Method | Path | Description |
29
- |--------|------|-------------|
30
- | `GET` | `/` | Default landing entry point for the API. |
31
- | `GET` | `/health` | Health check — returns server status and current timestamp. |
32
- | `GET` | `/routes` | Route discovery — lists all registered endpoints grouped by source. |
33
-
34
- ### User Management
35
-
36
- | Method | Path | Description |
37
- |--------|------|-------------|
38
- | `GET` | `/users` | Retrieve a list of all users. |
39
- | `POST` | `/users` | Create a new user. |
40
- | `GET` | `/users/{id}` | Retrieve a specific user by ID. |
41
- | `PUT` | `/users/{id}` | Update an existing user by ID. |
42
- | `DELETE` | `/users/{id}` | Delete a user by ID. |
43
- | `GET` | `/users/{id}/updateProfileImage` | Upload or update a user's profile image. |
44
- | `GET` | `/users/{id}/uploadDocuments` | Bulk upload documents for a user. |
45
-
46
- ### Cache Operations
47
-
48
- | Method | Path | Description |
49
- |--------|------|-------------|
50
- | `POST` | `/cache` | Store a value in the cache with an optional TTL. |
51
- | `GET` | `/cache/{key}` | Retrieve a cached value by its key. |
52
-
53
- ---
54
-
55
- ## Additional Notes
56
-
57
- ### Data Storage
58
- - **User data** is maintained in-memory and is not persisted across server restarts (demonstration mode).
59
- - **Uploaded files** (profile images, documents) are stored on disk with configurable size limits.
60
-
61
- ### Cache Availability
62
- All cache endpoints are protected by a middleware guard that verifies the Redis service is reachable before processing requests. If Redis is unavailable, cache requests will be rejected before reaching the handler.
63
-
64
- ### File Uploads
65
- - **Profile images**: Single-file upload tied to a specific user via `/users/{id}/updateProfileImage`.
66
- - **Bulk documents**: Multi-file upload supported via `/users/{id}/uploadDocuments`.
67
-
68
- File size limits are configurable at the application level.
69
-
70
- ---
71
-
72
- ## Quick Start
73
-
74
- 1. **Verify the API is running** — call `GET /health` and confirm a successful status response with a timestamp.
75
- 2. **Explore available routes** — call `GET /routes` to discover all registered endpoints.
76
- 3. **Create a user** — send a `POST` request to `/users` with the required user payload.
77
- 4. **Store and retrieve cache entries** — use `POST /cache` to set a key-value pair, then `GET /cache/{key}` to retrieve it.
package/example/README.md DELETED
@@ -1,155 +0,0 @@
1
- # te.js Example
2
-
3
- A comprehensive example demonstrating te.js framework features: routing, middleware, rate limiting, file uploads, services, and optional Redis caching.
4
-
5
- ## Quick Start
6
-
7
- ```bash
8
- npm install
9
- npm start
10
- ```
11
-
12
- Server runs at `http://localhost:1403`
13
-
14
- ## Project Structure
15
-
16
- ```
17
- example/
18
- ├── index.js # App setup, global middleware, rate limit
19
- ├── targets/ # Routes + handlers
20
- │ ├── index.target.js # /, /health, /routes
21
- │ ├── users.target.js # CRUD + file uploads (/users, /users/:id, …)
22
- │ └── cache.target.js # Redis key-value (optional)
23
- └── services/ # Business logic
24
- ├── user.service.js # In-memory user CRUD
25
- └── cache.service.js # Redis wrapper
26
- ```
27
-
28
- ## Endpoints
29
-
30
- ### Index
31
-
32
- | Method | Path | Description |
33
- | ------ | --------- | ------------------------------------ |
34
- | GET | `/` | Default HTML entry |
35
- | GET | `/health` | Health check |
36
- | GET | `/routes` | List all registered routes (grouped) |
37
-
38
- ### Users
39
-
40
- | Method | Path | Description |
41
- | ------ | ------------------------------- | --------------------------------- |
42
- | GET | `/users` | List all users |
43
- | POST | `/users` | Create user (JSON body) |
44
- | GET | `/users/:id` | Get user by id |
45
- | PUT | `/users/:id` | Update user |
46
- | DELETE | `/users/:id` | Delete user |
47
- | POST | `/users/:id/updateProfileImage` | Single file (field: image) |
48
- | POST | `/users/:id/uploadDocuments` | Multiple files (field: documents) |
49
-
50
- ### Cache (requires Redis)
51
-
52
- | Method | Path | Description |
53
- | ------ | ------------- | ---------------------------------- |
54
- | GET | `/cache/:key` | Get value |
55
- | POST | `/cache` | Set value (body: key, value, ttl?) |
56
-
57
- ## curl Examples
58
-
59
- ```bash
60
- # Health check
61
- curl http://localhost:1403/health
62
-
63
- # List routes
64
- curl http://localhost:1403/routes
65
-
66
- # Users CRUD
67
- curl -X POST http://localhost:1403/users -H "Content-Type: application/json" -d '{"name":"John","email":"john@example.com"}'
68
- curl http://localhost:1403/users
69
- curl http://localhost:1403/users/1
70
- curl -X PUT http://localhost:1403/users/1 -H "Content-Type: application/json" -d '{"name":"Jane"}'
71
- curl -X DELETE http://localhost:1403/users/1
72
-
73
- # File upload (single)
74
- curl -X POST http://localhost:1403/users/1/updateProfileImage -F "image=@./photo.jpg"
75
-
76
- # File upload (multiple)
77
- curl -X POST http://localhost:1403/users/1/uploadDocuments -F "documents=@./doc1.pdf" -F "documents=@./doc2.pdf"
78
-
79
- # Cache (requires REDIS_URL)
80
- REDIS_URL=redis://localhost:6379 npm start
81
- curl -X POST http://localhost:1403/cache -H "Content-Type: application/json" -d '{"key":"foo","value":"bar","ttl":60}'
82
- curl http://localhost:1403/cache/foo
83
- ```
84
-
85
- ## Optional: Redis
86
-
87
- To enable cache endpoints:
88
-
89
- ```bash
90
- npm run start:redis
91
- ```
92
-
93
- Or set `REDIS_URL` before starting:
94
-
95
- ```bash
96
- # Linux/macOS
97
- REDIS_URL=redis://localhost:6379 npm start
98
-
99
- # Windows (PowerShell)
100
- $env:REDIS_URL="redis://localhost:6379"; npm start
101
- ```
102
-
103
- ## Features Demonstrated
104
-
105
- - **Routing** — Flat targets, parameterized paths (`:id`)
106
- - **HTTP methods** — `ammo.GET`, `ammo.POST`, `ammo.notAllowed()`
107
- - **Body parsing** — JSON, multipart/form-data
108
- - **Error handling** — `TejError`, `ammo.notFound()`, `ammo.throw()`
109
- - **File uploads** — `TejFileUploader.file()`, `TejFileUploader.files()`
110
- - **Middleware** — Global (`app.midair`), target-level (`target.midair`)
111
- - **Rate limiting** — Memory store (60 req/min)
112
- - **Services** — Business logic in `services/`
113
- - **listAllEndpoints** — Route discovery at `/routes`
114
-
115
- ## Documentation generation
116
-
117
- Generate OpenAPI docs and serve them at `/docs`:
118
-
119
- ```bash
120
- npx tejas generate:docs
121
- ```
122
-
123
- Then use `app.serveDocs({ specPath: './openapi.json' })` in `index.js` (already configured in this example).
124
-
125
- ### Generate docs on push to production (inbuilt)
126
-
127
- To regenerate docs automatically when pushing to your production branch:
128
-
129
- 1. **Configure** the production branch and (optionally) doc options in `tejas.config.json`:
130
-
131
- ```json
132
- "docs": {
133
- "dirTargets": "targets",
134
- "output": "./openapi.json",
135
- "productionBranch": "main"
136
- }
137
- ```
138
-
139
- Set `LLM_API_KEY` (or `OPENAI_API_KEY`) in the environment for non-interactive generation.
140
-
141
- 2. **Add a pre-push hook** (e.g. with Husky):
142
-
143
- ```bash
144
- npx husky add .husky/pre-push "npx tejas docs:on-push"
145
- ```
146
-
147
- When you push to `main` (or your configured branch), the framework will run `tejas generate:docs --ci` before the push completes, so `openapi.json` (and optionally `API_OVERVIEW.md`) stay in sync.
148
-
149
- For CI pipelines, run:
150
-
151
- ```bash
152
- npx tejas generate:docs --ci
153
- ```
154
-
155
- See [te.js documentation](https://tejas-documentation.vercel.app) for more.
package/example/index.js DELETED
@@ -1,29 +0,0 @@
1
- import Tejas from 'te.js';
2
-
3
- const app = new Tejas();
4
-
5
- // Global middleware: request logging
6
- app.midair((ammo, next) => {
7
- console.log(`[${new Date().toISOString()}] ${ammo.method} ${ammo.path}`);
8
- next();
9
- });
10
-
11
- // Rate limiting (memory store - no Redis required)
12
- app.withRateLimit({
13
- maxRequests: 60,
14
- timeWindowSeconds: 60,
15
- });
16
-
17
- // Serve API docs at /docs (requires openapi.json from `tejas generate:docs`)
18
- app.serveDocs({ specPath: './openapi.json' });
19
-
20
- // Optional: Redis for /cache endpoints. Set REDIS_URL to enable.
21
- const redisUrl = process.env.REDIS_URL;
22
-
23
- app.takeoff(
24
- redisUrl
25
- ? {
26
- withRedis: { url: redisUrl },
27
- }
28
- : {},
29
- );
@@ -1,9 +0,0 @@
1
- const auth = (ammo, next) => {
2
- if (ammo.headers.authorization === "Bearer 123") {
3
- next();
4
- } else {
5
- return ammo.unauthorized();
6
- }
7
- };
8
-
9
- export default auth;
@@ -1,6 +0,0 @@
1
- const globalMidair = async (ammo, next) => {
2
- console.log('Global middleware');
3
- await next();
4
- };
5
-
6
- export { globalMidair };