@seip/bluebird-js 0.1.4 → 0.1.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.
package/AGENTS.md CHANGED
@@ -1,486 +1,495 @@
1
- # Bluebird.js Framework - AI Agent Guide
2
-
3
- This document serves as the primary manual for any AI Agent interacting with the codebase. It details the architecture of Bluebird.js (`@seip/bluebird-js`), its internal modules, and how features should be written or modified.
4
-
5
- ## 1. Core Architecture
6
-
7
- Bluebird.js is a performance-first web and API framework built on **Express** (Node.js 22.18+). It provides pure modern JavaScript ESM execution, JWT auth, HTML rendering with multi-level caching, BaseModel, schema validation, database access, and queue processing out of the box.
8
-
9
- - **Entrypoint (`index.js`)**: Located at the project root. Initializes the server using `App` from `core/app.js` and registers the routes.
10
- - **Application (`app/`)**: Application code — `app/routes/` (API + web), `app/models/` (BaseModels), `app/views/` (HTML templates), `app/jobs/` (background workers).
11
- - **Public assets (`public/`)**: Static files only (CSS, JS, images, fonts). Served directly by Nginx or Express fallback.
12
- - **Core (`core/`)**: The framework core. Contains `Router`, `Render`, `Validator`, `Auth`, `Cache`, `Redis`, `Database`, `Model`, `Csrf`, `Hash`, etc. **DO NOT MODIFY** the core unless explicitly requested.
13
-
14
- ## 2. Modern JavaScript Standard (ESM)
15
-
16
- Bluebird.js standardizes on pure modern JavaScript (Node.js 22.18+ ESM) with zero build steps or transpilation pipelines required:
17
-
18
- - **Root Entrypoint (`index.js`)**: Run in development with `node --watch --env-file=.env index.js`.
19
- - **Production Entrypoint (`index.js`)**: Run with `node --env-file=.env index.js` or via PM2 cluster.
20
- - **Initialization**: `npx bluebird-js` scaffolds a new project directly with `index.js` at the root.
21
- - **IDE Intellisense**: Powered by `core/index.d.ts` and `jsconfig.json`.
22
-
23
- ```javascript
24
- import App from "@seip/bluebird-js/core/app.js";
25
- import routerApi from "./app/routes/api.js";
26
- import routerWeb from "./app/routes/web.js";
27
-
28
- const app = new App({
29
- routes: [routerWeb, routerApi],
30
- port: process.env.PORT || 3000,
31
- });
32
-
33
- app.run();
34
- ```
35
-
36
- ## 3. Routing (Router)
37
-
38
- Do not use Express' native router directly. Always use Bluebird's `Router` wrapper.
39
-
40
- ```javascript
41
- import Router from "@seip/bluebird-js/core/router.js";
42
-
43
- const routerApi = new Router("/api");
44
-
45
- routerApi.get("/users", (req, res) => {
46
- res.json({ users: [] });
47
- });
48
-
49
- export default routerApi;
50
- ```
51
-
52
- When created with `{ seo: true }`, all GET routes registered on that router are tracked for search engine indexing.
53
-
54
- ## 4. Request Validation (Validator)
55
-
56
- Incoming request data is validated using `core/validate.js`, which automatically returns HTTP 400 JSON responses on error. The validator inspects request payloads without destructively mutating raw data.
57
-
58
- ```javascript
59
- import Validator from "@seip/bluebird-js/core/validate.js";
60
-
61
- const userSchema = {
62
- email: { required: true, email: true },
63
- password: { required: true, min: 8 },
64
- bio: { required: false },
65
- };
66
-
67
- const validateUser = new Validator(userSchema, "en");
68
-
69
- routerApi.post("/users", validateUser.middleware(), (req, res) => {
70
- res.json({ success: true });
71
- });
72
- ```
73
-
74
- ## 5. Lightweight BaseModel (Model)
75
-
76
- > **Important Architecture Note:**
77
- > Bluebird's `BaseModel` (`core/model.js`) is designed as a lightweight, zero-dependency static facade for high performance, simple queries, soft deletes, and migrations.
78
- > **For complex multi-tier enterprise ORM mapping, Prisma is recommended.**
79
-
80
- ### Defining a Model
81
-
82
- Create models inside `app/models/`:
83
-
84
- ```javascript
85
- import Model from "@seip/bluebird-js/core/model.js";
86
-
87
- export default class User extends Model {
88
- static table = "users";
89
- static primaryKey = "id";
90
- static timestamps = true;
91
- static softDelete = true;
92
-
93
- static schema = {
94
- id: { type: "int", primary: true, auto: true },
95
- name: { type: "string", length: 150, required: true },
96
- email: { type: "string", length: 150, unique: true, required: true, email: true },
97
- password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
98
- role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
99
- };
100
- }
101
- ```
102
-
103
- ### CRUD Shortcuts & Query Facades
104
-
105
- Every Model exposes direct shortcuts to database queries, transactions, and mutations:
106
-
107
- ```javascript
108
- const total = await User.query("SELECT COUNT(*) as count FROM users", [], "return_row");
109
- await User.transaction(async (tx) => {
110
- await tx.query("UPDATE users SET role = ? WHERE id = ?", ["admin", 1]);
111
- });
112
-
113
- const userId = await User.create({ name: "Alice", email: "alice@example.com", password: "secretPassword" });
114
-
115
- const user = await User.find(1, { cache: 60 });
116
- const userWithPosts = await User.find(1, { oneMany: Post });
117
- const postWithAuthor = await Post.find(10, { belongsTo: User });
118
-
119
- const page = await User.paginate({ where: { role: "user" }, page: 1, limit: 10 });
120
- await User.update(userId, { name: "Alice Smith" });
121
-
122
- const totalUsers = await User.count({ role: "user" });
123
- const exists = await User.exists({ email: "alice@example.com" });
124
-
125
- const matching = await User.all({
126
- where: {
127
- id: [1, 2, 3],
128
- role: { $ne: "banned" },
129
- views: { $gt: 100 },
130
- },
131
- });
132
-
133
- const userRecord = await User.firstOrCreate({ email: "john@example.com" }, { name: "John Doe" });
134
- const updatedRecord = await User.updateOrCreate({ email: "john@example.com" }, { name: "Johnathan" });
135
-
136
- await User.delete(userId);
137
- await User.delete(userId, { force: true });
138
- await User.delete(userId, { cascade: [Post] });
139
- await User.restore(userId);
140
- ```
141
-
142
- ## 6. CSRF Protection (Csrf)
143
-
144
- Bluebird provides native, zero-dependency HMAC-signed CSRF protection (`core/csrf.js`):
145
-
146
- ```javascript
147
- import Csrf from "@seip/bluebird-js/core/csrf.js";
148
-
149
- routerWeb.use(Csrf.middleware());
150
- ```
151
-
152
- ## 7. Authentication & Password Hashing (Auth & Hash)
153
-
154
- ### Password Hashing (Hash)
155
-
156
- Native password hashing using `node:crypto.scrypt` with random salt and timing-safe comparison (zero external npm dependencies required).
157
-
158
- ```javascript
159
- import Hash from "@seip/bluebird-js/core/hash.js";
160
-
161
- const hash = await Hash.make("mySecretPassword");
162
- const isValid = await Hash.verify("mySecretPassword", hash);
163
- ```
164
-
165
- ### JWT Handling (Auth)
166
-
167
- Native JWT handling with AES-256-GCM encryption and HMAC-SHA256 signature verification using `node:crypto`.
168
-
169
- ```javascript
170
- import Auth from "@seip/bluebird-js/core/auth.js";
171
-
172
- router.get("/profile", Auth.protect(), (req, res) => {
173
- res.json({ user: req.user });
174
- });
175
-
176
- router.post("/login", async (req, res) => {
177
- const user = { id: 1, name: "John" };
178
- await Auth.login(res, user);
179
- res.ok(user, "Logged in");
180
- });
181
-
182
- router.post("/logout", async (req, res) => {
183
- await Auth.logout(res);
184
- res.ok(null, "Logged out");
185
- });
186
- ```
187
-
188
- ## 8. HTTP Response Helpers & Health Check
189
-
190
- Bluebird decorates the Express `res` object with standardized helper methods:
191
-
192
- ```javascript
193
- res.ok(data, "Success message");
194
- res.created(data, "Created successfully");
195
- res.paginate(items, pagination, "Fetched");
196
-
197
- res.badRequest("Invalid input", errors);
198
- res.unauthorized("Authentication required");
199
- res.forbidden("Access denied");
200
- res.notFound("Resource not found");
201
- res.serverError("Internal failure", err);
202
- ```
203
-
204
- Every Bluebird application provides a native `/api/health` endpoint returning uptime, timestamp, environment, and memory consumption.
205
-
206
- ## 9. Performance Caching (Cache & Redis)
207
-
208
- Caching defaults to fast in-memory LRU storage, ideal for desktop applications and single or dual PM2 instances. Filesystem caching (`driver: "file"`) is available as persistent local fallback, and Redis (`driver: "redis"`) is isolated in `core/redis.js` on-demand for high-traffic environments.
209
-
210
- ```javascript
211
- import Cache from "@seip/bluebird-js/core/cache.js";
212
-
213
- router.get("/stats", Cache.middleware(60), (req, res) => {
214
- res.ok({ usersCount: 150 });
215
- });
216
-
217
- await Cache.set("custom_key", { data: "value" }, 120, { driver: "memory" });
218
- const cachedData = await Cache.get("custom_key", { driver: "memory" });
219
-
220
- const stats = await Cache.deduplicate("stats-key", async () => {
221
- return await calculateHeavyStats();
222
- });
223
-
224
- await Cache.delete("custom_key");
225
- await Cache.clear();
226
- ```
227
-
228
- ## 10. Database Module (database.js)
229
-
230
- Bluebird provides a unified wrapper class (`core/database.js`) supporting **SQLite (native `node:sqlite` in Node 22.18+ with `better-sqlite3` fallback)**, **MySQL (`mysql2/promise`)**, and **PostgreSQL (`pg`)**:
231
-
232
- - **Native SQLite by Default:** No native C++ compilation or build tools required.
233
- - **SQLite Concurrency & WAL:** Automatically configures WAL mode, busy timeout, and memory-mapped I/O.
234
- - **Prepared Statement Caching:** SQLite caches prepared statement ASTs automatically.
235
- - **Query Caching:** Supports `{ cache: 60 }` across memory, file, and redis backends.
236
-
237
- ```javascript
238
- import { Database, DB_TYPE } from "@seip/bluebird-js/core/database.js";
239
-
240
- const connection = new Database(20);
241
-
242
- const user = await connection.query("SELECT * FROM users WHERE id = ?", [1], "return_row");
243
- const stats = await connection.query("SELECT COUNT(*) as cnt FROM logs", [], { cache: 60 });
244
-
245
- await connection.transaction(async (tx) => {
246
- const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
247
- await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
248
- });
249
- ```
250
-
251
- ## 11. On-Demand Modules & CLI Add
252
-
253
- To keep dependencies lightweight and minimal, optional modules load dynamically on-demand:
254
-
255
- ```bash
256
- npx bluebird-js add upload # Installs multer for file uploads
257
- npx bluebird-js add ws # Installs ws for WebSockets
258
- npx bluebird-js add redis # Installs redis for distributed caching
259
- npx bluebird-js add sqlite # Installs better-sqlite3 (fallback for older environments)
260
- npx bluebird-js add mysql # Installs mysql2
261
- npx bluebird-js add postgres # Installs pg
262
- npx bluebird-js add bcrypt # Installs bcrypt
263
- npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
264
- npx bluebird-js add helmet # Installs helmet
265
- npx bluebird-js add ejs # Installs ejs
266
- npx bluebird-js add react-islands # Installs react, react-dom, vite & scaffolds island runtime
267
- ```
268
-
269
- ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
270
-
271
- Bluebird includes native zero-dependency security headers enabled by default (`X-Content-Type-Options: nosniff`, `X-XSS-Protection: 0`, `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy`).
272
-
273
- ### Native Rate Limiting (`core/ratelimit.js`)
274
-
275
- Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers):
276
-
277
- ```javascript
278
- import App from "@seip/bluebird-js/core/app.js";
279
-
280
- const app = new App({
281
- routes: [routerWeb, routerApi],
282
- rateLimit: { max: 120, windowMs: 60000 },
283
- });
284
-
285
- routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req, res) => {
286
- res.ok({ authenticated: true });
287
- });
288
- ```
289
-
290
- ### Automatic SEO Sitemap & Robots (`core/seo.js`)
291
-
292
- When a `Router` is created with `{ seo: true }`, all static `GET` routes are automatically registered and exposed at `/sitemap.xml` and `/robots.txt` by `App`.
293
-
294
- ### Helmet Integration
295
-
296
- Helmet can be applied per router when installed (`npx bluebird-js add helmet`):
297
-
298
- ```javascript
299
- import App from "@seip/bluebird-js/core/app.js";
300
-
301
- const apiRouter = new Router("/api");
302
- apiRouter.use(App.helmet());
303
- ```
304
-
305
- ## 13. Production Deployment & Electron Desktop Mode
306
-
307
- ### PM2 & Nginx Reverse Proxy
308
-
309
- Production deployments run directly via `npm start` or PM2 cluster mode:
310
-
311
- ```bash
312
- npx bluebird-js make:ecosystem # Generates ecosystem.config.cjs
313
- npx bluebird-js make:ecosystem --start # Generates and starts immediately in PM2
314
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx config with upstream keepalive & static try_files
315
- ```
316
-
317
- For complete deployment details including Nginx reverse proxy configuration and optional standalone Docker snippet, consult [production.md](production.md).
318
-
319
- ### Electron & Desktop Mode (`desktop: true`)
320
-
321
- Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
322
-
323
- - **Base Directory Resolution (`appPath`)**: Accepts `appPath: electronApp.getAppPath()` (or `Config.setAppDir()`) to ensure views (`app/views/`) and static assets (`public/`) resolve accurately regardless of shortcut launch locations (`process.cwd()`).
324
- - **Writable User Data (`userDataPath`)**: Automatically routes SQLite database files, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`electronApp.getPath("userData")`), copying bundled initial SQLite template databases from `appPath`, `process.resourcesPath`, or `.asar.unpacked` on first launch.
325
- - **Dynamic Port & LAN / QR Access**:
326
- - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
327
- - When `{ allowLan: true }` is enabled, binds to `0.0.0.0` and returns `{ server, port, url, lanUrl, lanIp }` ready for mobile QR code access on local WiFi.
328
- - **Uploads & Static Serving**:
329
- - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
330
- - **Clean Shutdown & WAL Checkpoint**:
331
- - Invoking `await app.close()` (e.g. in Electron `app.on("before-quit")`) automatically checkpoints SQLite WAL (`PRAGMA wal_checkpoint(TRUNCATE)`), closes open database handles via `Database.closeAll()`, and frees Windows file locks cleanly.
332
- - **Packaging with electron-builder**:
333
- - Recommended `electron-builder` configuration in `package.json`:
334
- ```json
335
- "build": {
336
- "asar": true,
337
- "asarUnpack": ["app/views/**/*", "database/**/*"]
338
- }
339
- ```
340
-
341
- ```javascript
342
- import App from "@seip/bluebird-js/core/app.js";
343
- import { app as electronApp, BrowserWindow } from "electron";
344
- import routerApi from "./app/routes/api.js";
345
- import routerWeb from "./app/routes/web.js";
346
-
347
- const app = new App({
348
- desktop: true,
349
- appPath: electronApp.getAppPath(),
350
- userDataPath: electronApp.getPath("userData"),
351
- routes: [routerWeb, routerApi],
352
- });
353
-
354
- electronApp.whenReady().then(async () => {
355
- const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
356
- const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
357
- mainWindow.loadURL(url);
358
-
359
- electronApp.on("before-quit", async () => {
360
- await app.close();
361
- });
362
- });
363
- ```
364
-
365
- ## 14. Developer Tooling CLI
366
-
367
- ```bash
368
- npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
369
- npx bluebird-js make:model <Name> # BaseModel scaffolding
370
- npx bluebird-js make:route <name> # REST route scaffolding
371
- npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
372
- npx bluebird-js make:view <name> # HTML or EJS template scaffolding
373
- npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
374
- npx bluebird-js make:migration --model <Model> # Auto DDL migration for specific Model schema
375
- npx bluebird-js migrate [--yes] # Executes pending migrations with auto-detection
376
- npx bluebird-js migrate:status # Displays applied batches
377
- npx bluebird-js migrate:rollback # Reverts latest batch
378
- npx bluebird-js make:seed <name> # Database seed file creation
379
- npx bluebird-js seed # Executes database seeds
380
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
381
- npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
382
- ```
383
-
384
- ## 15. Background Jobs & Queue (Queue)
385
-
386
- Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
387
-
388
- ```javascript
389
- import Queue from "@seip/bluebird-js/core/queue.js";
390
-
391
- Queue.process("sendWelcomeEmail", async (payload) => {
392
- console.log(`Sending email to ${payload.email}...`);
393
- });
394
-
395
- await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
396
- await Queue.work();
397
- ```
398
-
399
- ## 16. React JSX SSR, Auto-Routes, Client Islands & View Transitions
400
-
401
- Bluebird provides a modern, zero-build view architecture uniting database-driven server-rendered HTML with native React JSX (`.jsx`) and JavaScript (`.js`) views, declarative file-based Auto-Routes, shared layouts, Tailwind CSS v4, `<Client>` / `<Island>` components with anti-CLS skeletons, and instant View Transitions SPA navigation:
402
-
403
- - **Built-In Tailwind CSS v4 & Inter Font**:
404
- - `public/js/tailwind.js` and Google Fonts `Inter` are loaded by default in the main layout (`app/views/layouts/main/view.jsx`).
405
- - Zero build steps, zero transpilation, pure modern utilities out of the box with dark mode synchronization.
406
- - **Native Zero-Build React JSX SSR (`app/views/*.jsx`)**:
407
- - Powered by `core/jsx.js` and Node 22.18+ native `module.registerHooks()`. Compiles `.jsx` modules in memory with **zero temporary files on disk** and **zero external npm dependencies** required.
408
- - Supports `async` Server Components, Fragments (`<>...</>`), spread props, `style` objects, automatic XSS escaping, and mixed `html\`...\`` templates.
409
- - **Declarative Auto-Routes from Views (`ViewLoader.discoverRoutes()` / `Render.autoRoutes()`)**:
410
- - Automatically scans `app/views/` (ignoring `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) and mounts GET routes when `App` starts.
411
- - Export route settings directly from any view file:
412
- - `export const route = "/login"` (or inferred automatically from filename; `false` disables auto-routing)
413
- - `export const cache = 300` (applies `Render.cache(300)` automatically)
414
- - `export const layout = "main"` (uses `app/views/layouts/main/view.jsx`)
415
- - `export const middlewares = [Auth.protect({ redirect: "/login" })]`
416
- - `export const seo = true` (registers route in `/sitemap.xml` and `/robots.txt`)
417
- - Disable auto-discovery if desired via `new App({ noAutoDiscoverRoutes: true })`.
418
- - **Client Components & Anti-Accordion Skeletons (`<Client>` / `<Island>`)**:
419
- - Everything renders as pure SSR by default (0 KB client JS).
420
- - For client-side interactivity (`useEffect`, `useState`, or native DOM logic), use `<Client>` or `<Island>` from `@seip/bluebird-js/core/jsx.js`.
421
- - Pass `skeleton={...}`, `minHeight`, and `minWidth` to lock container dimensions before hydration and prevent layout shift ("accordion" effect), plus `persistent={true}` to preserve state across View Transitions.
422
- - Supports zero-build declarative client components with standard hooks (`useState`, `useEffect`, `useRef`, `html` tagged templates) via `component={LiveCounter}` (`LiveCounter.jsx`), inline functions via `client={(el, props) => { ... }}`, and full React Islands (`npx bluebird-js add react-islands`).
423
- - **Native Server Actions (`core/actions.js` & `export const actions = { ... }`)**:
424
- - Next.js-style Server Actions executed on the server with automatic CSRF verification (`_csrf` cookie + `X-CSRF-Token` header), payload byte limit guards (`maxBytes`, default 64KB), prototype-pollution & depth/key sanitization (`sanitizeActionPayload`), and optional `Validator` schema checks.
425
- - Triggered from the client via `await Bluebird.action("syncCount", { count: 10 })` or declarative `data-action="syncCount"` attributes on buttons/forms.
426
- - **Shared Layouts (`app/views/layouts/main/view.jsx`)**:
427
- - Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, children, head, ctx, data }`.
428
- - When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
429
- - Elements with `data-bb-outlet="true"` enable layout outlet swapping so navigation between pages sharing the same layout preserves header, menus, and media playback uninterrupted.
430
- - **Comprehensive Built-In Client UI Kit (`public/js/bluebird-client.js`)**:
431
- - `toast({ title, description, type, position, duration })`
432
- - `snackbar({ message, type, duration })`
433
- - `bluebird('drawer', { id, action: 'open'|'close'|'toggle' })`
434
- - `new ResponsiveDataTable(containerId, options)`
435
- - `bluebird('command')` palette (`Ctrl+K`), `bluebird('tab')`, `bluebird('popover')`, `bluebird('carousel')`
436
- - Declarative forms via `form[data-bb-form="true"]`: submits via `fetch`, auto-injects CSRF tokens, and follows `X-Bluebird-Redirect`.
437
- - Native `document.startViewTransition()` page navigation with preserved elements via `data-persist="true"`.
438
-
439
- ```jsx
440
- // app/views/dashboard.jsx
441
- import Auth from "@seip/bluebird-js/core/auth.js";
442
- import Actions from "@seip/bluebird-js/core/actions.js";
443
- import { Client } from "@seip/bluebird-js/core/jsx.js";
444
- import Header from "./components/Header.jsx";
445
- import LiveCounter from "./components/LiveCounter.js";
446
-
447
- export const route = "/dashboard";
448
- export const layout = "main";
449
- export const middlewares = [Auth.protect({ redirect: "/login" })];
450
- export const seo = false;
451
- export const head = (data) => ({ title: `Dashboard — ${data.user?.name}` });
452
-
453
- export const actions = {
454
- syncCount: Actions.define(
455
- {
456
- maxBytes: "16kb",
457
- schema: { count: { required: true, number: true } },
458
- },
459
- async ({ body, user }) => {
460
- return { syncedCount: Number(body.count), updatedBy: user?.email };
461
- }
462
- ),
463
- };
464
-
465
- export default async function DashboardView({ user, syncedCount = 7 }) {
466
- return (
467
- <>
468
- <Header title="Dashboard" user={user} count={syncedCount} />
469
- <Client
470
- component={LiveCounter}
471
- props={{ initial: syncedCount }}
472
- persistent={true}
473
- minHeight={56}
474
- skeleton={<div className="h-14 animate-pulse bg-slate-900 rounded-xl" />}
475
- />
476
- </>
477
- );
478
- }
479
- ```
480
-
481
- ## 17. AI Development Guidelines
482
-
483
- 1. **Assets & Views**: Static assets in `public/`. HTML views, layouts (`app/views/layouts/`), and partials (`app/views/partials/`) in `app/views/` served via `Render.view()`, `Render.send()`, or `Render.partial()`.
484
- 2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
485
- 3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
486
- 4. **All documentation in English**.
1
+ # Bluebird.js Framework - AI Agent Guide
2
+
3
+ This document serves as the primary manual for any AI Agent interacting with the codebase. It details the architecture of Bluebird.js (`@seip/bluebird-js`), its internal modules, and how features should be written or modified.
4
+
5
+ ## 1. Core Architecture
6
+
7
+ Bluebird.js is a performance-first web and API framework built on **Express** (Node.js 22.18+). It provides pure modern JavaScript ESM execution, JWT auth, HTML rendering with multi-level caching, BaseModel, schema validation, database access, and queue processing out of the box.
8
+
9
+ - **Entrypoint (`index.js`)**: Located at the project root. Initializes the server using `App` from `core/app.js` and registers the routes.
10
+ - **Application (`app/`)**: Application code — `app/routes/` (API + web), `app/models/` (BaseModels), `app/views/` (HTML templates), `app/jobs/` (background workers).
11
+ - **Public assets (`public/`)**: Static files only (CSS, JS, images, fonts). Served directly by Nginx or Express fallback.
12
+ - **Core (`core/`)**: The framework core. Contains `Router`, `Render`, `Validator`, `Auth`, `Cache`, `Redis`, `Database`, `Model`, `Csrf`, `Hash`, etc. **DO NOT MODIFY** the core unless explicitly requested.
13
+
14
+ ## 2. Modern JavaScript Standard (ESM)
15
+
16
+ Bluebird.js standardizes on pure modern JavaScript (Node.js 22.18+ ESM) with zero build steps or transpilation pipelines required:
17
+
18
+ - **Root Entrypoint (`index.js`)**: Run in development with `node --watch --env-file=.env index.js`.
19
+ - **Production Entrypoint (`index.js`)**: Run with `node --env-file=.env index.js` or via PM2 cluster.
20
+ - **Initialization**: `npx bluebird-js` scaffolds a new project directly with `index.js` at the root.
21
+ - **IDE Intellisense**: Powered by `core/index.d.ts` and `jsconfig.json`.
22
+
23
+ ```javascript
24
+ import App from "@seip/bluebird-js/core/app.js";
25
+ import routerApi from "./app/routes/api.js";
26
+ import routerWeb from "./app/routes/web.js";
27
+
28
+ const app = new App({
29
+ routes: [routerWeb, routerApi],
30
+ port: process.env.PORT || 3000,
31
+ });
32
+
33
+ app.run();
34
+ ```
35
+
36
+ ## 3. Routing (Router)
37
+
38
+ Do not use Express' native router directly. Always use Bluebird's `Router` wrapper.
39
+
40
+ ```javascript
41
+ import Router from "@seip/bluebird-js/core/router.js";
42
+
43
+ const routerApi = new Router("/api");
44
+
45
+ routerApi.get("/users", (req, res) => {
46
+ res.json({ users: [] });
47
+ });
48
+
49
+ export default routerApi;
50
+ ```
51
+
52
+ When created with `{ seo: true }`, all GET routes registered on that router are tracked for search engine indexing.
53
+
54
+ ## 4. Request Validation (Validator)
55
+
56
+ Incoming request data is validated using `core/validate.js`, which automatically returns HTTP 400 JSON responses on error. The validator inspects request payloads without destructively mutating raw data.
57
+
58
+ ```javascript
59
+ import Validator from "@seip/bluebird-js/core/validate.js";
60
+
61
+ const userSchema = {
62
+ email: { required: true, email: true },
63
+ password: { required: true, min: 8 },
64
+ bio: { required: false },
65
+ };
66
+
67
+ const validateUser = new Validator(userSchema, "en");
68
+
69
+ routerApi.post("/users", validateUser.middleware(), (req, res) => {
70
+ res.json({ success: true });
71
+ });
72
+ ```
73
+
74
+ ## 5. Lightweight BaseModel (Model)
75
+
76
+ > **Important Architecture Note:**
77
+ > Bluebird's `BaseModel` (`core/model.js`) is designed as a lightweight, zero-dependency static facade for high performance, simple queries, soft deletes, and migrations.
78
+ > **For complex multi-tier enterprise ORM mapping, Prisma is recommended.**
79
+
80
+ ### Defining a Model
81
+
82
+ Create models inside `app/models/`:
83
+
84
+ ```javascript
85
+ import Model from "@seip/bluebird-js/core/model.js";
86
+
87
+ export default class User extends Model {
88
+ static table = "users";
89
+ static primaryKey = "id";
90
+ static timestamps = true;
91
+ static softDelete = true;
92
+
93
+ static schema = {
94
+ id: { type: "int", primary: true, auto: true },
95
+ name: { type: "string", length: 150, required: true },
96
+ email: { type: "string", length: 150, unique: true, required: true, email: true },
97
+ password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
98
+ role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
99
+ };
100
+ }
101
+ ```
102
+
103
+ ### CRUD Shortcuts & Query Facades
104
+
105
+ Every Model exposes direct shortcuts to database queries, transactions, and mutations:
106
+
107
+ ```javascript
108
+ const total = await User.query("SELECT COUNT(*) as count FROM users", [], "return_row");
109
+ await User.transaction(async (tx) => {
110
+ await tx.query("UPDATE users SET role = ? WHERE id = ?", ["admin", 1]);
111
+ });
112
+
113
+ const userId = await User.create({ name: "Alice", email: "alice@example.com", password: "secretPassword" });
114
+
115
+ const user = await User.find(1, { cache: 60 });
116
+ const userWithPosts = await User.find(1, { oneMany: Post });
117
+ const postWithAuthor = await Post.find(10, { belongsTo: User });
118
+
119
+ const page = await User.paginate({ where: { role: "user" }, page: 1, limit: 10 });
120
+ await User.update(userId, { name: "Alice Smith" });
121
+
122
+ const totalUsers = await User.count({ role: "user" });
123
+ const exists = await User.exists({ email: "alice@example.com" });
124
+
125
+ const matching = await User.all({
126
+ where: {
127
+ id: [1, 2, 3],
128
+ role: { $ne: "banned" },
129
+ views: { $gt: 100 },
130
+ },
131
+ });
132
+
133
+ const userRecord = await User.firstOrCreate({ email: "john@example.com" }, { name: "John Doe" });
134
+ const updatedRecord = await User.updateOrCreate({ email: "john@example.com" }, { name: "Johnathan" });
135
+
136
+ await User.delete(userId);
137
+ await User.delete(userId, { force: true });
138
+ await User.delete(userId, { cascade: [Post] });
139
+ await User.restore(userId);
140
+ ```
141
+
142
+ ## 6. CSRF Protection (Csrf)
143
+
144
+ Bluebird provides native, zero-dependency HMAC-signed CSRF protection (`core/csrf.js`):
145
+
146
+ ```javascript
147
+ import Csrf from "@seip/bluebird-js/core/csrf.js";
148
+
149
+ routerWeb.use(Csrf.middleware());
150
+ ```
151
+
152
+ ## 7. Authentication & Password Hashing (Auth & Hash)
153
+
154
+ ### Password Hashing (Hash)
155
+
156
+ Native password hashing using `node:crypto.scrypt` with random salt and timing-safe comparison (zero external npm dependencies required).
157
+
158
+ ```javascript
159
+ import Hash from "@seip/bluebird-js/core/hash.js";
160
+
161
+ const hash = await Hash.make("mySecretPassword");
162
+ const isValid = await Hash.verify("mySecretPassword", hash);
163
+ ```
164
+
165
+ ### JWT Handling (Auth)
166
+
167
+ Native JWT handling with AES-256-GCM encryption and HMAC-SHA256 signature verification using `node:crypto`.
168
+
169
+ ```javascript
170
+ import Auth from "@seip/bluebird-js/core/auth.js";
171
+
172
+ router.get("/profile", Auth.protect(), (req, res) => {
173
+ res.json({ user: req.user });
174
+ });
175
+
176
+ router.post("/login", async (req, res) => {
177
+ const user = { id: 1, name: "John" };
178
+ await Auth.login(res, user);
179
+ res.ok(user, "Logged in");
180
+ });
181
+
182
+ router.post("/logout", async (req, res) => {
183
+ await Auth.logout(res);
184
+ res.ok(null, "Logged out");
185
+ });
186
+ ```
187
+
188
+ ## 8. HTTP Response Helpers & Health Check
189
+
190
+ Bluebird decorates the Express `res` object with standardized helper methods:
191
+
192
+ ```javascript
193
+ res.ok(data, "Success message");
194
+ res.created(data, "Created successfully");
195
+ res.paginate(items, pagination, "Fetched");
196
+
197
+ res.badRequest("Invalid input", errors);
198
+ res.unauthorized("Authentication required");
199
+ res.forbidden("Access denied");
200
+ res.notFound("Resource not found");
201
+ res.serverError("Internal failure", err);
202
+ ```
203
+
204
+ Every Bluebird application provides a native `/api/health` endpoint returning uptime, timestamp, environment, and memory consumption.
205
+
206
+ ## 9. Performance Caching (Cache & Redis)
207
+
208
+ Caching defaults to fast in-memory LRU storage, ideal for desktop applications and single or dual PM2 instances. Filesystem caching (`driver: "file"`) is available as persistent local fallback, and Redis (`driver: "redis"`) is isolated in `core/redis.js` on-demand for high-traffic environments.
209
+
210
+ ```javascript
211
+ import Cache from "@seip/bluebird-js/core/cache.js";
212
+
213
+ router.get("/stats", Cache.middleware(60), (req, res) => {
214
+ res.ok({ usersCount: 150 });
215
+ });
216
+
217
+ await Cache.set("custom_key", { data: "value" }, 120, { driver: "memory" });
218
+ const cachedData = await Cache.get("custom_key", { driver: "memory" });
219
+
220
+ const stats = await Cache.deduplicate("stats-key", async () => {
221
+ return await calculateHeavyStats();
222
+ });
223
+
224
+ await Cache.delete("custom_key");
225
+ await Cache.clear();
226
+ ```
227
+
228
+ ## 10. Database Module (database.js)
229
+
230
+ Bluebird provides a unified wrapper class (`core/database.js`) supporting **SQLite (native `node:sqlite` in Node 22.18+ with `better-sqlite3` fallback)**, **MySQL (`mysql2/promise`)**, and **PostgreSQL (`pg`)**:
231
+
232
+ - **Native SQLite by Default:** No native C++ compilation or build tools required.
233
+ - **SQLite Concurrency & WAL:** Automatically configures WAL mode, busy timeout, and memory-mapped I/O.
234
+ - **Prepared Statement Caching:** SQLite caches prepared statement ASTs automatically.
235
+ - **Query Caching:** Supports `{ cache: 60 }` across memory, file, and redis backends.
236
+
237
+ ```javascript
238
+ import { Database, DB_TYPE } from "@seip/bluebird-js/core/database.js";
239
+
240
+ const connection = new Database(20);
241
+
242
+ const user = await connection.query("SELECT * FROM users WHERE id = ?", [1], "return_row");
243
+ const stats = await connection.query("SELECT COUNT(*) as cnt FROM logs", [], { cache: 60 });
244
+
245
+ await connection.transaction(async (tx) => {
246
+ const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
247
+ await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
248
+ });
249
+ ```
250
+
251
+ ## 11. On-Demand Modules & CLI Add
252
+
253
+ To keep dependencies lightweight and minimal, optional modules load dynamically on-demand:
254
+
255
+ ```bash
256
+ npx bluebird-js add upload # Installs multer for file uploads
257
+ npx bluebird-js add ws # Installs ws for WebSockets
258
+ npx bluebird-js add redis # Installs redis for distributed caching
259
+ npx bluebird-js add sqlite # Installs better-sqlite3 (fallback for older environments)
260
+ npx bluebird-js add mysql # Installs mysql2
261
+ npx bluebird-js add postgres # Installs pg
262
+ npx bluebird-js add bcrypt # Installs bcrypt
263
+ npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
264
+ npx bluebird-js add helmet # Installs helmet
265
+ npx bluebird-js add ejs # Installs ejs
266
+ npx bluebird-js add react-islands # Installs react, react-dom, vite & scaffolds island runtime
267
+ ```
268
+
269
+ ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
270
+
271
+ Bluebird includes native zero-dependency security headers enabled by default (`X-Content-Type-Options: nosniff`, `X-XSS-Protection: 0`, `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy`).
272
+
273
+ ### Native Rate Limiting (`core/ratelimit.js`)
274
+
275
+ Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers):
276
+
277
+ ```javascript
278
+ import App from "@seip/bluebird-js/core/app.js";
279
+
280
+ const app = new App({
281
+ routes: [routerWeb, routerApi],
282
+ rateLimit: { max: 120, windowMs: 60000 },
283
+ });
284
+
285
+ routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req, res) => {
286
+ res.ok({ authenticated: true });
287
+ });
288
+ ```
289
+
290
+ ### Automatic SEO Sitemap & Robots (`core/seo.js`)
291
+
292
+ When a `Router` is created with `{ seo: true }`, all static `GET` routes are automatically registered and exposed at `/sitemap.xml` and `/robots.txt` by `App`.
293
+
294
+ ### Helmet Integration
295
+
296
+ Helmet can be applied per router when installed (`npx bluebird-js add helmet`):
297
+
298
+ ```javascript
299
+ import App from "@seip/bluebird-js/core/app.js";
300
+
301
+ const apiRouter = new Router("/api");
302
+ apiRouter.use(App.helmet());
303
+ ```
304
+
305
+ ## 13. Production Deployment & Electron Desktop Mode
306
+
307
+ ### PM2 & Nginx Reverse Proxy
308
+
309
+ Production deployments run directly via `npm start` or PM2 cluster mode:
310
+
311
+ ```bash
312
+ npx bluebird-js make:ecosystem # Generates ecosystem.config.cjs
313
+ npx bluebird-js make:ecosystem --start # Generates and starts immediately in PM2
314
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx config with upstream keepalive & static try_files
315
+ ```
316
+
317
+ For complete deployment details including Nginx reverse proxy configuration and optional standalone Docker snippet, consult [production.md](production.md).
318
+
319
+ ### Electron & Desktop Mode (`desktop: true`)
320
+
321
+ Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
322
+
323
+ - **Base Directory Resolution (`appPath`)**: Accepts `appPath: electronApp.getAppPath()` (or `Config.setAppDir()`) to ensure views (`app/views/`) and static assets (`public/`) resolve accurately regardless of shortcut launch locations (`process.cwd()`).
324
+ - **Writable User Data (`userDataPath`)**: Automatically routes SQLite database files, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`electronApp.getPath("userData")`), copying bundled initial SQLite template databases from `appPath`, `process.resourcesPath`, or `.asar.unpacked` on first launch.
325
+ - **Dynamic Port & LAN / QR Access**:
326
+ - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
327
+ - When `{ allowLan: true }` is enabled, binds to `0.0.0.0` and returns `{ server, port, url, lanUrl, lanIp }` ready for mobile QR code access on local WiFi.
328
+ - **Uploads & Static Serving**:
329
+ - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
330
+ - **Clean Shutdown & WAL Checkpoint**:
331
+ - Invoking `await app.close()` (e.g. in Electron `app.on("before-quit")`) automatically checkpoints SQLite WAL (`PRAGMA wal_checkpoint(TRUNCATE)`), closes open database handles via `Database.closeAll()`, and frees Windows file locks cleanly.
332
+ - **Packaging with electron-builder**:
333
+ - Recommended `electron-builder` configuration in `package.json`:
334
+ ```json
335
+ "build": {
336
+ "asar": true,
337
+ "asarUnpack": ["app/views/**/*", "database/**/*"]
338
+ }
339
+ ```
340
+
341
+ ```javascript
342
+ import App from "@seip/bluebird-js/core/app.js";
343
+ import { app as electronApp, BrowserWindow } from "electron";
344
+ import routerApi from "./app/routes/api.js";
345
+ import routerWeb from "./app/routes/web.js";
346
+
347
+ const app = new App({
348
+ desktop: true,
349
+ appPath: electronApp.getAppPath(),
350
+ userDataPath: electronApp.getPath("userData"),
351
+ routes: [routerWeb, routerApi],
352
+ });
353
+
354
+ electronApp.whenReady().then(async () => {
355
+ const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
356
+ const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
357
+ mainWindow.loadURL(url);
358
+
359
+ electronApp.on("before-quit", async () => {
360
+ await app.close();
361
+ });
362
+ });
363
+ ```
364
+
365
+ ## 14. Developer Tooling CLI
366
+
367
+ ```bash
368
+ npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
369
+ npx bluebird-js make:model <Name> # BaseModel scaffolding
370
+ npx bluebird-js make:route <name> # REST route scaffolding
371
+ npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
372
+ npx bluebird-js make:view <name> # HTML or EJS template scaffolding
373
+ npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
374
+ npx bluebird-js make:migration --model <Model> # Auto DDL migration for specific Model schema
375
+ npx bluebird-js migrate [--yes] # Executes pending migrations with auto-detection
376
+ npx bluebird-js migrate:status # Displays applied batches
377
+ npx bluebird-js migrate:rollback # Reverts latest batch
378
+ npx bluebird-js make:seed <name> # Database seed file creation
379
+ npx bluebird-js seed # Executes database seeds
380
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
381
+ npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
382
+ ```
383
+
384
+ ## 15. Background Jobs & Queue (Queue)
385
+
386
+ Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
387
+
388
+ ```javascript
389
+ import Queue from "@seip/bluebird-js/core/queue.js";
390
+
391
+ Queue.process("sendWelcomeEmail", async (payload) => {
392
+ console.log(`Sending email to ${payload.email}...`);
393
+ });
394
+
395
+ await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
396
+ await Queue.work();
397
+ ```
398
+
399
+ ## 16. React JSX SSR, Auto-Routes, Client Islands & View Transitions
400
+
401
+ Bluebird provides a modern, zero-build view architecture uniting database-driven server-rendered HTML with native React JSX (`.jsx`) and JavaScript (`.js`) views, declarative file-based Auto-Routes, shared layouts, Tailwind CSS v4, `<Client>` / `<Island>` components with anti-CLS skeletons, and instant View Transitions SPA navigation:
402
+
403
+ - **Built-In Tailwind CSS v4 & Inter Font**:
404
+ - `public/js/tailwind.js` and Google Fonts `Inter` are loaded by default in the main layout (`app/views/layouts/main/view.jsx`).
405
+ - Zero build steps, zero transpilation, pure modern utilities out of the box with dark mode synchronization.
406
+ - **Native Zero-Build React JSX & TSX SSR (`app/views/*.jsx`, `*.tsx`):**
407
+ - Powered by `core/jsx.js` and Node 22.18+ native `module.registerHooks()`. Compiles `.jsx` and TypeScript `.tsx` modules in memory with **zero temporary files on disk** and **zero external npm dependencies** required.
408
+ - Automatically strips TypeScript type annotations from `.tsx` and `.ts` components while preserving line mappings.
409
+ - Supports `async` Server Components, Fragments (`<>...</>`), spread props, `style` objects, automatic XSS escaping, and mixed `html\`...\`` templates.
410
+ - **`<ErrorBoundary>` Component**:
411
+ - Catches subtree runtime exceptions during SSR and renders a fallback UI without failing the entire page request: `<ErrorBoundary fallback={(err) => <ErrorBox message={err.message} />}>...</ErrorBoundary>`.
412
+ - **Dynamic Head Manager & Tag Hoisting (`<Head>`, `<Title>`, `<Meta>`):**
413
+ - Hoist `<title>` and `<meta>` tags from nested components directly into the document `<head>`: `<Head><Title>Dashboard</Title><Meta name="robots" content="noindex" /></Head>`.
414
+ - **Streaming SSR with `<Suspense>` & Smart Caching (`Render.stream()`):**
415
+ - Emits chunked transfer encoding responses with immediate shell and `<Suspense fallback={<Skeleton />}>` placeholders.
416
+ - Out-of-order chunks stream as async data resolves, with tiny inline scripts swapping templates seamlessly.
417
+ - Respects cache TTL (`Render.cache(300)` / `export const cache = 300`): subsequent requests are served as **instant Cache HITs** without streaming overhead, while streaming cache misses automatically caches the assembled final HTML.
418
+ - **Declarative Auto-Routes from Views (`ViewLoader.discoverRoutes()` / `Render.autoRoutes()`)**:
419
+ - Automatically scans `app/views/` (ignoring `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) and mounts GET routes when `App` starts.
420
+ - Export route settings directly from any view file:
421
+ - `export const route = "/login"` (or inferred automatically from filename; `false` disables auto-routing)
422
+ - `export const cache = 300` (applies `Render.cache(300)` automatically)
423
+ - `export const layout = "main"` (uses `app/views/layouts/main/view.jsx`)
424
+ - `export const middlewares = [Auth.protect({ redirect: "/login" })]`
425
+ - `export const seo = true` (registers route in `/sitemap.xml` and `/robots.txt`)
426
+ - Disable auto-discovery if desired via `new App({ noAutoDiscoverRoutes: true })`.
427
+ - **Client Components & Anti-Accordion Skeletons (`<Client>` / `<Island>`)**:
428
+ - Everything renders as pure SSR by default (0 KB client JS).
429
+ - For client-side interactivity (`useEffect`, `useState`, or native DOM logic), use `<Client>` or `<Island>` from `@seip/bluebird-js/core/jsx.js`.
430
+ - Pass `skeleton={...}`, `minHeight`, and `minWidth` to lock container dimensions before hydration and prevent layout shift ("accordion" effect), plus `persistent={true}` to preserve state across View Transitions.
431
+ - Supports zero-build declarative client components with standard hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `useRef`, `html` tagged templates) via `component={LiveCounter}` (`LiveCounter.jsx`), inline functions via `client={(el, props) => { ... }}`, and full React Islands (`npx bluebird-js add react-islands`).
432
+ - **Native Server Actions (`core/actions.js` & `export const actions = { ... }`)**:
433
+ - Next.js-style Server Actions executed on the server with automatic CSRF verification (`_csrf` cookie + `X-CSRF-Token` header), payload byte limit guards (`maxBytes`, default 64KB), prototype-pollution & depth/key sanitization (`sanitizeActionPayload`), and optional `Validator` schema checks.
434
+ - Triggered from the client via `await Bluebird.action("syncCount", { count: 10 })`, `useAction("syncCount")` in client components, or declarative `data-action="syncCount"` attributes on buttons/forms with automatic `disabled`, `aria-busy="true"`, and `is-pending` states.
435
+ - **Shared Layouts (`app/views/layouts/main/view.jsx`)**:
436
+ - Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, children, head, ctx, data }`.
437
+ - When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
438
+ - Elements with `data-bb-outlet="true"` enable layout outlet swapping so navigation between pages sharing the same layout preserves header, menus, and media playback uninterrupted.
439
+ - **Comprehensive Built-In Client UI Kit (`public/js/bluebird-client.js`)**:
440
+ - `toast({ title, description, type, position, duration })`
441
+ - `snackbar({ message, type, duration })`
442
+ - `bluebird('drawer', { id, action: 'open'|'close'|'toggle' })`
443
+ - `new ResponsiveDataTable(containerId, options)`
444
+ - `bluebird('command')` palette (`Ctrl+K`), `bluebird('tab')`, `bluebird('popover')`, `bluebird('carousel')`
445
+ - Declarative forms via `form[data-bb-form="true"]`: submits via `fetch`, auto-injects CSRF tokens, and follows `X-Bluebird-Redirect`.
446
+ - Native `document.startViewTransition()` page navigation with preserved elements via `data-persist="true"`.
447
+
448
+ ```jsx
449
+ // app/views/dashboard.jsx
450
+ import Auth from "@seip/bluebird-js/core/auth.js";
451
+ import Actions from "@seip/bluebird-js/core/actions.js";
452
+ import { Client } from "@seip/bluebird-js/core/jsx.js";
453
+ import Header from "./components/Header.jsx";
454
+ import LiveCounter from "./components/LiveCounter.js";
455
+
456
+ export const route = "/dashboard";
457
+ export const layout = "main";
458
+ export const middlewares = [Auth.protect({ redirect: "/login" })];
459
+ export const seo = false;
460
+ export const head = (data) => ({ title: `Dashboard — ${data.user?.name}` });
461
+
462
+ export const actions = {
463
+ syncCount: Actions.define(
464
+ {
465
+ maxBytes: "16kb",
466
+ schema: { count: { required: true, number: true } },
467
+ },
468
+ async ({ body, user }) => {
469
+ return { syncedCount: Number(body.count), updatedBy: user?.email };
470
+ }
471
+ ),
472
+ };
473
+
474
+ export default async function DashboardView({ user, syncedCount = 7 }) {
475
+ return (
476
+ <>
477
+ <Header title="Dashboard" user={user} count={syncedCount} />
478
+ <Client
479
+ component={LiveCounter}
480
+ props={{ initial: syncedCount }}
481
+ persistent={true}
482
+ minHeight={56}
483
+ skeleton={<div className="h-14 animate-pulse bg-slate-900 rounded-xl" />}
484
+ />
485
+ </>
486
+ );
487
+ }
488
+ ```
489
+
490
+ ## 17. AI Development Guidelines
491
+
492
+ 1. **Assets & Views**: Static assets in `public/`. HTML views, layouts (`app/views/layouts/`), and partials (`app/views/partials/`) in `app/views/` served via `Render.view()`, `Render.send()`, or `Render.partial()`.
493
+ 2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
494
+ 3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
495
+ 4. **All documentation in English**.