@seip/blue-bird 0.7.6 → 0.9.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 (40) hide show
  1. package/.env_example +34 -34
  2. package/AGENTS.md +174 -249
  3. package/LICENSE +21 -21
  4. package/README.md +331 -367
  5. package/{index.js → backend/index.js} +22 -30
  6. package/backend/routes/api.js +57 -57
  7. package/core/app.js +338 -402
  8. package/core/auth.js +262 -256
  9. package/core/cache.js +174 -174
  10. package/core/cli/docker.js +488 -457
  11. package/core/cli/init.js +333 -337
  12. package/core/cli/route.js +42 -42
  13. package/core/config.js +52 -52
  14. package/core/database.js +263 -263
  15. package/core/debug.js +248 -248
  16. package/core/logger.js +115 -115
  17. package/core/middleware.js +27 -27
  18. package/core/router.js +144 -144
  19. package/core/swagger.js +40 -40
  20. package/core/upload.js +77 -77
  21. package/core/validate.js +380 -380
  22. package/docker/Dockerfile +16 -16
  23. package/docker/docker-compose.dev.yml +6 -0
  24. package/docker/docker-compose.mysql.yml +92 -92
  25. package/docker/docker-compose.none.yml +68 -68
  26. package/docker/docker-compose.postgres.yml +93 -93
  27. package/docker/nginx.conf +98 -106
  28. package/docker-compose.yml +92 -92
  29. package/frontend/about.html +103 -0
  30. package/frontend/images/favicon.ico +0 -0
  31. package/frontend/index.html +141 -0
  32. package/frontend/js/tailwind.js +8 -0
  33. package/package.json +64 -71
  34. package/frontend/astro.config.mjs +0 -35
  35. package/frontend/public/css/app.css +0 -319
  36. package/frontend/public/favicon.ico +0 -0
  37. package/frontend/src/http/api.js +0 -29
  38. package/frontend/src/layouts/Layout.astro +0 -20
  39. package/frontend/src/pages/about.astro +0 -54
  40. package/frontend/src/pages/index.astro +0 -110
package/README.md CHANGED
@@ -1,367 +1,331 @@
1
- # Blue Bird Framework
2
-
3
- **High-Performance Express Framework — Built for Speed, Caching, and Visual Excellence**
4
-
5
- ![Blue Bird Logo](https://seip25.github.io/Blue-bird/blue-bird.png)
6
-
7
- [![npm version](https://img.shields.io/npm/v/@seip/blue-bird.svg)](https://www.npmjs.com/package/@seip/blue-bird)
8
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
-
10
- ---
11
-
12
- ## Introduction
13
-
14
- Blue Bird is a powerful, opinionated framework built on Express for backend routing and APIs, integrated with Astro (v7.0) for high-performance frontend rendering. It features pre-configured data validation, security middlewares, GCM-encrypted JWT authentication, and CLI/Docker developer workflows out of the box.
15
-
16
- ---
17
-
18
- ## 🚀 Key Features / Características Clave
19
-
20
- - All-In-One: Pre-configured Express server with JSON, URL encoding, Cookies, and CORS.
21
- - Astro Frontend: Native integration with Astro (v7.0) for server-side rendering (SSR), static site generation (SSG), and middleware mode.
22
- - Premium Security: AES-256-GCM encrypted JWT cookie auth, secure route filters, and built-in Helmet configurator.
23
- - File Uploads: Easy Multer-based single/multiple file storage handling.
24
- - Docker & PM2 Devops: Pre-built Docker Compose/Dockerfile templates and CLI tools for zero-config dev and VPS production.
25
-
26
- ---
27
-
28
- ## 🛠️ Quick Start / Inicio Rápido
29
-
30
- ### 1. Installation / Instalación
31
-
32
- ```bash
33
- npm install @seip/blue-bird
34
- ```
35
-
36
- ### 2. Initialize Project / Inicializar
37
-
38
- ```bash
39
- npx blue-bird
40
- ```
41
-
42
- When run, the interactive CLI prompts for your preferred infrastructure configuration:
43
- - Database Selection: Choose between `none`, `mysql`, or `postgres`.
44
- - Credentials: Set your database name, user, password, and port (`3306` or `5432`).
45
-
46
- The CLI intelligently copies the appropriate Docker configuration (`docker/docker-compose.mysql.yml`, `docker/docker-compose.postgres.yml`, or `docker/docker-compose.none.yml`) to your project root as `docker-compose.yml`. It also writes the environment settings (`DB_TYPE`, `DATABASE_URL`) to `.env` and installs the required database packages (`mysql2` or `pg`) automatically.
47
-
48
- ### 3. Run Development Server / Modo Desarrollo
49
-
50
- ```bash
51
- npm run dev
52
- ```
53
-
54
- ---
55
-
56
- ## 📁 Project Structure / Estructura del Proyecto
57
-
58
- ```
59
- project/
60
- ├── backend/
61
- │ └── routes/ # Express route files
62
- │ └── api.js # REST API routes
63
- ├── frontend/
64
- │ ├── src/
65
- │ │ └── pages/ # Astro routes and pages (.astro)
66
- │ │ ├── index.astro
67
- │ │ └── about.astro
68
- │ ├── public/ # Static assets mapped to root of Astro build
69
- │ │ └── css/
70
- │ │ └── app.css # Css files
71
- │ └── astro.config.mjs # Astro configuration file
72
- ├── docker/
73
- │ └── Dockerfile # Optimized production build file
74
- ├── docker-compose.yml # Dev/Prod container configurations
75
- ├── index.js # App startup and initialization entrypoint
76
- ├── AGENTS.md # AI coding assistant guidebook
77
- └── .env # App configuration (git-ignored)
78
- ```
79
-
80
- ---
81
-
82
- ## 📖 Core Modules Documentation / Documentación de Módulos
83
-
84
- ### 1. Routing (`Router`)
85
-
86
- Do not use Express' native router. Always use Blue Bird's wrapper class:
87
-
88
- ```javascript
89
- import Router from "@seip/blue-bird/core/router.js";
90
-
91
- const routerApi = new Router("/api");
92
- routerApi.get("/users", (req, res) => {
93
- res.json({ users: [] });
94
- });
95
- export default routerApi;
96
- ```
97
-
98
- ---
99
-
100
- ### 2. Astro Node Middleware Integration
101
-
102
- Blue Bird supports Astro (v7.0) Node middleware mode. Astro handles frontend SSR, routing, static assets, and layouts, while Express handles API endpoints and server logic.
103
-
104
- To enable Astro integration:
105
-
106
- ```javascript
107
- import App from "@seip/blue-bird/core/app.js";
108
- import routerApi from "./backend/routes/api.js";
109
-
110
- const app = new App({
111
- routes: [routerApi],
112
- astro: true, // Enables Astro middleware mode
113
- });
114
-
115
- app.run();
116
- ```
117
-
118
- #### Advanced Config Options
119
-
120
- You can pass a configuration object instead of a boolean value:
121
-
122
- ```javascript
123
- const app = new App({
124
- astro: {
125
- server: true, // Mounts Astro SSR handler
126
- serverEntry: "./frontend/dist/server/entry.mjs", // Path to compiled Astro server entrypoint
127
- client: false, // Set to true to serve static files from client build
128
- clientDir: "./frontend/dist/client", // Path to Astro client static assets
129
- base: "/", // Mount base path
130
- },
131
- });
132
- ```
133
-
134
- ---
135
-
136
- ### 3. Data Validation (`Validator`)
137
-
138
- Validates request payloads using a JSON schema. Returns structured `400 Bad Request` payloads automatically on schema failures.
139
-
140
- ```javascript
141
- import Validator from "@seip/blue-bird/core/validate.js";
142
-
143
- const userSchema = {
144
- email: { required: true, email: true },
145
- password: { required: true, min: 8 },
146
- bio: { required: false },
147
- };
148
-
149
- const validateUser = new Validator(userSchema, "en");
150
-
151
- routerApi.post("/users", validateUser.middleware(), (req, res) => {
152
- res.json({ success: true });
153
- });
154
- ```
155
-
156
- ---
157
-
158
- ### 4. JWT Authentication (`Auth`)
159
-
160
- Secure user sessions using stateless AES-256-GCM encrypted JWTs stored in secure HTTP-Only cookies.
161
-
162
- #### Protecting Routes
163
-
164
- ```javascript
165
- import Auth from "@seip/blue-bird/core/auth.js";
166
-
167
- // Secure API endpoint (returns 401 on failure)
168
- router.get("/profile", Auth.protect(), (req, res) => {
169
- res.json({ user: req.user });
170
- });
171
-
172
- // Secure web page (redirects to /login on failure)
173
- router.get("/dashboard", Auth.protect({ redirect: "/login" }), (req, res) => {
174
- Template.render(res, "dashboard");
175
- });
176
- ```
177
-
178
- #### Authentication Sessions
179
-
180
- ```javascript
181
- router.post("/login", async (req, res) => {
182
- const user = { id: 1, name: "John Doe" };
183
- await Auth.login(res, user);
184
- res.json({ message: "Logged in successfully" });
185
- });
186
-
187
- router.post("/logout", async (req, res) => {
188
- await Auth.logout(res);
189
- res.json({ message: "Logged out" });
190
- });
191
- ```
192
-
193
- ---
194
-
195
- ### 5. Performance Cache Middleware (`Cache`)
196
-
197
- Applies caching at the route handler level. Automatically caches JSON payloads (`res.json`) and rendered outputs (`res.send`).
198
-
199
- ```javascript
200
- import Cache from "@seip/blue-bird/core/cache.js";
201
-
202
- // Cache endpoint for 60 seconds
203
- router.get("/stats", Cache.middleware(60), (req, res) => {
204
- res.json({ usersOnline: 42 });
205
- });
206
- ```
207
-
208
- Integrates with Redis if `REDIS_HOST` is defined in the environment. Falls back to an in-memory cache automatically if Redis is not configured or not running.
209
-
210
- ---
211
-
212
- ### 6. Security Headers (`Helmet`)
213
-
214
- Apply security headers per-router. Preserves the framework's custom powered-by header by default:
215
-
216
- ```javascript
217
- import App from "@seip/blue-bird/core/app.js";
218
-
219
- const webRouter = new Router("/web");
220
- webRouter.use(App.helmet());
221
- ```
222
-
223
- ---
224
-
225
- ### 7. Database wrapper (`Database`)
226
-
227
- Blue Bird provides a unified, multi-database client wrapper (`core/database.js`) supporting **MySQL** and **PostgreSQL** with automated connection retry loops, query formatting utilities, and Redis query caching.
228
-
229
- #### Driver Support
230
- - **Native MySQL (`mysql2/promise`)**: High-performance connection pool for MySQL 8.0+.
231
- - **Native PostgreSQL (`pg`)**: Connection pool for PostgreSQL 18+. When running standard queries with `connection.query(sql, params)`, the wrapper automatically converts `?` parameter placeholders into PostgreSQL `$1, $2, ...` syntax, allowing unified SQL query writing across both database engines.
232
- - **No Database (`none`)**: If no database is configured, the wrapper is disabled gracefully without crashing the server.
233
-
234
- #### Standalone & Remote Database Configuration
235
- You can connect to any local or remote database instance (outside Docker, such as Supabase, Neon, AWS RDS, or local services) simply by defining the `DATABASE_URL` in your `.env` file:
236
-
237
- ```env
238
- DB_TYPE="postgres"
239
- DATABASE_URL="postgresql://postgres:password@localhost:5432/blue_bird?schema=public"
240
- # OR for MySQL:
241
- # DATABASE_URL="mysql://root:password@localhost:3306/blue_bird"
242
- ```
243
-
244
- #### Usage Examples
245
-
246
- ```javascript
247
- import { Database, DB_TYPE } from "@seip/blue-bird/core/database.js";
248
-
249
- // Instantiate the database connection pool with a connection limit (e.g., 20)
250
- const connection = new Database(20);
251
-
252
- // 1. Basic SELECT query returning single row (Works for both MySQL and PostgreSQL using ? placeholders)
253
- const user = await connection.query("SELECT * FROM users WHERE email = ?", ["test@example.com"], "return_row");
254
-
255
- // 2. Fetch rows with 60 seconds Redis caching enabled
256
- const stats = await connection.query("SELECT COUNT(*) as count FROM access_logs", [], { cache: 60 });
257
-
258
- // 3. INSERT query (returns insertId for MySQL, or inserted row ID / rowCount for PostgreSQL)
259
- const newId = await connection.query("INSERT INTO users (name) VALUES (?)", ["John"]);
260
- ```
261
-
262
- ---
263
-
264
- ### 8. Nginx Proxy Caching
265
-
266
- Nginx reverse proxy is preconfigured with a page cache zone (`astro_cache`) that stores public page outputs (Astro SSR/SSG) for 10 seconds.
267
- - **Cache Bypass:** Requests with an `auth` cookie or `Authorization` header automatically bypass the cache to ensure dynamic page outputs.
268
- - **Disabling:** Caching can be turned off in `docker/nginx.conf` by commenting out the `proxy_cache` directives.
269
- - **Caching API routes:** If you want Nginx to cache GET endpoints from `/api/` directly (which is much faster than Node query/redis caching), add a matching location block inside `docker/nginx.conf` before the generic `/api/` block:
270
- ```nginx
271
- location /api/cached-stats {
272
- limit_req zone=bluebird_limit burst=20 nodelay;
273
- set $upstream_target http://app:3000;
274
- proxy_pass $upstream_target;
275
- proxy_http_version 1.1;
276
- proxy_set_header Connection "";
277
- proxy_set_header Host $host;
278
-
279
- proxy_cache astro_cache;
280
- proxy_cache_valid 200 10s;
281
- add_header X-Cache-Status $upstream_cache_status;
282
- }
283
- ```
284
-
285
- ---
286
-
287
- ## Docker CLI Workflow
288
-
289
- Blue Bird comes with a built-in Docker CLI wrapper that handles both local development database bootstrapping and full-stack VPS production deployments across MySQL, PostgreSQL, or no-database architectures.
290
-
291
- ### Commands Syntax:
292
-
293
- ```bash
294
- npx blue-bird docker <command> [options]
295
- ```
296
-
297
- ### Supported Actions:
298
-
299
- - **`npx blue-bird docker start`**: Boots the production stack (Node.js App + Nginx + Database + Redis).
300
- - **`npx blue-bird docker start db`** (or `postgres` / `mysql`): Boots the configured database container only (great for local development outside Docker).
301
- - **`npx blue-bird docker start redis`**: Boots the Redis container only.
302
- - **`npx blue-bird docker start dbs`**: Boots both database containers (configured DB + Redis).
303
- - **`npx blue-bird docker stop`**: Stops all active project containers.
304
- - **`npx blue-bird docker build [--no-cache]`**: Builds or updates the Node.js production image.
305
- - **`npx blue-bird docker ps`**: Lists running project containers and ports.
306
- - **`npx blue-bird docker logs [app|db|postgres|mysql]`**: Tails logs for the specified container.
307
- - **`npx blue-bird docker pm2 [args]`**: Runs PM2 commands inside the Node.js application container (e.g. `status`, `monit`, `reload all`).
308
- - **`npx blue-bird docker db`** (or `psql` / `mysql`): Connects into the container's interactive database shell (`psql` for PostgreSQL, `mysql` for MySQL) using credentials from `.env`.
309
- - **`npx blue-bird docker redis`**: Connects into the container's interactive Redis CLI terminal.
310
- - **`npx blue-bird docker prune`**: Safely clears orphaned volumes, dangling build caches, and images.
311
-
312
- ---
313
-
314
- ## 🚀 Production Deployment Options
315
-
316
- You can deploy Blue Bird applications to production using two main workflows:
317
-
318
- ### A. Docker Container Stack (Highly Recommended)
319
-
320
- Using the built-in Docker stack is the recommended deployment method because it sets up a complete, hardened production environment automatically:
321
- - **Nginx Reverse Proxy:** Captures traffic on port 3000 (or custom PORT), serves Astro client-side assets directly from the filesystem to offload the Node.js server, and proxies the rest to Express.
322
- - **PM2 Clustering:** Launches Node.js in cluster mode inside the container, utilizing all available CPU cores based on `PM2_INSTANCES` configuration (defaulting to 1).
323
- - **Security Mitigation:** Nginx blocks common malicious scanners (e.g. `/.env`, `/.git`, `/wp-admin`) instantly using a 444 status code and implements a `10r/s` request rate-limit.
324
- - **Services Stack:** MySQL and Redis are configured in the same bridge network automatically.
325
-
326
- To deploy via Docker:
327
- 1. Configure `.env` with production keys, `DEBUG=false` and your custom `TITLE`.
328
- 2. Build the production image:
329
- ```bash
330
- npx blue-bird docker build
331
- ```
332
- 3. Run the container cluster:
333
- ```bash
334
- npx blue-bird docker start prod
335
- ```
336
-
337
- ### B. Standard Standalone PM2 / Node.js Runtime
338
-
339
- If you choose to run outside of Docker, you must set up the reverse proxy and databases manually. To deploy in a standard Linux environment using PM2:
340
-
341
- 1. Install PM2 globally:
342
- ```bash
343
- npm install pm2 -g
344
- ```
345
- 2. Start the application under PM2:
346
- ```bash
347
- pm2 start index.js --name "bluebird-app" --node-args="--env-file=.env" -i max
348
- ```
349
- 3. Monitor status:
350
- ```bash
351
- pm2 status
352
- pm2 logs
353
- ```
354
-
355
- ---
356
-
357
- ## 📄 License / Licencia
358
-
359
- Distributed under the **MIT License**. See `LICENSE` for more information.
360
-
361
- Distribuido bajo la **Licencia MIT**. Mira `LICENSE` para más información.
362
-
363
- ---
364
-
365
- <div align="center">
366
- <p>Made with ❤️ by <strong>Seip25</strong></p>
367
- </div>
1
+ # Blue Bird Framework
2
+
3
+ **High-Performance Express Framework — Built for Speed, Caching, and Visual Excellence**
4
+
5
+ ![Blue Bird Logo](https://seip25.github.io/Blue-bird/favicon.png)
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@seip/blue-bird.svg)](https://www.npmjs.com/package/@seip/blue-bird)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
10
+ ---
11
+
12
+ ## Introduction
13
+
14
+ Blue Bird is a powerful, performance-first API framework built on Express. It features pre-configured data validation, security middlewares, GCM-encrypted JWT authentication, and CLI/Docker developer workflows out of the box, with static frontend assets handled directly by Nginx.
15
+
16
+ ---
17
+
18
+ ## 🕊️ The Blue Bird Philosophy
19
+
20
+ Stop wasting time configuring CORS, security headers, database connections, and authentication flows. Blue Bird provides an opinionated, highly efficient core structure allowing you to focus on writing clean business logic. Nginx handles the static frontend directly from the filesystem, Express handles the backend APIs. Includes a preconfigured Docker stack with Nginx reverse proxy, Redis cache, and PM2 cluster scaling.
21
+
22
+ ### 🧩 Decoupled Architecture
23
+ Nginx natively serves static frontend assets and extensionless HTML pages from `frontend/`. Express owns the API layer, keeping your backend entirely focused on performance and logic.
24
+
25
+ - **Cross-Platform Versatility**: Because the Express backend API is fully decoupled from the HTML/JS/CSS frontend layer, developers can easily build and maintain multiple application targets pointing to the same core API:
26
+ - **Web Applications**: Static HTML, CSS, and client-side JS served natively by Nginx.
27
+ - **Mobile Applications**: Powered by **Capacitor**, Cordova, or React Native.
28
+ - **Desktop Applications**: Built with **Electron** or **Tauri**.
29
+ - **Strong Business Logic**: Enforces a strict separation of concerns — Nginx excels at ultra-fast static file delivery and public assets, while Express handles API routing, business rules, validation, and data operations without UI rendering overhead.
30
+ - **Lightweight Footprint**: Offloading static assets to Nginx optimizes Node.js event loop performance, resulting in extremely minimal RAM, CPU, and disk consumption under high concurrent workloads.
31
+
32
+ ### 🐳 Built-in Orchestration
33
+ Includes a comprehensive Docker Compose CLI wrapper to bootstrap, build, stop, and clean dev and production environments with zero manual scripting.
34
+
35
+ ---
36
+
37
+ ## 🚀 Key Features / Características Clave
38
+
39
+ - All-In-One: Pre-configured Express API server with JSON, URL encoding, Cookies, and CORS.
40
+ - Nginx Static Frontend: Lightning-fast static asset and extensionless HTML serving via Nginx, decoupled from Node.js.
41
+ - Premium Security: AES-256-GCM encrypted JWT cookie auth, secure route filters, and built-in Helmet configurator.
42
+ - File Uploads: Easy Multer-based single/multiple file storage handling.
43
+ - Docker & PM2 Devops: Pre-built Docker Compose/Dockerfile templates and CLI tools for zero-config dev and VPS production.
44
+
45
+ ---
46
+
47
+ ## 🛠️ Quick Start / Inicio Rápido
48
+
49
+ ### 1. Installation / Instalación
50
+
51
+ ```bash
52
+ npm install @seip/blue-bird
53
+ ```
54
+
55
+ ### 2. Initialize Project / Inicializar
56
+
57
+ ```bash
58
+ npx blue-bird
59
+ ```
60
+
61
+ When run, the interactive CLI prompts for your preferred infrastructure configuration:
62
+ - Database Selection: Choose between `none`, `mysql`, or `postgres`.
63
+ - Credentials: Set your database name, user, password, and port (`3306` or `5432`).
64
+
65
+ The CLI intelligently copies the appropriate Docker configuration (`docker/docker-compose.mysql.yml`, `docker/docker-compose.postgres.yml`, or `docker/docker-compose.none.yml`) to your project root as `docker-compose.yml`. It also writes the environment settings (`DB_TYPE`, `DATABASE_URL`) to `.env` and installs the required database packages (`mysql2` or `pg`) automatically.
66
+
67
+ ### 3. Run Development Server / Modo Desarrollo
68
+
69
+ ```bash
70
+ npm run dev
71
+ ```
72
+
73
+ ---
74
+
75
+ ## 📁 Project Structure / Estructura del Proyecto
76
+
77
+ ```
78
+ project/
79
+ ├── backend/
80
+ │ └── routes/ # Express route files
81
+ │ └── api.js # REST API routes
82
+ ├── frontend/
83
+ │ ├── css/ # CSS files
84
+ │ ├── js/ # JavaScript files
85
+ │ └── index.html # Static HTML files
86
+ ├── docker/
87
+ │ └── Dockerfile # Optimized production build file
88
+ ├── docker-compose.yml # Dev/Prod container configurations
89
+ ├── index.js # App startup and initialization entrypoint
90
+ ├── AGENTS.md # AI coding assistant guidebook
91
+ └── .env # App configuration (git-ignored)
92
+ ```
93
+
94
+ ---
95
+
96
+ ## 📖 Core Modules Documentation / Documentación de Módulos
97
+
98
+ ### 1. Routing (`Router`)
99
+
100
+ Do not use Express' native router. Always use Blue Bird's wrapper class:
101
+
102
+ ```javascript
103
+ import Router from "@seip/blue-bird/core/router.js";
104
+
105
+ const routerApi = new Router("/api");
106
+ routerApi.get("/users", (req, res) => {
107
+ res.json({ users: [] });
108
+ });
109
+ export default routerApi;
110
+ ```
111
+
112
+ ---
113
+
114
+
115
+
116
+ ### 3. Data Validation (`Validator`)
117
+
118
+ Validates request payloads using a JSON schema. Returns structured `400 Bad Request` payloads automatically on schema failures.
119
+
120
+ ```javascript
121
+ import Validator from "@seip/blue-bird/core/validate.js";
122
+
123
+ const userSchema = {
124
+ email: { required: true, email: true },
125
+ password: { required: true, min: 8 },
126
+ bio: { required: false },
127
+ };
128
+
129
+ const validateUser = new Validator(userSchema, "en");
130
+
131
+ routerApi.post("/users", validateUser.middleware(), (req, res) => {
132
+ res.json({ success: true });
133
+ });
134
+ ```
135
+
136
+ ---
137
+
138
+ ### 4. JWT Authentication (`Auth`)
139
+
140
+ Secure user sessions using stateless AES-256-GCM encrypted JWTs stored in secure HTTP-Only cookies.
141
+
142
+ #### Protecting Routes
143
+
144
+ ```javascript
145
+ import Auth from "@seip/blue-bird/core/auth.js";
146
+
147
+ // Secure API endpoint (returns 401 on failure)
148
+ router.get("/profile", Auth.protect(), (req, res) => {
149
+ res.json({ user: req.user });
150
+ });
151
+
152
+ // Secure web page (redirects to /login on failure)
153
+ router.get("/dashboard", Auth.protect({ redirect: "/login" }), (req, res) => {
154
+ Template.render(res, "dashboard");
155
+ });
156
+ ```
157
+
158
+ #### Authentication Sessions
159
+
160
+ ```javascript
161
+ router.post("/login", async (req, res) => {
162
+ const user = { id: 1, name: "John Doe" };
163
+ await Auth.login(res, user);
164
+ res.json({ message: "Logged in successfully" });
165
+ });
166
+
167
+ router.post("/logout", async (req, res) => {
168
+ await Auth.logout(res);
169
+ res.json({ message: "Logged out" });
170
+ });
171
+ ```
172
+
173
+ ---
174
+
175
+ ### 5. Performance Cache Middleware (`Cache`)
176
+
177
+ Applies caching at the route handler level. Automatically caches JSON payloads (`res.json`) and rendered outputs (`res.send`).
178
+
179
+ ```javascript
180
+ import Cache from "@seip/blue-bird/core/cache.js";
181
+
182
+ // Cache endpoint for 60 seconds
183
+ router.get("/stats", Cache.middleware(60), (req, res) => {
184
+ res.json({ usersOnline: 42 });
185
+ });
186
+ ```
187
+
188
+ Integrates with Redis if `REDIS_HOST` is defined in the environment. Falls back to an in-memory cache automatically if Redis is not configured or not running.
189
+
190
+ ---
191
+
192
+ ### 6. Security Headers (`Helmet`)
193
+
194
+ Apply security headers per-router. Preserves the framework's custom powered-by header by default:
195
+
196
+ ```javascript
197
+ import App from "@seip/blue-bird/core/app.js";
198
+
199
+ const webRouter = new Router("/web");
200
+ webRouter.use(App.helmet());
201
+ ```
202
+
203
+ ---
204
+
205
+ ### 7. Database wrapper (`Database`)
206
+
207
+ Blue Bird provides a unified, multi-database client wrapper (`core/database.js`) supporting **MySQL** and **PostgreSQL** with automated connection retry loops, query formatting utilities, and Redis query caching.
208
+
209
+ #### Driver Support
210
+ - **Native MySQL (`mysql2/promise`)**: High-performance connection pool for MySQL 8.0+.
211
+ - **Native PostgreSQL (`pg`)**: Connection pool for PostgreSQL 18+. When running standard queries with `connection.query(sql, params)`, the wrapper automatically converts `?` parameter placeholders into PostgreSQL `$1, $2, ...` syntax, allowing unified SQL query writing across both database engines.
212
+ - **No Database (`none`)**: If no database is configured, the wrapper is disabled gracefully without crashing the server.
213
+
214
+ #### Standalone & Remote Database Configuration
215
+ You can connect to any local or remote database instance (outside Docker, such as Supabase, Neon, AWS RDS, or local services) simply by defining the `DATABASE_URL` in your `.env` file:
216
+
217
+ ```env
218
+ DB_TYPE="postgres"
219
+ DATABASE_URL="postgresql://postgres:password@localhost:5432/blue_bird?schema=public"
220
+ # OR for MySQL:
221
+ # DATABASE_URL="mysql://root:password@localhost:3306/blue_bird"
222
+ ```
223
+
224
+ #### Usage Examples
225
+
226
+ ```javascript
227
+ import { Database, DB_TYPE } from "@seip/blue-bird/core/database.js";
228
+
229
+ // Instantiate the database connection pool with a connection limit (e.g., 20)
230
+ const connection = new Database(20);
231
+
232
+ // 1. Basic SELECT query returning single row (Works for both MySQL and PostgreSQL using ? placeholders)
233
+ const user = await connection.query("SELECT * FROM users WHERE email = ?", ["test@example.com"], "return_row");
234
+
235
+ // 2. Fetch rows with 60 seconds Redis caching enabled
236
+ const stats = await connection.query("SELECT COUNT(*) as count FROM access_logs", [], { cache: 60 });
237
+
238
+ // 3. INSERT query (returns insertId for MySQL, or inserted row ID / rowCount for PostgreSQL)
239
+ const newId = await connection.query("INSERT INTO users (name) VALUES (?)", ["John"]);
240
+ ```
241
+
242
+ ---
243
+
244
+ ### 8. Nginx Static Asset Caching
245
+
246
+ Nginx is configured to explicitly cache static assets (`.js`, `.css`, `.jpg`, `.png`, etc.) in the user's browser with the `Cache-Control` header (valid for 1 month). HTML and API endpoints (`/api/*`) are not cached by Nginx to ensure they serve dynamic and up-to-date content, relying instead on the Node.js application and Redis for data-layer caching.
247
+
248
+ ---
249
+
250
+ ## Docker CLI Workflow
251
+
252
+ Blue Bird comes with a built-in Docker CLI wrapper that handles both local development database bootstrapping and full-stack VPS production deployments across MySQL, PostgreSQL, or no-database architectures.
253
+
254
+ ### Commands Syntax:
255
+
256
+ ```bash
257
+ npx blue-bird docker <command> [options]
258
+ ```
259
+
260
+ ### Supported Actions:
261
+
262
+ - **`npx blue-bird docker dev`**: Boots the development stack (Node.js App with `npm run dev` + Nginx + Database + Redis).
263
+ - **`npx blue-bird docker start`**: Boots the production stack (Node.js App + Nginx + Database + Redis).
264
+ - **`npx blue-bird docker start db`** (or `postgres` / `mysql`): Boots the configured database container only (great for local development outside Docker).
265
+ - **`npx blue-bird docker start redis`**: Boots the Redis container only.
266
+ - **`npx blue-bird docker start dbs`**: Boots both database containers (configured DB + Redis).
267
+ - **`npx blue-bird docker stop`**: Stops all active project containers.
268
+ - **`npx blue-bird docker build [--no-cache]`**: Builds or updates the Node.js production image.
269
+ - **`npx blue-bird docker ps`**: Lists running project containers and ports.
270
+ - **`npx blue-bird docker logs [app|db|postgres|mysql]`**: Tails logs for the specified container.
271
+ - **`npx blue-bird docker pm2 [args]`**: Runs PM2 commands inside the Node.js application container (e.g. `status`, `monit`, `reload all`).
272
+ - **`npx blue-bird docker db`** (or `psql` / `mysql`): Connects into the container's interactive database shell (`psql` for PostgreSQL, `mysql` for MySQL) using credentials from `.env`.
273
+ - **`npx blue-bird docker redis`**: Connects into the container's interactive Redis CLI terminal.
274
+ - **`npx blue-bird docker prune`**: Safely clears orphaned volumes, dangling build caches, and images.
275
+
276
+ ---
277
+
278
+ ## 🚀 Production Deployment Options
279
+
280
+ You can deploy Blue Bird applications to production using two main workflows:
281
+
282
+ ### A. Docker Container Stack (Highly Recommended)
283
+
284
+ Using the built-in Docker stack is the recommended deployment method because it sets up a complete, hardened production environment automatically:
285
+ - **Nginx Reverse Proxy:** Captures traffic on port 3000 (or custom PORT), serves static assets and extensionless HTML directly from the filesystem to offload the Node.js server, and proxies API traffic to Express.
286
+ - **PM2 Clustering:** Launches Node.js in cluster mode inside the container, utilizing all available CPU cores based on `PM2_INSTANCES` configuration (defaulting to 1).
287
+ - **Security Mitigation:** Nginx blocks common malicious scanners (e.g. `/.env`, `/.git`, `/wp-admin`) instantly using a 444 status code and implements a `10r/s` request rate-limit.
288
+ - **Services Stack:** MySQL and Redis are configured in the same bridge network automatically.
289
+
290
+ To deploy via Docker:
291
+ 1. Configure `.env` with production keys, `DEBUG=false` and your custom `TITLE`.
292
+ 2. Build the production image:
293
+ ```bash
294
+ npx blue-bird docker build
295
+ ```
296
+ 3. Run the container cluster:
297
+ ```bash
298
+ npx blue-bird docker start prod
299
+ ```
300
+
301
+ ### B. Standard Standalone PM2 / Node.js Runtime
302
+
303
+ If you choose to run outside of Docker, you must set up the reverse proxy and databases manually. To deploy in a standard Linux environment using PM2:
304
+
305
+ 1. Install PM2 globally:
306
+ ```bash
307
+ npm install pm2 -g
308
+ ```
309
+ 2. Start the application under PM2:
310
+ ```bash
311
+ pm2 start index.js --name "bluebird-app" --node-args="--env-file=.env" -i max
312
+ ```
313
+ 3. Monitor status:
314
+ ```bash
315
+ pm2 status
316
+ pm2 logs
317
+ ```
318
+
319
+ ---
320
+
321
+ ## 📄 License / Licencia
322
+
323
+ Distributed under the **MIT License**. See `LICENSE` for more information.
324
+
325
+ Distribuido bajo la **Licencia MIT**. Mira `LICENSE` para más información.
326
+
327
+ ---
328
+
329
+ <div align="center">
330
+ <p>Made with ❤️ by <strong>Seip25</strong></p>
331
+ </div>