@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/README.md CHANGED
@@ -1,425 +1,528 @@
1
- # Bluebird.js Framework
2
-
3
- **Performance-first Node.js API and web framework with native JavaScript ESM, built-in Tailwind CSS, Inter fonts, declarative UI components, JWT auth, BaseModel, smart migrations, and multi-level caching.**
4
-
5
- [![npm version](https://img.shields.io/npm/v/@seip/bluebird-js.svg)](https://www.npmjs.com/package/@seip/bluebird-js)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
- [![Node.js Version](https://img.shields.io/badge/node-%3E%3D22.18.0-brightgreen.svg)](https://nodejs.org)
8
-
9
- ---
10
-
11
- ## Introduction
12
-
13
- Bluebird.js (`@seip/bluebird-js`) is a high-performance web and API framework built on Express (Node.js 22.18+). It provides native modern JavaScript ESM execution, built-in Tailwind CSS v4 runtime and Google Fonts (`Inter`), zero-build SSR with React/Next.js-style component tags, multi-driver caching (in-memory LRU by default with filesystem and Redis support), AES-256-GCM encrypted JWT authentication, BaseModel schema definitions with smart migrations, CSRF protection, background queues, and PM2 production clustering into a cohesive developer experience.
14
-
15
- ### Key Highlights
16
-
17
- - **Native Zero-Build React JSX SSR (`app/views/*.jsx`):** Compiles `.jsx` modules in memory via Node 22.18+ `module.registerHooks()` with zero temporary disk files and zero build steps.
18
- - **Declarative Auto-Routes from Views:** Export `const route`, `const cache`, `const middlewares`, `const layout`, and `const seo` directly from `app/views/*.jsx` to mount cached, protected web routes automatically (`noAutoDiscoverRoutes: true` in `new App()` to disable).
19
- - **Client Islands with Anti-Accordion Skeletons (`<Client>` / `<Island>`):** SSR by default (0 KB client JS), with `<Client>` boundaries that lock dimensions (`minHeight`, `minWidth`) and render a `skeleton` to prevent layout shift (CLS).
20
- - **Built-In Tailwind CSS & Inter Font:** Includes the official standalone Tailwind CSS runtime (`/js/tailwind.js`) and Google Fonts `Inter` by default with zero configuration or compilers.
21
- - **Smart Automatic Migrations:** CLI detects schema changes across `app/models/`, resolves foreign key dependencies topologically, generates consolidated `CREATE TABLE` / `ALTER TABLE ADD COLUMN` SQL files, and executes them with interactive terminal prompts.
22
- - **Lightweight BaseModel:** Static facade providing readable schemas, CRUD shortcuts, query operators (`IN`, `$gt`, `$like`), `count()`, `exists()`, `firstOrCreate()`, `updateOrCreate()`, smart relations without N+1 queries, soft deletes, and automatic query cache invalidation.
23
- - **Native SQLite & Desktop Mode (Electron/Tauri):** Uses Node's built-in `node:sqlite` driver with zero compilation overhead, plus first-class `desktop: true` mode (`app.runDesktop()`) for read-only `.asar` bundles.
24
- - **Comprehensive Client UI Kit:** Built-in `bluebird-client.js` with toasts, snackbars, drawers, command palette (`Ctrl+K`), responsive data tables, tabs, carousels, declarative forms (`data-bb-form`), and View Transitions SPA routing.
25
- - **Decoupled Caching:** High-speed in-memory LRU cache by default, persistent filesystem fallback, and modular Redis support via `core/redis.js`.
26
- - **CSRF, Rate Limiting & Security:** Native HMAC-SHA256 signed CSRF protection, built-in Rate Limiter (`rateLimit` in `App` or `App.rateLimit()`), automatic `/sitemap.xml` & `/robots.txt` generation, and secure HTTP headers.
27
- - **Production Ready:** Built-in PM2 clustering CLI (`npx bluebird-js make:ecosystem`), optimized Nginx generator (`npx bluebird-js nginx:conf`), and native runner (`npm start`).
28
-
29
- ---
30
-
31
- ## Quick Start
32
-
33
- ### 1. Requirements
34
-
35
- - Node.js 22.18.0 or higher
36
- - npm 10+
37
-
38
- ### 2. Installation and Initialization
39
-
40
- ```bash
41
- npm install @seip/bluebird-js
42
- npx bluebird-js
43
- ```
44
-
45
- The interactive CLI configures:
46
- - Project title and port settings
47
- - Database engine: `sqlite` (default, native zero-configuration), `mysql`, `postgres`, or `none`
48
- - Connection credentials and database paths
49
- - Automatic generation of `index.js`, `.env`, `jsconfig.json`, `app/`, and `public/`
50
-
51
- ### 3. Development Server
52
-
53
- ```bash
54
- npm run dev
55
- ```
56
-
57
- The server starts with Node's native file watcher (`--watch`) and loads `.env` automatically via `--env-file=.env`.
58
-
59
- ---
60
-
61
- ## Project Structure
62
-
63
- ```
64
- project/
65
- ├── index.js # Main application entrypoint
66
- ├── app/
67
- │ ├── models/ # BaseModel definitions
68
- │ │ ├── user.js # User model schema & methods
69
- │ │ └── post.js # Post model schema & relations
70
- │ ├── routes/ # Application routes
71
- │ │ ├── api.js # REST API routes
72
- │ │ └── web.js # HTML page routes
73
- │ ├── views/ # React JSX (.jsx) & JavaScript (.js) SSR views
74
- │ │ ├── components/ # Reusable JSX components (e.g. Header.jsx)
75
- │ │ ├── layouts/ # Shared page layouts (e.g. main/view.jsx)
76
- │ │ ├── index.jsx # Public home view (Auto-Route: /)
77
- │ │ ├── about.jsx # About page view (Auto-Route: /about)
78
- │ │ ├── login.jsx # Sign-in page view (Auto-Route: /login)
79
- │ │ └── dashboard.jsx # Protected dashboard view (Auto-Route: /dashboard)
80
- │ └── jobs/ # Background worker job handlers
81
- ├── public/ # Public static assets (CSS, JS, images, fonts)
82
- │ ├── js/
83
- │ │ ├── tailwind.js # Built-in Tailwind CSS runtime
84
- │ │ └── bluebird-client.js # Client UI kit, View Transitions & SPA router
85
- │ └── images/
86
- ├── core/ # Bluebird.js framework core
87
- ├── database/ # SQLite storage and SQL migrations
88
- │ └── migrations/ # Version-controlled SQL migrations
89
- ├── .env # Environment variables
90
- └── package.json
91
- ```
92
-
93
- ---
94
-
95
- ## Core Features & Usage Examples
96
-
97
- ### 1. Application Entrypoint (`index.js`)
98
-
99
- ```javascript
100
- import App from "@seip/bluebird-js/core/app.js";
101
- import routerApi from "./app/routes/api.js";
102
- import routerWeb from "./app/routes/web.js";
103
-
104
- const app = new App({
105
- routes: [routerWeb, routerApi],
106
- port: process.env.PORT || 3000,
107
- rateLimit: { max: 120, windowMs: 60000 },
108
- });
109
-
110
- app.run();
111
- ```
112
-
113
- For **Electron / Desktop** applications:
114
-
115
- ```javascript
116
- const app = new App({
117
- desktop: true,
118
- userDataPath: electronApp.getPath("userData"),
119
- routes: [routerWeb, routerApi],
120
- });
121
-
122
- const { url, lanUrl } = await app.runDesktop({ allowLan: true });
123
- mainWindow.loadURL(url);
124
- ```
125
-
126
- ---
127
-
128
- ### 2. BaseModel & Smart Automatic Migrations (`app/models/`)
129
-
130
- #### Defining a Model (`app/models/user.js`)
131
-
132
- ```javascript
133
- import Model from "@seip/bluebird-js/core/model.js";
134
-
135
- export default class User extends Model {
136
- static table = "users";
137
- static primaryKey = "id";
138
- static timestamps = true;
139
- static softDelete = true;
140
-
141
- static schema = {
142
- id: { type: "int", primary: true, auto: true },
143
- name: { type: "string", length: 150, required: true },
144
- email: { type: "string", length: 150, unique: true, required: true, email: true },
145
- password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
146
- role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
147
- };
148
- }
149
- ```
150
-
151
- #### Foreign Key References (`app/models/post.js`)
152
-
153
- ```javascript
154
- import Model from "@seip/bluebird-js/core/model.js";
155
-
156
- export default class Post extends Model {
157
- static table = "posts";
158
- static schema = {
159
- id: { type: "int", primary: true, auto: true },
160
- title: { type: "string", length: 200, required: true },
161
- content: { type: "text" },
162
- author_id: { type: "int", references: "users.id", onDelete: "cascade" },
163
- };
164
- }
165
- ```
166
-
167
- #### Powerful Query Methods
168
-
169
- ```javascript
170
- const totalUsers = await User.count({ role: "user" });
171
- const userExists = await User.exists({ email: "alice@example.com" });
172
-
173
- const activeUsers = await User.all({
174
- where: {
175
- id: [1, 2, 3],
176
- role: { $ne: "banned" },
177
- views: { $gt: 100 },
178
- },
179
- });
180
-
181
- const user = await User.firstOrCreate(
182
- { email: "john@example.com" },
183
- { name: "John Doe", role: "user" }
184
- );
185
-
186
- const updated = await User.updateOrCreate(
187
- { email: "john@example.com" },
188
- { name: "Johnathan Doe" }
189
- );
190
- ```
191
-
192
- #### Smart Automatic Migrations CLI
193
-
194
- When you create or modify models, simply run:
195
-
196
- ```bash
197
- npx bluebird-js make:migration
198
- ```
199
-
200
- Bluebird inspects your models in `app/models/`, connects to your database, sorts tables by foreign key dependencies topologically, and detects all missing tables and columns (`CREATE TABLE` and `ALTER TABLE ADD COLUMN`). It generates a consolidated SQL migration file and asks:
201
-
202
- ```
203
- [INFO] Detected database schema changes:
204
- + CREATE TABLE: users
205
- + CREATE TABLE: posts
206
- [OK] Migration created: database/migrations/20261022_120000_auto_migration.sql
207
- ? Do you want to execute pending migrations now? (Y/n):
208
- ```
209
-
210
- To run migrations directly without prompts (ideal for CI/CD):
211
- ```bash
212
- npx bluebird-js migrate --yes
213
- ```
214
-
215
- ---
216
-
217
- ### 3. React JSX SSR, Declarative Auto-Routes & `<Client>` Skeletons
218
-
219
- #### Default Tailwind CSS & Inter Typography
220
-
221
- The default layout (`app/views/layouts/main/view.jsx`) comes pre-wired with Google Fonts `Inter` and the standalone Tailwind CSS v4 runtime (`/js/tailwind.js`). You can write pure Tailwind utility classes immediately without running Vite, PostCSS, or Tailwind CLI.
222
-
223
- #### Native `.jsx` Views & Declarative Auto-Routes
224
-
225
- Bluebird compiles `.jsx` files in memory using Node's native module hooks (`core/jsx.js`)—no external bundler or disk temp files required. Even better, any view inside `app/views/` (excluding `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) can export its own route configuration (`route`, `cache`, `middlewares`, `layout`, `seo`) and `App` mounts it automatically on startup (pass `noAutoDiscoverRoutes: true` to `new App()` if you prefer manual registration only):
226
-
227
- ```jsx
228
- // app/views/components/Header.jsx
229
- export default function Header({ title, user, count = 0 }) {
230
- return (
231
- <header className="flex items-center justify-between p-6 border-b border-slate-800">
232
- <div>
233
- <h1 className="text-2xl font-bold text-slate-100">{title}</h1>
234
- <p className="text-sm text-slate-400">Welcome back, {user?.name || "Guest"}</p>
235
- </div>
236
- <span className="px-3 py-1 rounded-full text-xs font-semibold bg-sky-500/10 text-sky-400 border border-sky-500/20">
237
- Notifications: {count}
238
- </span>
239
- </header>
240
- );
241
- }
242
- ```
243
-
244
- ```jsx
245
- // app/views/dashboard.jsx
246
- import Auth from "@seip/bluebird-js/core/auth.js";
247
- import Actions from "@seip/bluebird-js/core/actions.js";
248
- import { Client } from "@seip/bluebird-js/core/jsx.js";
249
- import Header from "./components/Header.jsx";
250
- import LiveCounter from "./components/LiveCounter.js";
251
-
252
- export const route = "/dashboard";
253
- export const layout = "main";
254
- export const middlewares = [Auth.protect({ redirect: "/login" })];
255
- export const seo = false;
256
- export const head = (data) => ({ title: `Dashboard — ${data.user?.name || "Member"}` });
257
-
258
- // Server Actions: automatic CSRF, 16KB maxBytes guard, prototype pollution filter & Validator schema
259
- export const actions = {
260
- syncCount: Actions.define(
261
- {
262
- maxBytes: "16kb",
263
- schema: { count: { required: true, number: true } },
264
- },
265
- async ({ body, user }) => {
266
- return { syncedCount: Number(body.count), updatedBy: user?.email };
267
- }
268
- ),
269
- };
270
-
271
- export default async function DashboardView({ user, syncedCount = 7 }) {
272
- return (
273
- <>
274
- <Header title="Protected Dashboard" user={user} count={syncedCount} />
275
-
276
- <div className="space-y-6 mt-6">
277
- {/* Reusable imported Client component with persistent state & anti-CLS skeleton */}
278
- <Client
279
- component={LiveCounter}
280
- props={{ initial: syncedCount }}
281
- persistent={true}
282
- minHeight={56}
283
- skeleton={
284
- <div className="h-14 rounded-xl bg-slate-900 animate-pulse flex items-center px-4 text-xs text-slate-400">
285
- Loading interactive widget...
286
- </div>
287
- }
288
- />
289
- </div>
290
- </>
291
- );
292
- }
293
- ```
294
-
295
- ---
296
-
297
- ### 4. Built-in Client UI Kit (`public/js/bluebird-client.js`)
298
-
299
- Bluebird includes a lightweight, dependency-free client UI toolkit with Tailwind CSS styles built right into `public/js/bluebird-client.js`:
300
-
301
- #### Toasts & Snackbars
302
-
303
- ```javascript
304
- toast({
305
- title: "Profile Updated",
306
- description: "Your settings have been saved successfully.",
307
- type: "success",
308
- position: "top-right",
309
- duration: 4000,
310
- });
311
-
312
- snackbar({ message: "Network connection restored", type: "info" });
313
- ```
314
-
315
- Or trigger them declaratively via HTML attributes:
316
- ```html
317
- <button data-toast="Settings saved successfully!" data-toast-type="success">Save</button>
318
- <button data-snackbar="Item deleted" data-snackbar-type="error">Delete</button>
319
- ```
320
-
321
- #### Drawers & Mobile Navigation
322
-
323
- ```html
324
- <button data-drawer-target="cartDrawer">Open Cart</button>
325
-
326
- <div id="cartDrawer" class="hidden fixed top-0 right-0 h-full w-80 bg-slate-900 p-6 z-50">
327
- <button data-drawer-close="cartDrawer" class="text-slate-400">&times;</button>
328
- <h3>Shopping Cart</h3>
329
- </div>
330
- ```
331
-
332
- #### Responsive Data Table (`ResponsiveDataTable`)
333
-
334
- Transforms tables dynamically into touch-friendly cards on mobile devices:
335
-
336
- ```javascript
337
- new ResponsiveDataTable("usersTableContainer", {
338
- columns: [
339
- { key: "id", label: "ID", sortable: true },
340
- { key: "name", label: "Name", sortable: true },
341
- { key: "email", label: "Email" },
342
- { key: "role", label: "Role" },
343
- ],
344
- data: usersList,
345
- searchable: true,
346
- pagination: true,
347
- pageSize: 10,
348
- onEdit: (row) => editUser(row.id),
349
- onDelete: (row) => deleteUser(row.id),
350
- });
351
- ```
352
-
353
- #### Declarative SPA Forms (`data-bb-form`)
354
-
355
- ```html
356
- <form action="/api/profile" method="POST" data-bb-form="true">
357
- <input type="text" name="name" required />
358
- <button type="submit">Update</button>
359
- </form>
360
- ```
361
- Submissions are automatically handled via `fetch`, CSRF tokens are injected, and toasts/redirects are handled seamlessly via View Transitions.
362
-
363
- #### Declarative DOM Helpers
364
-
365
- - `data-copy="Text to copy"`: Copies text to clipboard on click.
366
- - `data-confirm="Are you sure?"`: Confirms before link navigation or button click.
367
- - `data-toggle="theme"`: Switches between dark and light modes and updates the `dark` class on `<html>`.
368
- - `data-password-toggle="passwordFieldId"`: Toggles password visibility.
369
- - `data-filter-target="tableId"`: Live filters rows or cards matching input value.
370
-
371
- ---
372
-
373
- ### 5. Multi-Driver Caching (`core/cache.js`)
374
-
375
- ```javascript
376
- import Cache from "@seip/bluebird-js/core/cache.js";
377
-
378
- await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
379
- const metrics = await Cache.get("metrics", { driver: "memory" });
380
-
381
- await Cache.set("report", htmlContent, 300, { driver: "file" });
382
- ```
383
-
384
- ---
385
-
386
- ### 6. Desktop Applications (Electron & Desktop Mode)
387
-
388
- Bluebird.js runs natively embedded inside **Electron** applications with ultra-fast boot (<200ms) and minimal RAM consumption (~25–40 MB vs ~300 MB with Nextron):
389
-
390
- - **Automatic Writable Paths:** Routes SQLite database, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`app.getPath("userData")`) to avoid read-only errors inside `.asar` archives.
391
- - **Dynamic Port & LAN / QR Access:** Binds to dynamic port `0` and generates LAN URLs (`allowLan: true`) for companion mobile/QR code access.
392
- - **Clean WAL Shutdown:** `await app.close()` truncates SQLite WAL and frees file locks cleanly on Windows/Mac/Linux.
393
-
394
- ```bash
395
- npx bluebird-js add electron
396
- ```
397
-
398
- ---
399
-
400
- ## Developer Tooling CLI
401
-
402
- ```bash
403
- npx bluebird-js doctor # Diagnostic audit and HTTP smoke tests
404
- npx bluebird-js make:model <Name> # Generates BaseModel class
405
- npx bluebird-js make:route <name> [--auth] # Scaffolds REST route
406
- npx bluebird-js make:view <name> [--ejs] # Scaffolds HTML/EJS template
407
- npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
408
- npx bluebird-js make:migration --model <Model> # Generates migration for specific Model
409
- npx bluebird-js migrate [--yes] # Executes pending migrations
410
- npx bluebird-js migrate:status # Displays applied migration batches
411
- npx bluebird-js migrate:rollback # Reverts latest migration batch
412
- npx bluebird-js make:seed <name> # Creates database seed file
413
- npx bluebird-js seed # Executes database seeds
414
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
415
- npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
416
- npx bluebird-js add electron # Scaffolds Electron desktop app & desktop.js
417
- npx bluebird-js add react-islands # Scaffolds React Islands, Vite & Client Router
418
- npx bluebird-js add <module> # Installs optional on-demand package
419
- ```
420
-
421
- ---
422
-
423
- ## License
424
-
425
- MIT License. Copyright (c) 2026 Seip25.
1
+ # Bluebird.js Framework
2
+
3
+ **Performance-first Node.js API and web framework with native JavaScript ESM, built-in Tailwind CSS, Inter fonts, declarative UI components, JWT auth, BaseModel, smart migrations, and multi-level caching.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@seip/bluebird-js.svg)](https://www.npmjs.com/package/@seip/bluebird-js)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+ [![Node.js Version](https://img.shields.io/badge/node-%3E%3D22.18.0-brightgreen.svg)](https://nodejs.org)
8
+
9
+ ---
10
+
11
+ ## Introduction
12
+
13
+ Bluebird.js (`@seip/bluebird-js`) is a high-performance web and API framework built on Express (Node.js 22.18+). It provides native modern JavaScript ESM execution, built-in Tailwind CSS v4 runtime and Google Fonts (`Inter`), zero-build SSR with React/Next.js-style component tags, multi-driver caching (in-memory LRU by default with filesystem and Redis support), AES-256-GCM encrypted JWT authentication, BaseModel schema definitions with smart migrations, CSRF protection, background queues, and PM2 production clustering into a cohesive developer experience.
14
+
15
+ ### Key Highlights
16
+
17
+ - **Native Zero-Build React JSX & TSX SSR (`app/views/*.jsx`, `*.tsx`):** Compiles `.jsx` and TypeScript `.tsx` modules in memory via Node 22.18+ `module.registerHooks()` with zero temporary disk files, automatic TypeScript type stripping, and zero build steps.
18
+ - **`<ErrorBoundary>` & Dynamic `<Head>` Hoisting:** Native JSX error boundary (`<ErrorBoundary fallback={...}>`) protects against subtree SSR errors, while `<Head>`, `<Title>`, and `<Meta>` automatically hoist metadata into the page head.
19
+ - **Streaming SSR with `<Suspense>` & Instant Caching:** Chunked progressive rendering (`Render.stream()`) with fallback skeletons and seamless deferred template swapping, automatically caching assembled output for instant cache HITs.
20
+ - **Client Components with `useAction` & `useActionState`:** Micro-reactive client runtime with standard hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `html` tagged templates), plus anti-CLS layout locking (`minHeight`, `minWidth`) and automatic button/form pending states.
21
+ - **Declarative Auto-Routes from Views:** Export `const route`, `const cache`, `const middlewares`, `const layout`, and `const seo` directly from `app/views/*.jsx` or `*.tsx` to mount cached, protected web routes automatically (`noAutoDiscoverRoutes: true` in `new App()` to disable).
22
+ - **Built-In Tailwind CSS & Inter Font:** Includes the official standalone Tailwind CSS runtime (`/js/tailwind.js`) and Google Fonts `Inter` by default with zero configuration or compilers.
23
+ - **Smart Automatic Migrations:** CLI detects schema changes across `app/models/`, resolves foreign key dependencies topologically, generates consolidated `CREATE TABLE` / `ALTER TABLE ADD COLUMN` SQL files, and executes them with interactive terminal prompts.
24
+ - **Lightweight BaseModel:** Static facade providing readable schemas, CRUD shortcuts, query operators (`IN`, `$gt`, `$like`), `count()`, `exists()`, `firstOrCreate()`, `updateOrCreate()`, smart relations without N+1 queries, soft deletes, and automatic query cache invalidation.
25
+ - **Native SQLite & Desktop Mode (Electron/Tauri):** Uses Node's built-in `node:sqlite` driver with zero compilation overhead, plus first-class `desktop: true` mode (`app.runDesktop()`) for read-only `.asar` bundles.
26
+ - **Comprehensive Client UI Kit:** Built-in `bluebird-client.js` with toasts, snackbars, drawers, command palette (`Ctrl+K`), responsive data tables, tabs, carousels, declarative forms (`data-bb-form`), and View Transitions SPA routing.
27
+ - **Decoupled Caching:** High-speed in-memory LRU cache by default, persistent filesystem fallback, and modular Redis support via `core/redis.js`.
28
+ - **CSRF, Rate Limiting & Security:** Native HMAC-SHA256 signed CSRF protection, built-in Rate Limiter (`rateLimit` in `App` or `App.rateLimit()`), automatic `/sitemap.xml` & `/robots.txt` generation, and secure HTTP headers.
29
+ - **Production Ready:** Built-in PM2 clustering CLI (`npx bluebird-js make:ecosystem`), optimized Nginx generator (`npx bluebird-js nginx:conf`), and native runner (`npm start`).
30
+
31
+ ---
32
+
33
+ ## Quick Start
34
+
35
+ ### 1. Requirements
36
+
37
+ - Node.js 22.18.0 or higher
38
+ - npm 10+
39
+
40
+ ### 2. Installation and Initialization
41
+
42
+ ```bash
43
+ npm install @seip/bluebird-js
44
+ npx bluebird-js
45
+ ```
46
+
47
+ The interactive CLI configures:
48
+ - Project title and port settings
49
+ - Database engine: `sqlite` (default, native zero-configuration), `mysql`, `postgres`, or `none`
50
+ - Connection credentials and database paths
51
+ - Automatic generation of `index.js`, `.env`, `jsconfig.json`, `app/`, and `public/`
52
+
53
+ ### 3. Development Server
54
+
55
+ ```bash
56
+ npm run dev
57
+ ```
58
+
59
+ The server starts with Node's native file watcher (`--watch`) and loads `.env` automatically via `--env-file=.env`.
60
+
61
+ ---
62
+
63
+ ## Project Structure
64
+
65
+ ```
66
+ project/
67
+ ├── index.js # Main application entrypoint
68
+ ├── app/
69
+ │ ├── models/ # BaseModel definitions
70
+ │ │ ├── user.js # User model schema & methods
71
+ │ │ └── post.js # Post model schema & relations
72
+ │ ├── routes/ # Application routes
73
+ │ │ ├── api.js # REST API routes
74
+ │ │ └── web.js # HTML page routes
75
+ │ ├── views/ # React JSX (.jsx) & JavaScript (.js) SSR views
76
+ │ │ ├── components/ # Reusable JSX components (e.g. Header.jsx)
77
+ │ │ ├── layouts/ # Shared page layouts (e.g. main/view.jsx)
78
+ │ │ ├── index.jsx # Public home view (Auto-Route: /)
79
+ │ │ ├── about.jsx # About page view (Auto-Route: /about)
80
+ │ │ ├── login.jsx # Sign-in page view (Auto-Route: /login)
81
+ │ │ └── dashboard.jsx # Protected dashboard view (Auto-Route: /dashboard)
82
+ │ └── jobs/ # Background worker job handlers
83
+ ├── public/ # Public static assets (CSS, JS, images, fonts)
84
+ │ ├── js/
85
+ │ │ ├── tailwind.js # Built-in Tailwind CSS runtime
86
+ │ │ └── bluebird-client.js # Client UI kit, View Transitions & SPA router
87
+ │ └── images/
88
+ ├── core/ # Bluebird.js framework core
89
+ ├── database/ # SQLite storage and SQL migrations
90
+ │ └── migrations/ # Version-controlled SQL migrations
91
+ ├── .env # Environment variables
92
+ └── package.json
93
+ ```
94
+
95
+ ---
96
+
97
+ ## Core Features & Usage Examples
98
+
99
+ ### 1. Application Entrypoint (`index.js`)
100
+
101
+ ```javascript
102
+ import App from "@seip/bluebird-js/core/app.js";
103
+ import routerApi from "./app/routes/api.js";
104
+ import routerWeb from "./app/routes/web.js";
105
+
106
+ const app = new App({
107
+ routes: [routerWeb, routerApi],
108
+ port: process.env.PORT || 3000,
109
+ rateLimit: { max: 120, windowMs: 60000 },
110
+ });
111
+
112
+ app.run();
113
+ ```
114
+
115
+ For **Electron / Desktop** applications:
116
+
117
+ ```javascript
118
+ const app = new App({
119
+ desktop: true,
120
+ userDataPath: electronApp.getPath("userData"),
121
+ routes: [routerWeb, routerApi],
122
+ });
123
+
124
+ const { url, lanUrl } = await app.runDesktop({ allowLan: true });
125
+ mainWindow.loadURL(url);
126
+ ```
127
+
128
+ ---
129
+
130
+ ### 2. BaseModel & Smart Automatic Migrations (`app/models/`)
131
+
132
+ #### Defining a Model (`app/models/user.js`)
133
+
134
+ ```javascript
135
+ import Model from "@seip/bluebird-js/core/model.js";
136
+
137
+ export default class User extends Model {
138
+ static table = "users";
139
+ static primaryKey = "id";
140
+ static timestamps = true;
141
+ static softDelete = true;
142
+
143
+ static schema = {
144
+ id: { type: "int", primary: true, auto: true },
145
+ name: { type: "string", length: 150, required: true },
146
+ email: { type: "string", length: 150, unique: true, required: true, email: true },
147
+ password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
148
+ role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
149
+ };
150
+ }
151
+ ```
152
+
153
+ #### Foreign Key References (`app/models/post.js`)
154
+
155
+ ```javascript
156
+ import Model from "@seip/bluebird-js/core/model.js";
157
+
158
+ export default class Post extends Model {
159
+ static table = "posts";
160
+ static schema = {
161
+ id: { type: "int", primary: true, auto: true },
162
+ title: { type: "string", length: 200, required: true },
163
+ content: { type: "text" },
164
+ author_id: { type: "int", references: "users.id", onDelete: "cascade" },
165
+ };
166
+ }
167
+ ```
168
+
169
+ #### Powerful Query Methods
170
+
171
+ ```javascript
172
+ const totalUsers = await User.count({ role: "user" });
173
+ const userExists = await User.exists({ email: "alice@example.com" });
174
+
175
+ const activeUsers = await User.all({
176
+ where: {
177
+ id: [1, 2, 3],
178
+ role: { $ne: "banned" },
179
+ views: { $gt: 100 },
180
+ },
181
+ });
182
+
183
+ const user = await User.firstOrCreate(
184
+ { email: "john@example.com" },
185
+ { name: "John Doe", role: "user" }
186
+ );
187
+
188
+ const updated = await User.updateOrCreate(
189
+ { email: "john@example.com" },
190
+ { name: "Johnathan Doe" }
191
+ );
192
+ ```
193
+
194
+ #### Smart Automatic Migrations CLI
195
+
196
+ When you create or modify models, simply run:
197
+
198
+ ```bash
199
+ npx bluebird-js make:migration
200
+ ```
201
+
202
+ Bluebird inspects your models in `app/models/`, connects to your database, sorts tables by foreign key dependencies topologically, and detects all missing tables and columns (`CREATE TABLE` and `ALTER TABLE ADD COLUMN`). It generates a consolidated SQL migration file and asks:
203
+
204
+ ```
205
+ [INFO] Detected database schema changes:
206
+ + CREATE TABLE: users
207
+ + CREATE TABLE: posts
208
+ [OK] Migration created: database/migrations/20261022_120000_auto_migration.sql
209
+ ? Do you want to execute pending migrations now? (Y/n):
210
+ ```
211
+
212
+ To run migrations directly without prompts (ideal for CI/CD):
213
+ ```bash
214
+ npx bluebird-js migrate --yes
215
+ ```
216
+
217
+ ---
218
+
219
+ ### 3. React JSX SSR, Declarative Auto-Routes & `<Client>` Skeletons
220
+
221
+ #### Default Tailwind CSS & Inter Typography
222
+
223
+ The default layout (`app/views/layouts/main/view.jsx`) comes pre-wired with Google Fonts `Inter` and the standalone Tailwind CSS v4 runtime (`/js/tailwind.js`). You can write pure Tailwind utility classes immediately without running Vite, PostCSS, or Tailwind CLI.
224
+
225
+ #### Native `.jsx` Views & Declarative Auto-Routes
226
+
227
+ Bluebird compiles `.jsx` files in memory using Node's native module hooks (`core/jsx.js`)—no external bundler or disk temp files required. Even better, any view inside `app/views/` (excluding `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) can export its own route configuration (`route`, `cache`, `middlewares`, `layout`, `seo`) and `App` mounts it automatically on startup (pass `noAutoDiscoverRoutes: true` to `new App()` if you prefer manual registration only):
228
+
229
+ ```jsx
230
+ // app/views/components/Header.jsx
231
+ export default function Header({ title, user, count = 0 }) {
232
+ return (
233
+ <header className="flex items-center justify-between p-6 border-b border-slate-800">
234
+ <div>
235
+ <h1 className="text-2xl font-bold text-slate-100">{title}</h1>
236
+ <p className="text-sm text-slate-400">Welcome back, {user?.name || "Guest"}</p>
237
+ </div>
238
+ <span className="px-3 py-1 rounded-full text-xs font-semibold bg-sky-500/10 text-sky-400 border border-sky-500/20">
239
+ Notifications: {count}
240
+ </span>
241
+ </header>
242
+ );
243
+ }
244
+ ```
245
+
246
+ ```jsx
247
+ // app/views/dashboard.jsx
248
+ import Auth from "@seip/bluebird-js/core/auth.js";
249
+ import Actions from "@seip/bluebird-js/core/actions.js";
250
+ import { Client } from "@seip/bluebird-js/core/jsx.js";
251
+ import Header from "./components/Header.jsx";
252
+ import LiveCounter from "./components/LiveCounter.js";
253
+
254
+ export const route = "/dashboard";
255
+ export const layout = "main";
256
+ export const middlewares = [Auth.protect({ redirect: "/login" })];
257
+ export const seo = false;
258
+ export const head = (data) => ({ title: `Dashboard — ${data.user?.name || "Member"}` });
259
+
260
+ // Server Actions: automatic CSRF, 16KB maxBytes guard, prototype pollution filter & Validator schema
261
+ export const actions = {
262
+ syncCount: Actions.define(
263
+ {
264
+ maxBytes: "16kb",
265
+ schema: { count: { required: true, number: true } },
266
+ },
267
+ async ({ body, user }) => {
268
+ return { syncedCount: Number(body.count), updatedBy: user?.email };
269
+ }
270
+ ),
271
+ };
272
+
273
+ export default async function DashboardView({ user, syncedCount = 7 }) {
274
+ return (
275
+ <>
276
+ <Header title="Protected Dashboard" user={user} count={syncedCount} />
277
+
278
+ <div className="space-y-6 mt-6">
279
+ {/* Reusable imported Client component with persistent state & anti-CLS skeleton */}
280
+ <Client
281
+ component={LiveCounter}
282
+ props={{ initial: syncedCount }}
283
+ persistent={true}
284
+ minHeight={56}
285
+ skeleton={
286
+ <div className="h-14 rounded-xl bg-slate-900 animate-pulse flex items-center px-4 text-xs text-slate-400">
287
+ Loading interactive widget...
288
+ </div>
289
+ }
290
+ />
291
+ </div>
292
+ </>
293
+ );
294
+ }
295
+ ```
296
+
297
+ #### Reactive Client Components & `useAction` (`LiveCounter.jsx`)
298
+
299
+ Client components run in the browser using Bluebird's micro-reactive runtime with hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `useRef`, `html` tagged templates). You can invoke Server Actions or standard API endpoints and handle native DOM events with standard `event.preventDefault()`:
300
+
301
+ ```jsx
302
+ // app/views/components/LiveCounter.jsx
303
+ import { useState, useEffect, useAction } from "@seip/bluebird-js/core/jsx.js";
304
+ import { html } from "@seip/bluebird-js/core/html.js";
305
+
306
+ export default function LiveCounter({ initial = 7, label = "Client Counter" }) {
307
+ const [count, setCount] = useState(Number(initial) || 0);
308
+ const [sync, isPending] = useAction("syncCount", {
309
+ onSuccess(res) {
310
+ window.toast?.({ title: "Synced", description: res.data.message });
311
+ },
312
+ });
313
+
314
+ const actualizarDashboard = (event) => {
315
+ event.preventDefault(); // Native DOM event support
316
+ sync({ count }); // Dispatches Server Action with pending states
317
+ };
318
+
319
+ return html`
320
+ <div class="h-14 rounded-xl border border-slate-800 bg-slate-950/90 px-4 flex items-center justify-between">
321
+ <span class="text-xs text-slate-300">${label}: <strong class="text-sky-400 font-mono">${count}</strong></span>
322
+ <div class="flex items-center gap-2">
323
+ <button type="button" onClick=${() => setCount(count + 1)} class="px-2.5 py-1 bg-sky-500 rounded text-xs font-bold text-slate-950">+1</button>
324
+ <button type="button" onClick=${actualizarDashboard} disabled=${isPending} class="px-2.5 py-1 bg-emerald-500/15 border border-emerald-500/30 rounded text-xs text-emerald-300">
325
+ ${isPending ? "Syncing..." : "Sync Server Action"}
326
+ </button>
327
+ </div>
328
+ </div>
329
+ `;
330
+ }
331
+ ```
332
+
333
+ #### `<ErrorBoundary>` & Dynamic `<Head>` Hoisting
334
+
335
+ Catch rendering errors during SSR in subtrees and hoist metadata directly into the document `<head>`:
336
+
337
+ ```jsx
338
+ import { ErrorBoundary, Head, Title, Meta } from "@seip/bluebird-js/core/jsx.js";
339
+
340
+ export default function ProfilePage({ user }) {
341
+ return (
342
+ <>
343
+ <Head>
344
+ <Title>Profile — {user.name}</Title>
345
+ <Meta name="robots" content="noindex,nofollow" />
346
+ </Head>
347
+
348
+ <ErrorBoundary fallback={(err) => <div className="p-4 bg-red-950 text-red-400 rounded-xl">Error: {err.message}</div>}>
349
+ <UserProfileWidget userId={user.id} />
350
+ </ErrorBoundary>
351
+ </>
352
+ );
353
+ }
354
+ ```
355
+
356
+ #### Streaming SSR with `<Suspense>` & Instant Cache HIT
357
+
358
+ Stream progressive chunked HTML responses with immediate skeletons. If route cache is enabled (`cache: 60`), cache misses stream progressively while caching the assembled final HTML, and subsequent requests are served as **instant Cache HITs** without streaming overhead:
359
+
360
+ ```jsx
361
+ import { Suspense } from "@seip/bluebird-js/core/jsx.js";
362
+
363
+ export const cache = 60; // Subsequent hits served instantly from RAM LRU
364
+
365
+ export default function FeedPage() {
366
+ return (
367
+ <div>
368
+ <h1>Live Activity</h1>
369
+ <Suspense fallback={<div className="h-40 animate-pulse bg-slate-900 rounded-xl">Loading feed...</div>}>
370
+ <AsyncFeedList />
371
+ </Suspense>
372
+ </div>
373
+ );
374
+ }
375
+ ```
376
+
377
+ #### Zero-Build TypeScript & TSX Support (`.tsx`, `.ts`)
378
+
379
+ Write views and components directly in TypeScript. Bluebird strips type annotations natively in memory using Node's native module customization hooks with zero build steps and zero disk temp files:
380
+
381
+ ```tsx
382
+ // app/views/components/UserCard.tsx
383
+ interface UserProps {
384
+ id: number;
385
+ name: string;
386
+ role: "admin" | "member";
387
+ }
388
+
389
+ export default function UserCard({ id, name, role }: UserProps): any {
390
+ return (
391
+ <div className="user-card" data-id={id}>
392
+ <strong>{name}</strong> <span>({role})</span>
393
+ </div>
394
+ );
395
+ }
396
+ ```
397
+
398
+ ---
399
+
400
+ ### 4. Built-in Client UI Kit (`public/js/bluebird-client.js`)
401
+
402
+ Bluebird includes a lightweight, dependency-free client UI toolkit with Tailwind CSS styles built right into `public/js/bluebird-client.js`:
403
+
404
+ #### Toasts & Snackbars
405
+
406
+ ```javascript
407
+ toast({
408
+ title: "Profile Updated",
409
+ description: "Your settings have been saved successfully.",
410
+ type: "success",
411
+ position: "top-right",
412
+ duration: 4000,
413
+ });
414
+
415
+ snackbar({ message: "Network connection restored", type: "info" });
416
+ ```
417
+
418
+ Or trigger them declaratively via HTML attributes:
419
+ ```html
420
+ <button data-toast="Settings saved successfully!" data-toast-type="success">Save</button>
421
+ <button data-snackbar="Item deleted" data-snackbar-type="error">Delete</button>
422
+ ```
423
+
424
+ #### Drawers & Mobile Navigation
425
+
426
+ ```html
427
+ <button data-drawer-target="cartDrawer">Open Cart</button>
428
+
429
+ <div id="cartDrawer" class="hidden fixed top-0 right-0 h-full w-80 bg-slate-900 p-6 z-50">
430
+ <button data-drawer-close="cartDrawer" class="text-slate-400">&times;</button>
431
+ <h3>Shopping Cart</h3>
432
+ </div>
433
+ ```
434
+
435
+ #### Responsive Data Table (`ResponsiveDataTable`)
436
+
437
+ Transforms tables dynamically into touch-friendly cards on mobile devices:
438
+
439
+ ```javascript
440
+ new ResponsiveDataTable("usersTableContainer", {
441
+ columns: [
442
+ { key: "id", label: "ID", sortable: true },
443
+ { key: "name", label: "Name", sortable: true },
444
+ { key: "email", label: "Email" },
445
+ { key: "role", label: "Role" },
446
+ ],
447
+ data: usersList,
448
+ searchable: true,
449
+ pagination: true,
450
+ pageSize: 10,
451
+ onEdit: (row) => editUser(row.id),
452
+ onDelete: (row) => deleteUser(row.id),
453
+ });
454
+ ```
455
+
456
+ #### Declarative SPA Forms (`data-bb-form`)
457
+
458
+ ```html
459
+ <form action="/api/profile" method="POST" data-bb-form="true">
460
+ <input type="text" name="name" required />
461
+ <button type="submit">Update</button>
462
+ </form>
463
+ ```
464
+ Submissions are automatically handled via `fetch`, CSRF tokens are injected, and toasts/redirects are handled seamlessly via View Transitions.
465
+
466
+ #### Declarative DOM Helpers
467
+
468
+ - `data-copy="Text to copy"`: Copies text to clipboard on click.
469
+ - `data-confirm="Are you sure?"`: Confirms before link navigation or button click.
470
+ - `data-toggle="theme"`: Switches between dark and light modes and updates the `dark` class on `<html>`.
471
+ - `data-password-toggle="passwordFieldId"`: Toggles password visibility.
472
+ - `data-filter-target="tableId"`: Live filters rows or cards matching input value.
473
+
474
+ ---
475
+
476
+ ### 5. Multi-Driver Caching (`core/cache.js`)
477
+
478
+ ```javascript
479
+ import Cache from "@seip/bluebird-js/core/cache.js";
480
+
481
+ await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
482
+ const metrics = await Cache.get("metrics", { driver: "memory" });
483
+
484
+ await Cache.set("report", htmlContent, 300, { driver: "file" });
485
+ ```
486
+
487
+ ---
488
+
489
+ ### 6. Desktop Applications (Electron & Desktop Mode)
490
+
491
+ Bluebird.js runs natively embedded inside **Electron** applications with ultra-fast boot (<200ms) and minimal RAM consumption (~25–40 MB vs ~300 MB with Nextron):
492
+
493
+ - **Automatic Writable Paths:** Routes SQLite database, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`app.getPath("userData")`) to avoid read-only errors inside `.asar` archives.
494
+ - **Dynamic Port & LAN / QR Access:** Binds to dynamic port `0` and generates LAN URLs (`allowLan: true`) for companion mobile/QR code access.
495
+ - **Clean WAL Shutdown:** `await app.close()` truncates SQLite WAL and frees file locks cleanly on Windows/Mac/Linux.
496
+
497
+ ```bash
498
+ npx bluebird-js add electron
499
+ ```
500
+
501
+ ---
502
+
503
+ ## Developer Tooling CLI
504
+
505
+ ```bash
506
+ npx bluebird-js doctor # Diagnostic audit and HTTP smoke tests
507
+ npx bluebird-js make:model <Name> # Generates BaseModel class
508
+ npx bluebird-js make:route <name> [--auth] # Scaffolds REST route
509
+ npx bluebird-js make:view <name> [--ejs] # Scaffolds HTML/EJS template
510
+ npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
511
+ npx bluebird-js make:migration --model <Model> # Generates migration for specific Model
512
+ npx bluebird-js migrate [--yes] # Executes pending migrations
513
+ npx bluebird-js migrate:status # Displays applied migration batches
514
+ npx bluebird-js migrate:rollback # Reverts latest migration batch
515
+ npx bluebird-js make:seed <name> # Creates database seed file
516
+ npx bluebird-js seed # Executes database seeds
517
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
518
+ npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
519
+ npx bluebird-js add electron # Scaffolds Electron desktop app & desktop.js
520
+ npx bluebird-js add react-islands # Scaffolds React Islands, Vite & Client Router
521
+ npx bluebird-js add <module> # Installs optional on-demand package
522
+ ```
523
+
524
+ ---
525
+
526
+ ## License
527
+
528
+ MIT License. Copyright (c) 2026 Seip25.