@seip/bluebird-js 0.0.0-stage → 0.1.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 (79) hide show
  1. package/.env_example +54 -0
  2. package/AGENTS.md +426 -0
  3. package/LICENSE +21 -0
  4. package/README.md +292 -3
  5. package/app/routes/api.js +50 -0
  6. package/app/routes/web.js +55 -0
  7. package/app/views/about.js +63 -0
  8. package/app/views/dashboard.js +147 -0
  9. package/app/views/index.js +80 -0
  10. package/app/views/layouts/main/view.js +81 -0
  11. package/app/views/legal/terms.html +19 -0
  12. package/app/views/login.js +80 -0
  13. package/core/app.d.ts +18 -0
  14. package/core/app.js +684 -0
  15. package/core/auth.d.ts +13 -0
  16. package/core/auth.js +326 -0
  17. package/core/cache.d.ts +17 -0
  18. package/core/cache.js +475 -0
  19. package/core/cli/doctor.js +287 -0
  20. package/core/cli/ecosystem.js +162 -0
  21. package/core/cli/init.js +779 -0
  22. package/core/cli/migrate.js +541 -0
  23. package/core/cli/model.js +66 -0
  24. package/core/cli/nginx.js +199 -0
  25. package/core/cli/route.js +121 -0
  26. package/core/cli/swagger.js +45 -0
  27. package/core/cli/view.js +96 -0
  28. package/core/config.d.ts +3 -0
  29. package/core/config.js +111 -0
  30. package/core/csrf.d.ts +3 -0
  31. package/core/csrf.js +114 -0
  32. package/core/database.d.ts +15 -0
  33. package/core/database.js +636 -0
  34. package/core/debug.d.ts +3 -0
  35. package/core/debug.js +250 -0
  36. package/core/hash.d.ts +3 -0
  37. package/core/hash.js +194 -0
  38. package/core/html.d.ts +42 -0
  39. package/core/html.js +217 -0
  40. package/core/index.d.ts +1176 -0
  41. package/core/logger.d.ts +3 -0
  42. package/core/logger.js +127 -0
  43. package/core/middleware.d.ts +3 -0
  44. package/core/middleware.js +28 -0
  45. package/core/model.d.ts +19 -0
  46. package/core/model.js +600 -0
  47. package/core/queue.d.ts +13 -0
  48. package/core/queue.js +172 -0
  49. package/core/ratelimit.d.ts +3 -0
  50. package/core/ratelimit.js +145 -0
  51. package/core/redis.d.ts +21 -0
  52. package/core/redis.js +230 -0
  53. package/core/render-cache.js +212 -0
  54. package/core/render.d.ts +3 -0
  55. package/core/render.js +320 -0
  56. package/core/router.d.ts +3 -0
  57. package/core/router.js +171 -0
  58. package/core/seo.d.ts +3 -0
  59. package/core/seo.js +106 -0
  60. package/core/swagger.d.ts +3 -0
  61. package/core/swagger.js +60 -0
  62. package/core/upload.d.ts +13 -0
  63. package/core/upload.js +102 -0
  64. package/core/util/colors.js +82 -0
  65. package/core/validate.d.ts +15 -0
  66. package/core/validate.js +364 -0
  67. package/core/view-loader.js +162 -0
  68. package/core/vite.d.ts +3 -0
  69. package/core/vite.js +145 -0
  70. package/core/ws.d.ts +13 -0
  71. package/core/ws.js +245 -0
  72. package/index.js +18 -0
  73. package/jsconfig.json +15 -0
  74. package/package.json +85 -5
  75. package/production.md +273 -0
  76. package/public/css/bluebird.min.css +2 -0
  77. package/public/images/favicon.ico +0 -0
  78. package/public/js/bluebird-client.js +1781 -0
  79. package/public/js/bluebird.min.js +1073 -0
package/core/app.js ADDED
@@ -0,0 +1,684 @@
1
+ import http from "node:http";
2
+ import express from "express";
3
+ import path from "node:path";
4
+ import colors from "./util/colors.js";
5
+ import Config from "./config.js";
6
+ import Logger from "./logger.js";
7
+ import Debug from "./debug.js";
8
+ import WebSocketManager from "./ws.js";
9
+ import RateLimit from "./ratelimit.js";
10
+ import Seo from "./seo.js";
11
+
12
+ const __dirname = Config.dirname();
13
+ const props = Config.props();
14
+ const SERVER_BOOT_ID = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
15
+
16
+ /**
17
+ * Lightweight native cookie parser middleware.
18
+ * @param {import('express').Request} req
19
+ * @param {import('express').Response} res
20
+ * @param {import('express').NextFunction} next
21
+ */
22
+ function nativeCookieParser(req, res, next) {
23
+ if (req.cookies) return next();
24
+ const cookieHeader = req.headers.cookie;
25
+ const cookies = {};
26
+ if (cookieHeader) {
27
+ const pairs = cookieHeader.split(";");
28
+ for (let i = 0; i < pairs.length; i++) {
29
+ const idx = pairs[i].indexOf("=");
30
+ if (idx > 0) {
31
+ const key = pairs[i].slice(0, idx).trim();
32
+ const val = pairs[i].slice(idx + 1).trim();
33
+ try {
34
+ cookies[key] = decodeURIComponent(val);
35
+ } catch {
36
+ cookies[key] = val;
37
+ }
38
+ }
39
+ }
40
+ }
41
+ req.cookies = cookies;
42
+ next();
43
+ }
44
+
45
+ /**
46
+ * Lightweight native CORS middleware.
47
+ * @param {Object|boolean} [corsOptions={}]
48
+ * @returns {Function} Express middleware.
49
+ */
50
+ function nativeCors(corsOptions = {}) {
51
+ if (corsOptions === false) {
52
+ return (req, res, next) => next();
53
+ }
54
+
55
+ const origin = corsOptions.origin ?? "*";
56
+ const methods = corsOptions.methods ?? "GET,HEAD,PUT,PATCH,POST,DELETE";
57
+ const allowedHeaders = corsOptions.allowedHeaders ?? "Content-Type,Authorization";
58
+ const credentials = corsOptions.credentials ?? true;
59
+
60
+ return (req, res, next) => {
61
+ const reqOrigin = req.headers.origin;
62
+
63
+ if (credentials && reqOrigin) {
64
+ if (origin === "*" || origin === true) {
65
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
66
+ res.setHeader("Vary", "Origin");
67
+ } else if (typeof origin === "string") {
68
+ res.setHeader("Access-Control-Allow-Origin", origin);
69
+ } else if (Array.isArray(origin) && origin.includes(reqOrigin)) {
70
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
71
+ res.setHeader("Vary", "Origin");
72
+ } else if (typeof origin === "function" && origin(reqOrigin, req)) {
73
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
74
+ res.setHeader("Vary", "Origin");
75
+ }
76
+ } else if (origin === "*") {
77
+ res.setHeader("Access-Control-Allow-Origin", "*");
78
+ } else if (typeof origin === "string") {
79
+ res.setHeader("Access-Control-Allow-Origin", origin);
80
+ } else if (Array.isArray(origin) && reqOrigin && origin.includes(reqOrigin)) {
81
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
82
+ res.setHeader("Vary", "Origin");
83
+ } else if (typeof origin === "function" && reqOrigin) {
84
+ if (origin(reqOrigin, req)) {
85
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
86
+ res.setHeader("Vary", "Origin");
87
+ }
88
+ } else if (reqOrigin) {
89
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
90
+ res.setHeader("Vary", "Origin");
91
+ }
92
+
93
+ if (credentials) {
94
+ res.setHeader("Access-Control-Allow-Credentials", "true");
95
+ }
96
+
97
+ if (corsOptions.exposedHeaders) {
98
+ res.setHeader(
99
+ "Access-Control-Expose-Headers",
100
+ Array.isArray(corsOptions.exposedHeaders)
101
+ ? corsOptions.exposedHeaders.join(",")
102
+ : corsOptions.exposedHeaders
103
+ );
104
+ }
105
+
106
+ if (req.method === "OPTIONS") {
107
+ res.setHeader(
108
+ "Access-Control-Allow-Methods",
109
+ Array.isArray(methods) ? methods.join(",") : methods
110
+ );
111
+ res.setHeader(
112
+ "Access-Control-Allow-Headers",
113
+ Array.isArray(allowedHeaders) ? allowedHeaders.join(",") : allowedHeaders
114
+ );
115
+ if (corsOptions.maxAge) {
116
+ res.setHeader("Access-Control-Max-Age", String(corsOptions.maxAge));
117
+ }
118
+ return res.status(204).end();
119
+ }
120
+
121
+ next();
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Generates middleware that applies modern HTTP security response headers.
127
+ * @param {Object} [options={}] - Options to override header values.
128
+ * @param {string|false} [options.csp=false] - Content-Security-Policy value.
129
+ * @returns {Function} Express middleware.
130
+ */
131
+ function securityHeaders(options = {}) {
132
+ return (req, res, next) => {
133
+ res.setHeader("X-Frame-Options", options.frameOptions ?? "SAMEORIGIN");
134
+ res.setHeader("X-Content-Type-Options", "nosniff");
135
+ res.setHeader("X-XSS-Protection", "0");
136
+ res.setHeader("Referrer-Policy", options.referrerPolicy ?? "strict-origin-when-cross-origin");
137
+ res.setHeader(
138
+ "Permissions-Policy",
139
+ options.permissionsPolicy ?? "camera=(), microphone=(), geolocation=()"
140
+ );
141
+ if (options.csp) {
142
+ res.setHeader("Content-Security-Policy", options.csp);
143
+ }
144
+ next();
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Main Application class to manage Express server, routes, and middlewares.
150
+ */
151
+ class App {
152
+ /**
153
+ * Initializes the App instance with the provided options.
154
+ * @param {Object} [options={}] - Configuration options for the application.
155
+ * @param {Array<{path: string, router: import('express').Router}>} [options.routes=[]] - Route objects.
156
+ * @param {Object|boolean} [options.cors={}] - CORS configuration options.
157
+ * @param {Array<Function>} [options.middlewares=[]] - Global middleware functions.
158
+ * @param {number|string} [options.port=3000] - Server port (use 0 for dynamic free port in Electron).
159
+ * @param {string} [options.host="http://localhost"] - Server host URL.
160
+ * @param {string} [options.appUrl] - Public application URL.
161
+ * @param {boolean} [options.logger=false] - Whether to enable the request logger.
162
+ * @param {boolean} [options.notFound=true] - Whether to enable the default 404 handler.
163
+ * @param {boolean} [options.json=true] - Whether to enable JSON body parsing.
164
+ * @param {boolean} [options.urlencoded=true] - Whether to enable URL-encoded body parsing.
165
+ * @param {Object} [options.static] - Static file configuration for public/ directory.
166
+ * @param {boolean} [options.cookieParser=true] - Whether to enable cookie parsing.
167
+ * @param {boolean} [options.swagger=false] - Enable Swagger documentation.
168
+ * @param {boolean} [options.compression=false] - Enable gzip/brotli compression.
169
+ * @param {boolean|Object} [options.security=true] - Enable built-in security headers middleware.
170
+ * @param {boolean|Object} [options.rateLimit=false] - Enable built-in rate limiting middleware.
171
+ * @param {boolean} [options.trustProxy=true] - Enable Express trust proxy for accurate IP behind reverse proxies.
172
+ * @param {boolean} [options.desktop=false] - Enable Electron/Desktop mode (binds 127.0.0.1 and uses writable userDataDir).
173
+ * @param {string} [options.userDataPath] - Custom writable directory path for SQLite, logs, and file cache in Electron.
174
+ */
175
+ constructor(options = {}) {
176
+ if (options.userDataPath) {
177
+ Config.setUserDataDir(options.userDataPath);
178
+ } else if (options.desktop) {
179
+ process.env.DESKTOP_MODE = "true";
180
+ Config.reload();
181
+ }
182
+
183
+ this.app = express();
184
+ this.app.disable("x-powered-by");
185
+ this.server = http.createServer(this.app);
186
+ this.wsManager = null;
187
+ this.routes = options.routes || [];
188
+ this.cors = options.cors || {};
189
+ this.middlewares = options.middlewares || [];
190
+ this.desktop = options.desktop ?? Config.isDesktop();
191
+ this.port = options.port !== undefined ? options.port : (this.desktop && !process.env.PORT ? 0 : props.port);
192
+ this.host = options.host || (this.desktop ? "http://127.0.0.1" : props.host);
193
+ this.appUrl = options.appUrl || props.appUrl;
194
+ this.logger = options.logger ?? false;
195
+ this.notFound = options.notFound ?? true;
196
+ this.json = options.json ?? true;
197
+ this.urlencoded = options.urlencoded ?? true;
198
+ this.static = options.static || props.static;
199
+ this.cookieParser = options.cookieParser ?? true;
200
+ this.swagger = options.swagger ?? false;
201
+ this.compression = options.compression ?? false;
202
+ this.security = options.security ?? true;
203
+ this.rateLimit = options.rateLimit ?? false;
204
+ this.trustProxy = options.trustProxy ?? !this.desktop;
205
+ this.debug = options.debug !== undefined ? Boolean(options.debug) : (props.debug || process.env.DEBUG === "true");
206
+ this._loggerInstance = null;
207
+ this._finalized = false;
208
+
209
+ if (this.trustProxy) {
210
+ this.app.enable("trust proxy");
211
+ }
212
+
213
+ this._setupCoreMiddlewares();
214
+ }
215
+
216
+ /**
217
+ * Lazily initializes and returns the Logger instance.
218
+ * @returns {Logger}
219
+ */
220
+ get loggerInstance() {
221
+ if (!this._loggerInstance) {
222
+ this._loggerInstance = new Logger();
223
+ }
224
+ return this._loggerInstance;
225
+ }
226
+
227
+ set loggerInstance(val) {
228
+ this._loggerInstance = val;
229
+ }
230
+
231
+ /**
232
+ * Registers a custom middleware or router in the Express application.
233
+ * @param {Function|import('express').Router} record - Middleware function or Express router.
234
+ */
235
+ use(record) {
236
+ this.app.use(record);
237
+ }
238
+
239
+ /**
240
+ * Sets a configuration value in the Express application.
241
+ * @param {string} key - Configuration key.
242
+ * @param {*} value - Configuration value.
243
+ */
244
+ set(key, value) {
245
+ this.app.set(key, value);
246
+ }
247
+
248
+ /**
249
+ * Returns the active port number after the server starts listening.
250
+ * @returns {number}
251
+ */
252
+ getPort() {
253
+ const addr = this.server?.address?.();
254
+ if (addr && typeof addr === "object" && addr.port) {
255
+ return addr.port;
256
+ }
257
+ return Number(this.port) || 3000;
258
+ }
259
+
260
+ /**
261
+ * Returns the active internal URL of the server.
262
+ * @returns {string}
263
+ */
264
+ getUrl() {
265
+ const port = this.getPort();
266
+ const cleanHost = this.host.replace(/:\d+$/, "");
267
+ return `${cleanHost}:${port}`;
268
+ }
269
+
270
+ /**
271
+ * Sets up base middleware stack.
272
+ * @private
273
+ */
274
+ _setupCoreMiddlewares() {
275
+ if (this.compression) {
276
+ import("compression")
277
+ .then((mod) => {
278
+ const comp = mod.default || mod;
279
+ this.app.use(comp());
280
+ })
281
+ .catch(() => {});
282
+ }
283
+
284
+ if (this.json) this.app.use(express.json());
285
+ if (this.urlencoded) this.app.use(express.urlencoded({ extended: true }));
286
+ if (this.cookieParser) this.app.use(nativeCookieParser);
287
+
288
+ if (this.security) {
289
+ this.app.use(securityHeaders(typeof this.security === "object" ? this.security : {}));
290
+ }
291
+
292
+ if (this.cors !== false) {
293
+ this.app.use(nativeCors(this.cors));
294
+ }
295
+
296
+ if (this.rateLimit) {
297
+ this.app.use(RateLimit.middleware(typeof this.rateLimit === "object" ? this.rateLimit : {}));
298
+ }
299
+
300
+ this.app.use((req, res, next) => {
301
+ req.lang = req.query?.lang || req.body?.lang || req.cookies?.lang || "en";
302
+ res.locals.lang = req.lang;
303
+
304
+ res.success = (data = null, message = "Success", statusCode = 200) =>
305
+ res.status(statusCode).json({ status: "success", message, data });
306
+
307
+ res.error = (message = "Error", statusCode = 400, errors = []) =>
308
+ res.status(statusCode).json({ status: "error", message, errors });
309
+
310
+ res.ok = (data = null, message = "Success") => res.success(data, message, 200);
311
+
312
+ res.created = (data = null, message = "Created") => res.success(data, message, 201);
313
+
314
+ res.badRequest = (message = "Bad Request", errors = []) => res.error(message, 400, errors);
315
+
316
+ res.unauthorized = (message = "Unauthorized") => res.error(message, 401);
317
+
318
+ res.forbidden = (message = "Forbidden") => res.error(message, 403);
319
+
320
+ res.notFound = (message = "Not Found") => res.error(message, 404);
321
+
322
+ res.serverError = (message = "Internal Server Error", errors = []) => res.error(message, 500, errors);
323
+
324
+ res.paginate = (data = [], pagination = {}, message = "Success") => {
325
+ const page = Number(pagination.page) || 1;
326
+ const limit = Number(pagination.limit) || data.length;
327
+ const total = Number(pagination.total) || data.length;
328
+ const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;
329
+ return res.status(200).json({ status: "success", message, data, pagination: { page, limit, total, totalPages } });
330
+ };
331
+
332
+ res.setHeader("X-Powered-By", "Blue Bird");
333
+ next();
334
+ });
335
+
336
+ this.app.get("/api/health", (req, res) =>
337
+ res.json({
338
+ status: "ok",
339
+ timestamp: new Date().toISOString(),
340
+ uptime: Math.floor(process.uptime()),
341
+ environment: this.debug ? "development" : "production",
342
+ desktop: this.desktop,
343
+ memory: {
344
+ rss: `${Math.round(process.memoryUsage().rss / 1024 / 1024)}MB`,
345
+ heapUsed: `${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`,
346
+ },
347
+ })
348
+ );
349
+
350
+ if (this.debug) {
351
+ this.app.get("/_bb/dev-reload", (req, res) => {
352
+ res.writeHead(200, {
353
+ "Content-Type": "text/event-stream",
354
+ "Cache-Control": "no-cache, no-transform",
355
+ Connection: "keep-alive",
356
+ "Access-Control-Allow-Origin": "*",
357
+ });
358
+
359
+ res.write(`data: ${JSON.stringify({ type: "connected", bootId: SERVER_BOOT_ID })}\n\n`);
360
+
361
+ const interval = setInterval(() => {
362
+ res.write(":ping\n\n");
363
+ }, 15000);
364
+
365
+ req.on("close", () => {
366
+ clearInterval(interval);
367
+ });
368
+ });
369
+ }
370
+
371
+ const staticPath = this.static?.path || "public";
372
+ const staticOptions = this.static?.options || {};
373
+ const isDebug = this.debug;
374
+
375
+ this.app.use(
376
+ express.static(path.join(__dirname, staticPath), {
377
+ ...staticOptions,
378
+ setHeaders: (res) => {
379
+ res.setHeader("X-Powered-By", "Blue Bird");
380
+ res.setHeader(
381
+ "Cache-Control",
382
+ isDebug ? "no-cache" : "public, max-age=2592000, immutable"
383
+ );
384
+ },
385
+ })
386
+ );
387
+
388
+ this.middlewares.forEach((middleware) => {
389
+ this.app.use(middleware);
390
+ });
391
+
392
+ if (this.logger || props.debug) this._middlewareLogger(this.logger);
393
+
394
+ if (props.debug) {
395
+ Debug.middlewareMetrics(this.app);
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Finalizes application routes, 404, and error handling.
401
+ * Called automatically before listening.
402
+ * @private
403
+ */
404
+ async _finalize() {
405
+ if (this._finalized) return;
406
+ this._finalized = true;
407
+
408
+ if (this.swagger) {
409
+ const { default: Swagger } = await import("./swagger.js");
410
+ const defaultSwaggerOptions = {
411
+ info: { title: "Blue Bird API", version: "1.0.0", description: "Blue Bird Framework API Documentation" },
412
+ url: this.appUrl ? this.appUrl : `${this.host}:${this.port}`,
413
+ route: "/docs",
414
+ };
415
+ Swagger.init(this.app, {
416
+ ...defaultSwaggerOptions,
417
+ ...(typeof this.swagger === "object" ? this.swagger : {}),
418
+ });
419
+ }
420
+
421
+ this._dispatchRoutes();
422
+
423
+ if (this.notFound) this._notFoundDefault();
424
+
425
+ this._errorHandler();
426
+ }
427
+
428
+ /**
429
+ * Middleware that logs incoming HTTP requests.
430
+ * @private
431
+ * @param {boolean} [logger=false]
432
+ */
433
+ _middlewareLogger(logger = false) {
434
+ this.app.use((req, res, next) => {
435
+ const method = req.method;
436
+ const url = req.url.replace(/(password|token|authorization)=([^&]+)/gi, "$1=***");
437
+ if (url.includes("chrome")) return next();
438
+ const params = Object.keys(req.params).length > 0 ? ` ${JSON.stringify(req.params)}` : "";
439
+ const ip = req.ip || req.socket?.remoteAddress;
440
+ const now = new Date().toISOString();
441
+ const time = `${now.split("T")[0]} ${now.split("T")[1].split(".")[0]}`;
442
+ let message = ` ${time} -${ip} -[${method}] ${url} ${params}`;
443
+
444
+ if (logger) this.loggerInstance.info(message);
445
+
446
+ if (props.debug) {
447
+ message = `${colors.bold.green(time)} - ${colors.bold.cyan(ip)} -[${colors.bold.red(method)}] ${colors.bold.blue(url)} ${colors.bold.yellow(params)}`;
448
+ console.log(message);
449
+ }
450
+ next();
451
+ });
452
+ }
453
+
454
+ /**
455
+ * Global error handler for the application.
456
+ * @private
457
+ */
458
+ _errorHandler() {
459
+ this.app.use((err, req, res, next) => {
460
+ const statusCode = err.statusCode || err.status || 500;
461
+ const message = err.message || "Internal Server Error";
462
+ const errors = err.errors || [];
463
+
464
+ if (this.logger) {
465
+ this.loggerInstance.error(`[${statusCode}] ${message} - ${err.stack}`);
466
+ }
467
+
468
+ const payload = {
469
+ status: "error",
470
+ message: statusCode === 500 && !props.debug ? "Internal Server Error" : message,
471
+ errors,
472
+ };
473
+
474
+ if (props.debug && err.stack) payload.stack = err.stack;
475
+
476
+ return res.status(statusCode).json(payload);
477
+ });
478
+ }
479
+
480
+ /**
481
+ * Attaches all registered routes to the Express application, including automatic SEO routes.
482
+ * @private
483
+ */
484
+ _dispatchRoutes() {
485
+ if (props.debug) {
486
+ const debug = new Debug();
487
+ const debugRouter = debug.getRouter();
488
+ this.app.use(debugRouter.path, debugRouter.router);
489
+ }
490
+
491
+ const hasSeoRouter = this.routes.some((r) => r._seo) || Seo.getRoutes().length > 0;
492
+ if (hasSeoRouter) {
493
+ this.app.get("/sitemap.xml", (req, res) => {
494
+ res.setHeader("Content-Type", "application/xml; charset=utf-8");
495
+ res.send(Seo.generateSitemap(this.appUrl));
496
+ });
497
+ this.app.get("/robots.txt", (req, res) => {
498
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
499
+ res.send(Seo.generateRobots(this.appUrl));
500
+ });
501
+ }
502
+
503
+ this.routes.forEach((route) => {
504
+ this.app.use(route.path, route.router);
505
+ });
506
+ }
507
+
508
+ /**
509
+ * Default 404 handler for unmatched routes.
510
+ * @private
511
+ */
512
+ _notFoundDefault() {
513
+ this.app.use((req, res) => {
514
+ const expectsHtml = req.headers.accept?.includes("text/html") && !req.path.startsWith("/api");
515
+ if (expectsHtml) return res.status(404).send("<h1>404 Not Found</h1>");
516
+ return res.status(404).json({ message: "Not Found" });
517
+ });
518
+ }
519
+
520
+ /**
521
+ * Starts the HTTP server and listens for incoming connections.
522
+ * In desktop mode, binds exclusively to 127.0.0.1 for local security.
523
+ * @returns {Promise<import('http').Server>}
524
+ */
525
+ async run() {
526
+ await this._finalize();
527
+
528
+ return new Promise((resolve, reject) => {
529
+ const onListening = () => {
530
+ const activePort = this.getPort();
531
+ this.port = activePort;
532
+ if (this.desktop) {
533
+ this.appUrl = `http://127.0.0.1:${activePort}`;
534
+ }
535
+ console.log(
536
+ colors.bold.blue("Blue Bird Server Online\n") +
537
+ colors.bold.cyan("App URL: ") +
538
+ colors.green(`${this.appUrl}`) +
539
+ "\n" +
540
+ colors.bold.cyan("Internal: ") +
541
+ colors.green(`${this.host}:${activePort}`) +
542
+ "\n" +
543
+ colors.gray("────────────────────────────────")
544
+ );
545
+ resolve(this.server);
546
+ };
547
+
548
+ this.server.on("error", reject);
549
+
550
+ if (this.desktop) {
551
+ this.server.listen(this.port, "127.0.0.1", onListening);
552
+ } else {
553
+ this.server.listen(this.port, onListening);
554
+ }
555
+ });
556
+ }
557
+
558
+ /**
559
+ * Starts the server in Electron / Desktop mode, binding to 127.0.0.1 (using a dynamic port if port is 0)
560
+ * and returning the server, resolved port, and local URL ready for Electron's mainWindow.loadURL(url).
561
+ * @param {Object} [options={}]
562
+ * @param {string} [options.userDataPath] - Optional path from Electron app.getPath("userData").
563
+ * @returns {Promise<{server: import('http').Server, port: number, url: string}>}
564
+ */
565
+ async runDesktop(options = {}) {
566
+ if (options.userDataPath) {
567
+ Config.setUserDataDir(options.userDataPath);
568
+ }
569
+ this.desktop = true;
570
+ this.host = "http://127.0.0.1";
571
+ await this.run();
572
+ const port = this.getPort();
573
+ const url = `http://127.0.0.1:${port}`;
574
+ return { server: this.server, port, url };
575
+ }
576
+
577
+ /**
578
+ * Closes the running HTTP server.
579
+ * @returns {Promise<void>}
580
+ */
581
+ close() {
582
+ return new Promise((resolve, reject) => {
583
+ if (this.server) {
584
+ this.server.close((err) => (err ? reject(err) : resolve()));
585
+ } else {
586
+ resolve();
587
+ }
588
+ });
589
+ }
590
+
591
+ /**
592
+ * Initializes and returns the WebSocket manager attached to the HTTP server.
593
+ * @param {Function|Object} [options] - Connection callback or options object.
594
+ * @returns {WebSocketManager}
595
+ */
596
+ websocket(options = {}) {
597
+ const handler = typeof options === "function" ? options : null;
598
+ const wsOptions = typeof options === "object" && options !== null ? options : {};
599
+
600
+ if (!this.wsManager) {
601
+ this.wsManager = new WebSocketManager(this.server, wsOptions);
602
+ }
603
+ if (handler) {
604
+ this.wsManager.onConnection(handler);
605
+ }
606
+ return this.wsManager;
607
+ }
608
+
609
+ /**
610
+ * Returns a pre-configured Helmet middleware function synchronously.
611
+ * Dynamically loads helmet on first request if installed, or passes through with warning.
612
+ * @param {Object} [options={}] - Helmet options.
613
+ * @returns {Function} Express middleware.
614
+ */
615
+ static helmet(options = {}) {
616
+ let helmetMiddleware = null;
617
+ let loadPromise = null;
618
+
619
+ return (req, res, next) => {
620
+ if (helmetMiddleware) return helmetMiddleware(req, res, next);
621
+
622
+ if (!loadPromise) {
623
+ loadPromise = import("helmet")
624
+ .then((mod) => {
625
+ const helmetFn = mod.default || mod;
626
+ helmetMiddleware = helmetFn({
627
+ contentSecurityPolicy: props.debug ? false : undefined,
628
+ hidePoweredBy: false,
629
+ ...options,
630
+ });
631
+ })
632
+ .catch(() => {
633
+ console.error("[APP WARN] 'helmet' is not installed. Run: npx bluebird-js add helmet");
634
+ });
635
+ }
636
+
637
+ loadPromise.then(() => {
638
+ if (helmetMiddleware) helmetMiddleware(req, res, next);
639
+ else next();
640
+ });
641
+ };
642
+ }
643
+
644
+ /**
645
+ * Returns the built-in security headers middleware without requiring helmet.
646
+ * @param {Object} [options={}] - Options for header values.
647
+ * @returns {Function} Express middleware.
648
+ */
649
+ static securityHeaders(options = {}) {
650
+ return securityHeaders(options);
651
+ }
652
+
653
+ /**
654
+ * Returns the native rate-limiting middleware for protecting specific routes or routers.
655
+ * @param {Object} [options={}] - Rate limit options (windowMs, max, message, driver, keyGenerator).
656
+ * @returns {Function} Express middleware.
657
+ */
658
+ static rateLimit(options = {}) {
659
+ return RateLimit.middleware(options);
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Operational application error class for standardizing custom API errors.
665
+ */
666
+ export class AppError extends Error {
667
+ /**
668
+ * Creates an AppError instance.
669
+ * @param {string} message - Error message.
670
+ * @param {number} [statusCode=500] - HTTP status code.
671
+ * @param {Array|Object} [errors=[]] - Detailed error list.
672
+ */
673
+ constructor(message, statusCode = 500, errors = []) {
674
+ super(message);
675
+ this.name = "AppError";
676
+ this.statusCode = statusCode;
677
+ this.errors = errors;
678
+ this.isOperational = true;
679
+ Error.captureStackTrace(this, this.constructor);
680
+ }
681
+ }
682
+
683
+ export { App };
684
+ export default App;
package/core/auth.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import {
2
+ Auth,
3
+ AuthProtectOptions,
4
+ AuthLoginOptions,
5
+ AuthTokenPayload,
6
+ } from "./index.js";
7
+ export default Auth;
8
+ export {
9
+ Auth,
10
+ AuthProtectOptions,
11
+ AuthLoginOptions,
12
+ AuthTokenPayload,
13
+ };